An awful lot of microcontroller projects use timers to repeat an action every few minutes, hours, or days. While these timers can be as accurate as a cheap digital wrist watch, there are times when you need a microcontroller’s timer to measure exactly, losing no more than a few milliseconds a day. It’s not very hard to get a timer to this level as accuracy, as [Karl] shows us in a tutorial.
The problem with keeping time with a microcontroller has to do with the crystal, clock frequency, and hardware prescalers of your chip of choice. [Karl] started his project with an ATMega168 and a 20 MHz crystal and the prescaler set at 256. This made the 78.125 interrupts per second, but the lack of floating point arithmetic means one second for the microcontroller will be 0.9984 seconds to you and me.
[Karl]‘s solution to this problem was to have the ATMega count out 78 interrupts per second for seven seconds, then count out 79 interrupts for one second. It’s not terribly complicated, and now [Karl]‘s timers are as accurate as the crystal used for the ’168′s clock.