【问题标题】:How can I use the gpiozero button.when_pressed function to use a function that inputs and outputs integers?如何使用 gpiozero button.when_pressed 函数来使用输入和输出整数的函数?
【发布时间】:2017-08-01 14:45:35
【问题描述】:

我正在尝试在 Raspberry Pi 上编写一个按钮以将一个整数添加到另一个整数,以便我可以通过检查变量 mod 2 是否为 0 在while 循环中的条件之间来回翻转。我实际上是在尝试通过检查变量是奇数还是偶数来翻转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

为什么我尝试运行它,我得到TypeError: unsupported operand type(s) for +: 'Button' and 'int'

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

或者,是否有其他一些 [更好的?] 方法可以使按钮在 while 循环中切换两种状态?

【问题讨论】:

    标签: python function while-loop raspberry-pi gpio


    【解决方案1】:

    可以将参数传递到 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()
    

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

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

    【讨论】:

      【解决方案2】:

      我更改了 lambda 示例。我花了很长时间才理解gpiozero纪录片中“强制变量”的含义。我也到处搜索,对这里的 lambda 解决方案感到失望。由于我是初学者,我更喜欢这个参数传递选项,而不是学习 lambda。

      from gpiozero import Button
      from signal import pause
      
      class X():
          value = 0
      
      def addSurf(obtained_but):
          obtained_but.x.value += 1
          print('Adding 1')
      
      def do_something_when_button_is_released(obtained_but):
          print('x = ',obtained_but.x.value)
      
      #attach the x to the class Button before initializing it 
      Button.x = X()
      btn = Button(24)  #my button is wired to GPIO pin 24
      
      btn.when_pressed = addSurf
      btn.when_released = do_something_when_button_is_released
      pause()
      

      【讨论】:

        【解决方案3】:

        我意识到button.when_pressed 函数不能接受任何参数。

        为了实现在while 循环中让按钮在两个不同状态之间切换的最初目标,我最终让按钮在while 循环中将整数的符号作为全局变量在其自己的线程中切换,并让全局变量的符号在原始while 循环中的另一个线程中切换条件。这不是一个真正的正确方法,但我得到了它的工作。

        【讨论】:

          猜你喜欢
          • 2015-08-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-23
          • 1970-01-01
          • 2022-11-21
          • 2017-11-27
          • 1970-01-01
          相关资源
          最近更新 更多