Skip to main content
Arduino

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How can I handle the millis() rollover?

I need to read a sensor every five minutes, but since my sketch also has other tasks to do, I cannot just delay() between the readings. There is the Blink without delay tutorial suggesting I code along these lines:

void loop()
{
 unsigned long currentMillis = millis();
 // Read the sensor when needed.
 if (currentMillis - previousMillis >= interval) {
 previousMillis = currentMillis;
 readSensor();
 }
 // Do other stuff...
}

The problem is that millis() is going to roll over back to zero after roughly 49.7 days. Since my sketch is intended to run for longer than that, I need to make sure the rollover does not make my sketch fail. I can easily detect the rollover condition (currentMillis < previousMillis), but I am not sure what to do then.

Thus my question: what would be the proper/simplest way to handle the millis() rollover?

Answer*

Draft saved
Draft discarded
Cancel
13
  • 4
    So, you are saying that the code written in the question will actually work correctly? Commented Feb 7, 2016 at 9:48
  • 8
    @Jasen: Exactly! I've seem more than once people trying to "fix" the problem that did not exist in the first place. Commented Feb 7, 2016 at 10:00
  • 2
    I'm glad I found this. I've had this question before. Commented Jul 2, 2016 at 1:28
  • 3
    One of the best and most useful answers on StackExchange! Thanks a lot! :) Commented May 18, 2018 at 12:43
  • 2
    This is such an amazing answer to the question. I come back to this answer basically once a year because I am paranoid of messing rollovers. Commented Sep 4, 2019 at 16:41

default

AltStyle によって変換されたページ (->オリジナル) /