0

I have a Raspberry Pi 4 (running retropie) that I am trying to get a shutdown button to work. I have a momentary switch wired to GPIO pins 5 and 6.

I have a python script:

import RPi.GPIO as GPIO
import time
import subprocess
from threading import Timer

SHUTDOWN_HOLD_TIME =3 # Time in seconds that power button must be held
SHUTDOWN_PIN = 5 # Pin to trigger shutdown, pin 5 will also start up the pi when it's off

# GPIO.BOARD means use pin numbering to matching the pins on the Pi, instead of the
# CPU's actual pin numbering (makes it easier to keep track of things)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(SHUTDOWN_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)

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

GPIO.cleanup()
subprocess.call("shutdown -h now", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

This doesn't seem to work. I test it by running it via SSH and it returned this message:

Traceback (most recent call last):
  File "shutdown.py", line 1, in <module>
    import RPi.GPIO as GPIO
RuntimeError: This module can only be run on a Raspberry Pi!

I made sure I had the latest Python3 and GPIO and yet still not working. Any help would be greatly appreciated!

Vishera
  • 127
  • 1
  • 1
  • 8
  • Did you run it as root? (with `sudo`) – Klaus D. Apr 29 '21 at 05:49
  • As an aside, you want to switch to `subprocess.call(["shutdown", "-h", "now"])` without `shell=True`; and if you are not reading anything from the pipes, I don't see why you add `stdout=subprocess.PIPE` and `stderr=subprocess.PIPE`. See also https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess – tripleee Apr 29 '21 at 06:29
  • Might you be seeing this rpi4 related issue, which was patched in as yet unreleased 0.7.1a4? https://sourceforge.net/p/raspberry-gpio-python/tickets/191/ – user650881 Apr 29 '21 at 07:36
  • I have been using sudo yes. I'll rework the subprocess and give that a shot – Vishera Apr 29 '21 at 12:00

1 Answers1

0

Found a quick and simple working solution! config.txt, add the following:

#shutdown with button script
dtoverlay=gpio-shutdown

and it works, it's that simple! Now to figure out how to do a hard reset button for just in case!

Vishera
  • 127
  • 1
  • 1
  • 8