/*
Forum: https://forum.arduino.cc/t/help-beginner-with-led-flash-for-specified-time/1337748
Wokwi: https://wokwi.com/projects/418890592487643137
*/
const byte buttonPin = 2;
const byte ledPin = 5;
boolean flashing = false;
byte currentButtonState = HIGH;
byte previousButtonState = HIGH;
unsigned long currentTime;
unsigned long onoffStarted;
long flashPeriod = 1000;
void setup()
{
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop()
{
currentButtonState = digitalRead(buttonPin);
if (currentButtonState != previousButtonState) //buttonstate has changed
{
delay(30); // Poor man's debouncing ... ;-)
previousButtonState = currentButtonState; //save the button state for the next check
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
}
}
}
if (flashing)
{
currentTime = millis();
if (currentTime - onoffStarted > flashPeriod) //if the flash period ended ?
{
digitalWrite(ledPin, !digitalRead(ledPin)); //flip the state of the LED
onoffStarted = currentTime; //save the time when it occured
}
}
}