What happens when an atmega168/328 millis() overflows?

For Adafruit customers who seek help with microcontrollers

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
joeelp
 
Posts: 17
Joined: Mon Mar 30, 2009 6:37 am

What happens when an atmega168/328 millis() overflows?

Post by joeelp »

I'm building a project by programming an arduino using a 168 or a 328, then setting the fuses to use the internal clock at 8 (i think), and then removing the chip and putting it into a breadboard with my own circuit.

The project is going to run 24/7, but I would like to use an if() to have it run a special command once every day or so. Its not exact by any means, but i need to know when somewhere around 24-100 hours have gone by. Thus I don't really care how inaccurate the internal clock is.

I've read that the millis() function has been fixed to use the whole of the long int, which is around 55 days.

So a few questions:

1. will I really get ~50 days out of millis()? Its hard to test this one:)

2. What exactly happens to millis() when it overflows?

2(a). if it really simply just resets to 0, does this affect ANYTHING else? The clock, other variables or registers or ANYTHING? I need to know if this is going to cause me a hassle.

3.just in theory, what about if this runs for 4 years? will there be any problem when millis() has overflowed a few times?

4. What would you recommend to keep track of, say, 50 hours? Use modulus somehow? I've been typing a few suggestions here, but none of them work when I finish thinking them through. I have a feeling I'm missing something simple.

mtbf0
 
Posts: 1645
Joined: Sat Nov 10, 2007 12:59 am

Re: What happens when an atmega168/328 millis() overflows?

Post by mtbf0 »

the arduino has three timers. millis is based on timer0. you could always hijack timer1 or timer2 if you won't be using the analogWrite functions.

try setting up timer1 with a prescaler of 1024 in ctc mode with a top of 7812 and enable a compare match interrupt.

have your interrupt handler increment a counter each time it's called and when it gets to 180000 do whatever it is that you want to do every fifty hours and reset your counter to zero.

User avatar
westfw
 
Posts: 2008
Joined: Fri Apr 27, 2007 1:01 pm

Re: What happens when an atmega168/328 millis() overflows?

Post by westfw »

In theory, you can set up your code so that it will continue to work correctly even when the timer wraps around (assuming post v12 Ardunio core, with the 50+ day wraparound.) You have to be a little careful, both near wraparound time and when the count exceeds 2^31 (and would become "negative" if you're not careful...) delay() should work even over a period when millis() wraps around, for instance...

Locked
Please be positive and constructive with your questions and comments.

Return to “Microcontrollers”