FEATURE: Optimize button pushes
This commit is contained in:
parent
e3e91ab1b5
commit
1fefd54499
|
@ -11,6 +11,7 @@ __all__ = (
|
|||
|
||||
from threading import Thread
|
||||
from logging import getLogger
|
||||
from time import time
|
||||
|
||||
import RPi.GPIO as GPIO
|
||||
|
||||
|
@ -40,25 +41,43 @@ class GPIOHandler(Thread):
|
|||
:param threading.Event stop_event: The stop event
|
||||
'''
|
||||
super(GPIOHandler, self).__init__()
|
||||
|
||||
self.core = core
|
||||
self.stop_event = stop_event
|
||||
|
||||
now = time()
|
||||
self.timestamps = {x: now for x in self.button_pins}
|
||||
|
||||
# pylint: disable=no-member
|
||||
def run(self):
|
||||
'''
|
||||
Run the thread.
|
||||
'''
|
||||
GPIO.setmode(GPIO.BOARD)
|
||||
|
||||
def callback(pin): # pylint: disable=missing-docstring
|
||||
play_sound('success.wav')
|
||||
self.button_pins[pin](self.core)
|
||||
|
||||
for pin in self.button_pins:
|
||||
LOGGER.debug('Setup pin %s as button pin', pin)
|
||||
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
|
||||
GPIO.add_event_detect(pin, GPIO.BOTH, callback=callback)
|
||||
GPIO.add_event_detect(pin, GPIO.RISING, callback=lambda pin: self.button_push(pin)) # pylint: disable=unnecessary-lambda
|
||||
|
||||
LOGGER.debug('Setup pin %s as LED pin', self.led_pin)
|
||||
GPIO.setup(self.led_pin, GPIO.OUT)
|
||||
GPIO.output(self.led_pin, GPIO.HIGH)
|
||||
|
||||
self.stop_event.wait()
|
||||
GPIO.cleanup() # pylint: disable=no-member
|
||||
|
||||
def button_push(self, pin):
|
||||
'''
|
||||
Callback method when a button is pushed.
|
||||
|
||||
:param int pin: Pin number
|
||||
'''
|
||||
now = time()
|
||||
before = self.timestamps[pin]
|
||||
|
||||
if (GPIO.input(pin) == GPIO.LOW) and (now - before > 0.25):
|
||||
LOGGER.debug('Button at pin %s was pushed', pin)
|
||||
play_sound('success.wav')
|
||||
self.button_pins[pin](self.core)
|
||||
self.timestamps[pin] = now
|
||||
|
|
Loading…
Reference in a new issue