Enhance button state handling with debounce logic to prevent false triggers

This commit is contained in:
Aaro Varis
2026-01-15 10:50:49 +02:00
parent 9775a97903
commit 959e0d3a10

View File

@@ -25,6 +25,8 @@ class AlarmClock:
lastKnownButtonState: bool = False
lcd: JHD1802
lastButtonPressTime: float = 0.0
lastButtonStateChangeTime: float = 0.0
debounceDelay: float = 0.05 # 50ms debounce delay
def __init__(self, pins: dict = {}):
self.ledGpio = GPIO(pins.get("led", 5), GPIO.OUT)
self.buttonGpio = GPIO(pins.get("button", 6), GPIO.IN)
@@ -43,8 +45,13 @@ class AlarmClock:
def loop(self):
currentButtonState = not self.buttonGpio.read()
currentTime = time()
# Only process button state change if debounce delay has passed
if currentButtonState != self.lastKnownButtonState:
if (currentTime - self.lastButtonStateChangeTime) >= self.debounceDelay:
self.lastKnownButtonState = currentButtonState
self.lastButtonStateChangeTime = currentTime
self.onButtonPress("button", currentButtonState)