/*
Forum: https://forum.arduino.cc/t/help-beginner-with-led-flash-for-specified-time/1337748
Wokwi: https://wokwi.com/projects/418893876002893825
2025/01/01
Solution by alto777
*/
const byte buttonPin = 2;
const byte ledPin = 5;
boolean flashing = false;
byte currentButtonState = HIGH;
byte previousButtonState = HIGH;
unsigned long currentTime;
unsigned long onoffStarted;
unsigned long flashPeriod = 777; // half-blink period
unsigned long howLongToFlash = 13000; // shut off after a time (13 seconds here for testing)
void setup()
{
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop()
{
static unsigned long lastTurnedOn;
static unsigned long lastButtonTime; // for debouncing
if (flashing)
{
currentTime = millis();
if (currentTime - onoffStarted > flashPeriod) // if the flash period ended ?
{
digitalWrite(ledPin, digitalRead(ledPin) == LOW ? HIGH : LOW); // flip the state of the LED
onoffStarted = currentTime; // save the time when it occured
}
}
if (flashing && millis() - lastTurnedOn > howLongToFlash) {
flashing = false;
digitalWrite(ledPin, LOW);
}
if (millis() - lastButtonTime < 30) return; // we done. too soon to look at the button again.
currentButtonState = digitalRead(buttonPin);
if (currentButtonState != previousButtonState) // buttonstate has changed
{
previousButtonState = currentButtonState; // save the button state for the next check
lastButtonTime = millis(); // and don't look until the debounce period is elapsed...
if (currentButtonState == LOW) { // Change the flash state only if the change was from HIGH to LOW
flashing = !flashing;
if (!flashing) { // We only need to do this once when going to "not flashing"
digitalWrite(ledPin, LOW); // force the LED off if not flashing
}
else lastTurnedOn = millis();
}
}
}