How to read sensor every minute and publish every 5 minutes

I have a sensor (sgp30) whose values need to read every minute for optimal operation. However, I want to publish the data every 5 minutes. I don’t necessarily want to store / aggregate the minute level data - just need a snapshot reading every 5 minutes. Will the code below work? Is there a better way to do it? I suspect over time, I will want to aggregate the minute level data and take an average of it to publish every 5 minutes, but for now, a simple snapshot every 5 minutes will suffice.

const unsigned long MEASURE_PERIOD_MS = 60000; // 1 minute
const unsigned long PUBLISH_PERIOD_MS = 300000; // 5  minutes
unsigned long lastPublish = 8000 - PUBLISH_PERIOD_MS;
unsigned long lastMeasure = 8000 - MEASURE_PERIOD_MS;

void setup() { 
}

void loop() {

     if (millis() - lastMeasure >= MEASURE_PERIOD_MS) {
        lastMeasure = millis();
        // sensor reading every minute
    }

     if (millis() - lastPublish >= PUBLISH_PERIOD_MS) {
        lastPublish = millis();
        // particle publish every 5 minutes
    }
    
}

Why long ? You can use const int and safe 2 bytes


Why you subtracting here ? It’s going to be some big value due the unsigned can’t be negative


just put =0 here and wait 1minute for first reading and 5 for first publish or 60000 and 300000 respectively to get your reading and publish immediately and then all should work.
Best,

Actually, since the Particle devices run 32bit architecture micro controllers, unsigned long and unsigned int are both 32bit.
Even with distinct uint16_t you would not save any bytes as distinct variables (i.e. not part of an array or packed struct) will be placed on 32bit boundaries.

Also with unsigned arithmetic it’s best to avoid mix’n’match and rely on the the compilers implicit type conversions. Since millis() returns a uint32_t it is good practice to also have the other two values of that type.

There is a thread by @rickkas7 that gives some background

4 Likes