Breaking while loop using Serial.read

Hi all,

I am extremely new to coding/arduino.

Below shows some code I have made, but I have a problem.

Once the board is in the "blinking" state, I want to be able to type "on" or "off" to stop the loop.

How do I do this? (Sorry for my ignorance, I have search the net but can't seem to find anything applicable)

Thanks for your time!

Nick

String ByteReceived;

void setup()
{
  Serial.begin(9600);  
    Serial.println(" To turn the on-board light on type 'on', to turn off type 'off' ");
    Serial.println("Alternatively, type 'blink' to flash the light");  
  Serial.println();
  pinMode(LED_BUILTIN,OUTPUT);
}


void loop()
{
  if (Serial.available() > 0)
  {
    ByteReceived = Serial.readString();

    
    if(ByteReceived == "on") 
    {
      Serial.println(ByteReceived);
      digitalWrite(LED_BUILTIN,HIGH);
      Serial.print(" LED ON ");
    }
    
    
    else if(ByteReceived == "off")
    {
      Serial.println(ByteReceived);
      digitalWrite(LED_BUILTIN,LOW);
      Serial.print(" LED OFF");
      delay(1000);
    }


    else if(ByteReceived =="blink")
    {
      Serial.println("blinking");
      do
      {
      digitalWrite(LED_BUILTIN,HIGH);
      delay(500);
      digitalWrite(LED_BUILTIN,LOW);
      delay(500);
      } while(ByteReceived = "blink");
      
    }
     else
  {
     Serial.print("Invalid response!");
     
    }
    
    Serial.println();    // End the line

  }
}

Hi user with a name i don't like, welcome nevertheless.

Please read the 'How to use the forum' topic you can find on top of any part of the forum, so you can learn how to use it correctly.

After you've done so, have a look at 'blink without delay'.
You'll find it in your IDE by clicking File - Examples - 02.Digital - BlinkWithoutDelay.

It will teach you how to do this.
You are using a double blocking code.
Delay() is blocking, and while is blocking.
You can google for 'blocking code' to find out more about what that is, and why it is a problem (although i think you just found out by yourself already).

Once you're in the while(), you lock yourself out of other code, so you'll never get any new serial data in and you get stuck in there.
Don't do that.
Set a flag instead, and reset it when appropriate.

The examples in Serial Input Basics use non-blocking code as does the demo Several Things at a Time and these ideas are all encompassed in the more extensive Planning and Implementing a Program

...R

      do
      {
      digitalWrite(LED_BUILTIN,HIGH);
      delay(500);
      digitalWrite(LED_BUILTIN,LOW);
      delay(500);
      } while(ByteReceived = "blink");

Once in this do/while loop the value of ByteReceived will not change. Can you see a problem ?

Once in this do/while loop the value of ByteReceived will not change.

It will be assigned a new value on every pass through the do loop. That, too, is probably not what OP wants.

A value which probably doesn't fit if we believe the name of the variable.