Why does the serial monitor needs to be repeated a command? I am experimenting with the serial monitor in an Arduino Uno. My project consists in a simple LED turning on and off at will with the commands "ON" and "OFF" respectively.

To achieve this, I use an HC-06 Bluetooth module, but because of the nature of the test I decided to disconnect it and 'debug' my project using the serial monitor as an equivalent.

The circuit has the following connection table:

LED +: Pin 12 on my Arduino.
LED -: GND on my Arduino.

...as you can see, I have tried to simplify as much as I can the circuit, as I wanted to make sure I didn't have wire problems.

Here's the code:

char command;
String string;
#define led 12 

void LEDOn()
    { 
          digitalWrite(led, HIGH);
    }

void LEDOff()
    {
      digitalWrite(led, LOW);
    }

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

void loop()
{
     if (Serial.available() &gt; 0)
           {string = "";}

     while(Serial.available() &gt; 0)
    {
           command = ((byte)Serial.read());

           if(command == ':')
           {
                  break;   
           }  

           else
           {
                  string += command;
           }

           delay(1);
    }

    if(string == "LO")
    {
           LEDOn();
     }   

   if(string == "LF")
    {
           LEDOff();
    }


The problem comes when I type the commands. Normally, an LED in the board will react (I think it's the RX one), but the LED in pin 12 will not react at all. After testing ten times with each command alternatively, I calculated the serial needs an average of 6 command repetitions in order to react. Exactly the same happens when the HC-06 is connected.

Is there a reason for this?
It worked fine for me, if I typed the entire command, "LO:" or LF:" (without the quotes of course). However, if I typed and sent one character at a time, it failed. The problem is quite likely the code:


   if (Serial.available() &gt; 0)
         {string = "";}



If you send all of the characters at once, the while( Serial.available() ) loop will get the whole line and match it. But if there is any pause between characters, what does that if statement do? (Hint: loop() executes way faster than you can type!)

I was using the serial terminal built into the Eclipse IDE. Different terminal software might behave differently when you type a string and send it. Remember, any gaps between characters, and that first if statement gets time to do its dirty work.