Millis assignment to variable not working

Hello all,
I am having trouble assigning a millis() result to a variable. The value of the variable is always zero after the statement var = millis(); The variable is declared as an unsigned long. I have the code using 2 ide's on separate machines with separate Arduino mega's and get the same result.

Following is the test code used and the serial monitor result.

// Global Variables

unsigned long set_time = 0;
unsigned long duration = 20000;
unsigned long calculated_result = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  set_time = millis();
}

void loop() {
   // put your main code here, to run repeatedly:
  Serial.print("The value of duration is ");
  Serial.println(duration);
  Serial.print("The value of set time is ");
  Serial.println(set_time);
  Serial.print("The current value of millis is ");
  Serial.println(millis());
  calculated_result = millis() - set_time;
  Serial.print("The value of calculated result is ");
  Serial.println(calculated_result);
  delay(1000);
}

Serial Monitor Result

The value of duration is 20000
The value of set time is 0
The current value of millis is 6038
The value of calculated result is 6038
The value of duration is 20000
The value of set time is 0
The current value of millis is 7044
The value of calculated result is 7045
The value of duration is 20000
The value of set time is 0
The current value of millis is 8050
The value of calculated result is 8050

Any help with why set_time is always 0 is most welcome.

You only assign to set_time within setup() so why do you think it will change? If you put a delay(1000) inside setup() at the very beginning, then set_time would always be 1000 (or close to it)

Thanks. Clearly not a logical thinking day for me.

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