I have the following script I used for testing:
#!/usr/bin/env python2.7
import RPi.GPIO as GPIO, time, subprocess, threading, socket, signal
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
button=21
led=19
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(led, GPIO.OUT)
GPIO.output(led,True)
def buttonpressed(channel):
if GPIO.input(button):
GPIO.output(led,True)
print "rising edge detected on " + str(button)
else:
GPIO.output(led,False)
print "falling edge detected on " + str(button)
# when a falling edge is detected on button, regardless of whatever
# else is happening in the program, the function my_callback will be run
GPIO.add_event_detect(button, GPIO.BOTH, callback=buttonpressed, bouncetime=200)
print "Waiting for button to be pressed"
while True:
try:
time.sleep(3600)
print "still waiting for button..."
except KeyboardInterrupt:
print "Exption caught after timer."
if killer.kill_now:
break
GPIO.cleanup() # clean up GPIO on normal exit
simulate this circuit – Schematic created using CircuitLab
Using an NO button on testing only the first button press is reliably sensed, but occasionally other presses are. Sample output:
$ ./test.py
Waiting for button to be pressed
falling edge detected on 21
rising edge detected on 21
rising edge detected on 21
rising edge detected on 21
rising edge detected on 21
rising edge detected on 21
rising edge detected on 21
rising edge detected on 21
rising edge detected on 21
rising edge detected on 21
falling edge detected on 21
rising edge detected on 21
rising edge detected on 21
rising edge detected on 21
rising edge detected on 21
rising edge detected on 21
If I remove the bouncetime I get a lot of false positives, and if I put it to 1ms it is relatively reliable but still not great.
As it seems to be clear that I need to put a capacitor in place is there any alternative to adding this, and if not what size of capacitor should I need? Are there any other attributes I should be mindful of when shopping for a capacitor?