char colour; // Store received byte here
//Define RGB pins
int redPin = 9;
int greenPin = 10;
int bluePin = 11;
void setup() {
Serial.begin(9600); // Start serial communication to BT module
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
// Set LEDs OFF
setColourRGB(0, 0, 0);
}
void loop() {
if (Serial.available() > 0) {
colour = Serial.read();
}
// OFF
if (colour == 'n') {
setColourRGB(0, 0, 0);
}
// RED
if (colour == 'r') {
setColourRGB(255, 0, 0);
}
// GREEN
if (colour == 'g') {
setColourRGB(0, 255, 0);
}
// BLUE
if (colour == 'b') {
setColourRGB(0, 0, 255);
}
// ORANGE
if (colour == 'o') {
setColourRGB(255, 20, 0);
}
// MINT
if (colour == 'm') {
setColourRGB(0, 255, 30);
}
// CYAN
if (colour == 'c') {
setColourRGB(1, 255, 208);
}
// YELLOW
if (colour == 'y') {
setColourRGB(255, 65, 0);
}
// WHITE
if (colour == 'w') {
setColourRGB(255, 255, 255);
}
// PINK
if (colour == 'p') {
setColourRGB(255, 0, 255);
}
// RANDOM
if (colour == '?') {
int redValue = random(0, 256);
int greenValue = random(0, 256);
int blueValue = random(0, 256);
setColourRGB(redValue, greenValue, blueValue);
}
// COLOUR CYCLE
if (colour == 's') {
unsigned int rgbColour[3];
while (Serial.available() == 0) {
// 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(50);
}
}
}
}
}
void setColourRGB(unsigned int red, unsigned int green, unsigned int blue) {
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
This is my code to control an RGB LED strip via bluetooth using an app I made. The app simply sends letters depending on the button pressed, the Arduino then takes that character and, depending on what it is, changes the RGB LED strip to display a colour.
However, I am having two problems with it right now:
1: The random colour mode only ever produces white and it flickers slightly - any clue as to why that is?
2: If you try to change the colour while a colour cycle is happening, the program has to finish the current colour cycle before it will react to the change you made - how do I stop this and make a new byte received break out of that while loop?
Thanks ![]()