Sunday, January 1, 2012

Using RGB LEDs on an Arduino

Click to embiggen.
For some reason, it wasn't easy to find sample code or pinouts for using a common-cathode RGB LED with Arduino.  I think I'm missing something obvious, but oh well.  So, I messed around and got it to work.

  • The longest pin takes 5v in.
  • Grounding the other three illuminate red, blue and green.
  • You can use digital PWM outputs to ground those pins.
  • Setting a pin to 0 illuminates that color.  1023, off.
  • Setting a pin to an intermediate value adjusts its brightness.
I've done a super simple diagram, at right.  And copypasted some bare-bones code that runs through each pin, in turn, grounding it for a half second.  These links go directly to the sketch, and the fritzing diagram.


//
// RGB LED figure-er-out-er by gabe.                 gms@causalloop.com
//    an Arduino & Beer (tm) Production.                blog.fnaard.com
//
// Run your RGB LED's longest pin to 5v.  Run the other pins to digital
// pins 9, 10 and 11.  I've put a 330 ohm resistor, in series, between
// each of those three pins and its corresponding digital pin.
//
// This sketch runs through pins 9, 10, 11 grounding each one in turn ..
// for sussing out which pin illuminates which color inside the thing.
//
// You gotta set all the pins to OUTPUT, so that you can write values
// to them.  They won't actually output any voltage .. in fact, they'll
// act as ground.  Setting a value for the pin will adjust its PWM rate
// and that adjusts how much electricity can flow through that color LED.
//
// Put simply, it's what you do with single-color LEDs, but in reverse.


void setup () {
  pinMode ( 11, OUTPUT );
  pinMode ( 10, OUTPUT );
  pinMode (  9, OUTPUT );
}


// Now just run through the pins, setting each one to full brightness (0)
// for a half second, while setting the other two to off (255).


void loop () {
  analogWrite ( 11, 255 );
  analogWrite ( 10, 255 );
  analogWrite (  9, 0    );        // Red, on mine.
  delay(500);
  analogWrite ( 11, 255 );
  analogWrite ( 10, 0    );
  analogWrite (  9, 255 );     // Green on mine.
  delay(500);
  analogWrite ( 11, 0    );
  analogWrite ( 10, 255 );
  analogWrite (  9, 255 );     // Blue on mine.
  delay(500);
  analogWrite ( 11, 255 );
  analogWrite ( 10, 255 );     // Everyone off.
  analogWrite (  9, 255 );
  delay(1000);                   // Pause longer.  For dramatic effect.
}

No comments:

Post a Comment