Pulsing digitalWrite while serial input is true and turning the pulse off.

Hi, I am generating a square wave pulse (10 Hz) from a loop outputting to pin 7. I am able to initiate the pulse by inputting "1" into Serial Monitor. I would like to be able to turn the pulse off by inputting "0" but am unable to with the current code. I think this line input += (char) Serial.read(); // Read in one char at a time may be causing the problem and would appreciate any suggestions for modifying this to work. The full code is below: Thanks

/*
 Generate a pulsed square wave; turn on, off.
 */

int pulse = 7; // Pin 7

void setup()
{
  pinMode(pulse, OUTPUT); // Set pin 7 as digital out

  // Start up serial connection
  Serial.begin(9600); 
  Serial.flush();
}

void loop()
{
  String input = "";

  // Read any serial input
  while (Serial.available() > 0)
  {
    input += (char) Serial.read(); // Read in one char at a time
    delay(5); // Delay for 5 ms so the next char has time to be received
  }

  while (input == "1")
  {
    digitalWrite(pulse, HIGH);
    delay(20);
    digitalWrite(pulse, LOW);
    delay (80); // on
  }
  while (input == "0")
  {
    digitalWrite(pulse, LOW); // off
  }
}

Once it gets here:

while (input == “1”)
{
digitalWrite(pulse, HIGH);
delay(20);
digitalWrite(pulse, LOW);
delay (80); // on
}

it just sits there and spins - input isn’t getting changed, so it’s always 1, so it will just sit there for eternity.

You’re going to need to rewrite it so it can toggle the pin while also checking serial. See “blink without delay” or any of the countless threads on “doing more than one thing at once”

The examples in serial input basics should be useful. The first example is relevant if you just want to receive a single character.

...R

Thanks both - I will try your recommendations