Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

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

This comment has been minimized.

Owner

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