Up until now, I’ve explained the concept for my particulate matter device (Blog #1), shown the material procurement process and tested all the sensors (Blog #2), and shown the wiring and assembly for the device (Blog #3). But I haven’t talked much about the code. so that’s what I’ll be doing in this blog. First of all, I should thank my amazing and brilliant husband Nathan who helped me get started with the coding and trying to decipher the example codes for the sensors and pick out what I needed to integrate together. But I caught on quickly and was able to do most of it myself! To make it more interesting, I made a couple videos of me going through my code and explaining it, but I will also post it at the bottom in case anyone is interested or wants to use all or part of my code for their own projects. So, without further ado, here we go!
Transmitting Arduino code
This first video explains the code for the transmitting (or sending) Arduino that will be attached to the drone.
//Author: Grace McNally
//Date: Feb. 3, 2022
//Project: Particulate Matter Monitoring System for Wildfires
//Particulate matter sensor code is based on the "sps30" example in the sensirion-sps library
//GPS code is based on "Example3_GetPosition" in the SparkFun u-blox GNSS Arduino Library
//Waterproof Temperature code based on the "Simple" example in the DallasTemperature Library
//Internal temperature code is based on the "p03_LoveOMeter" example in 10.StarterKit_BasicKit built in examples
//LoRa communication is using the LoRaSender example in the LoRa library
#include <sps30.h> //Library for sps30 particulate matter sensor
#include <Wire.h> //Needed for I2C to GNSS
#include <SparkFun_u-blox_GNSS_Arduino_Library.h> //Library for GPS sensor
#include <OneWire.h> //Needed for waterproof temperature sensor
#include <DallasTemperature.h> //Library for waterproof temperature sensor
#include <SPI.h> //Library used for communication between MKR board and LoRa module
#include <LoRa.h> //Library for LoRa transmission
SFE_UBLOX_GNSS myGNSS; //GPS defenition
#define ONE_WIRE_BUS 5 //Waterproof temperature sensor is plugged into port 5 on the Arduino
OneWire oneWire(ONE_WIRE_BUS); //Setup a oneWire instance to communicate with OneWire devices
DallasTemperature sensors(&oneWire); //Pass our oneWire reference to Dallas Temperature
const int sensorPin = A6; //TMP36 temperature sensor is plugged into port A6 on the Arduino
//Initialize timer variables
long lastTime = 0; //Simple local timer
long transmitStart = 0; //Beginning of LoRa transmission
long transmitEnd = 0; //End of LoRa transmission
void setup() {
//Setting up serial communication with computer if present.
Serial.begin(9600);
delay(500);
//setup for sps30 particulate matter sensor
int16_t ret;
uint8_t auto_clean_days = 4;
uint32_t auto_clean;
sensirion_i2c_init();
while (sps30_probe() != 0) {
Serial.print("SPS sensor probing failed\n");
delay(500);
}
ret = sps30_set_fan_auto_cleaning_interval_days(auto_clean_days);
if (ret) {
Serial.print("error setting the auto-clean interval: ");
Serial.println(ret);
}
ret = sps30_start_measurement();
if (ret < 0) {
Serial.print("error starting measurement\n");
}
//Setup for GPS sensor
Wire.begin();
if (myGNSS.begin() == false) //Connect to the u-blox module using Wire port
{
Serial.println(F("u-blox GNSS not detected at default I2C address. Please check wiring. Freezing."));
while (1);
}
myGNSS.setI2COutput(COM_TYPE_UBX); //Set the I2C port to output UBX only (turn off NMEA noise)
myGNSS.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT); //Save (only) the communications port settings to flash and BBR
//Setup for Waterproof Temperature sensor
//Start up the library
sensors.begin();
sensors.setResolution(9);
//start LoRa module
if (!LoRa.begin(915E6)) { //915E6 is the frequency for US and Canada
Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {
String message = ""; //The 'message' variable will be used to store the measurements from all the sensors for the LoRa transmission
//'-1' will be outputed if there is a failed measurement. To run diagnostics, plug the Arduino into a computer and open the serial monitor
if (millis() - lastTime > 1000) //Instead of a fixed delay between loop executions, the program will repeat if it has been at least a second (1000ms) since the last time it ran
{
lastTime = millis(); //Update the timer
//GPS sensor measurement
if (myGNSS.getTimeValid() == true) //This is getting the date and time from the GPS sensor in Greenwich Mean Time
{
int year = myGNSS.getYear();
int month = myGNSS.getMonth();
int day = myGNSS.getDay();
int hour = myGNSS.getHour();
int minute = myGNSS.getMinute();
int second = myGNSS.getSecond();
message = message + year + "-" + month + "-" + day + "," + hour + ":" + minute + ":" + second + ",";
}
else
{
Serial.println(" Time is not valid");
message = message + "0-0-0,0:0:0,"; //If zeros are outputted for the date and time, there is an error
//Note that it usually takes a couple minutes for the GPS to connect to sattelites and output data
}
//Get GPS sensor measurement
long latitude = myGNSS.getLatitude(); //in degrees * 10^-7
long longitude = myGNSS.getLongitude(); //in degrees * 10^-7
long altitude = myGNSS.getAltitude(); //in mm
byte SIV = myGNSS.getSIV(); //number of satellites in view
message = message + latitude + "," + longitude + "," + altitude + "," + SIV + ",";
//Get the sps30 particulate matter sensor measurement
struct sps30_measurement m;
char serial[SPS30_MAX_SERIAL_LEN];
uint16_t data_ready;
int16_t ret;
do {
ret = sps30_read_data_ready(&data_ready);
if (ret < 0) {
Serial.print("error reading data-ready flag: ");
Serial.println(ret);
} else if (!data_ready)
Serial.print("data not ready, no new measurement available\n");
else
break;
delay(100); /* retry in 100ms */
} while (1);
ret = sps30_read_measurement(&m);
if (ret < 0) {
Serial.print("error reading PM measurement\n");
message = message + "-1,-1,";
} else {
float pm2p5 = m.mc_2p5; //Concentration (in micrograms per meter cubed) of particles smaller than 2.5 microns
float pm10 = m.mc_10p0 - pm2p5; //Concentration (in micrograms per meter cubed) of particles between 2.5 and 10 microns
message = message + pm2p5 + "," + pm10 + ",";
}
// Get outside temperature with digital waterproof sensor
sensors.requestTemperatures(); // Send the command to get temperatures
float outsidetemp = sensors.getTempCByIndex(0); //Read temperature
if (outsidetemp != DEVICE_DISCONNECTED_C) // Check if reading was successful
{
message = message + String(outsidetemp, 1) + ","; //Temperature is in degrees Celsius
}
else
{
Serial.print(" Outside temperature error");
message = message + "-1";
}
//Get inside temperature from TMP36 sensor
//Get voltage on analog pin A6
int sensorVal = analogRead(sensorPin);
// convert the ADC reading to voltage
float voltage = (sensorVal / 1024.0) * 3.3; // multiplied by 3.3 because the board's logic is 3.3V.
// convert the voltage to temperature in degrees C
// the sensor changes 10 mV per degree
// the datasheet says there's a 500 mV offset
// ((voltage - 500 mV) times 100)
float insidetemp = (voltage - .5) * 100;
message = message + String(insidetemp, 1) + ","; //Temperature in degrees Celsius
//Add previous transmission time to message variable
//Note that in North America, the maximum LoRa transmission time is 400ms so this verifies if operation is compliant
message = message + (transmitEnd - transmitStart) + ",";
Serial.println(message); //Print to serial monitor if the Arduino is connected to a computer
transmitStart = millis(); //Start time of transmission
// send LoRa packet of 'message'
LoRa.beginPacket();
LoRa.print(message);
LoRa.endPacket();
transmitEnd = millis(); //End time of transmission
}
}
Receiving Arduino code
The second video explains the receiving Arduino code. Originally, I was going to include indicator lights and an LCD screen to the receiving device, but due to a small testing window, I didn’t have time to include these.
//Author: Grace McNally
//Date: Feb. 3, 2022
//Project: Particulate Matter Monitoring System for Wildfires
//This code is based on the LoRaReceiver example in the LoRa library
#include <SPI.h> //Library used for communication between MKR board and LoRa module
#include <LoRa.h> //Library for LoRa transmission
void setup() {
Serial.begin(9600);
while (!Serial);
if (!LoRa.begin(915E6)) {
Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {
// Parsing and printing LoRa packets
int packetSize = LoRa.parsePacket();
if (packetSize) {
// read packet
while (LoRa.available()) {
Serial.print((char)LoRa.read());
}
Serial.print("\n");
}
}
Saving to CSV
In order to communicate with the receiving Arduino and save the data in a csv file format, I decided to use Python. Since I don’t know Python though, my husband wrote this code, so thank you Nathan!
# Author: Nathan McNally # Date: Feb. 3, 2022 # Particulate Matter Device for Forest Fire Applications import serial from datetime import datetime # Make new file with date and time in filename now = datetime.now() # datetime object containing current date and time filename = "drone-PM-Data-" + now.strftime("%Y-%m-%d-%H-%M-%S") + ".csv" print("Filename:", filename) file_out = open(filename, mode='w') file_out.write("Date,Time,Lat,Long,Elev,SIV,PM2.5,PM2.5-10,OutsideTemp,InsideTemp,TransmitTime(ms)\n") # Start serial communication with Arduino arduino = serial.Serial(port='COM10', baudrate=9600) try: while True: data = str(arduino.readline())[2:-3] # Reading message from Arduino and removing message container characters file_out.write(data+"\n") # Writing the data to the csv file print(data) except KeyboardInterrupt: pass print("Ended program") file_out.close()