millis() and micros() overflow periodically. However, this is not a
problem: as long as you compare durations instead of
timestamps you can
forget about the overflows.
The liked answer also gives the trick for resetting millis(). Can be
handy for testing purposes, but you do not need this to handle the
millis() rollover problem. Notice that there is no clean way to reset
micros(): it relies on a static variable, i.e. a variable private to
the file defining it.
millis() and micros() overflow periodically. However, this is not a
problem: as long as you compare durations instead of
timestamps you can
forget about the overflows.
The liked answer also gives the trick for resetting millis(). Can be
handy for testing purposes, but you do not need this to handle the
millis() rollover problem. Notice that there is no clean way to reset
micros(): it relies on a static variable, i.e. a variable private to
the file defining it.
Overflow is never really an issue if you always calculate time difference. (Unless the time difference is more that 50 days.)
unsigned long previousTime = millis();
... wait for some event to happen ...
unsigned long elapsedTime = millis() - previousTime;
Even if previousTime was before the overflow, and millis() is after the overflow (so essentially millis()<previousTime), elapsedTime will still be the correct value.
This is because the calculation itself will also overflow. Since millis()<previousTime, the result would be negative, but the type of the variable is unsigned, so it wraps around. I hope that makes sense.
Just don't ever do something like if( millis() > (previousTime+1000) )
If you still want to reset millis, you can use the following:
extern volatile unsigned long timer0_millis;
unsigned long new_value = 0;
void setup(){
//Setup stuff
}
void loop(){
//Do stuff
//--------
//Change Millis
setMillis(new_value);
}
void setMillis(unsigned long new_millis){
uint8_t oldSREG = SREG;
cli();
timer0_millis = new_millis;
SREG = oldSREG;
}