andrewm@268: #!/bin/bash andrewm@268: # andrewm@268: # shutdown_switch.sh: script for gracefully halting the BeagleBone Black andrewm@268: # when an onboard button is pressed. andrewm@268: # andrewm@268: # (c) 2016 Andrew McPherson, C4DM, QMUL andrewm@268: # Developed for Bela: http://bela.io andrewm@268: andrewm@268: andrewm@268: # Prepare P9.27 as input (will be configured with pullup) andrewm@268: # via BB-BONE-PRU-BELA overlay andrewm@268: andrewm@268: BUTTON_PIN=115 andrewm@268: andrewm@268: echo $BUTTON_PIN > /sys/class/gpio/export andrewm@268: echo in > /sys/class/gpio/gpio"$BUTTON_PIN"/direction andrewm@268: andrewm@268: if [ ! -r /sys/class/gpio/gpio"$BUTTON_PIN"/value ] andrewm@268: then andrewm@268: echo "$(basename $0): Unable to read GPIO pin $BUTTON_PIN for shutdown button." andrewm@268: exit andrewm@268: fi andrewm@268: andrewm@268: # First, wait for pin to go high. If it starts at 0, that's more andrewm@268: # likely that the GPIO is not set correctly, so do not treat this andrewm@268: # as a button press andrewm@268: andrewm@268: while [ $(cat /sys/class/gpio/gpio"$BUTTON_PIN"/value) -ne 1 ]; do andrewm@268: # Keep checking pin is readable in case it gets unexported andrewm@268: if [ ! -r /sys/class/gpio/gpio"$BUTTON_PIN"/value ] andrewm@268: then andrewm@268: echo "$(basename $0): Unable to read GPIO pin $BUTTON_PIN for shutdown button." andrewm@268: exit andrewm@268: fi andrewm@268: sleep 0.5 andrewm@268: done andrewm@268: andrewm@268: # Now for button press. Make sure the button is held at least andrewm@268: # 1 second before shutting down andrewm@268: andrewm@268: PRESS_COUNT=0 andrewm@268: andrewm@268: while true; do andrewm@268: # Keep checking pin is readable in case it gets unexported andrewm@268: if [ ! -r /sys/class/gpio/gpio"$BUTTON_PIN"/value ] andrewm@268: then andrewm@268: echo "$(basename $0): Unable to read GPIO pin $BUTTON_PIN for shutdown button." andrewm@268: exit andrewm@268: fi andrewm@268: andrewm@268: # Button pressed? (pressed = low) andrewm@268: if [ $(cat /sys/class/gpio/gpio"$BUTTON_PIN"/value) -eq 0 ] andrewm@268: then andrewm@268: PRESS_COUNT=$((PRESS_COUNT+1)) andrewm@268: if [ "$PRESS_COUNT" -ge 4 ] andrewm@268: then andrewm@268: echo "$(basename $0): Shutdown button pressed. Halting system..." andrewm@268: halt andrewm@268: exit 1 andrewm@268: fi andrewm@268: else andrewm@268: PRESS_COUNT=0 andrewm@268: fi andrewm@268: sleep 0.5 andrewm@268: done