pythonraspberry-piraspberry-pi2gpio

Push button GPIO.FALLING event getting triggered twice


This is my first attempt at coding a Raspberry Pi and a hardware push button on a breadboard. The program is simple, when a button press is detected, turn on an LED on the breadboard for 1 second. My code seems to work, but strangely every so often one button push triggers the callback function twice. I'm a total programming noob, so I'm not sure if the problem is with my code, or if the HW or button is somehow actually falling twice. I'm hoping someone here can help me troubleshoot this strangeness. Here is my code:

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time


LedPin = 11    # pin11 --- led
BtnPin = 12    # pin12 --- button

def setup():
    GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
    GPIO.setup(LedPin, GPIO.OUT)   # Set LedPin's mode is output
    GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)    # Set BtnPin's mode is input, and pull up to high level(3.3V)
    GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led

def Light(ev=None):
        print 'A button press was detected'
        GPIO.output(LedPin, 0)  # switch led status on
        time.sleep(1)
        GPIO.output(LedPin, 1)  # switch led status off

def loop():
    GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=Light) # wait for Button Press (GPIO Falling)
    while True:
        pass   # Don't do anything, sit forever 

def destroy():
        GPIO.output(LedPin, GPIO.HIGH)     # led off
        GPIO.cleanup()                     # Release resource

if __name__ == '__main__':     # Program start from here
    setup()
    try:
        loop()
    except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
        destroy()

Solution

  • I found a solution. Using the code here, solved my problem.

    If you're like me, and getting random duplicate button press events when using GPIO.add_event_detect, try the linked code instead.