2

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 ?

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()
  • This isn't particularly helpful in that one is probably using the event detection functions to avoid this type of looping in the first place. – robo Mar 5 '18 at 2:37
-3

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

  • 2
    How would one do that? And what is the benefit of using pygame before other means of accomplishing this? – Bex Mar 24 '15 at 10:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.