Timers and counter are the most used peripherals in a microcontroller. They are being able to measure time periods, measure frequency, determine pulse width or provide output signals. Example applications might include producing tones to create music, create a time base for a real time clock or measure rpm of an engine. Timers and counter are simply binary up-counters. In timing mode the binary counter are counting the time periods and in counter mode, they are counting the events or pulses.
The AVR microcontrollers have both 8-bit and 16-bit timer/counters. An important issue for the program is to know when the counter reaches its maximum count and rolls over. The 8 bits counter rolls over from 255 to 0 and the 16 bits counter rolls over from 65.535. When a counter rolls over an interrupt is generated.
TIMER/COUNTER PRESCALERS AND INPUT SELECTORS
Timer/counter units may use a variety of internal frequencies derived from the system clock as their input, or they may get their input from an external pin. The timer counter control register (TCCRx) associated with the timer contains the counter select bits (CSx2, CSx1, CSx0) that control which input is used with a specific counter. The figure below shows the prescaler and input selector configuration for a timer counter control register as used in most AVR microcontrollers.
The following code example shows how to initialize Timer 0 to use the system clock divided by 8 as its clock source (the counter select bits are the three least significant bits of TCCR0):
TCCR0 = 0x2; /* Timer 0 uses clock/8 */
- Next >>