Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save SamClayton/9965643 to your computer and use it in GitHub Desktop.

Select an option

Save SamClayton/9965643 to your computer and use it in GitHub Desktop.
Color wash fades with RGB LEDs straight off Arduino analog ports
/*
* RGB_LEDs sketch
* RGB LEDs driven from analog output ports
*/
const int redPin = 3; // choose the pin for each of the LEDs
const int greenPin = 5;
const int bluePin = 6;
const int redPin2 = 11; // choose the pin for each of the LEDs
const int greenPin2 = 9;
const int bluePin2 = 10;
const boolean invert = true; // set true if 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
int brightness = 255; // 255 is maximum brightness
boolean increaseBright = false;
int brightIncrement = 0; // also used 20
int delaySpeed = 5; // also used 250
void setup()
{
// pins driven by analogWrite do not need to be declared as outputs
}
void loop()
{
/*
if(color % 24 == 0)
brightness = random(128, 255);
*/
/*
brightness += 20;
if (brightness > 255)
brightness = 50;
*/
if (brightness > (255 - brightIncrement))
increaseBright = false;
if (brightness < brightIncrement)
increaseBright = true;
if(increaseBright)
brightness += brightIncrement;
else
brightness -= brightIncrement;
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 );
hueToRGB(255 - color, brightness);
// write the RGB values to the second set of pins for the second LED
analogWrite(redPin2, R);
analogWrite(greenPin2, G);
analogWrite(bluePin2, B);
color++; // increment the color
if(color > 255)
color = 0;
delay(delaySpeed);
}
// 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 complement = 0;
unsigned int prev = (brightness * ( 255 - segmentOffset)) / 256;
unsigned int next = (brightness * segmentOffset) / 256;
if(invert)
{
brightness = 255-brightness;
complement = 255;
prev = 255-prev;
next = 255-next;
}
switch(segment ) {
case 0: // red
R = brightness;
G = next;
B = complement;
break;
case 1: // yellow
R = prev;
G = brightness;
B = complement;
break;
case 2: // green
R = complement;
G = brightness;
B = next;
break;
case 3: // cyan
R = complement;
G = prev;
B = brightness;
break;
case 4: // blue
R = next;
G = complement;
B = brightness;
break;
case 5: // magenta
default:
R = brightness;
G = complement;
B = prev;
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment