Button to shutdown the Raspberry Pi 3B+

The 3B+ behaves a little differently. The LEDs are, by default, controlled by the kernel. There are device drivers for them. This is a new script to enable an added momentary action button to control the LEDs and shutdown the Pi 3B+

#!/usr/bin/env python3
from gpiozero import Button
from signal import pause
import warnings, os, sys

# Script to process a button press on the GPIO of a Raspberry Pi 3B+
# and alter the LEDs of the device according to:
#
# Press and release, toggle the LEDs off, or default, depending.
# Press and hold, for 6 seconds, shutdown the Pi.
# Note the Pi 3B+ is controlled from kernel devices, not direct from the GPIO
# unless you wish to.
#
# Add to /etc/rc.local
# For example
#
# ~pi/shutdown_pi.py 21 6 1  

offGPIO = int(sys.argv[1]) if len(sys.argv) >= 2 else 21
offtime = int(sys.argv[2]) if len(sys.argv) >= 3 else 6
defaultOff = True if len(sys.argv) >= 4 else False

mintime=1

powerLedDev = "/sys/class/leds/led1/"
activityLedDev = "/sys/class/leds/led0/"

powerLedDefAction = "default-on"
activityLedDefAction = "mmc0"

powerLedNewAction = powerLedDefAction
activityLedNewAction = activityLedDefAction

def ledSet(led, item, value):
    f = open(led + item, "w+")
    f.write(value)
    f.close()

def LEDsOff():
    ledSet(powerLedDev, "trigger", "none")
    ledSet(activityLedDev, "trigger", "none")

def when_held(b):
    p = b.pressed_time

    #timer_val = "{0:.0f}".format(500/p)
    timer_val = int(500/p)
    os.system("echo timer > " + powerLedDev + "trigger")

    ledSet(powerLedDev, "delay_on", str(timer_val))
    ledSet(powerLedDev, "delay_off", str(timer_val))

    if p > offtime:
        ledSet(powerLedDev, "trigger", "none")
        ledSet(activityLedDev, "trigger", activityLedDefAction)
        os.system("/sbin/shutdown -h now")

def when_pressed():
    global powerLedNewAction
    global activityLedNewAction

    if powerLedNewAction == powerLedDefAction:
        powerLedNewAction = "none"
        activityLedNewAction = "none"
    else:
        powerLedNewAction = powerLedDefAction
        activityLedNewAction = activityLedDefAction

    LEDsOff()

def when_released():
    ledSet(powerLedDev, "trigger", powerLedNewAction)
    ledSet(activityLedDev, "trigger", activityLedNewAction)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")

if defaultOff:
    LEDsOff()

btn = Button(offGPIO, hold_time=mintime, hold_repeat=True)
btn.when_held = when_held
btn.when_pressed = when_pressed
btn.when_released = when_released
pause()

 

Sharing...