用Python中的按钮输入更改LED闪烁间隔

时间:2018-09-06 21:46:29

标签: python raspberry-pi gpio led

我想每次按下按钮都更改LED的闪烁时间。
我用python编写的代码不响应按钮输入的点击。它需要什么变化?貌似回调不起作用

import RPi.GPIO as GPIO
from time import sleep

inbutton = 13
outpin = 7
z = 1


def init():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(outpin, GPIO.OUT)
    GPIO.setup(inbutton, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    global z
    z = 1


def zest():
    global z
    if z == 1:
        z = 2
        while z == 2:
            GPIO.output(outpin, 1)
            print("led on")
            sleep(1)

            GPIO.output(outpin, 0)
            print("led off")
            sleep(1)

    elif z == 2:
        z = 1
        while z == 1:
            GPIO.output(outpin, 1)
            print("led on")
            sleep(2)

            GPIO.output(outpin, 0)
            print("led off")
            sleep(2)


def loop():
    GPIO.add_event_detect(inbutton, GPIO.FALLING, callback=zest(), bouncetime=1000)


if __name__ == '__main__':
    init()
    try:
        while True:
            loop()

    except KeyboardInterrupt:
        GPIO.output(outpin, 0)
        GPIO.cleanup()

正在运行时,LED每隔1秒闪烁一次。但是请不要对按钮click作出反应。请在那里看看专家。

1 个答案:

答案 0 :(得分:0)

更改此行:

GPIO.add_event_detect(inbutton, GPIO.FALLING, callback=zest(), bouncetime=1000)

对此:

GPIO.add_event_detect(inbutton, GPIO.FALLING, callback=zest, bouncetime=1000)

如您所知,注册该回调时会调用一次,并将已注册的回调保存为None,因为这是zest()返回的内容。

回调也需要接受一个参数:channel。因此,将您的函数定义更改为:

def zest(channel):