如何使用gpiozero button.when_pressed函数使用输入和输出整数的函数?

use*_*467 1 python function while-loop gpio raspberry-pi

我正在尝试对Raspberry Pi上的按钮进行编程,以将一个整数添加到另一个整数,以便可以while通过检查变量mod 2是否为0来在循环中的条件之间来回切换。我本质上是在尝试while通过检查变量是奇数还是偶数来翻转循环中的条件。

我正在尝试使用该gpiozero库的when_pressed函数,但是它似乎无法调用添加和输出整数的函数。

所以,我的代码是:

from gpiozero import Button
btn = Button(17) #the button is wired to GPIO pin 17

def addSurf(a):
    a = a + 1
    return(a)

x = 0
btn.when_pressed = addSurf(x)

while True:
    if x == 0:
        #do some stuff
    else:
        #do some other stuff
Run Code Online (Sandbox Code Playgroud)

为什么我尝试运行此程序,我明白了TypeError: unsupported operand type(s) for +: 'Button' and 'int'

如何使用该btn.when_pressed函数使用输入和输出整数的函数?

或者,是否还有其他[更好的]方法来使按钮在while循环中切换两个状态?

Red*_*jed 5

可以将参数传递到gpiozero按钮的“ when_pressed”属性中,但文档记录不充分。我找不到任何例子。(提示向gpiozero创建者寻求帮助!)

我所做的是将一个lambda函数传递到“ when_pressed”中,其中包含我希望该函数访问的变量。

这是我的程序版本:

from gpiozero import Button
from signal import pause

btn = Button(17) #the button is wired to GPIO pin 17

class X():
    value = 0


def addSurf(x):
    x.value += 1
    print('Adding 1')

def do_something_when_button_is_released(x):
    print('x = ',x.value)


x = X()
btn.when_pressed = lambda : addSurf(x)
btn.when_released = lambda : do_something_when_button_is_released(x)
pause()
Run Code Online (Sandbox Code Playgroud)

我已经使用一个类作为您原始“ x”变量的容器。这可能是矫kill过正,但是我试图用x作为整数来做同样的事情,但是没有用!真的不明白为什么。无论如何,一类允许您添加多个变量。

另一点是,“ while True”循环不适用于此方法,因为它占用了所有CPU时间。最好使用我称为“ do_something_when_button_is_released”的函数来触发执行其他操作。