Enhance button state handling with debounce logic to prevent false triggers
This commit is contained in:
11
init.py
11
init.py
@@ -25,6 +25,8 @@ class AlarmClock:
|
|||||||
lastKnownButtonState: bool = False
|
lastKnownButtonState: bool = False
|
||||||
lcd: JHD1802
|
lcd: JHD1802
|
||||||
lastButtonPressTime: float = 0.0
|
lastButtonPressTime: float = 0.0
|
||||||
|
lastButtonStateChangeTime: float = 0.0
|
||||||
|
debounceDelay: float = 0.05 # 50ms debounce delay
|
||||||
def __init__(self, pins: dict = {}):
|
def __init__(self, pins: dict = {}):
|
||||||
self.ledGpio = GPIO(pins.get("led", 5), GPIO.OUT)
|
self.ledGpio = GPIO(pins.get("led", 5), GPIO.OUT)
|
||||||
self.buttonGpio = GPIO(pins.get("button", 6), GPIO.IN)
|
self.buttonGpio = GPIO(pins.get("button", 6), GPIO.IN)
|
||||||
@@ -43,9 +45,14 @@ class AlarmClock:
|
|||||||
|
|
||||||
def loop(self):
|
def loop(self):
|
||||||
currentButtonState = not self.buttonGpio.read()
|
currentButtonState = not self.buttonGpio.read()
|
||||||
|
currentTime = time()
|
||||||
|
|
||||||
|
# Only process button state change if debounce delay has passed
|
||||||
if currentButtonState != self.lastKnownButtonState:
|
if currentButtonState != self.lastKnownButtonState:
|
||||||
self.lastKnownButtonState = currentButtonState
|
if (currentTime - self.lastButtonStateChangeTime) >= self.debounceDelay:
|
||||||
self.onButtonPress("button", currentButtonState)
|
self.lastKnownButtonState = currentButtonState
|
||||||
|
self.lastButtonStateChangeTime = currentTime
|
||||||
|
self.onButtonPress("button", currentButtonState)
|
||||||
|
|
||||||
|
|
||||||
def onButtonPress(self, button: str, state: bool):
|
def onButtonPress(self, button: str, state: bool):
|
||||||
|
|||||||
Reference in New Issue
Block a user