element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Raspberry Pi Projects
  • Products
  • Raspberry Pi
  • Raspberry Pi Projects
  • More
  • Cancel
Raspberry Pi Projects
Blog Adding a Shutdown Button to the Raspberry Pi B+
  • Blog
  • Documents
  • Events
  • Polls
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Raspberry Pi Projects to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: ipv1
  • Date Created: 10 May 2021 6:51 PM Date Created
  • Views 8135 views
  • Likes 16 likes
  • Comments 40 comments
  • rpibeginner
  • ip_iot
  • raspberry_pi
  • raspberry_pi_projects
Related
Recommended

Adding a Shutdown Button to the Raspberry Pi B+

ipv1
ipv1
10 May 2021

  • Introduction
  • What do you need?
  • Step 1. Setup the RPi
  • Step 2. Connecting the button
  • Step 3. Writing a Python Script
  • Step 4. Adding it to startup
  • Step 5. More to do

 

Introduction

 

For a beginner to the world of raspberry pi, there are a number of projects that can become the start of something big. In this article, I discuss such a simple project which is adding a button that can be used to shutdown the raspberry pi using a bit of software tinkering. I wrote a similar article in 2013 at my blog “embeddedcode.wordpress.com” and its got its share of attention since a lot of people starting out with a single board computer, kept looking for a power button. Additionally, those who wanted a headless system, needed a way to shutdown the computer without the mess of connecting to it over the network or attaching a monitor and keyboard to it. In this article, I revisit the tutorial on how to add a shutdown button while trying to explain the workings and perhaps beginners will find it an amusing to add find more things to do with this little recipe.

 

What do you need?

 

Here is a basic bill of materials required for this exercise.

- Raspberry Pi B+(Product LinkProduct Link)

- A push button

- Connecting wires

- Breadboard OR...

- Nipper & Soldering Iron and related stuff(not necessary)

 

The Raspberry Pi B+ can be replaced by another Pi model but for this exercise, I will be explaining things with the RPi B+ as a reference. The push button also depends on availability and preference. Do you prefer a BIG RED BUTTON? No problem… use that. The Connecting wires are required since we need to connect the button to the Raspberry Pi GPIOs. I will start with using the breadboard and upgrade to a soldered button. In case you have something like a button break out which does not need soldering, thats fine too. We will make these decisions at the end. Right now lets get prototyping.

 

Step 1. Setup the RPi

 

We need a raspberry Pi fully setup with the latest version of Raspbian OS. Since the you probably have that done, I won’t go into the details but for those who have not done it yet, I have a few links you might like to visit.

https://embeddedcode.wordpress.com/2013/07/10/the-geek-getting-started-guide-to-the-raspberry-pi/

https://www.raspberrypi.org/help/noobs-setup/

https://www.raspberrypi.org/help/quick-start-guide/

 

Connect up a monitor, keyboard, mouse, ethernet cable(not necessary) and the power adaptor. Boot up the RPi and login.

 

Step 2. Connecting the button

 

Next we need to add the button. I added a push button to the breadboard and added the connecting wires. This part will vary with the button availability. Now where do we connect it to the RPi? Well lets take a look at the diagram below.

 

image

 

From the diagram its clear that some of the GPIOs have dual roles as well such as UART, I2C, SPI etc. From these I chose GPIO18 because its near the GND or ground pin but you can choose one that fits your need. I suggest staying away from the dual purpose pins since you never know when you might want to add an SPI, I2C or serial peripheral in you next project. image

 

The image below shows my setup and you should make sure you connected the pins right.

 

7Pt-YEAgHs53P_ClRovFCyZTdPm5qdBG2hpdMm-d3WE=w1343-h755-no

 

Step 3. Writing a Python Script

 

There are other ways to do a shutdown script but over time, I have come to the understanding that since python has gained so much popularity, its better go this route and if you want to extend functionality to say starting or stopping a service, we can do that as well. In order to keep things organised, we create a folder called ‘Scripts’ and then an empty file called shutdown_pi.py

 

mkdir Scripts
cd Scripts
touch shutdown_pi.py

 

Next we need to edit the file and add the contents. Execute the command

 

nano shutdown_pi.py

 

and then type the following into it.

 

#!/bin/python
# Simple script for shutting down the raspberry Pi at the press of a button.
# by Inderpreet Singh

import RPi.GPIO as GPIO
import time
import os

# Use the Broadcom SOC Pin numbers
# Setup the Pin with Internal pullups enabled and PIN in reading mode.
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_UP)

# Our function on what to do when the button is pressed
def Shutdown(channel):
    os.system("sudo shutdown -h now")

# Add our function to execute when the button pressed event happens
GPIO.add_event_detect(18, GPIO.FALLING, callback = Shutdown, bouncetime = 2000)

# Now wait!
while 1:
    time.sleep(1)

 

Save the file by pressing CTRL+X and then y, Enter

Note that in Python, you do not need parentheses({}) to create a sub-section. The tabbed or indented format tells the interpreter that its a sub block so please make sure that the spacing matches the above code.

 

Now since our python script is trying to access some GPIOs and trying to shutdown the system this scripts needs to be run as root. To test its working, enter the following command

 

sudo python shutdown_pi.py

 

The ‘sudo’ ensures that python is given all the privileges for this run. If at this point you press the button, the RPi should shutdown. If it doesn’t then you need to check the script as well as the connections. No Pull up resistances are needed since we enable the internal pull-ups on the Pi itself.

 

Step 4. Adding it to startup

 

We need our python script to run automatically every time the RPi starts. For this we need to do a little manual editing of the RPI generated files. Run the following command

 

sudo nano /etc/rc.local

 

This file is what gets executed everytime your RPi boots up. We need to add our python command before the last line which closes the if loop. Therefore, add the following line before the #fi at the end of the file.

 

sudo python /home/pi/Scripts/shutdown_pi.py &

 

Please note that everything is case sensitive so Scripts is not the same as scripts. The & at the end of the command tells it to run the process in the background. If you omit it, then your login prompt probably will not appear.

 

Now reboot the RPi. Thats it! You are done and once you get everything working, you can start making modifications to the script for adding more buttons to start a process such as a GUI etc or kill the process, send a command over the network etc. The possibilities are endless and I would love feedback on how you made your own shutdown button.

 

Step 5. More to do

 

Since we have a working prototype we may want to improve the ergonomics. I simple soldered two wires to the press button and use a little hot glue to stick the button to the side of the RPi Case. You may chose to use a panel mount button but the connections remain the same.

xqSSY96MxYLQl4DhE1bArwvpRMqzCkumMVz-ZGvVZCM=w1343-h755-no

If you happen to have a 3D printer, then you may print your own case such as the one at ([Project VIRUS][Week 6] A bit on 3D printing)

Have fun!

IP

  • Sign in to reply
Parents
  • Former Member
    Former Member over 9 years ago

    I have your code working very well on my PI, however I'd now like to expand it and be able to boot the Pi via a pushbutton, preferably the same pushbutton. (I'm building a simply internet radio for my elderly mother, it plays just one station, her favorite, and I'd like to keep the number of buttons to just one if possible, to make it easy for her to operate.

     

    Thanks!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Former Member
    Former Member over 9 years ago in reply to Former Member

    I'm doing the same, well sort off. I operate an internet radio station and I use my PI to monitor my stream. When powered up it loads a browser and goes straight to my stream's url. When the button is pressed it shuts down. I don't think there is a way to use the same button or another one since nothing is running.
    If you can lay your hands on a little reverse push button (breaks the circuit when pressed) it can power cycle the PI to have it boot up again. image

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Former Member
    Former Member over 9 years ago in reply to Former Member

    I decided to go with 3 buttons. I know, I know, that's 300% more button than I originally wanted! LOL

     

    I figure for my mom, who will be turning it off and on in very low light, that navigating 3 buttons would be easier than remembering how many times to push 1 button.

     

    So I have the 2 Shutdown buttons working now, I used a python shutdown script via Rpi-GPIO and have it set to monitor 2 GPIO pins, connected to 2 buttons. One triggers a "shutdown -h now" and the other triggers a "shutdown -h +60" (which does a shutdown in 60 minutes).

     

    For the Power On and Off I'm using a relay triggered by a Adafruit 3V Trinket. The Power button enables an output on the Trinket to Enable the Relay to send Power to the Pi (and the audio amplifier) for 40 seconds. I have a second input on the Trinket connected to a RPi GPIO pin that sends 3.3V to the Trinket when the Pi is booted.

     

    Those 2 Trinket inputs are set in code to be an OR gate, if either of them is HIGH, the Relay will be Enabled. The 40 seconds on the 1 input gives the Pi time to boot, then it goes back LOW. When the Pi is booted it provides a HIGH to the 2nd input of the OR gate to keep the Relay Enabled.

     

    When the Pi shuts down because either the "Shutdown" button or the "Shutdown After 60 Minutes" button has been pressed, the OR gate loses its HIGH and it turns off the Relay, which removes Power from the Pi (and the audio amplifier).

     

    I'm still working on the Power OR gate portion but should have it working soon.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
Comment
  • Former Member
    Former Member over 9 years ago in reply to Former Member

    I decided to go with 3 buttons. I know, I know, that's 300% more button than I originally wanted! LOL

     

    I figure for my mom, who will be turning it off and on in very low light, that navigating 3 buttons would be easier than remembering how many times to push 1 button.

     

    So I have the 2 Shutdown buttons working now, I used a python shutdown script via Rpi-GPIO and have it set to monitor 2 GPIO pins, connected to 2 buttons. One triggers a "shutdown -h now" and the other triggers a "shutdown -h +60" (which does a shutdown in 60 minutes).

     

    For the Power On and Off I'm using a relay triggered by a Adafruit 3V Trinket. The Power button enables an output on the Trinket to Enable the Relay to send Power to the Pi (and the audio amplifier) for 40 seconds. I have a second input on the Trinket connected to a RPi GPIO pin that sends 3.3V to the Trinket when the Pi is booted.

     

    Those 2 Trinket inputs are set in code to be an OR gate, if either of them is HIGH, the Relay will be Enabled. The 40 seconds on the 1 input gives the Pi time to boot, then it goes back LOW. When the Pi is booted it provides a HIGH to the 2nd input of the OR gate to keep the Relay Enabled.

     

    When the Pi shuts down because either the "Shutdown" button or the "Shutdown After 60 Minutes" button has been pressed, the OR gate loses its HIGH and it turns off the Relay, which removes Power from the Pi (and the audio amplifier).

     

    I'm still working on the Power OR gate portion but should have it working soon.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
Children
  • Former Member
    Former Member over 9 years ago in reply to Former Member

    OK, I'm finished with the project all except final assembly, but it's all working 100%.

     

    The final piece of the puzzle was to get a signal from the Pi to the Arduino Trinket that let the Trinket know that the Pi was booted or not. The Pi uses 3.3V logic on its GPIO pins and the Trinket I used was a 5V version (there is a 3.3V version but I didn't have one on hand, and my relays were 5V so I had to choose between 3.3V and 5V Trinket anyway).

     

    I tried a logic level shifter circuit that I bought on eBay and I never got it to work, probably my fault. But while reading online I found someone who suggested just using the 3.3V signal from the Pi GPIO to feed one of the Trinket's Analog inputs and do a analogRead on the signal. Sure enough that worked perfectly!

     

    I tested it using a Uno, so I could monitor the signal via Serial Monitor because the Trinket doesn't offer that function. I found that with Pi NOT booted the analogRead was between 0 and 120 or so when booting to a solid 620 when fully booted. So there it was, I just needed to set one of the OR conditions in Arduino code to keep the relay Enabled if my Analog pin read greater than 500. (I could have chosen anywhere from 200-600 but I thought 500 gave me a nice margin of error on either side.)

     

    So now the Pi boots with the touch of the Green button, and shuts down Now with the touch of the Red button or in 1 Hour with the touch of the Yellow button. And when it shuts down, the relays disengage and ALL power is removed from the Pi (and the audio amp).

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube