Friday, January 9, 2015

Raspberry Pi Toggle An LED on GPIO Howto

With RPi.GPIO :

#!/usr/bin/python

import RPi.GPIO as GPIO

# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)

# set up GPIO output channel
GPIO.setup(11, GPIO.OUT)

GPIO.output(11, not GPIO.input(11) )

Don't run GPIO.cleanup at the end and then complain that it doesn't work :). Note that the above one sets the port as output. That's not what you want to do - you want to check that the port is already an output and only then toggle. If the port was configured as input from another app and is connected to a voltage source on the board, you don't want to pull it to the opposite voltage.

So, if you upgrade to RPIO using

sudo apt-get install python-setuptools
sudo easy_install -U RPIO

Then, you can do

#!/usr/bin/python

import RPIO as GPIO

# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)

if GPIO.gpio_function(11) is GPIO.OUT :
        # this is stupid, but just to trick RPIO
        GPIO.setup(11, GPIO.OUT)
        GPIO.output(11, not GPIO.forceinput(11))

Note how amateurish that is - finding out that something is already an output and then telling the same library to set as output - no surprise considering Pi was targeted at kids. If you didn't, you get :

Traceback (most recent call last):
  File "./nu_toggle_17.py", line 12, in
    GPIO.output(11, not GPIO.forceinput(11))
RPIO.Exceptions.WrongDirectionException: The GPIO channel has not been set up as an OUTPUT

..

No comments:

Post a Comment