Page 192 - Programming Microcontrollers in C
P. 192
Timers 177
if one wants a real clock because the error amounts to 2.1 seconds per
hour. One way this error could be corrected is to adjust the crystal
frequency of the microcontroller. Suppose we would use a frequency
of 3.996354 MHz instead of 4.0 MHz. This number is derived by
122*2^15/f=1
which yields the above value for f. The 122 periods of 8.196721 milli
seconds, which is the real-time interrupt time for this frequency, is exactly
1 second. Another approach involves making small corrections to the
time periodically so that on the average the time is correct. An example
of an interrupt service routine that makes these corrections is as follows:
void __TIMER(void) /*routine executed every RTI
(8.192 ms)*/
{
static int corr1,corr2,corr3;
TCST.RTIF=0; /* flags */
if (++count==122) /* increment seconds */
{ /* To correct for 8.192 */
sec++; /* ms per tick. Run 122*/
if(++corr1==14) /* ticks per second for */
{ /* 13 seconds, and 123 */
corr1=0; /* for the 14th second */
if(++corr2==80) /* With this algorithm */
{ /* there are 14.000128 */
corr2=0; /* actual seconds per */
if(++corr3==4) /* 14 indicated. Then */
{ /* run 79 of these */
count=1; /* cycles followed by */
corr3==0; /* one cycle of 14 */
} /* seconds with 122 ticks */
else /* per second. The */
count=0; /* elapsed time for this*/
} /* cycle is 1120.002048 */
else /* seconds for and */
count=(-1); /* the count is 1120 */
} /* seconds. Repeat this */
else /* cycle 4 times and on */