【问题标题】:Simulate "button pressed" an rise an event in gpiozero模拟“按下按钮”在 gpiozero 中增加一个事件
【发布时间】:2019-12-03 02:03:58
【问题描述】:

我尝试在没有 GPIO 的机器上开发一些代码。作为 GPIO 库,我选择了一个 gpiozero 来编写我的代码,而无需访问树莓派的 gpio。 我的问题,我无法在代码中使用 .when_pressed 事件。 我模拟了按钮的状态变化,但是没有调用函数。

Device.pin_factory = MockFactory()

def interrupt_Event(channel):
   print("%s puted in the queue", channel)

InputPin.Device.pin_factory.pin(channel)
InputPin.when_pressed  = interrupt_Event

def main():
   try:
        while True:

            time.sleep(1)
                    InputPins[channel].pull=drive_high()
                    time.sleep(0.1) 
                    print("State CHANNEL %s" % channel)
                    print(InputPins[channel].state)
                    InputPins[channel].drive_low()

到现在我都不知道出了什么问题。

【问题讨论】:

    标签: python raspberry-pi gpio gpiozero


    【解决方案1】:

    when_pressed 函数不应有参数(参见 https://gpiozero.readthedocs.io/en/stable/recipes.html 中的 2.7)。

    您可以使用循环定义回调:Creating functions in a loop (使用 channel=channel 强制提前绑定通道值,如下例所示)

    for channel in channels:
        def onpress(channel=channel):
            print("%s puted in the queue", channel)
        InputPins[channel].when_pressed = onpress
    

    【讨论】:

      【解决方案2】:

      我不相信您正在使用 drive_high 和 drive_low 来模拟按钮按下。 我有一个几乎相同的问题。在windows上使用Mock pin开发Pi程序,发现没有调用回调例程。

      from gpiozero.pins.mock import MockFactory
      from gpiozero import Device, Button, LED
      from time import sleep
      
      Device.pin_factory = MockFactory()  # set default pin 
      factory
      
      btn = Button(16)
      
      # Get a reference to mock pin 16 (used by the button)
      btn_pin = Device.pin_factory.pin(16)
      
      def pressed():       #  callback 
          print('pressed')
      
      def released():       #  callback 
          print('released')    
      
      btn.when_pressed  = pressed  
      btn.when_released = released  # callback routine
      
      for i in range(3):           # now try to signal sensor
          print('pushing the button')
          btn_pin.drive_high
          sleep(0.1)
          btn_pin.drive_low
          sleep(0.2)
      

      输出没有回调,只是

      pushing the button
      
      pushing the button
      
      pushing the button
      >>> 
      

      【讨论】:

      • 你没有打电话drive_high()drive_low(),那么他们当然什么也没做。
      猜你喜欢
      • 2019-06-01
      • 2021-05-29
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多