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:
Only the last value 15.32 Hz can be used. The other values would result in continuous light.
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
|Compiler||AVR Studio + GCC|
See attached pwm_ledflash.zip 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).