2

我尝试在没有 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()

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

4

2 回答 2

1

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

您可以使用循环定义回调:在循环中创建函数 (使用 channel=channel 强制提前绑定通道值,如下例所示)

for channel in channels:
    def onpress(channel=channel):
        print("%s puted in the queue", channel)
    InputPins[channel].when_pressed = onpress
于 2019-10-12T16:55:43.513 回答
0

我不相信您正在使用 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
>>> 
于 2019-12-02T18:03:58.877 回答