// https://wokwi.com/projects/373589174724221953
// https://forum.arduino.cc/t/measure-time-that-a-condition-is-true-to-then-trigger-and-action/1159366
unsigned long durationMillis = 500; // DURATION for LED ON after BUTTON is pressed
#define buttonPin 2 // the Arduino pin connected to the BUTTON
#define ledPin 3 // the Arduino pin connected to the LED
bool ledState; // store the state (ON/OFF) of the LED
bool buttonState; // store the state (pressed/not pressed) of the button
unsigned long ledOnMillis; // timer for LED ON time
unsigned long ledOffMillis; // timer for LED OFF time
void setup() {
Serial.begin(115200); // start Serial Monitor communications
pinMode (ledPin, OUTPUT); // set Arduino pin for the LED to OUTPUT
pinMode (buttonPin, INPUT_PULLUP); // set Arduino pin for the BUTTON to INPUT with PULLUP resistor
digitalWrite(ledPin, LOW); // LED OFF
welcome();
}
void loop() {
bool buttonReading = !digitalRead(buttonPin);
unsigned long now = millis();
bool buttonEvent = false; // unless...
if (buttonReading != buttonState) {
buttonState = buttonReading;
if (buttonState)
buttonEvent = true; // we saw the button go down
}
if (buttonEvent) {
ledOnMillis = millis(); // record LED ON time
digitalWrite(ledPin, HIGH); // LED ON
ledState = 1; // set LED flag meaning LED is ON
printOn(); // format and print current status
}
if ((millis() - ledOnMillis > durationMillis) && ledState) { // difference between button to now
ledOffMillis = millis(); // get LED OFF time
digitalWrite(ledPin, LOW); // LED OFF
ledState = 0; // clear LED flag
printOff(); // format and print current status
duration();
}
delay(10); // poor man's debouncing
}
//*************************************************************
// Formatted printout
//*************************************************************
void printOn() {
Serial.print("TIME ON ");
Serial.print(ledOnMillis);
Serial.print(" <-- the milliseconds clock");
Serial.println();
}
void printOff () {
Serial.print("TIME OFF ");
Serial.print(ledOffMillis);
Serial.print(" <-- DURATION plus current milliseconds clock");
Serial.println();
}
void duration () {
Serial.print("DURATION ");
Serial.print(ledOffMillis - ledOnMillis); // show duration
Serial.print(" <-- difference between ON and OFF");
Serial.println();
}
void welcome() {
Serial.println("Press the green button.");
}