Quantcast
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
    GPIO.setmode(GPIO.BCM)
    # setup pin 25 as an output
    GPIO.setup(25,GPIO.OUT)

    # turn pin on 
    GPIO.output(25,True)
    # sleep for 3 seconds
    time.sleep(3)
    # turn the pin off
    GPIO.output(25,False)

    GPIO.cleanup()

if __name__=="__main__":
    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

Comments

comments powered by Disqus



Follow me