Adding an On/Off switch to your Raspberry Pi

Interrupts

Using an interrupt-based script is the best way to enable the soft shutdown feature of the Pi Supply switch. Using interrupts improves the efficiency of the code and minimizes load on the CPU compared with the while loop. The code for the interrupt method is shown in Listing 1. See the comments in the listing for a description of what the code is doing.

Listing 1

Interrupt Method

01 # Import the modules to send commands to the system and access GPIO pins
02 from subprocess import call
03 import RPi.GPIO as gpio
04
05 # Define a function to keep script running
06 def loop():
07    raw_input()
08
09 # Define a function to run when an interrupt is called
10 def shutdown(pin):
11     call('halt', shell=False)
12
13 gpio.setmode(gpio.BOARD) # Set pin numbering to board numbering
14 gpio.setup(7, gpio.IN) # Set up pin 7 as an input
15 gpio.add_event_detect(7, gpio.RISING, callback=shutdown, bouncetime=200) # Set up an interrupt to look for button presses
16
17 loop() # Run the loop function to keep script running

while Loop

A while loop is a basic fundamental of almost every programming language in existence, and it is a very useful tool. The code in Listing 2 has the same end result as the interrupt-based script – it allows the safe shutdown of your Rasp Pi, but it does so in a significantly more resource-hungry way. On the other hand, the while loop is a more basic piece of code that is perhaps easier to understand. Although I recommend using the interrupt-based code, I include the while loop approach also, because it works fine, and some people might prefer to use this code (or at least play with it and try to get their head around how it works).

Listing 2

while Loop

01 # Import the libraries to use time delays, send os commands and access GPIO pins
02 import RPi.GPIO as GPIO
03 import time
04 import os
05
06 GPIO.setmode(GPIO.BOARD) # Set pin numbering to board numbering
07 GPIO.setup(7, GPIO.IN) # Setup pin 7 as an input
08 while True: # Setup a while loop to wait for a button press
09    if(GPIO.input(7)): # Setup an if loop to run a shutdown command when button press sensed
10    os.system("sudo shutdown -h now") # Send shutdown command to os
11    break
12    time.sleep(1) # Allow a sleep time of 1 second to reduce CPU usage

Buy this article as PDF

Express-Checkout as PDF

Pages: 8

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content