首页 > 解决方案 > GPIO.add_event_detect() 正在检测连续按下错误按钮

问题描述

我的问题是:GPIO.add_event_detect() 在无限循环中连续检测到错误的上升沿并无限运行 call_back 函数(),即使我没有按下连接到 GPIO 25 的按钮一次但是 call_back 函数()继续执行。

这是我的代码,我想在其中调用包含函数 WhatsApp(lat_o,long_o) 的 call_back 函数 x1() 仅在按下按钮但 WhatsApp(lat_o,long_o) 继续执行而无需我按下按钮。此外,我将 WhatsApp(lat_o,long_o) 放入 x1() 以消除将参数传递给 call_back 函数的问题。

#                           INTERRUPTS (NOT WORKING)

# Sample Coordinates
lat_o=33
long_o=72

# Import Libraries
import RPi.GPIO as GPIO
from time import sleep

def x1(channel):
    WhatsApp(lat_o,long_o)

# Configure GPIO of Rpi
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BCM) # Use GPIO pin numbering
button1 = 25 # For WhatsApp

# Setup GPIO for Whatsapp
GPIO.setup(button1, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) # Set GPIO 25 (pin 22) to be an input pin for WhatsApp

# Detect button1-press
GPIO.add_event_detect(button1 ,GPIO.RISING, callback = x1)


try:  
    while True : pass  
except:
    GPIO.cleanup()

请帮忙! 我不想在我的最后一年项目的最终代码中使用轮询(即在 while 循环中使用 if-else)执行 WhatsApp(lat_o,long_o),因为我希望 GPIO 连续检测按钮按下并在此处使用轮询将耗尽了我的 Raspberry Pi 4 的大量电量。

标签: python-3.xeventsinterruptgpioraspberry-pi4

解决方案


根据这个关于raspsberrypi讨论的讨论

上升沿将在大约检测到。1.25V。然而,当电压再次降低且输入电压降至 1.16V 以下时,将开始一系列中断,并持续到电平低于 1.12V。

当出现较慢的上升沿或下降沿时,这一点最为显着,例如,当采取了过度的防去抖动措施时。

这是给定的解决方案

在软件中,我使用另外两种技术来消除错误命中。首先,边缘被系统识别后,我们不知道它是否是我们期望的。通过等待 5 毫秒,然后再次读取输入,但现在使用逻辑电平命令,我们可以确定边缘是否确实是我们所期望的,然后我们避免并丢弃所有其他(错误)边缘。

最后是上升沿的代码

import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BCM)

Input_Sig = 23 # any plain GPIO pin
# if there is no external pull, use the internal one (pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(Input_Sig, GPIO.IN)


def interrupt_service_routine(Input_Sig):
    sleep(0.005) # edge debounce of 5mSec
    # only deal with valid edges
    if GPIO.input(Input_Sig) == 1:
        print("RISING")
    return

# define the event; bountime of 5mSec means that subsequent edges will be ignored for 5mSec
GPIO.add_event_detect(Input_Sig, GPIO.RISING, callback=interrupt_service_routine, bouncetime=5)


def main():

    try:
        while True:
            pass # your code

    except KeyboardInterrupt:
        pass
    finally:
        print("\nRelease the used pin(s)")
        GPIO.cleanup([Input_Sig])


if __name__ == '__main__':
    main()

推荐阅读