Created
January 5, 2011 20:59
-
-
Save jimsynz/766994 to your computer and use it in GitHub Desktop.
Arduino sketch to cycle an RGB LED through the colour spectrum.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const int redPin = 11; | |
const int greenPin = 10; | |
const int bluePin = 9; | |
void setup() { | |
// Start off with the LED off. | |
setColourRgb(0,0,0); | |
} | |
void loop() { | |
unsigned int rgbColour[3]; | |
// Start off with red. | |
rgbColour[0] = 255; | |
rgbColour[1] = 0; | |
rgbColour[2] = 0; | |
// Choose the colours to increment and decrement. | |
for (int decColour = 0; decColour < 3; decColour += 1) { | |
int incColour = decColour == 2 ? 0 : decColour + 1; | |
// cross-fade the two colours. | |
for(int i = 0; i < 255; i += 1) { | |
rgbColour[decColour] -= 1; | |
rgbColour[incColour] += 1; | |
setColourRgb(rgbColour[0], rgbColour[1], rgbColour[2]); | |
delay(5); | |
} | |
} | |
} | |
void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) { | |
analogWrite(redPin, red); | |
analogWrite(greenPin, green); | |
analogWrite(bluePin, blue); | |
} |
dreamer1048576
commented
Apr 10, 2024
Here is some code that address the issue pointed by @michalmonday (eg: colors such as (255, 255, 0)
, (255, 0, 255)
, (0, 255, 255)
never reached). Additionally, it's a non-blocking version. Unlike original code, it does not keep 100% brightness anymore (eg: at some point 2 leds are fully on, sometimes only one...).
const int redPin = 11;
const int greenPin = 10;
const int bluePin = 9;
unsigned char rgbColor[3] = { 255, 0, 0 }; //start with red
int state = 0;
unsigned char colors[6]= { 1, 0, 2, 1, 0, 2 }; //green, red, blue
unsigned char directions[6]= { 1, -1, 1, -1, 1, -1 }; //up, down
void setup() {
// Start off with the LED off.
setColourRgb(0,0,0);
}
void loop() {
int color = colors[state];
rgbColor[color] += directions[state];
if (rgbColor[color] == 0 || rgbColor[color] == 255) {
state = (state + 1) % 6; //next state
}
setColourRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
delay(3);
}
void setColourRgb(unsigned char red, unsigned char green, unsigned char blue) {
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment