Projects for geeks

Blinking LED

11 Aug 2009

This is probably the simplest possible project. The goal is to flash LED.

A LED is flashing when it is turned on for a moment and than turned off. Number of on/off cycles must be lower than 50 times a second. When it is greater than 50, the human eye recognizes the LED as continuously lighting. This effect is utilized in the next example where brightness of LED is controlled.

LED is on when AVR output pin is 5V and off for 0V. PWM signal suits perfectly this task. We use timer2, that require LED to be connected to OC2 pin (PD7).

PWM frequency must be lower than 50 Hz, the best results are visible when LED flash 1-20 times a second. Any PWM mode is suitable for flashing LED but in this example we use Phase Correct mode (without any special reason).

PWM wave frequency in this mode is:

where N is prescaler divider. For all possible prescaler dividers (assuming 8MHz system clock) we have:

Prescaler PWM frequency
1 15686.27 Hz
8 1960.78 Hz
32 490.20 Hz
64 245.10 Hz
128 122.55 Hz
256 61.27 Hz
1024 15.32 Hz

Only the last value 15.32 Hz can be used. The other values would result in continuous light.

Code snippets

Configure OC2 pin as output.

DDRD |= _BV(DDD7);

Configure timer2 in Phase Correct PWM mode.

TCCR2 = _BV(WGM20) // PWM, Phase Correct mode
      | _BV(COM21); // Clear OC2 on compare match when up-counting. 

Set 1024 prescale divider.

TCCR2 | = _BV(CS22) | _BV(CS21) | _BV(CS20); //prescaler 1024

Sample code

Chip ATmega32
System clock 8MHz
Compiler AVR Studio + GCC
AVR hardware timer2
External hardware LED

See attached file. The code is not really complicated. First timer2 is configured for phase correct mode, than a value is written to OCR2 register to start PWM generation. LED blinks with 15Hz frequency. At the end program goes to infinite loop (LED still blinks).

Package icon pwm_ledflash.zip2.35 KB