I really wanted to make a cycling RGB light for this week’s homework so I did some research on the RGB LED in the kit and how to use it, and I ended up making a circuit in which the switch lets the user switch between control of the two LEDs, one RGB and the other just blue and a potentiometer to control the color of the RGB and the brightness of the other LED. To learn how to use the RGB LED, I went through other projects that used it online and learned that it sort of acts as 3 separate LEDs one red, one green and one blue. Using analogWrite() with each pin allows you to generate different colors the same way we used color() in p5js.
I wanted to make the light cycle through colors as seen in some gaming keyboards, for example. To achieve this, I mapped the value from the potentiometer to 0-767 (256×3), and I found that keeping one of the 3 colors at 0 and changing the other two colors according to the mapped value would achieve a nice cycling effect. I was inspired by this project to come up with this.
When the switch is pressed, the RGB LED would turn off, the blue LED would turn on and the potentiometer would then be used to control the brightness of the LED.
Here is my code and video:
bool pressed = false; unsigned long timer = 0; int prevButtonState = 0; void setup() { Serial.begin(9600); pinMode(2, OUTPUT); //bluepin pinMode(3, OUTPUT); //redpin pinMode(5, OUTPUT); //greenpin pinMode(10, OUTPUT); //ledpin pinMode(9, OUTPUT); //switch } void loop() { int potValue = analogRead(A0); int buttonState = digitalRead(9); if (buttonState == 1 && prevButtonState == 0){ pressed = !pressed; } prevButtonState = buttonState; int mappedValue; int r; int g; int b; if (pressed){ digitalWrite(2, LOW); mappedValue = map(potValue, 0, 1023, 0, 767); int color = mappedValue; color = constrain(color, 0, 767); if (color <= 255){ r = 255 - color; g = color; b = 0; } else if (color <= 511){ r = 0; g = 511 - color; b = color - 256; } else{ r = color - 512; g = 0; b = 767 - color; } analogWrite(6, r); analogWrite(5, g); analogWrite(3, b); } else { analogWrite(6, 0); analogWrite(5, 0); analogWrite(3, 0); mappedValue = map(potValue, 0, 1023, 0, 255); analogWrite(10, mappedValue); } }