There is no on/off switch on Raspberry Pi. Once you install your lights outside, it may be outside the wireless range to shut it down from terminal. Simply yanking off power cable will corrupt the OS; so we need to add on/off switch. We will be using a script written by Inderpreet Singh that uses a GPIO pin to send a shutdown command to Raspbian OS.
Create a directory called ‘myscript’ in the home folder of the Pi (of course, you have to ssh into Pi)
Then cd to this directory:
And create a file:
Copy the following lines into that empty file:
#!/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(21, 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(21, GPIO.FALLING, callback = Shutdown, bouncetime = 2000) # Now wait! while 1: time.sleep(1)
Save and close the file. Stay inside the ‘myscript’ directory and set this script to run as root:
sudo python shutpi.py
We now need to set the script to run as system boot:
sudo nano /etc/rc.local
There add the following line between ‘fi’ and ‘exit 0’ line:
sudo python /home/pi/myscript/shutpi.py &
So it looks like this:
# Print the IP address _IP=$(hostname -I) || true if [ "$_IP" ]; then printf "My IP address is %s\n" "$_IP" fi sudo python /home/pi/myscript/shutpi.py & exit 0
Shut down your system and connect a push button to GPIO pin 21 and GND using male-female breadboard cable.
Reboot your system and when you push the button; your system should shut down.