Thursday 4 December 2014

Popping my GPIO cherry

Today I had to shut down the rPi, and realised that the only way to do it is to log in, and sudo a shutdown command.  Surely there must be a hardware way to do a controlled shutdown?
A bit of googling later it turns out that it's quite easy to do this in a python script that waits on a GPIO pin being grounded.  The script is run from rc.local when raspbian boots, which means that it's already running as root!

The script looks like this:

 #!/usr/bin/env python2.7  
 import RPi.GPIO as GPIO  
 import subprocess  
 GPIO.setmode(GPIO.BCM)  
 GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)  
 try:  
   GPIO.wait_for_edge(21, GPIO.FALLING)  
   subprocess.call(['shutdown -h now "System halted by GPIO action"'], shell=True)  
 except KeyboardInterrupt:  
   GPIO.cleanup()  
 GPIO.cleanup()

Just to run through it quickly it does the following:

  1. Loads the libraries
  2. Sets the GPIO mode to the GPIO numbering scheme rather than pin numbering
  3. Pulls GPIO pin 21 high (sets the voltage to +5V)
  4. Waits for the voltage to drop (shorted to GND)
  5. When it does, it runs a system shutdown
  6. Resets the GPIO pins
The script runs the whole time, but because it's listening for a pin to go to GND it doesn't use any resources.

So, how do you send pin 40 (GPIO 21) to ground?  Well, normally you'd wire in a "push to make" button, but I don't have any of those yet, so for now, a wire will have to do:


I guess I'm just going to have to go shopping (again)!



0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home