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 Answers 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()
-
1This 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– robo2018年03月05日 02:37:08 +00:00Commented Mar 5, 2018 at 2:37
I would suggest you use pygame libraries and detect a key press event. It works....
-
2How would one do that? And what is the benefit of using pygame before other means of accomplishing this?Bex– Bex2015年03月24日 10:00:14 +00:00Commented Mar 24, 2015 at 10:00