Introduction to controlling GPIO pins with Python

Setting up your Pi for GPIO programming
You need to install a few things to get Python to talk to the GPIO pins and control them. If you're using the standard Raspian OS, it's an easy affair. Fire up your terminal if you're in the GUI and run these commands to install what you need:

Code:
sudo apt-get update
sudo apt-get install python-dev
sudo apt-get install python-rpi.gpio

What you're doing:
The first command updates your package manager database so you're sure to get the latest version of your files.
The second command installs any missing Python development tools.
The third command installs Python libraries to control the GPIO pins.
Introduction to controlling GPIO pins with PythonThere's no need to restart anything when you're done. Got it? Great — let's go

Copying files
If you're using the GUI on your Pi, whether from a physical connection or via VNC, you can write and save your code using any text editor. If you're using SSH to connect, you can use a SCP client app on your computer to access your home folder. Grab Filezilla, and use the IP address of your Pi and your user credentials to log in.

Wiring an LED to a GPIO pin

This diagram shows a normal LED wired to ground (pin 6) and GPIO 18 (pin 12). Note the resistor between the LED and the ground. This is a safety precaution to keep your LED from popping. It's always best to use a resistor, even with a single LED. For standard LEDs and 3.3v GPIO pins, any resistor between 200 Ohms and 1K Ohms should work fine. I use 330 Ohm resistors because I have a bin full of them

Always turn your Pi off when wiring anything to the GPIO header, or any type of breakout attached to the GPIO header!

You can use a breadboard and breakout cobbler, or you can use female jumpers, or you could even solder the connections if this is a permanent installation. Remember that any bare wire (like the electrodes on your LED or resistor) will have voltage and current flowing and can short out. If you're going to be experimenting a lot, get a solderless breadboard and a GPIO cobbler and ribbon cable — you'll be glad you did.

Your LED has two legs coming out of it. One is longer than the other. LEDs are polarity sensitive, meaning they have a positive and a negative side. The longer lead (they're call electrodes) is the positive. It will connect to the GPIO pin. For the LED_test code attached to this post, connect it to pin 11, which is GPIO 17. The shorter lead connects to one end of your resistor, and the other end of your resistor connects to ground, which is pin 6 (or 9, 14, 20 and 25 — use 6 for this example).

Once you're sure you have everything connected, fire your Pi back up.

The code

Code:

[1]import RPi.GPIO as GPIO ##imports the GPIO Library
[2]
[3]## GPIO pin manipulation
[4]GPIO.setmode(GPIO.BCM) ## Use Broadcomm pin numbers
[5]GPIO.setup(17, GPIO.OUT) ## Sets GPIO pin 17 as an output 
[6]GPIO.output(17,True) ## Sets GPIO pin 17 to high (on, 3.3v)
[7]
[8]
[9]## Error handling and cleanup
[10]counter = 0  
[11] 
[12]try:  
[13]    ## 10 second counter  
[14]    while counter < 4500000:   
[15]        counter += 1  
[16]    print "%d" % counter  
[17]  
[18]except KeyboardInterrupt:  
[19]    ## This code runs when you break the program with CTRL+c
[20]    ## then the code in the finally block will run
[21]    print "\n", counter 
[22]  
[23]except:  
[24]    ## This code runs when an error is encountered
[25]    ## then the code in the finally block will run
[26]    print "Put error handling code here instead of this message"  
[27]  
[28]finally:  
[29]	## This code runs any and every time the code exits 
[30]	## even if there was an uncaught error.
[31]	## We're using it to reset the GPIO pin
[32]    GPIO.cleanup()

Introduction to controlling GPIO pins with Python SchematicDon't copy and paste this code! I've put line numbers in so that we can look at each line below, and it won't run as-is because of that. Instead, download the attached LED_Test.py.txt file, and remove the .txt extension. It's only there because we can't upload executable code to the forums for security reasons. Place it in a Project folder in your home directory, then open it with a text editor so we can have a look

Don't use Windows Notepad or Wordpad to write code. You need an editor with UNIX line breaks, like Notepad++.
Mac users — don't use TextEdit because you can't easily save a new file as plain text. Install TextWrangler from the Mac App Store.
Linux users — use whatever you want

The code is commented, but we'll have a look at each section. Because we're using Python, mind the indents in your code. Nested code must be indented, or you'll get an error.

 

For more detail: Introduction to controlling GPIO pins with Python


About The Author

Ibrar Ayyub

I am an experienced technical writer holding a Master's degree in computer science from BZU Multan, Pakistan University. With a background spanning various industries, particularly in home automation and engineering, I have honed my skills in crafting clear and concise content. Proficient in leveraging infographics and diagrams, I strive to simplify complex concepts for readers. My strength lies in thorough research and presenting information in a structured and logical format.

Follow Us:
LinkedinTwitter

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top