/*
Forum: https://forum.arduino.cc/t/help-beginner-with-led-flash-for-specified-time/1337748
Wokwi: https://wokwi.com/projects/418894200161797121
Now with a timed reset function ;-)
ec2021
*/
#define TEST
const byte buttonPin = 2;
const byte ledPin = 5;
#ifdef TEST
const unsigned long autoResetAfter {10000UL}; // 10000 ms = 10 sec
#else
const unsigned long autoResetAfter {120 * 60000UL}; // 120 x 60000 ms = 2h (with 60 x 1000 ms = 1 min)
#endif
boolean flashing = false;
byte currentButtonState = HIGH;
byte previousButtonState = HIGH;
unsigned long currentTime;
unsigned long onoffStarted;
unsigned long flashPeriod = 1000;
unsigned long lastFlashStartTime = 0;
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
} else {
lastFlashStartTime = millis();
}
}
}
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
}
if (millis() - lastFlashStartTime >= autoResetAfter) {
flashing = false;
digitalWrite(ledPin, LOW); //force the LED off if not flashing
}
}
}