Skip to main content
  1. Posts/

Raspberry Pi Pulling the Plug

<time datetime="2013-11-28 00:00:00 &#43;0000 UTC">28 November 2013</time><span class="px-2 text-primary-500">&middot;</span><span>421 words</span>
Table of Contents

While browsing for different breakout boards for the Rover I’ve discovered a nice little board that has a push button and logic pin to control a MOSFET.
This little contraption allows switching on and off the power, say through a USB cable.

Below is what I did to make the Raspberry Pi switch itself off completely on system shutdown.

Hardware #

The hardware itself is very simple. I’ve taken the the Pololu Pushbutton Power Switch and connected it to a standard MicroUSB cable.

Pololu Pushbutton Power Switch
The Pololu Pushbutton Power Switch

I’ve only taken the V+ and GND cables (red and black) from the cable and connected them to the respective pins on the board.

Also I’ve connected the “Power Off” pin on the board to a GPIO pin (GPIO25) on the Raspberry Pi.

Pressing the switch toggles the power on and off, as expected. Putting a “high” signal on the “Power Off” pin (i.e. GPIO25), turns the power off as well.

Software #

The software part is also simple. GPIO is exposed through the Linux kernel via the /sys filesystem.
In order to make the GPIO pin writable and set it to “high”, the following sequence of shell commands is necessary:

# you need to be root to execute this.
echo 25 > /sys/class/gpio/export             # Activate GPIO25. This will create the /sys/class/gpio/gpio25 device.
echo out > /sys/class/gpio/gpio25/direction  # Setting GPIO25 to output (i.e. controlling, not reading)
echo 1 > /sys/class/gpio/gpio25/value        # Set the output value of GPIO25 to 1 (="high")

Executing this will shut down the Pi immediately as it cuts the power. Be careful.

I’ve checked what is called when Linux is shutting down, i.e. when it reaches runlevel 0.
The files for this are in /etc/rc0.d/ on a standard Debian/Raspbian/Raspbmc Linux installation.
The file called last is a command called “halt”, which is softlinked from /etc/init.d/halt.

This file contains a shutdown command, including potential power-off when that is requested for the shutdown. I’m hooking into there and shortly before the “halt” command would be triggered and a full power-off is requested, I execute the few lines above.

The section looks something like the following:

# [...]

    if [ "$poweroff" = "-p"]
        log_action_msg "Shutting down via GPIO"
        echo 25 > /sys/class/gpio/export
        echo out > /sys/class/gpio/gpio25/direction
        echo 1 > /sys/class/gpio/gpio25/value

    log_action_msg "Will now halt"
    halt -d -f $netdown $poweroff $hddown

# [...]

Like that reboots still work without cutting power. When requesting a shutdown, e.g. via XBMC, the Raspberry Pi shuts down all processes and pulls the plug when it’s ready.