O.K. its easy to divide exact 12.000000MHz. But how using other crystals, or correct the deviation ?
The way is always the same:
First on 8051 processors, the crystal was divided to give the timer clock.
On T0, T1 of 80C51 devices by 12, on the 80C52 for timer T2 by 2, also in
the Dallas DS80C320 at T0, T1 by 4.
Then you can use the timers to count 8 or 16 bit. The remaining divider stages
can be realized in software. On using only 8 of the 128 bytes of the 8051
you can count up to 2 Giga years at 40MHz !
In most cases you get no exact divider values. But this is not important,
you must then calculate the error and can correct it, if needed. E.g. if
the second differ, nobody can detect it. But if the Error was accumulated
over 1 month or year, it can be seen. So correction can be done every second,
minute, hour or day. So the error was not accumulated and also not detected.
Following an example with assembler code:
Random choice of a crystal: 12345701 Hz (use every other crystal for your calculation)
Crystal / 12 = 1028808.417
Using Timer T0: Crystal / 12 / 65536 = 15.69837062
So you need an additional Byte in RAM to divide down to 1 second. If this
byte divide by 256 you must not reload it.
Then the reload value of the T0: Crystal / 12 / 256 = 4018.782878 rounded
to 4019.
The resulting error is: 1 - 4018.782878 / 4019 = 0.000054 = 5 sec / day =
140 sec / month.
This is to high for using as RTC. So every second we use a different T0 reload
value:
Crystal / 12 - 255 * 4019 = 3963.41667 rounded to 3963.
Then the resulting error is: 1 - 1028808.417 / (255 * 4019 + 3963) = 0.0000004
= 1 sec / month = 12 sec / year.
This is enough for most RTC applications. But additional correction every
minute can reduce it further.
For extreme high accuracy also deviation over temperature was important and
must be corrected.
The C example is easiest to use, since it can make all calculations for you. You must only tell the real crystal frequency, thats all.
To correct the deviation you need a very high accurate and also very expensive
frequency meter to count the real crystal frequency with precision over more
than 10 digits.
The cheaper way was, let the RTC running over several months. Then the deviation
can be measured in seconds to calculate the true frequency.
Repeat the previous calculation with this real frequency and program the
new values into the micro.
E.g. you found an error of +12 seconds during 30 days. Then the true
frequency was:
12.345701 Hz * (1 + 12 / (30 * 24 * 60 * 60)) = 12345758Hz. Use this to repeat
the above described calculation and further the accuracy was very good.