I'm writing an Arduino program that changes an RGB LED's colour based on bluetooth serial input. While successfully implementing code that changes the LED to a static colour, I'm having trouble coming up with a solution for performing a loop that infinitely fades the LED's colour across the spectrum (where one iteration of the loop could take a long time) while simultaneously checking for serial input in order to switch the LED to a static colour or turn it off.
Here's the code:
int red = 11;
int green = 10;
int blue = 9;
char state;
void setup()
{
Serial.begin(38400);
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
}
int getState(){
if(Serial.available() > 0){
state = (char)Serial.read();
return state;
}
else{
return 0;
}
}
void colours(int r, int g, int b){
analogWrite(red, r);
analogWrite(green, g);
analogWrite(blue, b);
}
void loop(){
state = getState();
if(String(state) == "1"){ // Red
colours(255, 0, 0);
}
else if(String(state) == "2"){ // Green
colours(0, 255, 0);
}
else if(String(state) == "3"){ // Blue
colours(0, 0, 255);
}
else if(String(state) == "6"){ // Fading colours
// Loop here
}
else if(String(state) == "9"){ // Off
colours(0, 0, 0);
}
}
I suppose I could call getState()
and check if it's not "0" after every line in the loop or something, but that's way too hacky.
How can I begin the loop while ensuring that the LED can change to another state as instantly as changing from all the other states is?