// https://forum.arduino.cc/t/measure-time-that-a-condition-is-true-to-then-trigger-and-action/1159366/20
unsigned long durationMillis = 300; // DURATION for LED ON after BUTTON is pressed
unsigned long ledOnMillis; // timer for LED ON time
unsigned long ledOffMillis; // timer for LED OFF time
#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;
bool buttonStateOld;
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() {
buttonState = digitalRead(buttonPin); // store button state
if (buttonState != buttonStateOld) { // if button state has changed
if (!buttonState) { // check for LOW (button pressed)
digitalWrite(ledPin, HIGH); // LED ON to indicate button was pressed
ledOnMillis = millis(); // store LED ON time
ledState = 1; // set LED flag that LED is ON
printOnTime(); // 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
printOffTime(); // format and print current status
duration();
}
buttonStateOld = buttonState; // update the old button state for next button read
}
//*************************************************************
// Formatted printout
//*************************************************************
void printOnTime() {
delay(150); // debounce the button press
Serial.print("TIME ON ");
spacePad(ledOnMillis);
Serial.print(ledOnMillis);
Serial.println(" <-- timer start");
Serial.print("DURATION ");
Serial.println(durationMillis);
}
void printOffTime () {
Serial.print("TIME OFF ");
spacePad(ledOffMillis);
Serial.print(ledOffMillis);
Serial.print(" <-- DURATION plus timer");
Serial.println();
}
void duration () {
Serial.print("DIFFERENCE");
spacePad(ledOffMillis - ledOnMillis);
Serial.print(ledOffMillis - ledOnMillis); // show duration
Serial.println(" <-- difference between ON and OFF");
Serial.println("---------------------------------------------");
}
void spacePad(int value) {
if (value < 10000)
Serial.print(" ");
if (value < 1000)
Serial.print(" ");
if (value < 100)
Serial.print(" ");
}
void welcome() {
Serial.println("Press the green button.");
}