We have considered a variety of LEDs, structure, use, etc. etc. Today I would like to focus on one of the types of LEDs (if I may say so) - RGB LEDs.
What is RGB LED and device
Connecting RGB diodes to PWM Altmega8
The anodes of the RGB LED are connected to the lines 1,2,3 of port B, the cathodes are connected to the minus. To get a variety of color palettes, we will apply a PWM signal to the anodes in a specific sequence. In this example, we specifically use software PWM, although on the Atmega8 you can easily get hardware PWM for 3 channels. Software PWM can be used in cases of shortage of timers / counters and for other reasons. To generate a PWM of a certain frequency, we use an 8-bit timer T0 overflow interrupt (TIMER0_OVF_vect). Since the prescaler is not used, the timer overflow frequency will be equal to 31250Hz. And if the variable "pwm_counter" counts up to 163, then the PWM frequency will be 190 Hz. In the interrupt handler, based on the values in the variables pwm_r, pwm_g, pwm_b, the pins of port B are switched. Color effects are configured using functions where the LED lighting time is set. In the test program, red, green, blue, white colors first light up, and then a cycle with color transitions begins.
Program code:
// Control RGB LED. Software PWM
#include
#include
volatile char pwm_counter, pwm_r, pwm_g, pwm_b;
// Interrupt on overflow T0
ISR (TIMER0_OVF_vect)
if (pwm_counter ++> 163)
pwm_counter = 0;
if (pwm_counter> pwm_r) PORTB | = (1<< PB1);
if (pwm_counter> pwm_g) PORTB | = (1<< PB2);
if (pwm_counter> pwm_b) PORTB | = (1<< PB3);
// Procedure delay in microseconds
void delay_us (unsigned char time_us)
(register unsigned char i;
for (i = 0; i< time_us; i++) // 4 цикла
(asm ("PUSH R0"); // 2 cycles
asm ("POP R0"); // 2 cycles
// 8 cycles = 1 us for 8MHz
// Procedure delay in milliseconds
void delay_ms (unsigned int time_ms)
(register unsigned int i;
for (i = 0; i< time_ms; i++)
(delay_us (250);
// Red color
void red (unsigned int time)
for (char a = 0; a< 165; a++)
pwm_r = 164 - a; //increase
for (char a = 0; a< 165; a++)
pwm_r = a; //decrease
// Green color
void green (unsigned int time)
for (char a = 0; a< 165; a++)
pwm_g = 164 - a;
for (char a = 0; a< 165; a++)
// Blue color
void blue (unsigned int time)
for (char a = 0; a< 165; a++)
pwm_b = 164 - a;
for (char a = 0; a< 165; a++)
// White color
void white (unsigned int time)
for (char a = 0; a< 165; a++)
pwm_r = 164 - a;
pwm_g = 164 - a;
pwm_b = 164 - a;
for (char a = 0; a< 165; a++)
// Color transition
void rgb (unsigned int time)
for (char a = 0; a< 165; a++)
pwm_b = 164 - a;
for (char a = 0; a< 165; a++)