Interval based actions with minimum external library

Friends,

I am trying to get some data values to pass through a Particle.Publish command in the background as the other parts of my code run. It has worked for me in the past so I do not know why it all of the sudden stopped working.

The main function of my code is working off the timer0 vairable but for some reason it doesn’t enter the if statement associated with publish command.

Here is how i am doing it;

  if(timer1%publishInterval==0){ //every hour these will push to every hour to google sheets

    Particle.publish("googleDocs", "{\"ambTempF\":\"" + String(ambTempF) + "\",\"ambHumid\":\"" + String(ambHumid) +"\",\"waterTempF\":\"" + String(waterTempF) +"\"}", 60, PRIVATE);
        
    timer1=0;
    

    }         //used for doing things at a certain time interval

I haven’t seen the residual operator used much, is there a reason for that? I wanted to see what is the best way to have data publish in the background.

Thanks in advace

@jjlee32 You have referred to timer0 as the main variable and the code snippet uses timer1? If I were doing a regular publish of data I would do it like this;

#define PUBLISH_INTERVAL (60 * 60 * 1000)   //one hour in milliseconds
uint32_t publishTime = 0;  //declare time variable

In setup() you may want to include publishTime = millis();

then in loop()

if (millis() - publishTime > PUBLISH_INTERVAL) {
Particle.publish();
publishTime = millis();
}

This way you don’t need to increment the timer1 value and the interval will be very accurate using the system clock function.

3 Likes

Yes, what Armor said. millis() is the best way to handle this, and make sure you structure it exactly like that:

if (millis() - lastTime >= interval)

This is necessary to make sure millis rollover does not cause problems:

1 Like

Friends,

That did it.

@armor In regard to the timer1; i tried doing it with it’s own independtant timer before posting. Looks like i didnt switch it back.

Any reason why the residual wouldn’t be the best option?

Thanks for the help @rickkas7 and @armor

@jjlee32 Good to hear. @rickkas7 is much better placed to answer your question about using the modulus operator % I would simply say that a. you do not need to increment your timer counter, b. the difference of two unsigned long numbers is quicker to perform than the modulus and lastly, c. using millis() will be more accurate.

1 Like

The modulus operator in the main loop is risky.

What if the something takes longer than the publishInterval? then it will miss that event entirely as the time will roll past and the if statement won’t be true when it returns to the loop.

That’s why the <= or >= will catch the event, even if it returns to the loop a bit late.

2 Likes