Electronic – arduino – void loop executes even when the while loop inside is true in arduino

arduinoarduino unobluetoothcmicrocontroller

I made a simple mobile application to send LED_ON or LED_OFF when a button is clicked. In the below code the while loop is not fully completed while execution but the controller is going to the void loop() and continuing from there.

char command;
String my_final="LED_OFF";
#define led 9

void setup(){
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  Serial.println("ready");
}

void loop(){
  if(Serial.available() > 0){
    my_final = "";
    while(Serial.available() > 0){
      command = (byte)Serial.read();
      my_final += command;
      Serial.println("test");
    }
    Serial.println(my_final);
    }

  if(my_final == "LED_ON"){
    Serial.println(my_final);
    analogWrite(led, 255);
    my_final == "LED_ON";
  }

  if(my_final == "LED_OFF"){
    Serial.println(my_final);
    analogWrite(led, 0);
    my_final == "LED_OFF";
  }
}

The main problem happens in my_final="" as i have to do this to accept new input from the bluetooth. i just cant seem to find a way around this problem.

EDIT

This is what im getting in the serial monitor. test L test E test D test _ test O test N.

Best Answer

Serial communication is transmitting data one byte at a time. Your code is fast enough to read and process one byte before the next one is received.

There are many possible solutions to this, and using delays is not a good one.

You could send a marker character at the end of each command, e.g. LED_ON!. Then you know you have to keep adding characters to your array until you see an exclamation mark. A common candidate for a marker is the newline character.

Another solution is to make sure all commands have the same length (e.g. 6 bytes). Then you could simply wait until you receive so many characters, that is

if(Serial.available() >= 6) ...

Beware that in the second solution, if you lose a single byte you will not be able to receive commands correctly until you re-sync. In order to re-sync, you could for example throw away the contents of Serial after a timeout, if an incomplete command is sitting there for too long.