Serial Communication Problem - Buffer Not Clearing?

The intent of the code below is to blink a red LED one time when I type the number 3 into the Arduino Serial Monitor. Unfortunately, the code causes the red LED to blink repeatedly every two seconds.

I cannot understand why the code is causing repetitive blinking rather than a single blink.

I have typed in the number 3 only one time in the Arduino Serial Monitor, and the rx-tx LEDs on the Arduino register no further serial traffic. I am certain that the Task variable is set to “RedHasBlinkedOnce” after the red LED blinks once, because the yellow LED lights up as expected.

Making a call to the flushSerial() routine is supposed to read (and thus clear) the serial buffer.

Does anyone have any ideas why the red LED is blinking repetitively, rather than just once?

int LEDyellow = 9;
int LEDred = 10;

int SerialMessage = 0;

String Task;

void setup()
{
  pinMode(LEDyellow, OUTPUT);
  pinMode(LEDred, OUTPUT);
  
  digitalWrite(LEDyellow, LOW);
  digitalWrite(LEDred, LOW);

  Task = "None";
  SerialMessage = 0;
  Serial.begin(9600);
}

void loop()
{
  if(Serial.available())
    {
      SerialMessage = Serial.read();
    }

  if(SerialMessage == 51) //3 entered on Serial Monitor is read as ASCII 51
    {
      Task = "BlinkRedOnce"
      Serial.end();
      flushSerial();
    }

  if(Task == "BlinkRedOnce")
    {
      digitalWrite(LEDred, HIGH);
      delay(100);
      digitalWrite(LEDred, LOW);
      delay(2000);
      Task = "RedHasBlinkedOnce";
    }

  if(Task == "RedHasBlinkedOnce")
    {
      digitalWrite(LEDyellow, HIGH);
    }

}

void flushSerial()
{
  while (Serial.available())
  {
    Serial.read();
  }
}
void loop()
{
  if(Serial.available())
    {
      SerialMessage = Serial.read();
    }

  if(SerialMessage == 51) //3 entered on Serial Monitor is read as ASCII 51

Be easier to type == '3' wouldn't it?

Anyway, once SerialMessage has 51 in it, it stays there because you don't clear it. Better would be:

void loop()
{
  if(Serial.available())
    {
      SerialMessage = Serial.read();
    }
  else
    SerialMessage = 0;

  if(SerialMessage == '3') //3 entered on Serial Monitor is read as ASCII 51

Oh man, did I lose the plot there!! Should have realized that. Thanks Nick!

Alternatively if you declare your serialMessage as a local variable within your loop (instead of needlessly making it a global variable), it will automatically get reset for every iteration.

As long as you keep the "= 0" part, otherwise it will get some undefined value.

Yes BUT I think my advice was premature anyhow, as the OP will need it to be a global variable when he gets around to replacing the delays with millis().

What is the Serial.end( ) for ?

I don't think you actually want to do that.

Agreed. You don't want that at all, and you don't need to "flush" the serial either.