OK, so for a RTC you need some sort of precision and regularity, as things like a single instruction cycle ambiguity can kill you in the long term.
A clock requires excellent long term stability, but surprisingly, short term instability may be acceptable. I have something in mind like an alarm clock where if it rings at 7:00:00 AM or 7:00:02 AM it makes no difference.
Here’s what I mean: say you desire a 1 second “heartbeat” in your code to update the seconds indicator of the clock. You can use the 1MHz instruction rate into TMR0 with a 256 prescaler to generate an interrupt every .256ms. OK, you might get it a little faster or a little slower, but the important thing is you get them with a long term average (accuracy) of once every .256 ms.
So you count interrupts to see if a second has transpired. A second with .256ms rate lasts… dang! 3906.25 counts. OK, not so bad… make an interrupt routine fired by the TMR0 overflow, when it fires add 1 to a counter (call it TICKS), when the TICKS gets to 3906 reset it, AND add 1 to the SECONDS variable.
This by itself would be OK for the short haul, but it has an error of 1ms every 4 secs. We can correct for that: note 4 seconds takes 3906.25 x 4 = 15625 counts, but when TICKS increments 4 times we’ve only counted 3906 x 4 = 15624. We’re one count short! But ONE, not one point something, but exactly integer ONE.
Cool. So, use the same TICKS counter, add 1 to SECONDS at TICKS = 3906, 7812, 11718, and 15625, and when TICKS hits 15625 also reset TICKS.
You’ve just traded a short term error of .75ms for a long term error of zero.
(Of course, this all depends on the instruction rate being 1.000000MHz, so use a crystal to clock this thing.)
Bookmarks