Simple Shutdown Raspberry Pi Button by Using GPIO

by masteruan in Circuits > Raspberry Pi

6469 Views, 33 Favorites, 0 Comments

Simple Shutdown Raspberry Pi Button by Using GPIO

Raspberry Pi switch.png

When I use my Raspberry Pi without screen and keyboard, I have a lan or something else. But if I can't see my Raspberry Pi in lan, or if I can't see my Raspberry Pi on my screen, or if my keyboards not work because the batteries are died, I use my secret shutdown switch.

Do you want a Raspberry Pi 3? or a switch

Write the Code

All the secret is in the code. Go to home folder.

cd /~

Create a new file with:

sudo nano shutdown.py

now write inside this:

import RPi.GPIO as GPIO import time import os

buttonPin = 21

GPIO.setmode(GPIO.BCM)

GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

last_state = True

input_state = True

while True:

input_state = GPIO.input(buttonPin)

if (not input_state):

print("Shutdown")

os.system('sudo shutdown -h now')

time.sleep(0.05) GPIO.cleanup()

First the Code

When you start your Raspberry Pi, you can run the previous code by modifying the rc.local file.
Write this in terminal:

sudo nano /etc/rc.local

Then modify the file by adding this line before "exit 0"

python /home/pi/shutdown.py &

Now Try to Shutdown by Wire

IMG_0521.JPG
IMG_0520.JPG
IMG_0523.JPG
IMG_0522.JPG

Now it's the time of truth.
Reboot you Raspberry Pi, and try to connect the last two GPIO pin like in figure. The last two pin in Raspberry Pi Zero are Ground and GPIO 21.

Ta taaa your Raspberry Pi shutdown without screen, keyboard or others kind of solutions. All you need is a cable...or a switch. See the image. My Raspberry Pi zero shutdown only when turn it upside down. I have used a tilt switch.

Do you want a tilt switch ?