在Python中运行Raspberry Pi GPIO事件后,如何在特定时间段内禁用它? [英] How to disable Raspberry Pi GPIO event for certain time period after it runs in Python?

查看:137
本文介绍了在Python中运行Raspberry Pi GPIO事件后,如何在特定时间段内禁用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只要Raspberry Pi的GPIO引脚出现下降沿,我就会创建一个事件。但是,我想在每次运行后一定时间(例如5秒)内禁用此事件。我希望在该时间段后再次启用该事件。

I am creating an event whenever my Raspberry Pi's GPIO pin has a falling edge. However, I want to disable this event for a certain amount of time (5 seconds for example) after each time it runs. I want the event to be enabled again after that time period.

我的第一个想法只是在实际事件函数中使用 sleep(5)。但是我认为由于事件是在单独的线程中运行而无法实现。

My first thought was just to use sleep(5) within the actual event function. But I believe this will not work due to the event being ran in a separate thread.

有人能指出我正确的方向吗?这并不像我想象的那么简单。

Can anyone point me in the right direction to what I am trying to accomplish? This is not as straightforward as I imagined it would be.

import RPi.GPIO as GPIO                   
import time
from time import sleep

# wait 1 second at startup
sleep(1)

# event function
def event(ev=None):
        print("Event was triggered! Should not run again for 5 seconds.")
        # sleep(5)

# initialize GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# setup the pin and the event
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(21, GPIO.FALLING, callback=event)



while 1:
        continue


推荐答案

有一个开关弹跳效果,当我们使用只有两个触点连接到GPIO的简单廉价按钮时就会发生。

There is a switch bounce effect which happens when we use simple cheap buttons with just two contacts connected to GPIO.

在新闻发布期间,压抑大量类似的东西

During the press and depress alot of analogue stuff happens which do not belong to digital domain.

有两种方法可以解决这些反弹问题:

There are two ways to solve those bounces :


  • 硬件方式(添加RC过滤器)

  • 软件方式-等待一段时间以过滤掉这些模拟世界效果(这可能是虚拟延迟,状态使用机器,临时禁用中断)

Fortunaly python GPIO库支持用于反跳的软件实现。

Fortunaly python GPIO library supports software implementation for debouncing.

当您为此类中断定义回调时,可以指定侦听器对指定引脚上的任何更改充耳不闻的时间。

When you define callback for such "interrupt" you can specify the time for which listener go deaf to any changes on specified pin.

是否使用不良(嘈杂)按钮并不重要。
您可以使用此反跳内置函数来实现所需的功能:

It does not really matter whether you use "bad"( noisy) button or not. You can use this debouncing built-in function to achieve what you need:

GPIO.add_event_detect(21, GPIO.FALLING, callback=event, bouncetime=5000 )

这篇关于在Python中运行Raspberry Pi GPIO事件后,如何在特定时间段内禁用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆