The RPi.GPIO Python library allows you to easily configure and read-write the input/output pins on the Pi’s GPIO header within a Python script. Thankfully this library is now including in the standard Raspbian image available from the Foundations Download Page.
If you are using a fresh image you don’t need to install it but I’ve kept the instructions here in case you ever want to try a manually installation.
Method 1 – Install from repository
If the package exists in the Raspbian repository is can be installed using apt-get. First you need to update the available package versions :
sudo apt-get update
Then attempt to install the RPi.GPIO package :
sudo apt-get install rpi.gpio
If it isn’t already installed it will be installed. If it is already installed it will be upgraded if a newer version is available.
Method 2 – Manual Installation
The package is available from http://pypi.python.org/pypi/RPi.GPIO and the current version is 0.5.11 (February 2015). If this version is updated you will need to make appropriate changes to the version number in the commands below.
Step 1 – Download the library
Step 2 – Extract the archive to a new folder
tar -xvf RPi.GPIO-0.5.11.tar.gz
Step 3 – Browse to the new directory
Step 4 – Install the library
sudo python setup.py install
Step 5 – Remove the directory and archive file
cd ~ sudo rm -rf RPi.GPIO-0.*
This will now mean you can use the library within Python.
import RPi.GPIO as GPIO # to use Raspberry Pi board pin numbers GPIO.setmode(GPIO.BOARD) # set up the GPIO channels - one input and one output GPIO.setup(11, GPIO.IN) GPIO.setup(12, GPIO.OUT) # input from pin 11 input_value = GPIO.input(11) # output to pin 12 GPIO.output(12, GPIO.HIGH) # the same script as above but using BCM GPIO 00..nn numbers GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN) GPIO.setup(18, GPIO.OUT) input_value = GPIO.input(17) GPIO.output(18, GPIO.HIGH)
Example to run script on key press
import RPi.GPIO as GPIO import time import os GPIO.setmode(GPIO.BCM) #This will import the necessary libraries in the GPIO namespace and set the pin numbering to correspond to your breakout board. #Now we need to set the pin as input, pin 18 is used in this example. GPIO.setup(18,GPIO.IN) #Reading the pin is now as easy as: input = GPIO.input(18) #If we want to print Button Pressed each time a button is pressed while True: if (GPIO.input(18)): print("Button Pressed") time.sleep(1) os.system('startx') #os.system('reboot') #os.system('/etc/network/if-up.d/sayIP') else: print("Button Not pressed") time.sleep(1) # use 0.1 for 1 ms delay