Go Down

Topic: formula: RGB color ro RGB LED? (Read 849 times) previous topic - next topic

roypardi

Hi - I've started playing around with some RGB LEDs (ShiftBrites). Wondering if there is a semi-standard formula for converting an RGB color to PWM values to drive the RGB LED. I've searched around here and on the web and seen a few posts (@shiftBrites, @ RGB >> HSV, etc.) but nothing that clearly states the problem or a solution.

I would imagine that the RGB hardware specifics factor quite a bit - but before I reinvent the wheel I thought I would ask @ this.

--Roy

mem

#1
Oct 11, 2009, 07:42 pm Last Edit: Oct 11, 2009, 07:42 pm by mem Reason: 1
Roy, here is the code I use to convert a color value to RGB values suitable for the PWM pins. The example sketch fades through  the color spectrum

Code: [Select]
const int redPin   = 3;        // choose the pin for each of the LEDs
const int greenPin = 5;
const int bluePin  = 6;
const boolean invert = true; // set true of common anode, false if common cathode.

int color = 0; // a value from 0 to 255 representing the hue
int R, G, B;  // the Red Green and Blue color components

void setup()
{
 // pins driven by analogWrite do not need to be declared as outputs
}

void loop()
{
 int brightness = 255; // 255 is maximum brightness  
 hueToRGB( color, brightness);  // call function to convert hue to RGB
 // write the RGB values to the pins
 analogWrite(redPin, R);
 analogWrite(greenPin, G);
 analogWrite(bluePin, B );

 color++;           // increment the color
 if(color > 255)    //
    color = 0;
      delay(10);
}

// function to convert a color to its Red, Green, and Blue components.

void hueToRGB( int hue, int brightness)
{  
   unsigned int scaledHue = (hue * 6);
   unsigned int segment = scaledHue / 256; // segment 0 to 5 around the color wheel
   unsigned int segmentOffset = scaledHue - (segment * 256);      // position within the segment
   
   unsigned int compliment = 0;
   unsigned int prev = (brightness * ( 255 -  segmentOffset)) / 256;
   unsigned int next = (brightness *  segmentOffset) / 256;

 if(invert)
   {
     brightness = 255-brightness;
     compliment = 255;
     prev = 255-prev;
     next = 255-next;
   }
   
   switch(segment ) {
   case 0:      // red
      R = brightness;
        G = next;
      B = compliment;
     break;
   case 1:     // yellow
     R = prev;
     G = brightness;
     B = compliment;
     break;
   case 2:     // green
     R = compliment;
     G = brightness;
     B = next;
     break;
   case 3:    // cyan
     R = compliment;
     G = prev;
     B = brightness;
     break;
   case 4:    // blue
     R = next;
     G = compliment;
     B = brightness;  
     break;
  case 5:      // magenta
   default:
     R = brightness;
     G = compliment;
     B = prev;
     break;
   }
}

roypardi

thanks! - I'll give that a try.

Go Up