szaske
szaske

Reputation: 2027

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()

Upvotes: 5

Views: 4880

Answers (3)

Ridhwan Luthra
Ridhwan Luthra

Reputation: 121

Like what @DanGoodrick mentioned you need to add bouncetime but it needs to be greater than how long your callback takes to complete its compute.

eg. if your callback takes 1 second to exit your bouncetime needs to be more than that, so maybe like 1.5 seconds.
GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=Light bouncetime=1500)

Upvotes: 1

DanGoodrick
DanGoodrick

Reputation: 3208

Try adding a debounce value to your event detection call. The units are milliseconds.

GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=Light, bouncetime = 250) 

Upvotes: 3

szaske
szaske

Reputation: 2027

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.

Upvotes: 2

Related Questions