Adding a turn off to LED delay

Hi everyone,

I've got some pretty simple code that basically turns an LED on for 5s and then switches it off with the push of a button. I can't for the life of me find out how to make a second push of the button switch the LED off if it's pin is high, but still making the timed output work as normal if there is no second button push within the 5s since the LED was switched on.

I'm new to all of this and I've been trying to no avail :frowning:

Any help/guidance would be very much appreciated :slight_smile:

int pinButton = 7;
int LED = 9;
int stateLED = LOW;
int stateButton;
int previous = LOW;
long time = 0;
long debounce = 500;
int stayON = 5000;
 
void setup() {
  pinMode(pinButton, INPUT);
  pinMode(LED, OUTPUT);
}
 
void loop() {
  stateButton = digitalRead(pinButton);  
  if(stateButton == HIGH && previous == LOW && millis() - time > debounce) {
    if(stateLED == HIGH){
      digitalWrite(LED, LOW);
    } else {
       digitalWrite(LED, HIGH);
       delay(stayON);
       digitalWrite(LED, LOW);
    }
    time = millis();
  }
  previous == stateButton;
}

millis() and delay() can not be used together in a more than one thing at a time scenario. When delay() is running, the Arduino is dead to the world.

Thanks for your reply. Ah, of course! I did recently read about the delay() thing hogging the arduino for all the time it's running, but completely overlooked it.

So I'd have to remove the delay() and use only millis(), then I could interrupt by switching off, is that correct?

yes