Hello everyone. I'm new to Arduino and I would like to ask for your help in creating a program that will turn on the LED for 5 seconds after a pushbutton is pressed using millis() instead of delay(). I could have just used delay but adding another pushbutton and LED with the same function makes the program not work as intended because only one of them get to turn on after pressing their respective pushbuttons. Thank you for reading and hoping for your kind help.
When you get the read signal for the push button, set a variable
Buttonpushed=millis()
And turn your led on. Then all you need is to check
if (millis()-buttonpushed >=5000){
And turn it off (hint...check it’s actually on first...)
Thank you very much! I managed to do it using your hints.
In the spirit of sharing, maybe you could post your final code to help the next soul with a similar need.
And turn it off (hint...check it's actually on first...)
Whilst it is neater to check whether it is turned on first neither the program or the LED will care if you turn it off every time through loop() once the period has elapsed.
What would be nice would be to detect when the button becomes pressed rather than when it is pressed. That way the time period would start immediately a button press was detected even if the button is held down.
I use latching buttons quite a lot. They don’t always latch so button and LED (or whatever) can get out of sync. Confusing when th latching switch is also illuminated, so looks like something is on when it’s not...or vice verse. It’s why I always put a check in.