使用python中的按钮输入更改led闪烁间隔

问题描述 投票:1回答:1

我希望每按一次按钮就可以改变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.experts那里请看看。

python raspberry-pi gpio led
1个回答
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):
© www.soinside.com 2019 - 2024. All rights reserved.