首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在gpiozero中模拟“按钮被按下”上升事件

在gpiozero中模拟“按钮被按下”上升事件
EN

Stack Overflow用户
提问于 2019-10-08 21:19:42
回答 2查看 617关注 0票数 2

我尝试在没有GPIO的机器上开发一些代码。作为GPIO库,我选择了gpiozero,这样就可以在不访问raspberry pi的gpio的情况下编写代码。我的问题是,我不能在代码中使用.when_pressed事件。我模拟了按钮的状态改变,但是函数没有被调用。

代码语言:javascript
复制
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()

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-13 00:55:44

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

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

代码语言:javascript
复制
for channel in channels:
    def onpress(channel=channel):
        print("%s puted in the queue", channel)
    InputPins[channel].when_pressed = onpress
票数 1
EN

Stack Overflow用户

发布于 2019-12-03 02:03:59

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

代码语言:javascript
复制
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)

输出没有回调,只是

代码语言:javascript
复制
pushing the button

pushing the button

pushing the button
>>> 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58287200

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档