// https://forum.arduino.cc/t/switch-on-a-led-for-5-sec-and-turn-off/112548/9
void setup()
{
pinMode(7,OUTPUT); // LED output
pinMode(12,INPUT); // Button input
Serial.begin(9600);
}
void loop()
{
static unsigned char ledState = LOW;
static unsigned char buttonState = LOW;
static unsigned char lastButtonState = LOW;
static unsigned long ledCameOn = 0;
// If the LED has been on for at least 5 seconds then turn it off.
if(ledState == HIGH)
{
if(millis()-ledCameOn > 5000)
{
digitalWrite(7,LOW);
ledState = LOW;
}
}
// If the button's state has changed, then turn the LED on IF it is not on already.
buttonState = digitalRead(12);
if(buttonState != lastButtonState)
{
lastButtonState = buttonState;
if((buttonState == HIGH) && (ledState == LOW))
{
digitalWrite(7,HIGH);
ledState = HIGH;
ledCameOn = millis();
}
}
}