Arduino Millis() Rollover Handling

Millis Police

On the Arduino microcontroller, the millis() function counts the number of milliseconds since the program started running. Unfortunately, this count resets to zero after approximately 9 hours and 32 minutes. I have written a millisRollover() function that detects these rollovers, so that programs can respond properly to the overflow event. This can solve problems with servo routines, steppers, timed pauses and a variety of other calculations. In addition, because my millisRollover() function counts the number of times rollover has happened, it is now possible to record total Arduino runtime with a counter that’s good for over 35 years.

You want to blink an LED only on Christmas during leap years? Totally possible now.

(yes, there really is a millis police department)

2 Responses to “Arduino Millis() Rollover Handling”


  1. 1 John

    I’m having a little difficulty understanding how I would use your rollover function in a scenario where I tick a clock if 1000 ms has elapsed, like:

    if( millis() - previousMillis > 1000 ) {
    previousMillis = millis();
    // One second has elapsed, tick the clock.
    }

    It seems like this will “hiccup” during a rollover.

  2. 2 faludi

    Glad you asked because it’s worth noting that the millis() function was greatly improved in Arduino 0012:

    * Improved millis(): it now overflows after 49 days instead of 9 hours, but
    now uses slightly more processing power.

    I’m assuming this means that it now fills the full unsigned long variable. So in your case you should just be able to do the math. The rollover will cause your subtraction to overflow an the result would be correct.

Leave a Reply