# 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.

Need to brush up on how millis() works?  I’ve got a tutorial on how to effectively multi-task with millis() and another line-by-line tutorial on blink Without delay

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} = 49dayshuge$

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.

Long comments, URLs, and code tend to get flagged for spam moderation. No need to resubmit.

ALL comments submitted with fake or throw-away services are deleted, regardless of content.

Don't be a dweeb.

## 69 thoughts on “Arduino: How do you reset millis() ?”

1. Demetri says:

Will doing something like this accomplish the same thing?

/////////////////////////////////////////////////////////////////////////////////

unsigned long time = 0;
int CycleTime = 6000;

time = millis();
time = time + CycleTime;

while(true)
{

if (millis() > time)
{

//DO SOMTHING

time = millis();
time = time + CycleTime;
}

}

/////////////////////////////////////////////////////////////////////////////////

Will doing this on an Arduino Nano cause any problems with memory, as millis() can get quite large?

• Yes it will but it’s not good code because you’re setting up your own permanent loop inside a function that is itself a permanent loop. Let the loop function do the looping and never use while(true) {}.

You also have to repeat yourself with the two lines which update time which you should wither try to avoid or put in to a separate function so you only have to write it out once.

Finally, this uses no more memory no matter how large millis() gets. Try not to think of memory usage based on the size of a number. You only use more memory when you define new variables and you’re not doing that here. I think a long like your time variable uses 32-bits or in other words 4 bytes of memory. It will always use 4 bytes if you put 0, 1, 10 or 60 billion in it so the size of the number is irrelevant. When the number gets too big to fit in 32-bits it will go back to the smallest number that will fit in 32-bits. That’s called an overflow and is why we have to handle the rollover and hence this article.

• I like Demetri’s code. Forget about the while(true), that’s just semantics (he should put the initializing code in the setup{} section, that’s all). But his code does something your’s does not. It will never miss an interval. eg. If interval is say, 1 second to update a RTC value, then if the code further down the line takes up more time than this interval (say 10 seconds), then his code will actually run the event 10 times later when it can.

Just the same, thank you for this explaination. I think it would be more clear if you spelled out what happens on the roll over and show how the unsigned long still comes out larger than the interval. This is the same math I use for following the pointers in a buffer that rolls over.

Hey.. wait a minute, how does he get around the roll over??? Bah, there’s still something not perfect about either of these solutions for the purpose of running a software driven RTC.

2. David says:

Hello

can you explain to me, why this retyping in IF statement is really needed for unsigned long variables? Because your example (your proof) use type uint8_t variables and with this variable type the rollover is really there, but for some reason the rollover is not present for 16 or 32 bit variables (I’m using Atmega328). Here is mine sample code

Serial.begin(9600);

uint8_t a=0, b=1;
Serial.println(a-b); // -1
Serial.println((uint8_t)(a-b)); // 255

uint16_t c=0, d=1;
Serial.println(c-d); // 65535
Serial.println((uint16_t)(c-d)); // 65535

uint32_t e=0, f=1;
Serial.println(e-f); // 4294967295
Serial.println((uint32_t)(e-f)); // 4294967295

I tried to rewrite your proof code with unsigned long variables and I set to “counter” variable near the overflow variable and it works correct even without retyping in IF statement.

thank you

• People who understand the compiler’s rules much better than I have told me it is a good idea. I haven’t proven to myself yet if it is required.

• David says:

Ok I asked about this on arduino forum and looks like your retyping of variable in IF statement is not need, it will work just with simple millis() – previousMillis.

The mistake is your sample code, where you use a byte variable as “timer”. Byte variables are promoted to (signed) int, that is why your sample code actually “rollover”, but that is not case with unsigned long.

If anything, please feel free to write a post here

http://forum.arduino.cc/index.php?topic=414348.0

• I don’t see it as an error, but thanks for the follow up.

3. Hi, this is a great article and makes handling an interval with millis() much more simple than the approach I was previously taking. Something to note is that on line 21 you are setting previousMillis to be currentMillis but this will introduce a very tiny amount of drift in your intervals. If, for example currentMillis – previousMillis is 10002 and the if statement was therefore true, you would perform your action, but will have lost 2 milliseconds from the next interval. I would, instead set previousMillis += interval so that the intervals are kept consistent with real time.

4. The issue i’m seeing with this, is, unless you can accurately place previousmillis before your first time using this method, it will always return true.

example… say you wanted to draw a series of bmp’s on a tft touchscreen with a slight delay between..

//Button
if (p.y > 110 && p.y 250 && p.x = interval){ // here you are saying if currentMillis is greater than 0, it’s true!
bmpDraw(“redbutton.bmp”, 15, 105);
Serial.println(F(“Button Pressed!”));
button = 0;
}
}
}

In this scenario, if this is the first button, then you have no previousmillis set, or it’s still at it’s default setting of 0.. this means the if statement will always return true, as millis() counts from the beginning of the program, you are essentially saying that anything above 0 is true, and millis() will always be above 0

So.. how does one work around this catch 22 type of situation?

• I don’t see this as a problem or a catch-22 at all.

In most situations, the “if (currentMillis…” check that occurs when the program first starts is not a problem. If for some reason this ONE TIME event was an issue, you have two options:

1. Set previousMillis at the end of setup(). It’ll be non-zero.
2. Create a flag that causes the first check to be skipped.

#2 is way overkill in my opinion. Again, I’ve never encountered a situation where the first check was an issue. It only happens once and in most cases you WANT your code to run. The critical timing comes on the 2nd iteration, not the first one.

5. Rinus Boone says:

Thanks for the clear explanation. Just as an extra information: I found that the if statement (line 16 of the first example) goes wrong when the value of ‘interva’l is negative. This happened to me and it took some debugging to find out.

6. // added second
if (((local_time.lastMillis + COUNT_SECOND) actualMillis)) // rollover (1 per 50 days)
{
// how many seconds add
if ((local_time.lastMillis + COUNT_SECOND) < actualMillis)
{
local_time.second += (actualMillis – local_time.lastMillis) / COUNT_SECOND;
local_time.milisecond = (actualMillis – local_time.lastMillis) % COUNT_SECOND;
}
else
{
// rollover
local_time.second++;
local_time.milisecond = 0;
}

local_time.lastMillis = actualMillis;

• Not sure what you are trying to do there. But that looks far more complicated than just using simple twos-complement math.

7. hape says:

hi
if i test your source (the example to explain how it works) i get an error message:
—————————————————————————————————
Arduino: 1.6.5 (Windows 7), Platine: “Arduino Uno”

Build-Optionen wurden verändert, alles wird neu gebaut

millis_timer.ino: In function ‘void loop()’:
millis_timer:13: error: ‘amp’ was not declared in this scope
millis_timer:13: error: ‘lt’ was not declared in this scope
millis_timer:13: error: expected ‘)’ before ‘;’ token
millis_timer.ino:13:31: warning: statement has no effect [-Wunused-value]
millis_timer:13: error: name lookup of ‘x’ changed for ISO ‘for’ scoping [-fpermissive]
millis_timer.ino:13:33: note: (if you use ‘-fpermissive’ G++ will accept your code)
millis_timer:13: error: expected ‘;’ before ‘)’ token
millis_timer:26: error: expected ‘}’ at end of input
‘amp’ was not declared in this scope
————————————————————————————————————–

So i think i have to do anything else than only compile the code?
Any ideas?
thx for your idea
hape

• Yeah, my fault. I changed something in the post and the code got messed up. It is fixed now.

8. Francescomm says:

This works only if the time you are comparing millis() to is not far away in the past. It is a good technique for intervals A-B where both A and B are near enough.

if(millis()-farAwayInThePast>60000) { … }

is NOT OK. Or not probably doing what you’d expect.

After 49 days millis() will rollover to zero (ok thanks to unsigned math) and then eventually become equal to farAwayInThePast again, so this condition will evaluate to FALSE for one minute every 49 days.

9. MJ says:

Thank you for the very cool technique … I have a need for exactly this but I just cannot get my head around how it works.

I modified your sketch to uotput the values of currentCounter and previousCunter like so:

``` Serial.print(currentCounter); Serial.print(" - "); Serial.print(previousCounter); Serial.print(" = "); Serial.println(currentCounter - previousCounter);```

``` And I get output like this: 19 19 - 240 = -221 20 20 - 240 = -220 21 21 - 240 = -219 22 22 - 240 = -218 23 23 - 240 = -217 24 24 - 240 = -216 25 25 - 240 = -215 26 26 - 240 = -214 27 27 - 240 = -213 28 28 - 240 = -212 29 29 - 240 = -211 30 30 - 240 = -210 31 31 - 240 = -209 Trigger Event! 32 32 - 31 = 1 33 33 - 31 = 2 34 This is obviously after a rollover or 2 ... no how is -209 (the result just above the last trigger event above) >=47? Brain hurts! ```

`Thanks :)`

The maximum value a char can hold is 255 because it is 8-bits.

So 209+47 = 256. Can’t store 256 in a variable that can only hold a maximum of 255.

• > This is obviously after a rollover or 2 … no how is -209 (the result just above the last trigger event above) >=47?

Because you need to use unsigned types (eg. byte rather than char). Then it is impossible for them to hold a negative number, and thus the question “how is -209 >= 47?” goes away.

• wen says:

Hi,
I learned to use millis for multitask(RGB LED flashing & MP3 IR remote).I just wanted to control IR remote to select music(RGBLED flashing itself) but the LED stopped flashing when currenttime:2977 & previoustime:2527
Anyone could help me to debug and solve followed issue?Thanks!!
The code was as followed:

```#include
#include
#include
//********************************************************
const int redPin1 = 3;
const int greenPin1 = 5;
const int bluePin1 = 6;
const int redPin2 = 9;
const int greenPin2 = 10;
const int bluePin2 = 11;
unsigned long PreviousTime = 0;
const long interval = 500;
long cmd2[2];
//MP3 mp3;                               // define mp3 class
const int irReceiverPin = 2;           //
//char val;
decode_results results;
//long IRstop=0x00FFA25D;        //
//long IRplay=0x00FF22DD;        //
//long IRmute=0x00FFE21D;        //
//long IRnoise=0x00FF629D;       //
//long IRprevious=0x00FF02FD;    //
//long IRnext=0x00FFC23D;        //
//long IRvolumeup=0x00FF906F;    //
//long IRvolumedown=0x00FFA857;  //
//long IRsingle=0x00FFE01F;      //
//long IRrepeat=0x00FF6897;      //
//long IRcycle=0x00FF9867;       //
//long IRrandom=0x00FFB04F;      //
//long IR1=0x00FF30CF;           // 1
//long IR2=0x00FF18E7;           // 2
//long IR3=0x00FF7A85;           // 3
//long IR4=0x00FF10EF;           // 4
//long IR5=0x00FF38C7;           // 5
//long IR6=0x00FF5AA5;           // 6
//long IR7=0x00FF42BD;           // 7
//extern SoftwareSerial COM_SOFT;
//********************************************************
void setup()
{
Serial.begin(9600);
// first RGB control pins
pinMode(redPin1, OUTPUT);
pinMode(greenPin1, OUTPUT);
pinMode(bluePin1, OUTPUT);
// second RGB control pins
pinMode(redPin2, OUTPUT);
pinMode(greenPin2, OUTPUT);
pinMode(bluePin2, OUTPUT);
// mp3 setting
//   mp3.begin(MP3_SOFTWARE_SERIAL);       // select software serial
//   mp3.volume(0x1F);                     // set volum to the MAX
//    mp3.set_mode(MP3::CYCLE);             // set MP3 Shield CYCLE mode
irrecv.enableIRIn();                  //

}
//********************************************************
void loop()
{
unsigned long CurrentTime = millis();
Serial.print("Current");
Serial.println(CurrentTime);
// wait a second so as not to send massive amounts of data

if (irrecv.decode(&amp;results)) {         //
irrecv.resume();                     //
}
if (CurrentTime - PreviousTime &gt;= interval)
{
PreviousTime = CurrentTime;
Serial.print("PreviousTime");
Serial.println(PreviousTime);
analogWrite(redPin1, random(0,255));
analogWrite(greenPin1, random(0,255));
analogWrite(bluePin1, random(0,255));
analogWrite(redPin2, random(0,255));
analogWrite(greenPin2, random(0,255));
analogWrite(bluePin2, random(0,255));
}
}
```
10. Michael says:

Hi, I always use this code for doing stuff at a certain interval. I guess people do this especially when reading sensors, as this helps mimic “parallelization” and it spares cycles / power. The opposite, inefficient ways would be to just do the digital/analog readings every time, in every loop, but that would be consuming a lot of CPU cycles and would be very inefficient, and if you also have input readings (like buttons) in the loop, the Arduino won’t respond as it should to those button presses.

Here’s the code I use:

unsigned long lastCheckedTime = 0;
unsigned int CHECK_INTERVAL = 1000; // sensors check / reading interval

```void loop() { if (lastCheckedTime == 0) { // if this is the first loop, force a sensors check this cycle lastCheckedTime = millis() - CHECK_INTERVAL; } if (millis() - lastCheckedTime >= CHECK_INTERVAL) { doSomething(); lastCheckedTime = millis(); } } ```
My questions are:
– Does my code already account for millis rollover?
– Do I need the currentMillis variable from your example code? Isn’t millis() returning an “unsigned long”, do I need to explicitly type cast it so the rollover would be handled?
– Is the explicit typecast “(unsigned long)(currentMillis – previousMillis)” really needed? If both operands are of the same type, “unsigned long”, wouldn’t the result be an “unsigned long”? Typecasting is good for ie operations with mixed “float” and “int” variables, but is it needed in this case?

And an observation:
The way you save the last checked time (“previousMillis = currentMillis”) changes the time reference for the next interval. In my code, the next interval starts when the doSomething() function finishes (because of the line “lastCheckedTime = millis()”). In your code, doSomething() would be triggered more often and it could be a problem if it is a time consuming function.

• Does my code already account for millis rollover?

Yes

Do I need the currentMillis variable from your example code? Isn’t millis() returning an “unsigned long”, do I need to explicitly type cast it so the rollover would be handled?

Time is more accurate this way. Each time you call millis(), enough time may have elapsed to cause the value to change. So you call it once, and use that reference until its time to check again.

Is the explicit typecast “(unsigned long)(currentMillis – previousMillis)” really needed?

This depends on who you ask. I’ve done experiments where I explicitly tested with and without the typecasting. For example, I set an unsigned long to 0xFFFF FFFE, and watched what happened manually. I found that it did not matter. Far more experienced programmers told me my experiment wasn’t valid, but couldn’t explain how and that typecasting was necessary. Since I haven’t wanted to sit around for 49 days to prove them wrong, I continue to do it just in case.

In your code, doSomething() would be triggered more often and it could be a problem if it is a time consuming function.

Well, for one, you would need to verify that your doSomething() finishes within your internal. That’s the responsibility of you, the programmer.

Second, your code will have unpredictable timing intervals, depending on what doSomething() does. If it takes 100ms one time and 1000ms next time, your intervals will occur 900ms later than expected.

If you want consistent, reliable timing intervals, you only use one time reference per iteration. Your code can lead to unpredictable intervals.

Think of it this way. If you are boiling an egg in water. It needs to be in there for 10 minutes, but your timer only operates on 1 minute intervals. So you look at the clock and it says “8:01”. You set your timer and go wash your hands. When the timer goes off you look at the clock and it says 8:02. So you reset the timer and go take out the trash. You repeat this process each time your timer goes off until the clock says 8:11. The idea is when the timer goes off, that’s when you reset it. This method ensures we check once per minute.

Now, let’s look at how your code works. You look at the clock and it says 8:01 and you wash your hands (this is your doSomething()). Washing your hands takes about a minute, so the clock now says 8:02 when you finally set the timer (previousMillis = millis()). This means for 2 minutes your timing code wasn’t being checked. The first check happens at 8:03. You decide to take out the trash (that’s your doSomething() this time) which takes you 6 minutes. You come back and start the timer again (thats your previousMillis() = millis()). Problem is, now the time is 8:08 and the timer won’t off until 8:09. This method might work most of the time. But in this case your time checking is entirely inconsistent because your reference point for each cycle is moving around.

You need to only check millis() once per iteration otherwise you’ll have a lot of jitter in your timing.

• podro says:

dears,
sorry
nothinkg of this in discus is not working
try simulate
replace “doSomething();” by “digitalWrite(13, !digitalRead(13));” to see flashing
run the program and see led
as you can see is flashing as expected.

then replace “millis()” by “(millis() & 0x0fff)” – to simulate roll out every 4096ms.

you can see how it blinking now?

normally the same will happend also with original source but rollout will happed every 49days.
how to make any timer to prevent this problem if my app is running longer then 49days?