debouncing an interrupt trigger

A couple of salient points, AK:

So when millis() overflows, it resets back to zero, so that when the state machine checks against its previous state, a massive error value comes up.

Not necessarily. If you use the subtraction operator - to compare the "new" time with the "previous" time, as I did in reply #2, the overflow is perfectly harmless. This is because of the nature of unsigned arithmetic in C. Let's say the "previous" value of millis() you captured was 0xFFFFFFFF. 10ms later you check millis() and it's value has "rolled over" to 9. Well, good news! In C unsigned arithmetic 9 - 0xFFFFFFFF is 10, exactly what you were expecting!

Secondly, there is already a tidy way to write the resetMillis() function you propose. Unfortunately, it relies on undocumented system internals, so this (for now) only works in Arduino 0012:

void resetMillis()
{
  extern volatile unsigned long timer0_millis;
  timer0_millis = 0;
}

Mikal

1 Like