Troubleshooting millis() function

Hi there

I am trying to resolve a problem on a bigger program, so i tested my issue with a smaller one.

My test program is below:

unsigned long lastTime = 0; 
unsigned long now;          
char publishString[64];

void setup()               
{
}

void loop()   
{    
    now = millis();     
    if (lastTime == 0 ||  ((now - lastTime) > 15000)) { 
        sprintf(publishString, "{\"lastTime\":%u}",  lastTime);
        Spark.publish("Time ", publishString);
        lastTime = now; 
    }
}

As I understand and my intention is that I should get millis value at start when lastTime is still 0, and then every 15 seconds.

What I get is different:

{"lastTime":0}
{"lastTime":7004}
{"lastTime":22005} 

There is 15 seconds between 7004 and 22005, but why do I receive last time value at 7 seconds, and why not at 15 seconds and then 30. Does it take 7 seconds for publish() function?

You are entering immediately when lastTime == 0, but at that time now will be 7004 which is the value that you’ll publish 15sec later.
You always publish the time you stored in lastTime on round later.

The first 7sec is the time your Photon needs from power up to connect to cloud and after that enter loop()

Try setting lastTime = millis(); as last statement of setup() and see the difference :wink:

2 Likes

Seen my edit to prev post?

thank you

1 Like