模拟gpiozero中的“按下按钮”事件

时间:2019-10-08 13:19:42

标签: python raspberry-pi gpio gpiozero

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

到目前为止,我不知道出什么问题了。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我不认为您使用drive_high和drive_low模拟按钮按下。 我有一个几乎相同的问题。使用Mock引脚在Windows上开发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
>>>