Police light push button while loop

Hi!

After +- 5 years I am back to Arduino! I have a question how can I add a while loop to my code for red and blue leds blinking while till I turn it off with button?!

int button = 2;

int redLed = 8;
int blueLed = 10;

int ledFlag = 0;

void setup() {

  pinMode(button, INPUT_PULLUP);

  pinMode(redLed, OUTPUT);
  pinMode(blueLed, OUTPUT);
  digitalWrite(redLed, LOW);
  digitalWrite(blueLed, LOW);

  Serial.begin(9600);
}

void loop() {

  if (digitalRead(button) == LOW)
  {
    if (ledFlag == 0)
    {
      ledFlag = 1;
      digitalWrite(redLed, HIGH);
      delay(200);
      digitalWrite(blueLed, HIGH);
      delay(200);
      digitalWrite(redLed, LOW);
      delay(100);
      digitalWrite(blueLed, LOW);
      delay(100);
      Serial.println(ledFlag);
    }
    else {
      ledFlag = 0;
      digitalWrite(redLed, LOW);
      digitalWrite(blueLed, LOW);
      Serial.println(ledFlag);
    }
    delay(500);
  }
}

I tried to add while loop but then it goes over and over and I can't stop it with button. So I hope for your help.

Yes, of course. Nothing can happen in loop() while any delay() call is running. Use millis() instead.

Try reading these then try writing your code again from the start:
https://forum.arduino.cc/index.php?topic=503368.0
https://forum.arduino.cc/index.php?topic=223286.0
https://forum.arduino.cc/index.php?topic=719995.0

I think those cover what you need.

In your code, you uses the delay() function. This makes your code miss some button pressing event. Use millis() function instead. See how to use millis() instead of delay()

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.