How to disable Raspberry Pi GPIO event for certain time period after it runs in Python?

吃可爱长大的小学妹 提交于 2020-05-15 08:39:12

问题


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.

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

回答1:


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 :

  • hardware way (adding RC filters)
  • software way - wait for some time to filter out those analogue world effects (this could be "dummy delay", "usage of state machines", "temporary disable interrupt")

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 )


来源:https://stackoverflow.com/questions/61515521/how-to-disable-raspberry-pi-gpio-event-for-certain-time-period-after-it-runs-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!