使用RPi GPIO库进行中断操作非常简单。
定义回调函数
def test_callback(channel):
print('In test_callback fuc')
定义检测函数
add_event_detect(channel, GPIO.RISING, callback=test_callback, bouncetime=200)
上升沿检测,关联回调,bouncetime用于按键软件防抖
按钮控制led灯亮灭:
#!/usr/bin/python
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(37, GPIO.IN)
def led_on():
GPIO.output(22, GPIO.HIGH)
def led_off():
GPIO.output(22, GPIO.LOW)
GPIO.add_event_detect(37, GPIO.RISING, callback=led_on, bouncetime=200)
GPIO.add_event_detect(37, GPIO.FALLING, callback=led_off, bouncetime=200)