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.9k7 gold badges48 silver badges58 bronze badges
asked Mar 24, 2015 at 0:00

2 Answers 2

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.9k7 gold badges48 silver badges58 bronze badges
answered Dec 30, 2015 at 18:40
1
  • 1
    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. Commented Mar 5, 2018 at 2:37
-4

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

answered Mar 24, 2015 at 3:21
1
  • 2
    How would one do that? And what is the benefit of using pygame before other means of accomplishing this? Commented Mar 24, 2015 at 10:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.