Two AVR-GCC examples of using AVR 8 bit Timers

Timers are very important part of microcontrollers. They can can be used in many areas starting with simple timed routines to RTOS. Good thing is that timers run independently to main program flow. Set up the timer counter and let it do its job while your main program runs and does its job.

Lets take AVR Atmega8 microcontroller. It has two independent 8 bit timers. One is little simpler which is featured with basic 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 to implement PWM routines. It has 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.

Lets view couple examples with both 8 bit timers.

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:

Timer0_example.PNG

Another example is for second 8 bit timer. Code example shows phase correct PWM routine:

Timer2_example.PNG

Added screen shot of simulation with VMLAB:

PWM_Scope.PNG

Second simulation files You may download here Timer2.

Blogsphere: TechnoratiFeedsterBloglines
Bookmark: Del.icio.usSpurlFurlSimpyBlinkDigg
RSS feed for comments on this post
 |  TrackBack URI for this post

New on WinAVR Tutorial
Running TX433 and RX433 RF modules with AVR microcontrollers,
Sometimes in embedded design you may want to go wireless. Might be you will want to log various readi …
Programming AVR ADC module with WinAVR,
Most of AVR microcontrollers have Analog to Digital Converter (ADC) integrated in to chip. Such solut …
New on WinARM Tutorial
What are differences between WinARM and WinAVR,
Everyone who is working with AVR microcontrollers knows this powerful tool – WinAVR (http://win …
LPC2000 watchdog timer,
As in all microcontrollers watchdog timers purpose isto reset microcontroller after reasonable amount …

Leave a Reply