Microcontrollers in Practice

This chapter contains a description of the timer system of microcontrollers, including the general-purpose timer, the PWM timer, and the watchdog.
Timing is essential for the operation of microcontroller systems, either for generating signals with precisely determined duration, or for counting external events. For this reason, the timer subsystem is present in all microcontroller implementations, and covers a wide range of functions including:
Generation of precise time intervals
Measurement of duration of external events
Counting external events.
Most microcontrollers are provided with dedicated timers, or use the general-purpose timer to implement the following additional functions:
Real time clock
Generation of Pulse Width Modulated (PWM) signals
Watchdog for detecting program runaway situations.
Although there are significant variations between different implementations of the general-purpose timer in different microcontrollers, there are many similarities in the principles of operation and the structure of the timer subsystem.
Figure 6.1 shows a general block diagram of the timer system, illustrating the principles of implementation of most MCU timers.
The central element of the timer subsystem is a counter, TCNT (8 or 16-bits in length), which may be read or (sometimes) written by software. The clock for TCNT is obtained either from the system clock, divided by a programmable prescaler, or an external clock applied to one of the MCU pins. The software control upon the timer is performed by means of the...