What I'm trying to achieve is to use GPIO pin 5 (BCM) on my raspberry pi b+ to receive input from a momentary switch and in response take specified actions.
The actions will differ based on how long the momentary switch is held for.
I was using a piece of code that monitored the pull up pin for interrupts and when detected toggled a different GPIO pin set as an output.
Now I'm trying to do more....and it is not working very well.
I'm trying to use this:
import os
import RPi.GPIO as GPIO
import webiopi
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
BUTTON_5 = 5
GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(12,GPIO.OUT)
GPIO.output(12,1)
def system_action(BUTTON_5):
print('Button press = negative edge detected on channel %s'%BUTTON_5)
button_press_timer = 0
while True:
if (GPIO.input(5) == False) : # if button is pressed down
button_press_timer += 1 # count seconds until button is released
else: # button is released, figure out for how long
if (button_press_timer > 7) : # pressed for > 7 seconds
subprocess.call(['shutdown -r now "System halted by GPIO action" &'], shell=True)
elif (button_press_timer > 1) : # press for > 1 < 7 seconds
GPIO.output(12, not GPIO.input(12))
button_press_timer = 0
time.sleep(1)
GPIO.add_event_detect(BUTTON_5, GPIO.FALLING,callback=system_action(BUTTON_5), bouncetime=200)
while True:
time.sleep (2)
I've tried a few similar variations without any success.
I think this version is the closest I've come.
To elaborate, the goal is to have a momentary switch attached to a pin as a pull up resistor.
The the button is pressed for anything more than one second up to anyhting less than seven seconds it toggles the state of an output pin.
When the button is pressed for seven or more seconds it will reboot the pi.
The code runs without error but when I interact with the button I have wired up.....nothing happens.
What have I missed here? What have I done wrong? What have I done right and what could I do differently.
Any and all help/feedback is appreciated.
I am new to coding and am trying hard to teach myself with practical projects.
datetime.now()
to get a timestamp, do that in both events (let's say you use variablest1
andt2
) and then compare the two by doingt2 - t1
to get the elapsed time. – Phil B. Sep 30 '15 at 14:53