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:
echo $GPIO > /sys/class/gpio/export
echo in > /sys/class/gpio/gpio$GPIO/direction
while true; do
if [ "$value" = "0" ]
echo "Shutdown button pressed"
/usr/bin/sync; /usr/bin/sync; /usr/bin/shutdown -h now
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:
Description=Power button check
ExecStart=/root/scripts/pwrbtncheck/pwrbtncheck.sh > /dev/null 2>&1 &
Then enable it by running this command:
sudo systemctl enable pwrbtncheck.service