// https://forum.arduino.cc/t/how-to-delay-using-millis/1142938
// https://forum.arduino.cc/t/timer-on-pin-low-high-detection/1325679
// https://wokwi.com/projects/415656135572365313
// version 5. same same with variants
const byte buttonPin = 2;
const byte ledPin = 3;
const unsigned long actionDelay = 2500; // action 2.5 seconds for testing - life too short
void setup() {
Serial.begin(115200);
Serial.println("\nWake up!\n");
pinMode (buttonPin, INPUT_PULLUP);
pinMode (ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
void loop() {
static unsigned long startTime; // time at action
unsigned long now = millis(); // fancier 'currentMillis' ooh!
bool buttonIsPressed = digitalRead(buttonPin) == LOW; // button pulled up! true is button pressed
// when the button is _not_ pressed, reset the timer, turn OFF the LED
if (!buttonIsPressed) {
startTime = now;
digitalWrite(ledPin, LOW);
}
// when (if!) the timer expires, turn ON the LED
if (now - startTime >= actionDelay) {
digitalWrite(ledPin, HIGH);
}
}
// alternate method - throttled loop counter
# define frameTime 20 // milliseconds per loop
# define longEnough 100 // # of loops to recognize a button press 10 * 20 = 2000, two seconds
void loop0()
{
static unsigned long lastLoopTime;
unsigned long now = millis();
// time to do the loop again?
if (now - lastLoopTime < frameTime)
return;
// yes.
lastLoopTime = now;
static int buttonCounter = 0;
bool buttonIsPressed = digitalRead(buttonPin) == LOW; // button pulled up! true is button pressed
if (buttonIsPressed)
buttonCounter++;
else {
buttonCounter = 0;
digitalWrite(ledPin, LOW);
}
if (buttonCounter >= longEnough)
digitalWrite(ledPin, HIGH);
}