非阻塞用法示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) btn_input = 4; LED_output = 17; # GPIO btn_input set up as input. GPIO.setup(btn_input, GPIO.IN) GPIO.setup(LED_output, GPIO.OUT) # handle the button event def buttonEventHandler_rising (pin): # turn LED on GPIO.output(LED_output,True) def buttonEventHandler_falling (pin): # turn LED off GPIO.output(LED_output,False) GPIO.add_event_detect(btn_input, GPIO.RISING, callback=buttonEventHandler_rising) GPIO.add_event_detect(btn_input, GPIO.FALLING, callback=buttonEventHandler_falling) try: while True : time.sleep(0.1) finally: GPIO.remove_event_detect(btn_input) GPIO.cleanup() |