Introduction: Raspberry Pi Zero Switch Off by Button

I've a small and sweet Raspberry Pi zero . When I switch on my Raspy zero without a monitor or keyboard or LAN, I don't want switch off the pi directly by putting off the socket by the line. In fact this action can compromise the Raspy. You can be breaking the kernel, and the system can crash after that.

I've written a code that put the last pin in standby for a connection between the ground. When I connect the last pin with the ground, the code starts. The code is a simple sudo shutdown -h now


Buy your Raspberry Pi zero on Amazon

Step 1: Create the Code

Go to GitHub and read the code (https://github.com/masteruan/Raspbery_switch).

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()

Step 2: Connect the Pins

Now is the moment to connect the pin. After the starting of Raspberry Pi, you can connect the last pin to ground.

You can read on screen, the command: sudo shudown-h now and the Raspberry Pi switch off.

Materials

Buy a switch on Amazon

Buy a tilt switch on Amazon

Step 3: Modify the Rc.local

Now if you want start automatically the script do you modify the rc.local file. This file start when you switch on the Raspberry Pi

#!/bin/sh -e

# # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing.

# Print the IP address _IP=$(hostname -I) || true if [ "$_IP" ]; then printf "My IP address is %s\n" "$_IP" fi

python /home/pi/Desktop/shutdown.py &

exit 0

Step 4: Mounting a Switch Or...

Now you can mount a switch like in photo. I've mounted a tilt switch. When I turn upside down the Raspberry Pi, this switch off.

Comments

author
rkränzlein (author)2017-07-23

Python has some problems with Indentation.

This code works for me:

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()

author
masteruan (author)rkränzlein2017-07-25

Yes you are right! Follow this: https://github.com/masteruan/Raspbery_switch

About This Instructable

6,424views

75favorites

License:

More by masteruan:Guess the Number With Arduino KeyPadArduino Edit, Compile, Upload, Read Serial by LInux Pocket ChipMeteo Node IoT Smart Meteo Station
Add instructable to: