Search code examples
pythonraspberry-pi3gpio

RPi.GPIO.wait_for_edge(4, GPIO.FALLING) detects both press and release of button


I've read the documentation for RPi.GPIO, and searched Google as well as SO, but can't quite find a solution to what is probably a very dumb problem. I'm trying to ONLY detect the edge of my button being pressed. But regardless of whether I specify to look for a "falling" or "rising" edge, the Pi will execute a command on both press and release of my button. Sometimes it executes the code a bunch of times. My code:

import RPi.GPIO as GPIO

buttonPin = 4                 # this is the pin for the button
GPIO.setmode(GPIO.BCM)                 # pinmode
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)                 #setting up my pin to be input w/ pullup resistor

if __name__ == '__main__':
    while True:                 # loop
        GPIO.wait_for_edge(buttonPin,GPIO.RISING)                 # looking for a rising edge
        print('Edge detected')                 # this happens regardless of my button being pressed or released

Quite sure I'm missing something fundamental here, any help greatly appreciated.


Solution

  • You can solve it programmatically with parameter bouncetime but, you have to use

    GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback, bouncetime=200)

    or

    GPIO.add_event_callback(channel, my_callback, bouncetime=200)

    instead of GPIO.wait_for_edge(channel,GPIO.RISING)

    or with additional hardware: add a 0.1uF capacitor across your switch,

    or you can use combination of both.

    More in Documentation

    Peace