RPiKids | Raspberry Pi Shutdown via Arduino

Arduino Sketch

Gracefully shutting down a Raspberry Pi has been covered in many posts. There are many solutions but none seemed to meet my requirements.

  • Full power off – Low power consumption when not being used
  • Switch Multiple Sources – Simultaneous power switching for Pi a small amplifier running at different operation voltages
  • Parental Controls implemented at the hardware level

My basic approach was sparked a post found here. I will be using a Raspberry Pi2 and an Arduino Uno.

Adding no additional hardware you can create  a USB serial link between the Pi and the Uno. This is possible because the Uno implements a serial port firmware uploading. Using the serial link the Pi2 can listen for the Arduino’s shut down command and issue a safe shut down.

GOTCHA – The Arduino Uno’s serial port wants to “auto reset” during serial port initialization so I needed to put a 10uF capacitor between the GND and RESET pin to disable reset.

The Arduino sketch can be found here

Here is my Hardware schematic. The two relay coils are shown on the left, but the relay contacts are not. I simply used the normally open contacts to switch the power supply for the Pi and the audio amplifier.

Powering ON

  1. Everything is powered OFF, the Arduino is polling for the encoder button to be depressed
  2. Power button is pressed, the Arduino will wake up and assert the appropriate GPIO lines to close the relay and power up the Pi and audio amplifier

Powering OFF

  1.  Everything is powered ON, the Pi has a Python daemon program running in the background, awaiting input from the Arduino.
  2. Power Button is pressed, the Arduino issues a serial command to the Pi, notifying it to shut down.
  3. The Pi issues the shut down command
  4. NOW the Arduino can wait for a safe amount of time before opening the relay and disconnecting power
  5. The Arduino waits for some more user input

The Arduino sketch (available at the top of this page) basically has one line when the encoder button is pressed:

Serial.println("shutdown");

A simple python daemon /home/pi/pwrd/pwrd.py

import serial
import os

ser = serial.Serial('/dev/ttyACM0', 9600)

while 1 :
   line = ser.readline()
   if line == 'shutdownrn':
      os.system("sudo shutdown -h now")

Create a /etc/init.d/pwrd to launch on start up
case "$1" in
  start)
    echo "Starting pwrd.py"
    # run application you want to start
    python /home/pi/pwrd/pwrd.py &
    ;;
  stop)
    # kill application you want to stop
    ;;
  *)
    echo "Usage: /home/pi/pwrd/pwrd.py {start|stop}"
    exit 1
    ;;
esac

exit 0

Make /etc/init.d/pwrd executable:

sudo chmod 755 /etc/init.d/pwrd

 

Register script to be run at start-up:

sudo update-rc.d /etc/init.d/pwrd defaults