Simple Question on Millis

Hi All,

We have a really simple question when looking at millis. Everything I can find online seems to suggest millis will start counting from when the program starts running.

Returns the number of milliseconds passed since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 50 days.

The code below returns zero, where I would have expected it to be closer to 50. Thoughts?

Starting Program
0

unsigned long time = millis();

void setup() {
  Serial.begin(9600);
  Serial.println("Starting Program");
  delay(50);
  Serial.println(time);
}

void loop() {
  //
}

You are reading Time as the first step. It's never getting updated so you can wait 50 milliseconds or 50 days and it will still be zero.

3 Likes

millis( ) returns milliseconds.

Lines of code in your sketches only take a few microseconds.

Hence, at start up time, it is very reasonable millis( ) will return 0 (zero).

1 Like

The variable Time gets initialized to the value of millis() at the very start of the code (before setup() begins execution). This value does not update automatically, so it will remain at 0 until you assign a new value to Time.

1 Like

You are reading Time as the first step.

Isn't it the 3rd step? I first run the print line, then a delay of 50ms, then read the time.

Hence, at start up time, it is very reasonable millis( ) will return 0 (zero).

I even added a 50ms delay, so it should show up? Even with a 5 second delay, I don't get a value.

it seems like I can't assign mills to a variable while initializing the global, or during setup. But if I assigned the variable in the loop, it seems to work fine.

This line of code is where time is set.

unsigned long time = millis();

1 Like

Sorry all, I think I understand what you are all saying.

When the variable time is set, the program isn't running yet. Even though I have a delay the variable doesn't keep updating.

If I add another 'time = millis();' after the delay, I get the expected results.

Thank you alL!

unsigned long time;

void setup() {
  Serial.begin(9600);
  Serial.println("Starting Program");
  delay(50);

  time = millis();

  Serial.println(time);
}

void loop() {
  //
}
1 Like

Hello adriavia

Consider:

unsigned long time = millis();

void setup() {
  Serial.begin(9600);
  Serial.println("Starting Program");
  Serial.println(time);
  delay(50);
  Serial.println("delay(50);");
  time = millis();
  Serial.println(time);
}

void loop() {
  //
}

p.s. LarryD was faster again :wink:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.