Skip to main content
 首页 » 编程设计

python之在 gpiozero 中模拟 "button pressed"上升事件

2024年11月01日1252php

我尝试在没有 GPIO 的机器上开发一些代码。作为 GPIO 库,我选择了一个 gpiozero 来编写我的代码而无需访问 raspberry pi 的 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() 

到现在我都不知道哪里出了问题。

请您参考如下方法:

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

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

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