Raspberry Pi GPIO with Python (without root)

Posted on January 1, 2012
Tags:

While playing around with the rasp­berry pi I wanted to try out the GPIO func­tion. I de­cided I wanted to use python to con­trol the pins. I found sev­eral al­ter­na­tives, one was RPi.GPIO, but since you need to run the scripts as root I de­cided to try an al­ter­na­tive: Wiring­Pi-python. WiringPi is a port of the pop­ular Wiring li­brary for the Rasp­berry Pi.
### In­stalling WiringPi First follow the in­struc­tions found here to in­stall WiringPi. After you have done that you need to in­stall Wiring­Pi-python:

sudo ap­t-get in­stall python-dev  
git clone http­s://github.­com/Wiring­Pi/Wiring­Pi-Python.git  
cd Wiring­Pi-Python  
git sub­module up­date --init  
sudo python set­up.py in­stall  

Using the li­brary

When every­thing is in­stalled you need to setup (ex­port) your pins. A scheme of the pins can be found here. In this tu­to­rial I will use the BCM GPIO num­bering (the doc­u­men­ta­tion is sketchy at best on ex­plaining which pin number you should use when).
I will use a LED on the BCM 18 pin just con­nect the long pin of the led to pin GPIO18 and the short pin to Ground on the fol­lowing pic­ture EDIT: as a com­menter sug­gested, you should al­ways use a re­sistor when con­necting an led
Raspberry pi pinout

To ex­port a pin enter the fol­lowing com­mand to ex­port your GPIO1 pin (bcm pin 18):

gpio ex­port 18 out  

Then you need to set up your pin mode and test it (I don’t know if these steps are nec­es­sary):

gpio -g mode 18 out  
gpio -g write 18 1  

The “-g” flag in the com­mand means that the com­mand will use the BCM GPIO pinout.
If your led (con­nected to GPIO1) is lit, every­thing is work­ing. Let’s create a demo file named blink.py:

vim blink.py  

Add the fol­lowing to it and save:

im­port wiringpi  
from time im­port sleep  
io = wiring­pi.G­PI­O(wiring­pi.G­PI­O.W­PI_­MOD­E_SYS)  
io.pin­Mod­e(18,io.OUT­PUT)  # Setup pin 18 (G­PIO1)
while True:  
    io.dig­i­tal­Write(18,io.HIGH)  # Turn on light
    sleep(2)  
    io.dig­i­tal­Write(18,io.LOW)  # Turn off
    sleep(2)  

Ex­e­cute the script:

python blink.py  

Your led should blink now, you are now ready to start using Wiring­Pi-python. More doc­u­men­ta­tion on Wiring­Pi-python can be found here

blog comments powered by Disqus