Adding an On/Off switch to your Raspberry Pi

Loading a Python File During Boot

After you have entered the interrupt-based or while-loop-based code into the Python IDE, you need to create a folder called PiSupply in the /home/pi directory. Save the code (either Listing 1 or 2, whichever you choose) in the newly created folder at /home/pi/PiSupply, naming the file or something similar. Then, open an LXTerminal session and use the Nano text editor to add some code to enable the Python script you just created to run when the Rasp Pi boots up. Type

sudo nano /etc/rc.local

and then add the line

python /home/pi/PiSupply/

before the line that says

exit 0

Press Ctrl+X to exit the Nano editor and, when prompted, press Y and then Enter to save the file you just edited. The file name, and the folder names and locations, can be whatever you want them to be, but you need to make sure you maintain the names consistently. Listings 1 and 2 use physical pin 7 on the GPIO header, which corresponds to the fourth pin from the right on the top row (when looking down on the Pi from above with the RCA video connector socket facing toward you). You can change this code to use any other GPIO pin; I just chose pin 7 because it is next to physical pin 8, which is the required pin to use for the automatic power supply switching without any additional code.

Replacing Pin 8 (TXD)

It is possible to add some code to the preceding examples to change to a pin other than physical pin 8 for the main automatic power-off functionality of the full On/Off power switch. You might want to use this code if you are using pin 8 as the serial TX in part of a serial connection. The code to add is shown in Listing 3.

Listing 3

Changing from the Default Pin

01 keep_powered_pin = 18 # Default pin is 8
03 # Pin to pull high to keep the Pi Supply giving power
04 gpio.setup(keep_powered_pin, gpio.OUT, initial=gpio.HIGH)

As you can see, the code in Listing 3 changes the pin from the default pin 8 (which requires no code) to pin 18. You can change this pin number to any GPIO pin that is capable of being configured as an output.

Add this snippet to either the while loop or the interrupt-based script. I recommend adding it after the line in Listing 1 that says:

import RPi.GPIO as gpio

In Listing 2, add the pin change code after line 4, import os.

Buy this article as PDF

Express-Checkout as PDF

Pages: 8

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content