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

查看:36
本文介绍了在 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天全站免登陆