Skip to content

Instantly share code, notes, and snippets.

@spraints
Created September 9, 2023 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spraints/0551c8a5dfe4a5d37790eb0b869aeb11 to your computer and use it in GitHub Desktop.
Save spraints/0551c8a5dfe4a5d37790eb0b869aeb11 to your computer and use it in GitHub Desktop.
cycle through colors on an RGB LED
int red = 11;
int green = 10;
int blue = 9;
long spectrum[] = {
0xff0000, // 0 red
0xffa500, // 1 orange
0xffff00, // 2 yellow
0x00ff00, // 3 green
0x0000ff, // 4 blue
0x4b0082, // 5 indigo
0x9400d3, // 6 dark violet
};
int colors = 7;
int redAmount = 255;
int greenAmount = 0;
int blueAmount = 0;
int nextColor = 1;
int stepsSinceLastSwitch = 0;
void setup() {
// put your setup code here, to run once:
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
Serial.begin(9600);
}
void RGB_color(int red_value, int green_value, int blue_value)
{
analogWrite(red, red_value);
analogWrite(green, green_value);
analogWrite(blue, blue_value);
// Serial.print(redAmount);
// Serial.print(" red, ");
// Serial.print(greenAmount);
// Serial.print(" green, ");
// Serial.print(blueAmount);
// Serial.println(" blue");
}
void loop() {
// put your main code here, to run repeatedly:
RGB_color(redAmount, greenAmount, blueAmount);
int nextRed = (spectrum[nextColor]&0xff0000) >> 16;
int nextGreen = (spectrum[nextColor]&0x00ff00) >> 8;
int nextBlue = (spectrum[nextColor]&0x0000ff);
int dR = nextRed - redAmount;
int dG = nextGreen - greenAmount;
int dB = nextBlue - blueAmount;
if (dR == 0 && dG == 0 && dB == 0) {
nextColor = (nextColor + 1) % 7;
Serial.print("after ");
Serial.print(stepsSinceLastSwitch);
Serial.print(" steps, next color will be ");
Serial.println(nextColor);
stepsSinceLastSwitch = 0;
delay(250);
return;
}
stepsSinceLastSwitch += 1;
int aR = abs(dR);
int aG = abs(dG);
int aB = abs(dB);
int steps = 0;
if (aR > 0 && (aR < aG || aG == 0) && (aR < aB || aB == 0)) {
steps = aR;
} else if (aG > 0 && (aG < aB || aB == 0)) {
steps = aG;
} else {
steps = aB;
}
if (steps == 0) {
// this shouldn't happen?
Serial.println("BOOOM!");
redAmount = 0;
greenAmount = 0;
blueAmount = 0;
return;
}
if (steps > 50) {
steps /= 4;
}
redAmount = takestep(redAmount, dR, steps);
greenAmount = takestep(greenAmount, dG, steps);
blueAmount = takestep(blueAmount, dB, steps);
delay(20);
}
int takestep(int val, int d, int steps) {
if (d == 0) {
return val;
}
return val + (d / steps);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment