Raspberry Pi GPIO with Python (without root)
While playing around with the raspberry pi I wanted to try out the GPIO function. I decided I wanted to use python to control the pins. I found several alternatives, one was RPi.GPIO, but since you need to run the scripts as root I decided to try an alternative: WiringPi-python. WiringPi is a port of the popular Wiring library for the Raspberry Pi.
### Installing WiringPi First follow the instructions found here to install WiringPi. After you have done that you need to install WiringPi-python:
sudo apt-get install python-dev
git clone https://github.com/WiringPi/WiringPi-Python.git
cd WiringPi-Python
git submodule update --init
sudo python setup.py install
Using the library
When everything is installed you need to setup (export) your pins. A scheme of the pins can be found here. In this tutorial I will use the BCM GPIO numbering (the documentation is sketchy at best on explaining which pin number you should use when).
I will use a LED on the BCM 18 pin just connect the long pin of the led to pin GPIO18 and the short pin to Ground on the following picture EDIT: as a commenter suggested, you should always use a resistor when connecting an led
To export a pin enter the following command to export your GPIO1 pin (bcm pin 18):
gpio export 18 out
Then you need to set up your pin mode and test it (I don’t know if these steps are necessary):
gpio -g mode 18 out
gpio -g write 18 1
The “-g” flag in the command means that the command will use the BCM GPIO pinout.
If your led (connected to GPIO1) is lit, everything is working. Let’s create a demo file named blink.py:
vim blink.py
Add the following to it and save:
import wiringpi
from time import sleep
io = wiringpi.GPIO(wiringpi.GPIO.WPI_MODE_SYS)
io.pinMode(18,io.OUTPUT) # Setup pin 18 (GPIO1)
while True:
io.digitalWrite(18,io.HIGH) # Turn on light
sleep(2)
io.digitalWrite(18,io.LOW) # Turn off
sleep(2)
Execute the script:
python blink.py
Your led should blink now, you are now ready to start using WiringPi-python. More documentation on WiringPi-python can be found here
blog comments powered by Disqus