Any explanation for this?

I'm having an odd issue.

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

float total_time;
float total_time2;

void loop() {

  long loop_start_time = millis();
  delay(200);
  
  total_time += (millis() - loop_start_time) / 1000;
  Serial.println(total_time); // always prints 0!
    
  float t = millis() - loop_start_time;
  total_time2 += t/1000;
  Serial.println(total_time2); // works
  
  Serial.println("---");
}

In the above, total_time is always 0, while total_time2, which does the same thing although in two steps, keeps track of the time correctly.

Any idea why total_time wouldn't be working?

The right hand side is always zero, so the result you see is the result you should expect. Look up integer arithmetic.

because integer division 200/1000 always = 0

Why float?
Use this:

unsigned long total_time;
unsigned long total_time2;

/ 1000.0

And print total_time/1000...

Provided the accumulated time is in milliseconds, yes.

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