From 1435ed32d8b216eb1f3c1f1092068b45a6c4a9a9 Mon Sep 17 00:00:00 2001 From: Lyubomir Penev Date: Wed, 8 Oct 2025 13:53:32 +0200 Subject: [PATCH] Added debounce read function --- src/main.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/main.cpp b/src/main.cpp index b0267cc..965af29 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -7,8 +7,14 @@ int maxVolume = 64; int userVolume = 64; int oldUserVolume = userVolume; +int buttonState; +int lastButtonState = LOW; +unsigned long lastDebounceTime = 0; +unsigned long debounceDelay = 50; + void volumeUp(); void volumeDown(); +bool debounceRead(); void setup() { @@ -272,4 +278,35 @@ void volumeDown() digitalWrite(9, LOW); delay(1); digitalWrite(10, HIGH); +} + +bool debounceRead(int buttonPin) +{ + int reading = digitalRead(buttonPin); + + // If the switch changed, due to noise or pressing: + if (reading != lastButtonState) + { + // reset the debouncing timer + lastDebounceTime = millis(); + } + + if ((millis() - lastDebounceTime) > debounceDelay) + { + // whatever the reading is at, it's been there for longer than the debounce delay, so take it as the actual current state: + + // if the button state has changed: + if (reading != buttonState) + { + buttonState = reading; + + if (buttonState == HIGH) + return true; + else + return false; + } + } + + // save the reading. Next time through the loop, it'll be the lastButtonState: + lastButtonState = reading; } \ No newline at end of file