I want to calculate the duration of a loop and use this value in my code. Hovewer the result (I called 'timeloop") gived me often 0 because the code is short, so I would like to constrain this value with minimum 1 with the code :
timeloop = max(millis() - timeprev , 1);
But in this example below, instead to have a Serial.print every second, I have the serial.print "timeloop = 1" every millisecond in the monitor like if the command 'mytimer += timeloop;' was broken.
Also if I add a delay(1) at the end, the code works correctly.
I tried also this formula without good result :
timeloop = max(millis() - long(timeprev),long(1));
The code :
unsigned long timeprev;
unsigned long timeloop;
int mytimer ;
void setup()
{
Serial.begin(9600);
}
void loop()
{
timeloop = max(millis() - timeprev , 1);
timeprev = millis();
if(mytimer > 1000)
{
Serial.print("timeloop = ");
Serial.println(timeloop);
Serial.println("--------------");
mytimer = 0;
}
else
{
mytimer += timeloop;
}
}