Turn-key PCB assembly services in prototype quantities or low-volume to mid-volume production runs

Two AVR-GCC examples of using AVR 8 bit Timers

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 to 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 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 simple task – every time timer overflows it has to increase variable value by one. And this variable is sent to PORTB in forever loop.

AVR-GCC code:


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.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.