Sunday, September 14, 2014

Python RPi.GPIO: Read Button using GPIO.add_event_detect() with callback

The example show how to detect events of GPIO, to detect button pressed/released. It have the same operation in the post "Python RPi.GPIO: Button and LED".



import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(18, GPIO.OUT)

def ButtonCallback(channel):
    if (GPIO.input(17)):
        GPIO.output(18, False)
    else:
        GPIO.output(18, True)
    
GPIO.add_event_detect(17, GPIO.BOTH, callback=ButtonCallback);

while(True):
    #do nothing
    time.sleep(1)

No comments: