From 517877559d7f334cbc6694767dd71585f425f677 Mon Sep 17 00:00:00 2001 From: Michael Mandl Date: Thu, 31 Dec 2015 14:11:37 +0100 Subject: [PATCH] Button-handling via callback --- button_led.py | 28 ++++++++++++++++------------ led.py | 10 ++++++---- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/button_led.py b/button_led.py index 3093c68..c634b6c 100755 --- a/button_led.py +++ b/button_led.py @@ -4,23 +4,27 @@ from time import sleep import RPi.GPIO as GPIO +ledPin = 14 +buttonPin = 16 + +def buttonHandler(channel): + print "button pushed" + GPIO.output(ledPin, not GPIO.input(ledPin)) + try: GPIO.setmode(GPIO.BCM) - GPIO.setup(4, GPIO.OUT) - GPIO.setup(14, GPIO.IN, pull_up_down=GPIO.PUD_UP) + GPIO.setup(ledPin, GPIO.OUT) + GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) + GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP) - last_state = True - last_led_state = False + GPIO.add_event_detect(buttonPin, GPIO.FALLING, callback=buttonHandler, bouncetime=300) + GPIO.output(ledPin, False) + while True: - input_state = GPIO.input(14) - if input_state == False and input_state != last_state: - print 'Button pressed' - GPIO.output(4, ~last_led_state) - last_led_state = ~last_led_state - last_state = input_state - sleep(0.1) + GPIO.wait_for_edge(15, GPIO.RISING) + print "blah" except KeyboardInterrupt: - GPIO.output(4, False) + GPIO.output(ledPin, False) finally: GPIO.cleanup() diff --git a/led.py b/led.py index 5aa4052..94b7d31 100755 --- a/led.py +++ b/led.py @@ -6,17 +6,19 @@ import RPi.GPIO as GPIO print 'blah' +pin = 14 + try: GPIO.setmode(GPIO.BCM) - GPIO.setup(4, GPIO.OUT) + GPIO.setup(pin, GPIO.OUT) while True: - GPIO.output(4, 1) + GPIO.output(pin, 1) sleep(1) - GPIO.output(4, 0) + GPIO.output(pin, 0) sleep(1) except KeyboardInterrupt: - GPIO.output(4, 0) + GPIO.output(pin, 0) finally: GPIO.cleanup()