【问题标题】:Change led blinking interval with button input in python在 python 中使用按钮输入更改 LED 闪烁间隔
【发布时间】:2018-09-06 21:46:28
【问题描述】:

我想在每次按下按钮时更改 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 秒的间隔闪烁。但不要响应按钮点击。那里的专家请看一下。

【问题讨论】:

    标签: python raspberry-pi gpio led


    【解决方案1】:

    改变这一行:

    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):
    

    【讨论】:

    • 进行了此更改,然后我运行了代码。每次单击按钮时,以下错误都会显示为输出 - TypeError: zest() 不接受任何参数(给定 1 个)。
    • @sas 我以前从未使用过RPi 模块。显然,add_event_detect 需要一个带有一个参数的回调:channel。我已经更新了答案。
    • 通过使用 self 参数,即 def zest(self) 并使用 callback=zest,消除了上述错误。但仍然无法在每次按下按钮时更改闪烁间隔。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多