From 8d2e275b2af1b5decb6330fe8ea8a76c5a186e84 Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Mon, 20 Mar 2023 10:17:22 +0100 Subject: [PATCH] Fix debounce --- src/config.cpp | 2 ++ src/config.h | 5 ++++- src/main.cpp | 10 +--------- src/utils.cpp | 15 +++++++++++++++ src/utils.h | 1 + 5 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/config.cpp b/src/config.cpp index 0ad9e6f..dbee63f 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -11,3 +11,5 @@ Audio audio; Preferences preferences; long lastActionTime = 0; +byte buttonLastState = HIGH; +long startPress = NOT_PRESSED; diff --git a/src/config.h b/src/config.h index 589ecd9..e23e12d 100644 --- a/src/config.h +++ b/src/config.h @@ -21,7 +21,8 @@ #define BUTTON 33 #define DEEP_SLEEP_WAKEUP GPIO_NUM_33 -#define DEBOUNCE_DELAY_MS 1000 +#define MIN_PRESS_DURATION 500 +#define NOT_PRESSED -1 #define DEEP_SLEEP_DELAY_MS 3600000 // 1h // Screen @@ -57,5 +58,7 @@ extern AsyncWebServer server; extern Audio audio; extern Preferences preferences; extern long lastActionTime; +extern byte buttonLastState; +extern long startPress; #endif \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index abb28e5..332a587 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -8,8 +8,6 @@ #include "utils.h" #include "config.h" -byte buttonLastState = HIGH; -long lastDebounceTime = 0; bool wasRunning = false; void setup() @@ -51,13 +49,7 @@ void setup() void loop() { - if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY_MS) - { - byte buttonCurrentState = digitalRead(BUTTON); - if (buttonCurrentState == LOW && buttonLastState == HIGH) - play(); - buttonLastState = buttonCurrentState; - } + checkButtonAndPlay(); audio.loop(); diff --git a/src/utils.cpp b/src/utils.cpp index 3d13da8..d665fe4 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -30,6 +30,21 @@ void displayText(String text) display.display(); } +void checkButtonAndPlay() { + byte buttonCurrentState = digitalRead(BUTTON); + if (buttonCurrentState == HIGH && buttonLastState == LOW) { + startPress = millis(); + } else if (buttonCurrentState == LOW && buttonLastState == HIGH) { + startPress = NOT_PRESSED; + } + long pressDuration = millis() - startPress; + if (startPress != NOT_PRESSED && pressDuration >= MIN_PRESS_DURATION) { + play(); + startPress = NOT_PRESSED; + } + buttonLastState = buttonCurrentState; +} + void play() { updateLastAction(); diff --git a/src/utils.h b/src/utils.h index 012f18f..56a0d77 100644 --- a/src/utils.h +++ b/src/utils.h @@ -9,6 +9,7 @@ bool fileIsValid(String fileName); bool fileExists(String fileName); void clearMessageArea(); void displayText(String text); +void checkButtonAndPlay(); void play(); void selectFile(String fileName);