millis() troubles

Hi everyone! This is my first post to this forum.

I'm trying to get a hang of the millis() function because it seems very useful. I wrote this quick sketch to test out millis(), and it doesn't even work!

It's supposed to Serial.print the current millis() every 10 seconds, but it ends up just printing it every cycle with no delay! It's so basic, but I just can't see what I'm doing wrong! Please help!

Thanks :slight_smile:

unsigned long timestamp = 0;
unsigned long interval = 10000;
unsigned long noww;

void setup() {
  Serial.begin(9600);
}

void loop() {
  unsigned long noww = millis();
  if (noww >= timestamp)
  {
    Serial.println(noww);
    unsigned long timestamp = noww + interval;
  }
}

What is the value of noww + interval at say, 11 seconds?

Remove unsigned long from this line

   Serial.println(noww);
    unsigned long timestamp = noww + interval;

The way you have it you are creating a new variable each time loop() is called and the value is lost when loop() terminates.

Omitting the unsigned long means that you use the variable that you defined at the top of the program.

The correct way to test for millis() is like this

if (noww - timestamp >= interval) {
   timestamp += interval;
   // other code
}

Comparing for an exact match might result in missing an interval.

The demo Several Things at a Time illustrates the use of millis() to manage timing. It may help with understanding the technique.

...R

Robin2:
Remove unsigned long from this line

   Serial.println(noww);

unsigned long timestamp = noww + interval;




The way you have it you are creating a new variable each time loop() is called and the value is lost when loop() terminates.

Omitting the unsigned long means that you use the variable that you defined at the top of the program.

The correct way to test for millis() is like this


if (noww - timestamp >= interval) {
  timestamp += interval;
  // other code
}




Comparing for an exact match might result in missing an interval.

The demo [Several Things at a Time](http://forum.arduino.cc/index.php?topic=223286.0) illustrates the use of millis() to manage timing. It may help with understanding the technique.


...R

That did it! Thanks!