Projects for geeks

LED brightness

11 Aug 2009

When LED blinks with the frequency >50Hz human eye see LED as continuous lighting. Any PWM signal of frequency greater than 50 Hz can be used for that purpose. Brightness of LED is proportional to the amount of energy provided to LED. As the voltage is constant 5V, we can regulate brightness changing duty cycle of PWM signal. Greater duty cycle means grater brightness.

In this example any PWM mode can be used. Because in the previous example Phase Correct mode was used, this time we use Fast PWM mode, timer remain the same (timer2).
The previous example can be used to control brightness as well. Only prescaler divider must be change to have PWM frequency >50Hz.

Frequency for Fast PWM mode is:

Because higher PWM frequency is better for bright control we use prescaler divider 1 as it gives the maximum frequency equal to 31.25kHz.
Brightness is controlled by the OCR2 register which is responsible for duty cycle.

The example code changes brightness of LED from 0 (LED off) to maximum. The entire cycle (from 0 to max) takes 2.55s (OCR2 value is changed every 10ms).

Code snippets

Configure OC2 pin as output

DDRD |= _BV(DDD7);

Configure timer2

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

Sample code

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

See attached file. Timer2 is configured to work in Phase Correct mode, then duty cycle is set from 0 to 255 by 1 every 10ms in infinite loop. In that way LED brightness is changed from minimum to maximum every 2.5s.

Package icon pwm_ledbrightness.zip2.39 KB