Timers are an essential part of microcontrollers. They can be used in many areas starting with simple timed routines to RTOS. The good thing is that timers run independently of the main program flow. Set up the timer counter and let it do its job while your main program runs and does its job.
Let’s take the AVR Atmega8 microcontroller. It has two independent 8-bit timers. One is a little simpler which is featured with essential functions like:
- Single-channel counter;
- Frequency generator;
- External Event counter;
- 10 – bit clock pre-scaler.
Another is more advanced where is OCR (output compare register) included, which allows implementing PWM routines. It has the following features:
- Single Channel Counter
- Clear Timer on Compare Match (Auto Reload)
- Glitch-free, phase Correct Pulse Width Modulator (PWM)
- Frequency Generator
- 10-bit Clock Pre-scaler
- Overflow and Compare Match Interrupt Sources (TOV2 and OCF2)
- Allows Clocking from External 32 kHz Watch Crystal Independent of the I/O Clock
Datasheet documents these timers pretty well.
Let’s view a couple of examples with both 8-bit timers.
The first example is to do a simple task – every time timer overflows, it has to increase the variable value. And this variable is sent to PORTB in a forever loop.
Another example is for the second 8-bit timer. The code example shows phase correct PWM routine:
Added screenshot of simulation with VMLAB:
Second simulation files You may download here Timer2.