Controlling R_G_B Led using Microcontroller

November 2, 2009 by admin · 2 Comments
Filed under: Microcontrollers, electronics 

Hi…

Here is another experiment to share. An RGB led is a electroluminescent device capable of creating any color by some combination of Red, Green and Blue LED. Actually it is a LED with 3 led’s (red, green & blue) inside one package.

RGB led has 4 Legs. The one i have has one leg for Vcc (Positive Supply) and other three terminals corresponding to R, G and B values.

Different color patterns can be generated by controlled PWM Pulses on respective terminals.

RGB-4pin1

From left to right in above picture -> 1. RED  2. Vcc   3. GREEN  4. BLUE

Now lets move onto the main part that is How to control using Microcontroller. I am going to use ATmega8l from AVR family for demo. You can use any controller the concept will remian the same.

rgb_led

And here is the code that generates almost all combination’s of R G B using PWM over three pins of MEga8.

PORTC_0 —-Controlling  RED

PORTC_1 —-Controlling GREEN

PORTC_2 —-Controlling BLUE

#include<avr/io.h>
#include<util/delay.h>
#include<compat/deprecated.h>
#include<avr/interrupt.h>
unsigned char r=255,g=0,b=0;

ISR(TIMER0_OVF_vect)
{
  sbi(PORTC,0);
  _delay_ms(255-r);
  cbi(PORTC,0);
  _delay_ms(r); 

   sbi(PORTC,1);
  _delay_ms(255-g);
  cbi(PORTC,1);
  _delay_ms(g);

  sbi(PORTC,2);
  _delay_ms(255-b);
  cbi(PORTC,2);
  _delay_ms(b);   

}

int main(void)
{
  DDRC=0xFF;   // PORTC as output
  PORTC=0xFF;  // Initially all leds off no color
  TCCR0=0x01;  // No prescaling of timer clock
  TIMSK=0x01;  // Timer Overflow interrupt enable
  TCNT0=0;
  sei();   // Global interrupt enable
  while(1==1)    // Infinite loop
  {
    if(r==255 && g==0 && b==0)
    {
        r=r-1;g=g+1;
        if(g==255 && b==0 && r==0)
        {
          g=g-1; b=b+1;
           if(b==255 && r==0 && g==0)
           {
              b=b-1;r=r+1;
           }
         }
    }
  }
  return (0);
}