// https://forum.arduino.cc/t/timed-response-after-release/964154
// https://wokwi.com/projects/324897525243839060
// version 2. remove crude debouncing, put didIt flag in more obvious place
int soundSensor = 2;
// several tweaks because I use a button not a sound sensor
int buttonState = 0;
int lastButtonState = 0;
const int debouncePeriod = 33;
const unsigned long actionTrigger = 5000; //serial print action 5 seconds for testing - life too short
unsigned long startTimer; // time until action
unsigned long currentMillis;
void setup() {
Serial.begin(115200);
Serial.println("\nWake up!\n");
pinMode (soundSensor, INPUT_PULLUP); // for proxy pushbutton here
}
void loop() {
static bool didIt = true; // intial condition
static unsigned long startTimer; // time until action
static unsigned long lastButtonTime;
unsigned long currentMillis;
currentMillis = millis();
int buttonState = !digitalRead(soundSensor); // button upside down
if (currentMillis - lastButtonTime > debouncePeriod) { // OK bounce-wise to even look at the button?
// compare the buttonState to its previous state
if (buttonState != lastButtonState) { // has the state changed?
lastButtonTime = currentMillis; // so we don't look again too soon (bounce)
if (buttonState == HIGH) { // if high, button pressed
// if the current state is HIGH then the button went from off to on:
Serial.println("pressed");
didIt = false; // reset do something trigger gaurd
}
else {
Serial.println("released");
}
lastButtonState = buttonState; // Save button state
}
}
// when the button is pressed, reset the timer
if (buttonState == HIGH) {
startTimer = currentMillis;
didIt = false; // reset do something trigger gaurd
// trust or verify Serial.println(" reset timer");
}
if ((currentMillis - startTimer > actionTrigger) && !didIt) {
Serial.println(" Do something!");
didIt = true;
}
}