3

I have a python script working that will shutdown the raspberry pi when I close a momentary switch, using the RPi.GPIO interrupts. However as soon as the switch is closed the pi shuts down. Is there a way to program in a time function i.e. only shutdown the pi with the momentary switch is closed for 2 seconds? I am trying to avoid accidental bumps of the shutdown switch.

Thanks!

Here is my script:

import subprocess
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.wait_for_edge(17, GPIO.FALLING)
subprocess.call(['shutdown -h now "System halted by GPIO action"'], shell=True)
GPIO.cleanup()
3

You could try something like this:

buttonReleased = True
while buttonReleased:
    GPIO.wait_for_edge(17, GPIO.FALLING)
    # button has been pressed
    buttonReleased = False
    for i in range(20):
        time.sleep(0.1)
        if GPIO.input(17):
            buttonReleased = True
            break

GPIO.cleanup()
subprocess.call(...
3
  • This will shut down the system if the button is pressed for more than 0.1second, not 2 seconds. If you put the buttonReleased = True after the for loop, it should only trigger if button is pressed for at least 2 seconds.
    – Gerben
    Feb 21 '14 at 14:30
  • 1
    No, if it's pressed for less than 2 seconds and then released, it goes back to waiting for the falling edge. Bonus is that it doesn't get fooled by two presses 2 seconds apart.
    – francis
    Feb 21 '14 at 14:52
  • Sorry. I stand corrected. :-)
    – Gerben
    Feb 21 '14 at 20:05
0
import time
import subprocess
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
  GPIO.wait_for_edge(17, GPIO.FALLING)
  time.sleep(2)
  if GPIO.input(17)==False:
    subprocess.call(['shutdown -h now "System halted by GPIO action"'], shell=True)
    break

GPIO.cleanup()

Somewhat crude version that only check is the button is still pressed after 2 seconds.

2
  • I don't think it will like doing a GPIO.wait_for_edge after the GPIO.cleanup(). Of course the system is shutting down anyway so I guess it wouldn't matter too much!
    – francis
    Feb 21 '14 at 13:40
  • True. See edit above.
    – Gerben
    Feb 21 '14 at 14:21

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.