0

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?

Ken White
  • 123,280
  • 14
  • 225
  • 444
frol
  • 79
  • 4
  • Break the loop into steps and let the loop function be the only loop in the code. Break the fading stuff into steps and let the loop function take one step at a time instead of a nested loop. – Delta_G Aug 26 '23 at 14:16
  • Open the example ***02digital->BlinkwithoutDelay*** and create a fade effect according to it. And it would also be good to replace comparing String with comparing char in all conditions. Your solution is terribly inefficient, especially for an MCU with 2KiB SRAM – Peter Plesník Aug 27 '23 at 10:55

0 Answers0