# Arduino: How do you reset millis() ?

The quick answer to “How do you reset millis()” is:  You Don’t!  And here’s why:  if you did, it would potentially break most libraries and functions that rely on it.  Generally the reason people want to reset it, is that they are concerned about rollover.  Instead of focusing on resetting millis(), here is how to use it correctly.

Avoiding rollover and checking how much time as passed is done in a single line:

if ((unsigned long)(millis() - previousMillis) >= interval)

That single line of code is all that is really needed, to avoid rollover!  Pretty simple, huh?  So let’s go into more detail about how this works and what each of those variables do.

Update Dec 8 2013. I’ve updated the examples below to a more robust implementation.

## What is millis() rollover?

Every millisecond a timer interrupt fires to increment a global variable.  When millis() is called, the value of that variable is returned.  The data type used is an unsigned long which is 4-bytes or 32-bits.  This means the maximum value it can hold is 4,294,967,295.  Convert that many milliseconds into days and you can see the rollover will occur in 49 days.

$\frac{4,294,967,295ms}{1000} = \frac{4,294,967secs}{60} = \frac{71852mins}{60} = \frac{1193}{24} = 49days$

In HEX the maximum value is 0xFFFFFFFF.  Add one more and it “rolls over” to zero.  Hence the name “millis() rollover.”

## Will my Arduino Lock-Up?

Let’s be very clear:  when millis() rolls-over, your Arduino will not lock-up.  In fact the Arduino’s ATmega processors very rarely lock-up.    So no, when the millis() value rolls over to 0, your Arduino won’t lock up and your project won’t explode.  Ok?  [Editor's Note:  If your project is designed to explode when millis() equals 0, then in that case, it would explode.]

## How to reset millis() to avoid rollover

When it comes down to it, there’s no reason to reset millis().  In fact, it turns out this seemingly trivial task requires changing quite a few things buried deep inside of the Arduino core functions.  The worst part is, if you make those changes you may very well break libraries and other projects!  Instead, all that you need to do is simple subtraction:

unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval) {


That if-statement is a simple way to detect when time a predetermined amount of time has past and it handles rollover! With such a simple statement, why bother with trying to reset millis()?

Here’s an extended example of how to handle millis rollover [pastebin]:

// Interval is how long we wait
// add const if this should never change
int interval=1000;
// Tracks the time since last event fired
unsigned long previousMillis=0;

void setup() {
pinMode(13, OUTPUT);
}

void loop() {
// Get snapshot of time
unsigned long currentMillis = millis();

// How much time has passed, accounting for rollover with subtraction!
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
// It's time to do something!
digitalWrite(13, !digitalRead(13)); // Toggle the LED on Pin 13

// Use the snapshot to set track time until next event
previousMillis = currentMillis;
}
}


## Why does this work?

Long story short, it is what happens when do math with unsigned variables. Don’t trust that this will work? Okay, consider the following example using an unsigned char data type which is a single byte or 8 bits.

The maximum the data type can hold in HEX is 0xFF which means in DECimal it is 255.  Let’s select an arbitrary value of decimal 47.  This code will use “counter” to simulate millis(). Every 255 counts it will rollover to zero. Every time we count up 47 steps, we will print the message “Trigger Event!”.

//Pretend "counter" is "millis"
unsigned char counter = 0;

unsigned char previousCounter = 0;
unsigned int interval=47;

void setup() {
Serial.begin(9600);
delay(5000);  // give enough time to open the serial monitor after uploading
Serial.println("Starting...");
}
void loop() {
for (int x=0; x<1000; x++) { // run through uchar a few times
// ******* simulate millis()
counter++; // simulate millis()
Serial.println(counter);
// ******
unsigned char currentCounter = counter;
if ((unsigned char)(currentCounter - previousCounter) >= interval) { // check for rollover
Serial.println("Trigger Event!");
previousCounter = currentCounter;
}
}
Serial.println("...stopping!");
while(1); // Stop the Serial monitor output
}


When you look at the serial output of that code, make sure you open the serial monitor before it opens itself.  You want to start look at the top of the output right after “Starting”.  The first time through 255, you’ll see a trigger after 47, as expected.  The second time through 255 it’ll be after 26.  The value of 47 was picked in this example because it won’t always be in the same place in the count.  However, it will always be 47 steps after the previous “Trigger.”  That’s how we know this code is accounting for rollover.

## Conclusion

Instead of trying to reset millis(), just use subtraction to handle the millis() time detection and rollover. It is a simple method that won’t involve modifying any code in the Arduino libraries. (This also works with micros() too!)  Also,  if you want to learn more about how to how to use millis to multitask or replace delay(), checkout this tutorial.

### written by James Lewis

Capacitor Expert by Day, Enginerd at Night. On paper I have a EE which I use to make things blink, beep, and fly. I created and enjoy making the AddOhms Tutorials at addohms.com

#### 10 Responses to "Arduino: How do you reset millis() ?"

1. frececroka says:

As far as I understand your code, it will not work on a rollover. Let’s look at the case, where counter is close to rolling over (counter = 250) and waitUntil equals counter. waitUntil will be set to waitUntil + interval == 250 + 47. Because of rolling over, waitUntil will become 250 + 47- 256 = 41. When the for loop checks the if condition the next time, counter will be 251 and the condition will give true (251 – 41 == 210 and 210 >= 0), although the wanted delay of 47 wasn’t followed.

Please correct me if I’m wrong.

• James says:

You’re right. The code as posted is incorrect. It was from an earlier revision of the post when I mixed up “correct” versus “incorrect” way. Recent reload my wp database and I forgot to update it.

Should be more along the lines of ” if ((counter – start_time) >= interval) { // check for rollover”

2. Deskwizard says:

I’ll have a look into this, this looks like EXACTLY what I needed!

Big thanks !

3. James says:

Code here and on Pastebin has been updated to the correct rollover code. Sorry for the mix-up.

4. Phase 1: Complete « Mohammod says:

[...] dilemma, which is how I hoped to have resolved this issue in my 1st attempt.  I then went onto CMiYC.com where I found a solution, which was to used the following code: if ((unsigned long)(counter – [...]

5. Michael Wyraz says:

The code above works fine but has the disadvantage that if some processing takes too long time, the “work” next time is executed more than one time without delay.

Example:
interval=1000, waitUntil=3000, millis()=3000.
now some processing takes 5 seconds
interval=1000, waitUntil=4000, millis()=8000.
now the condition returns true until “waitUntil” reaches 8000.

So it’s better to add interval to waitUntil until the condition is false.

• James says:

Good point. While the delay will be (most likely) deterministic, it will be longer than expected. I’ll look at modifying the examples.

6. Bruce says:

It seems to me that this code simply transfers the roll-over problem from the millis() function to the waitUntil variable. The waitUntil variable holds 4294967295 values which means that for an interval of 1000 it will run out after 49.7 days. What am I missing?

• James says:

First roll-over isn’t a “problem”. It is just how millis() works.

In order to detect roll-over, it doesn’t matter what the actual maximum value either waitUntil can hold or millis() can return. The key is that they both need have the same limit. By setting the interval, even if roll-over occurs, you can detect if “interval” number of ticks have occurred.

The only limitation becomes you can’t detect more than the amount you can hold in waitUntil or millis() can return, which is 49 days. As long as your “interval” is less than 49 days, you’ll never know how many times roll-over have occurred (and you probably won’t care.)