Determining Oscillator Frequency

The comparison between the calibration clock (C-clock) and the internal RC oscillator is performed using the 8-bit Timer/Counter0 (TC0). The 8-bit timer is used since it is present in all devices that have a tunable RC oscillator. The idea is to time the duration of 40 C-clock cycles and compare the number of timer ticks to predefined limits. The C-frequency is specified in the interface specific include file. The method for determining the oscillator frequency is described in the flowchart below.

Figure 1. Flowchart of Algorithm Determining Relationship Between the C-clock and Internal RC Frequency

To cover the full range of oscillator frequencies from 1MHz to 9.6MHz, inspection of the TC0 overflow (OVF) flag is used to expand the timer range by eight bits, effectively providing a 16-bit timer. The OVF flag is inspected once every half-cycle (of the C-clock), which is sufficiently often to ensure that all TC0 OVF events are detected. In relation to the range of the 16-bit timer implemented, the worst-case for overflow is at 9.6MHz where the OSCCAL register is loaded with 0xFF. In this case, the oscillator can be 100% above the specified frequency. The timer will in this case count to 23,541, which is still within the range of the 16-bit timer.

Going in the other direction, the lowest oscillator frequency must also be considered. The lowest obtainable frequency occurs when writing 0x00 to OSCCAL. In that case the frequency may be 50% lower than the specified one. Since the TC0 OVF flag is inspected every half-cycle, there is potentially no more than seven CPU-cycles to handle the OVF flag and detect the next C-clock edge - at a specified frequency of 1MHz. This timing constraint can be met when the OVF flag is not set, but when the flag is set eight cycles are required. This will cause a small error in the detection of the timing, but will not affect the overall outcome: the oscillator will correctly be determined as too slow. However, these extremes are very unlikely to be encountered due to the binary search method used.