submit to reddit       

Using Python to control GPIO pins

The Raspberry Pi comes with Python libraries for controlling GPIO. You can use the functions in these libraries to set the voltages of the GPIO pins and control circuits like the one in the previous post where I connected an LED to my Pi's GPIO.

Before you can acess GPIO, you need to set up the library by calling the 'setmode' function. This determines which pin numbering scheme will be used in future calls to the GPIO library. It's also important to set up one of the GPIO pins as an output.

The next lines of code turn on pin 25, sleep for three seconds, turn off pin 25, and then clean up the GPIO library.

#!/usr/bin/env python

import RPi.GPIO as GPIO
import time

def main():

    print "executing script"

    # tell the GPIO module that we want 
    # to use the chip's pin numbering scheme
    # setup pin 25 as an output

    # turn pin on 
    # sleep for 3 seconds
    # turn the pin off


if __name__=="__main__":

Save this code in your home directory in a file named led.py, and make sure it's executable with this command:

chmod +x led.py

Run the script by typing this command:

sudo ./led.py

You need to use sudo because the GPIO libraries access operating system resources.



comments powered by Disqus

Follow me