Skip to content

Instantly share code, notes, and snippets.

@dbrgn
Created June 29, 2018 09:34
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dbrgn/bfad33a3fed5a1e4b06c6a58080c3827 to your computer and use it in GitHub Desktop.
Example: Shutdown script for iC880A backplane
#!/usr/bin/env python3
import os
import sys
import time
import RPi.GPIO as g
print('Initializing...')
# Pins
LED_R = 36
LED_Y = 38
LED_B = 40
BTN = 32
# Set up GPIO
g.setmode(g.BOARD)
g.setup(LED_R, g.OUT)
g.setup(LED_Y, g.OUT)
g.setup(LED_B, g.OUT)
g.setup(BTN, g.IN, pull_up_down=g.PUD_UP)
print('Waiting for button...')
try:
g.wait_for_edge(BTN, g.FALLING)
except KeyboardInterrupt:
print('Aborted.')
g.cleanup()
sys.exit(0)
g.remove_event_detect(BTN)
g.output(LED_R, g.HIGH)
g.output(LED_Y, g.HIGH)
g.output(LED_B, g.HIGH)
print('Shutting down in 12 seconds... Press the button again to abort.')
def abort(channel):
print('Aborted.')
for _ in range(6):
g.output(LED_R, g.HIGH)
g.output(LED_Y, g.HIGH)
g.output(LED_B, g.HIGH)
time.sleep(0.05)
g.output(LED_R, g.LOW)
g.output(LED_Y, g.LOW)
g.output(LED_B, g.LOW)
time.sleep(0.05)
g.cleanup()
sys.exit(0)
def blink(led, seconds):
for _ in range(seconds):
g.output(led, g.LOW)
time.sleep(0.5)
g.output(led, g.HIGH)
time.sleep(0.5)
g.add_event_detect(BTN, g.FALLING, callback=abort, bouncetime=200)
blink(LED_B, 4)
blink(LED_Y, 4)
blink(LED_R, 4)
print('Shutdown')
os.system('sudo shutdown now')
[Unit]
Description=Button shutdown
ConditionPathExists=|/usr/local/bin
After=network.target
[Service]
User=root
ExecStart=/usr/bin/env python3 -u /usr/local/bin/button-shutdown.py
RestartSec=2
Restart=always
[Install]
WantedBy=multi-user.target
@soubinet
Copy link

soubinet commented Aug 25, 2018

Hello,

To help people (like me) whom have an error with RPi.GPio not Found, you can install GPio with the line below :
sudo apt-get -y install python3-rpi.gpio

Hope it will help somebody !

@dbrgn
Copy link
Author

dbrgn commented Aug 25, 2018

To install this script, copy the Python script to /usr/local/bin/button-shutdown.py and the service file to /etc/systemd/system/button-shutdown.service.

Then, reload systemd (or alternatively reboot the Raspberry Pi):

sudo systemctl daemon-reload

Now you can start and enable (=autostart) the service:

sudo systemctl enable button-shutdown
sudo systemctl start button-shutdown

To see the current status of the service, type:

sudo systemctl status button-shutdown

To see the logs:

sudo journalctl -u button-shutdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment