Sunday, May 15, 2016

Adding shutdown button to UDOO

By default, the PWb button on UDOO is for waking up the board after a proper shutdown (use the reset button instead).  It cannot be used to shutdown Linux. But we could implement a shutdown button by using one of the GPIO pins.

First, the physical connection.  We will be connecting a GPIO pin to a push button.  In this example we will be using GPIO42, which is pin 7 on UDOO.  A 10K resistor is used as pull-up resistor.



Then we need to enable and monitor the GPIO pin in Linux. I am using Arch Linux but it should be similar for other flavor of Linux.  The script to do it:

#!/bin/sh

GPIO=42

echo $GPIO > /sys/class/gpio/export
echo in > /sys/class/gpio/gpio$GPIO/direction

while true; do
 value=`cat /sys/class/gpio/gpio$GPIO/value`
 if [ "$value" = "0" ]
 then
   echo "Shutdown button pressed"
   /usr/bin/sync; /usr/bin/sync; /usr/bin/shutdown -h now
 fi
 sleep 2
done


Some explanations of the script.  With kernel GPIO Sysfs, we need to specify which pin we will be using by writing the GPIO number (42 here) to /sys/class/gpio/export.  Since we will be reading from the pin, we also write "in" to the /sys/class/gpio/gpioXX/direction.

Then the script will enter an infinite loop to monitor if the GPIO value is 0 (i.e. push button is pressed).  If so, it will sync the disks and shutdown the system.

This polling method is less efficient than an event trigger approach. But that will be another exercise. :P

Save this script (e.g. /root/scripts/pwrbtncheck/pwrbtncheck.sh) and we will tell systemd to run it every time the board is booted.

Create a file named pwrbtncheck.service in /etc/systemd/system:

[Unit]
Description=Power button check

[Service]
ExecStart=/root/scripts/pwrbtncheck/pwrbtncheck.sh > /dev/null 2>&1 &

[Install]
WantedBy=multi-user.target


Then enable it by running this command:

sudo systemctl enable pwrbtncheck.service



2 comments:

nereus said...

Hi, why is it not possible to use this button for shutdowns?

nereus said...

Hi, why is it not possible to use this button for shutdowns?