I have had no problems running the SGP30 on an Argon and Xenon using the Adafruit example.
Initially it worked fine using code modified from the example provided with the library for the sensor, but that only read and stored the CO2 and VOC readings. Now I would like to be warned of rapidly increasing levels and it won’t work. The code below is meant to take samples of 5 readings 1 sec apart and average them. If the averages increase for 3 consecutive samples, then I want an alarm published to the cloud. I have mostly copied the SGP code from the example and placed it into a boiler plate that builds and rotates the samples. This code keeps reading 400 CO2 and 0 VOC, which means 0. This is still the case even after running it over night. I assume that I am mishandling the baselines somehow.
I have tried to organize and comment my amateurish code. Any help is appreciated.
// This #include statement was automatically added by the Particle IDE.
#include <Adafruit_SGP30.h>
Adafruit_SGP30 sgp;
int sampleSize = 5; //# of readings included in a sample
int sample[5];
const char room = 'B200'; //Location of sensor
void setup() {
Serial.begin();
RGB.control(true);
RGB.brightness(0); //Turn off the RGB LED
if (! sgp.begin()){
Serial.println("Sensor not found :(");
while (1);
}
Serial.print("Found SGP30 serial #"); //Retrieve the serial number of the sensor
Serial.print(sgp.serialnumber[0], HEX);
Serial.print(sgp.serialnumber[1], HEX);
Serial.println(sgp.serialnumber[2], HEX);
}
void loop() {
Time.zone(-5);
int defcon = 0; //The number of consecutive increases before triggering alert.
int newAvg = 0;
int oldAvg = 0;
int sampling = 1;
int sum = 0;
if (! sgp.IAQmeasure()) {
Serial.println("Measurement failed");
return;
}
Particle.publish("Sampling Beginning");
while (sampling < 7) {
for (int reading = 0;reading < sampleSize ;reading++) { //Build sample of 5 readings, 1 second apart.
sample[reading] = sgp.TVOC;
sum = sum + sample[reading];
delay(1000);
}
newAvg = sum / sampleSize;
Mesh.publish("sgp reading", Time.format("%H:%M:%S") + "," + String(newAvg));
sum = 0;
if (newAvg > oldAvg) { //Raise alert level if new avg is greater than previous
defcon++;
Serial.print("Defcon: " + String(defcon));
}
else {
defcon = 0; // Reset alert level if new avg not greater than previous
}
oldAvg = newAvg;
if (defcon > 3){ // Publish alert after enough consecutive increases
Mesh.publish("sgp reading", "Alert: " + String(room) + "," + String(newAvg));
Particle.publish("alert", room + "," + String(newAvg));
defcon = 0;
}
if (sampling == 6) { //Reset the baseline every 6 samples (30 readings). I think my issue may lie here!
uint16_t TVOC_base, eCO2_base;
if (! sgp.getIAQBaseline(&eCO2_base, &TVOC_base)) {
Serial.println("Failed to get baseline readings");
return;
}
sampling = 1; //Resart the loop
}
} //end while
}