Despite the Raspberry Pi's many strengths, it lacks something that is taken for granted on most other electronic devices: a power button.
Step One: Mount the Button
Start by mounting the push button on the breadboard.
If your push button has four terminals, you'll need to use two that get connected when the button is pressed. Make the connections to the buttons using the connecting wires as shown.
Step 2: Select a GPIO Pin
Next, you'll need to select a GPIO. Here we are interested in using one of the pins to detect a button press: the button will be connected between the GPIO pin and the ground pin, so pressing the button reduces the voltage to zero.
For this project, select GPIO 21, which is at one end of the connector, right next to the ground pin (you are free to use any other unused GPIO).
Use the connecting wires to complete the circuit, as shown.
Step 3: Code Your Pi
Boot up your Raspberry Pi and open a terminal window.
Type leafpad shutdown.py to open up a new Leafpad editor window. Enter the following code and when you're done, save the file and close the terminal window.
# Simple script for shutting down the Raspberry Pi at the press of a button.
# by Inderpreet Singh
import RPi.GPIO as GPIO
# Use the Broadcom SOC Pin numbers
# Setup the pin with internal pullups enabled and pin in reading mode.
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Our function on what to do when the button is pressed
os.system("sudo shutdown -h now")
# Add our function to execute when the button pressed event happens
GPIO.add_event_detect(21, GPIO.FALLING, callback=Shutdown, bouncetime=2000)
# Now wait!
Step 4: Test Your Script
Test your script by opening the terminal and typing sudo python3 shutdown.py
Press the shutdown button.
A message saying 'shutting down' should appear on screen and after a five-second delay your Raspberry Pi will shut down. If you press Ctrl + C before those five seconds are up, the script will be stopped, aborting the shutdown procedure.
Step 5: Activate On Startup
In order to make the shutdown button 'active' when your Raspberry Pi starts up, you need to include it in an rc.local script.
Open a new terminal and type sudo leafpad /etc/rc.local
This will open the Leafpad editor, with the rc.local file loaded. At the end of the file (before exit 0 in the code) add the following:
sudo python3 /home/shutdown.py &
Save the file and exit Leafpad.
Step 6: Success!
Reboot your Raspberry Pi and your shutdown button should be functioning.
You've given your Raspberry Pi a simple, reliable and extremely useful power button.