programming - Resetting millis() and micros() - Arduino Stack Exchange
Resetting Micros() to 0
Reset Arduino millis() and micros()
reset micros() timer
Videos
Tl;dr: Created code that disabled computer and now can’t change code
I created a Arduino for a buddy that automatically Rick Rolls the person when it is plugged in using they keyboard function. I also made it so you are can’t click anywhere with the mouse when it is plugged in. The mouse part was added after the Rick roller and broke the Rick roller. The mouse sending a constant stream of command prevents it from fully uploading. How do I reset it to factory settings by hardware?
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;
}
If you used millis a lot and there's risk something will go awiry when it's been running for over 49 days. Rather than trying to handle the rollover, how about resetting Arduino? If there's unused GPIO pin, connect it to reset pin. When rollover is detected, set that pin to output and low. On reset, the pin will default to input until it's set again.