Skip to content

Instantly share code, notes, and snippets.

@pmuller
Last active February 28, 2018 14:39
Show Gist options
  • Save pmuller/9cf8624b89f3f2dc1c42768df85695f6 to your computer and use it in GitHub Desktop.
Save pmuller/9cf8624b89f3f2dc1c42768df85695f6 to your computer and use it in GitHub Desktop.
from time import sleep
import RPi.GPIO
class PushButton:
def __init__(self, pin, rpi_gpio=RPi.GPIO):
self.pin = pin
self.rpi_gpio = rpi_gpio
self.state = None
self.state_changed = False
self.rpi_gpio.setup(self.pin, self.rpi_gpio.IN)
@property
def was_pressed(self):
state = not self.rpi_gpio.input(self.pin)
if state != self.state:
self.state = state
if self.state_changed:
self.state_changed = False
return True
else:
self.state_changed = True
return False
def main():
RPi.GPIO.setmode(RPi.GPIO.BOARD)
pin = 42
button = PushButton(pin)
try:
while True:
if button.was_pressed:
print('You pushed the button')
else:
print('You did not push the button')
# Sleep for 1s
sleep(1)
except KeyboardInterrupt:
pass
finally:
RPi.GPIO.cleanup()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment