Check for Action During Delay

Let's say I have a button and an LED.

When the button is pressed, the LED lights up for 30 seconds. If the button is not pressed during the 30 seconds, the LED turns off until the button is pressed again. If during that 30 seconds the button is pressed, the LED will remain on for another 30 seconds. Any idea of the code for this?

I thought about using delay but am pretty sure I need a while loop with some sort of time delay. Unsure.

Thanks!

Hello and welcome,

A while loop will have the same effect as delay(), it will block your code, so it won't respond to button presses unless you setup an interrupt for your button.

But you should look at the Blink Without Delay example for a better, non blocking method :slight_smile:

The demo Several Things at a Time illustrates how to manage timing using millis() rather than delay(). It is an extended example of BWoD.

...R

Something like this

start of loop()
  if millis() - start time >= 30 seconds and timing == true
    turn off LED
    timing = false
  end if
  
  if button becomes pressed
    turn on LED
    save start time from millis()
    timing = true
  end if
end of loop()