Raspberry Pi Safe Reboot and Shutdown Button

Pages
Contributors: bboyho
Favorited Favorite 1

Introduction

Pulling the plug on your Raspberry Pi before it safely shuts down... is a bad idea! This can result in a corrupt microSD card and file system. Normally, we can use the menu bar from the GUI or type a command in the terminal window to safely shutdown the Pi. If you are looking for a quicker solution (especially if you are using a headless setup), have no fear! You can safely reboot or shut down your Raspberry Pi using a general purpose button and a Python script!

Configure the pHAT V2.0 GPIO Button to Safely Reboot and Shutdown Your Raspberry Pi

Required Materials

To follow along with this tutorial, you will need the following materials. You may not need everything though depending on what you have and your setup. Add it to your cart, read through the guide, and adjust the cart as necessary.

Raspberry Pi LCD - 7" Touchscreen

Raspberry Pi LCD - 7" Touchscreen

LCD-13733
$60.00
45
SparkFun Raspberry Pi 4 Basic Kit - 4GB

SparkFun Raspberry Pi 4 Basic Kit - 4GB

KIT-16384
$89.95
4
SparkFun Qwiic pHAT v2.0 for Raspberry Pi

SparkFun Qwiic pHAT v2.0 for Raspberry Pi

DEV-15945
$5.95
1
Multimedia Wireless Keyboard

Multimedia Wireless Keyboard

WIG-14271
$29.95
3

Suggested Reading

We would also recommend taking a look at the following tutorials if you aren't familiar with them.

Raspberry Pi 4 Kit Hookup Guide

March 14, 2020

Guide for hooking up your Raspberry Pi 4 Model B basic, desktop, or hardware starter kit together.

Qwiic pHAT for Raspberry Pi Hookup Guide

May 23, 2019

Get started interfacing your Qwiic enabled boards with your Raspberry Pi. The Qwiic pHAT connects the I2C bus (GND, 3.3V, SDA, and SCL) on your Raspberry Pi to an array of Qwiic connectors.

Serial Terminal Basics

This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.

Raspberry gPIo

How to use either Python or C++ to drive the I/O lines on a Raspberry Pi.

Python Programming Tutorial: Getting Started with the Raspberry Pi

This guide will show you how to write programs on your Raspberry Pi using Python to control hardware.

How to Run a Raspberry Pi Program on Startup

In this tutorial, we look at various methods for running a script or program automatically whenever your Raspberry Pi (or other Linux computer) boots up.

Hardware Hookup

The connection is quick. If you have not already, simply stack the Qwiic pHAT v2.0 on top of your Raspberry Pi's GPIO header. If you are using an enclosure, you may need to have additional pair of stackable headers for a secure connection. The image below shows the pHAT v2.0 connecting to a Pi 3 with the help of stackable headers.

Qwiic pHAT v2.0 stacked on Raspberry Pi

For the scope of this tutorial, we'll using a desktop setup with a monitor, keyboard, and mouse to easily configure your Raspberry Pi. If you have not already, connect the necessary peripherals and power up your Pi!

Example 1: Safe Shutdown

For those familiar with the text based command line, we can shutdown the Pi using the following command.

language:bash
sudo shutdown -h now

The following example loads a Python script at startup and safely shuts down the Raspberry Pi using that command when the button connected to GPIO17 is pressed.

Example Code

On your Raspberry Pi, download the Python script by pressing the button below.

You can also copy the code and paste it in a text editor. Just make sure to name this file as safe_shutdown_Pi.py and remember the location that the file was saved.

language:python
# safe_shutdown_Pi.py
#
# -----------------------------------------------------------------------------
#                 Raspberry Pi Safe Shutdown Python Script
# -----------------------------------------------------------------------------
# WRITTEN BY: Ho Yun "Bobby" Chan
# @ SparkFun Electronics
# DATE: 3/31/2020
#
# Based on code from the following blog and tutorials:
#
#    Kevin Godden
#    https://www.ridgesolutions.ie/index.php/2013/02/22/raspberry-pi-restart-shutdown-your-pi-from-python-code/
#
#    Pete Lewis
#    https://learn.sparkfun.com/tutorials/raspberry-pi-stand-alone-programmer#resources-and-going-further
#
#    Shawn Hymel
#    https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-raspberry-pi/experiment-1-digital-input-and-output
#
# ==================== DESCRIPTION ====================
#
# This python script takes advantage of the Qwiic pHat v2.0's
# built-in general purpose button to safely reboot/shutdown you Pi:
#
#    1.) If you press the button momentarily, the Pi will shutdown.
#
# ========== TUTORIAL ==========
#  For more information on running this script on startup,
#  check out the associated tutorial to adjust your "rc.local" file:
#
#        https://learn.sparkfun.com/tutorials/raspberry-pi-safe-reboot-and-shutdown-button
#
# ========== PRODUCTS THAT USE THIS CODE ==========
#
#   Feel like supporting our work? Buy a board from SparkFun!
#
#        Qwiic pHAT v2.0
#        https://www.sparkfun.com/products/15945
#
#   You can also use any button but you would need to wire it up
#   instead of stacking the pHAT on your Pi.
#
# LICENSE: This code is released under the MIT License (http://opensource.org/licenses/MIT)
#
# Distributed as-is; no warranty is given
#
# -----------------------------------------------------------------------------

import time
import RPi.GPIO as GPIO

# Pin definition
shutdown_pin = 17

# Suppress warnings
GPIO.setwarnings(False)

# Use "GPIO" pin numbering
GPIO.setmode(GPIO.BCM)

# Use built-in internal pullup resistor so the pin is not floating
# if using a momentary push button without a resistor.
#GPIO.setup(shutdown_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Use Qwiic pHAT's pullup resistor so that the pin is not floating
GPIO.setup(shutdown_pin, GPIO.IN)

# modular function to shutdown Pi
def shut_down():
    print "shutting down"
    command = "/usr/bin/sudo /sbin/shutdown -h now"
    import subprocess
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output = process.communicate()[0]
    print output

# Check button if we want to shutdown the Pi safely
while True:

    # For troubleshooting, uncomment this line to output button status on command line
    #print GPIO.input(shutdown_pin)
    if GPIO.input(shutdown_pin)== False:
        shut_down()

Setting Up the Path

This will be saved in your Downloads folder. Once downloaded, you'll need to move the Python script to the /home/pi. To do that, open the command line. Move to the Downloads folder with the following command.

language:bash
cd Downloads

using a command in the terminal to navigate to the downloads

We'll use the mv Linux command to move the file to a certain location (in this case /home/pi) with the following command:

language:bash
mv shutdown_Pi.py /home/pi

using a command in the terminal move python file to a different location

Just to make sure that the file was moved correctly, use the change directory command to move back up a level:

language:bash
cd ..

using a command in the terminal to move to the location of the file that was just moved

Followed by the list command to see what's in the path. If you look closely at the images above, it was used to verify what was in the location. You should notice the shutdown_Pi.py file in the location.

language:bash
ls

verifying that the file is in the correct path in the terminal

Modify rc.local

With the terminal still open, type the following command:

language:bash
sudo nano /etc/rc.local

configuring the rc.local file

Scroll down using the button on your keyboard, and just before the exit 0 line, enter the following:

language:bash
python /home/pi/safe_shutdown_Pi.py &

add the following line in the rc.local file

Save and exit by pressing CTRL + X on your keyboard, followed by y when prompted, and then hit Enter. To ensure that the changes take effect, type the following command.

language:bash
sudo reboot

reboot to ensure the changes are saved

What You Should See

After rebooting, hit the GPIO17 button on the Qwiic pHAT v2.0. This should shutdown the Pi. You'll notice the monitor disconnect if you have one attached but make sure to give it a few more seconds to finish shutting down before removing power. The green status LED on the Pi will stop blinking when it is completely shutdown.

Shutdown Button Safely Safely Turning Off Raspberry Pi

You can now safely remove power from the Pi. To power your Pi again, just insert the power connector back into the Pi.

Power Being Removed After Safely Shutting Down

Example 2: Safe Reboot and Shutdown

Sweet. But what if you wanted more functionality from just one button? How about we add a condition to distinguish between a momentary button press to reboot or when it is pressed for a certain period of time to shutdown? We can reboot the Pi by switching from the halt (-h) to reboot (-r) command.

language:bash
sudo shutdown -r now

The following example loads another Python script on startup. The Raspberry Pi will safely reboot or shutdown with the commands depending on how long we press on the button connected to GPIO17.

Example Code

On your Raspberry Pi, download the Python script by clicking on the button below.

You can also copy the code and paste it in a text editor. Just make sure to name this file as safe_restart_shutdown_Pi.py and remember the location that the file was saved.

language:python
# safe_restart_shutdown_Pi.py
#
# -----------------------------------------------------------------------------
#                 Raspberry Pi Safe Restart and Shutdown Python Script
# -----------------------------------------------------------------------------
# WRITTEN BY: Ho Yun "Bobby" Chan
# @ SparkFun Electronics
# DATE: 3/31/2020
#
# Based on code from the following blog and tutorials:
#
#    Kevin Godden
#    https://www.ridgesolutions.ie/index.php/2013/02/22/raspberry-pi-restart-shutdown-your-pi-from-python-code/
#
#    Pete Lewis
#    https://learn.sparkfun.com/tutorials/raspberry-pi-stand-alone-programmer#resources-and-going-further
#
#    Shawn Hymel
#    https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-raspberry-pi/experiment-1-digital-input-and-output
#
# ==================== DESCRIPTION ====================
#
# This python script takes advantage of the Qwiic pHat v2.0's
# built-in general purpose button to safely reboot/shutdown you Pi:
#
#    1.) If you press the button momentarily, the Pi will reboot.
#    2.) Holding down the button for about 3 seconds the Pi will shutdown.
#
# ========== TUTORIAL ==========
#  For more information on running this script on startup,
#  check out the associated tutorial to adjust your "rc.local" file:
#
#        https://learn.sparkfun.com/tutorials/raspberry-pi-safe-reboot-and-shutdown-button
#
# ========== PRODUCTS THAT USE THIS CODE ==========
#
#   Feel like supporting our work? Buy a board from SparkFun!
#
#        Qwiic pHAT v2.0
#        https://www.sparkfun.com/products/15945
#
#   You can also use any button but you would need to wire it up
#   instead of stacking the pHAT on your Pi.
#
# LICENSE: This code is released under the MIT License (http://opensource.org/licenses/MIT)
#
# Distributed as-is; no warranty is given
#
# -----------------------------------------------------------------------------

import time
import RPi.GPIO as GPIO

# Pin definition
reset_shutdown_pin = 17

# Suppress warnings
GPIO.setwarnings(False)

# Use "GPIO" pin numbering
GPIO.setmode(GPIO.BCM)

# Use built-in internal pullup resistor so the pin is not floating
# if using a momentary push button without a resistor.
#GPIO.setup(reset_shutdown_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Use Qwiic pHAT's pullup resistor so that the pin is not floating
GPIO.setup(reset_shutdown_pin, GPIO.IN)

# modular function to restart Pi
def restart():
    print "restarting Pi"
    command = "/usr/bin/sudo /sbin/shutdown -r now"
    import subprocess
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output = process.communicate()[0]
    print output

# modular function to shutdown Pi
def shut_down():
    print "shutting down"
    command = "/usr/bin/sudo /sbin/shutdown -h now"
    import subprocess
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output = process.communicate()[0]
    print output

while True:

    # For troubleshooting, uncomment this line to output button status on command line
    #print GPIO.input(reset_shutdown_pin)
    if GPIO.input(reset_shutdown_pin) == False:
        counter = 0

        while GPIO.input(reset_shutdown_pin) == False:     
            counter += 1
            time.sleep(0.5)

            # long button press
            if counter > 4:
                shut_down()

        #if short button press, restart!
        restart()

Setting Up the Path

This will be saved in your Downloads folder again. Once downloaded, you'll need to move the Python script to the /home/pi. To do that, open the command line. Move to the Downloads folder with the following command.

language:bash
cd Downloads

using a command in the terminal to navigate to the downloads

We'll use the mv Linux command to move the file with the following command once again:

language:bash
mv safe_restart_shutdown_Pi.py /home/pi

using a command in the terminal move python file to a different location

Just to make sure that the file was moved correctly, use the change directory command to move back up a level:

language:bash
cd ..

using a command in the terminal to move to the location of the file that was just moved

Followed by the list command:

language:bash
ls

verifying that the file is in the correct path in the terminal

Modify rc.local

With the terminal still open, type the following command again:

language:bash
sudo nano /etc/rc.local

configuring the rc.local file

Scroll down using the button on your keyboard, and just before the exit 0 line, adjust the file name for safe_restart_shutdown_Pi.py:

language:bash
python /home/pi/safe_restart_shutdown_Pi.py &

add the following line in the rc.local file

Save and exit by pressing CTRL + X on your keyboard, followed by y when prompted, and then hit Enter

To ensure that the changes take effect, type the following command.

language:bash
sudo reboot

reboot to ensure the changes are saved

What You Should See

After rebooting, hit the GPIO17 button momentarily on the qwiic pHAT v2.0. This should reboot the Pi.

Shot button press for reboot

Press and hold GPIO17 button a little longer to initiate the shutdown command. You'll need to give it a few seconds for the Pi to shutdown. You'll notice the monitor disconnect first if you have one attached. At this point, you should be good to remove your finger off the button. Again, you will want to observe the green status LED on the Pi. The LED will stop blinking when the Pi is completely shutdown. You can now safely remove power from the Pi.

Long button press for shutdown

Resources & Going Further

For more resources, check out the links below:

Need some inspiration for your next project? Check out the Pi AVR Programmer! We implement a shutdown code after programming and testing boards.

Raspberry Pi Stand-Alone Programmer

March 8, 2018

This tutorial will show you how to use a headless Raspberry Pi to flash hex files onto AVR microcontrollers as a stand-alone programmer. It also tells the story about production programming challenges, how SparkFun came to this solution, and all the lessons learned along the way.

Pi AVR Programmer HAT Hookup Guide

July 26, 2018

In this tutorial, we will use a Raspberry Pi 3 and the Pi AVR Programmer HAT to program an ATMega328P target. We are going to first program the Arduino bootloader over SPI, and then upload an Arduino sketch over a USB serial COM port.

Or check out some of these related tutorials:

FLIR Lepton Hookup Guide

See the invisible world of infrared radiation using the FLIR Dev Kit and Raspberry Pi.

Qwiic Joystick Hookup Guide

Looking for an easy way to implement a joystick to your next Arduino or Raspberry Pi project? This hookup guide will walk you through using the Qwiic Joystick with the Arduino IDE on a RedBoard Qwiic and in Python on a Raspberry Pi.

SparkFun Photodetector (MAX30101) Hookup Guide

The SparkFun Photodetector - MAX30101 (Qwiic) is the successor to the MAX30105 particle sensor, a highly sensitive optical sensor. This tutorial will get you started on retrieving the raw data from the MAX30101 sensor.

SparkFun Qwiic Quad Solid State Relay Kit Hookup Guide

A Hookup Guide to get you started with the SparkFun Qwiic Quad Solid State Relay Kit (say that five times fast!).