Aquaticus

Projects for geeks

Summary

11 Aug 2009

Not all the timers have the same features. ATmega16/32 has 3 timers with the possibility to generate 4 PWM signals, ATmega8 only 2 timers with PWM which gives us 3 PWM and ATmega 48/88/168 6 PWM channels. Here we concentrate on ATmega16/32 chips.

ATmega16 and ATmega32 have 3 timers, one 16 bit and two 8 bits. Timer1 is 16 bit and has two PWM channels. That means it is not possible to set different frequency for both channels (A and B). 16 bits of timer0 gives you better resolution, but note OCRx and ICRx registers are 10 bit max, so duty cycle or frequency can be adjusted with 10 bits resolution not 16 bits.

In addition prescaler module is shared between timer1 and 8 bit timer0. This limits freedom of choice.
8 bit timer0 and timer2 has much less PWM modes than timer1 – only 3 modes: Fast PWM, Phase Correct PWM and CTC. Timer2 has its own prescaler module but with different dividers: 1, 8, 32, 64, 128, 256, 1024, while for timer0 and timer1 dividers are: 1, 8, 64, 256, 1024.

If you want to use all 4 PWM channels to control 4 motors it is recommended to use the same PWM modes for all channels. First look at the mode tables gives the answer. Common parameters for all the timers are: 8 bit Phase Correct PWM mode and prescaler 1, 8, 64, 256 or 1024. Other common modes are: CTC and Fast PWM but they are less suitable for motor control.

Here are the most important things about PWM for AVR micro controllers you should remember:

  • PWM signal is visible on OCRx pin.
  • OCRx pin must be configured as output, e.g. DDRD |= _BV( DDD5 );
  • Write value different from 0 and 255 for 8bit mode (or 511 for 9bit or 1023 for 10bit) to start generating PWM
  • OCRx = 0 gives you constant 0V level on output
  • OCRx = 255 for 8bit (or 511 for 9bit or 1023 for 10bit) gives you constant VCC (e.g. 5V for 5V VCC) level on output
  • ICRx register controls frequency for Phase and Frequency correct/CTC modes.
  • Using higher resolution gives you lower maximum frequency.
  • Timer1 is 16 bit, has 2 PWM channels and a lot of modes.
  • Timer0 and Timer2 are 8 bits and have only 2 PWM modes.
  • Prescaler is common for Timer0 and Timer1
  • Software PWM can generate many PWM waves but is not as robust as hardware generated PWM
  • There are AVR microcontrollers with more than 4 PWM channels.

Which mode to use

Task Mode
Blinking LED Any mode, use low frequency like 3-4Hz
Control brightness of light Any mode, use frequency greater then 50Hz
Servo Phase Correct
Motor speed Phase Correct, higher frequency better, limited by external components.
Generate sounds Phase and Frequency Correct or CTC (for timer0/2), change frequency to generate different notes.
Digital to Analog converters Fast PWM, higher frequency better.

Simulators sometimes do not properly simulate all PWM modes. Wave is not generated in simulator, but in real AVR device works perfectly.

Links