我正在尝试对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循环中切换两个状态?