3

I use this to detect momentary button (connected to GPIO) press :

import RPi.GPIO as GPIO  
GPIO.setmode(GPIO.BCM)  
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)  

def my_callback(channel):  
    print channel

GPIO.add_event_detect(18, GPIO.RISING, callback=my_callback, bouncetime=300)  

raw_input()

Even with the debouncing thanks to bouncetime=300, I often get 2 messages instead of just 1 for a single button press.

How to detect properly one button press ?

Jacobm001
  • 11,904
  • 7
  • 47
  • 58
Basj
  • 800
  • 3
  • 21
  • 49

2 Answers2

2

I hope it's not too late to answer your question; I encountered the same issue and wanted to post the solution I found! What I did was using the buttons and switches introduction on the official Raspberry site and their workaround.

It doesn't use add_event_detect but defines a function (called BtnCheck). What I use looks like this:

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

# setup everything
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)
count = 0
prev_inp = 1

# define a function that checks for buttons pressed. The heart of the answer...
def BtnCheck(PinNr):
    global prev_inp
    global count

    inp = GPIO.input(PinNr)
    if ((not prev_inp) and inp):
        count = count + 1
        print "Button pressed"
        print count
    rev_inp = inp
    time.sleep(0.05)

try:
    while True:
        BtnCheck(12)
except KeyboardInterrupt:
    GPIO.cleanup()
Jacobm001
  • 11,904
  • 7
  • 47
  • 58
David
  • 233
  • 1
  • 3
  • 10
-4

I would suggest you use pygame libraries and detect a key press event. It works....

ketan
  • 1