millis() and Serial.print

First of I should state that I am a novice at this stuff. I was familiarizing with the millis() function and I am now more confused than when I started.

I was just printing out millis(). As expected, with this code Serial.print displays :
0 499
600 1099
1200 1699
1801 2300
2401 2900
3001 3502...

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

void loop() {
  unsigned long Time1 = 0;
  unsigned long Time2 = 0;

  Time1 = millis();
  delay(500);
  Time2 = millis();
  Serial.print(Time1);
  Serial.print("       ");
  Serial.println(Time2);
  delay(100);
}

But by just moving where the Serial.print is I get this:
0 0
600 0
1200 0
1800 0
2401 0
3001 0
3601 0....

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

void loop() {
  unsigned long Time1 = 0;
  unsigned long Time2 = 0;

  Time1 = millis();
  delay(500);
  Serial.print(Time1);
  Serial.print("       ");
  Serial.println(Time2);
  Time2 = millis();
  delay(100);
}

Can someone help me understand why in this example Time2 is showing up as 0? Is Serial.print interfering with the millis() function? Do I just misunderstand how millis() works? Or am I an idiot and missing something obvious.

Thanks

You're initializing time2 to 0 at the top of loop() everytime through, and since you now print it before you take it again, it's still 0 when you print it. Then you read it at the bottom of loop() and immediately re-zero it at the top.

Thanks. I knew it had to be something simple.

static unsigned long Time1 = 0;
static unsigned long Time2 = 0;

Change to that in the second code and see what happens... :slight_smile: