How can I break my while loop using a Serial input?

235 Views Asked by At

I'm trying to break this while loop with the serial input of "Clear" but my serial monitor shuts down when the loop is going. This loop basically makes my siren and light blink until the serial input of "clear" is given but it's not executing. Any suggestions? my code with the loop

I tried to use the current method, then tried to use the method of basically declaring two ints of hubHazard; and clear; and coding it to if i type "hubHazard == 1" into the monitor it would activate the siren and "clear == 1" would end it, but since I found out the problem is the loop, that obviously didn't work. I also couldn't manage to get both working in the same code at the same time. I couldn't use the method of just trying to do all of this under a void loop function. The loop would only run it once when activated by a button, but I need it to go until it's told to stop, which is why I used a while loop.

1

There are 1 best solutions below

0
On

Your approach should be like this:

bool alertOn = false;
    
    void alert(){
      digitalWrite(ledPin, HIGH);
      delay(500);
      digitalWrite(ledPin, LOW);
      delay(500);
      //stuff
      //stuff
      
    }
    
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
    
    }
    
    void loop() {
      // put your main code here, to run repeatedly:
      //stuff
      if(message_received == "Hazzard"){
        alertOn = true;
        
        
      }
      else if(message_received == "Clear"){
        alertOn = false;
        
      }
      if(alertOn){
        alert();
      }
    }