Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
133 views

Using The Raspberry Pi GPIO With Python MaxEmbedded

The document discusses using the Raspberry Pi's GPIO pins with Python. It describes how the GPIO pins allow the RPi to connect to external devices. It then explains how to install and use the RPi.GPIO Python library to control the pins. As an example, it walks through building a simple circuit with an LED connected to a GPIO pin and blinking the LED on and off by programming the pin's state.

Uploaded by

dan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views

Using The Raspberry Pi GPIO With Python MaxEmbedded

The document discusses using the Raspberry Pi's GPIO pins with Python. It describes how the GPIO pins allow the RPi to connect to external devices. It then explains how to install and use the RPi.GPIO Python library to control the pins. As an example, it walks through building a simple circuit with an LED connected to a GPIO pin and blinking the LED on and off by programming the pin's state.

Uploaded by

dan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

http://maxembedded.

com/2014/07/using-raspberry-pi-gpio-using-python/

UsingtheRaspberryPiGPIOwithPython
SoyougotyourRaspberryPi,installedanOSandusingitjustlikeyourcomputer.Great!
Nowwhat?YoudidntbuyaRaspberryPijusttoreplaceyourcomputer,didyou?Well,
RaspberryPicandoalotmoremuchmorethanyourcomputercando!
Didyounoticethattherearelotsoftiny
littlepinsononecornerofyourRPi?
ThesearecalledGeneralPurposeInput
Outputpins(orGPIOpins).Thesepins
allowyourRPitobeconnectedtothe
externalworld.RaspberryPiModelsAand
Bhave26pins(17GPIO)whereasthe
modelsB+andB2comewith40pins(26
GPIO).ThemodelsB+andB2arepin
compatiblewithmodelsAandB.

RaspberryPiModelA/BGPIO

Theeasiestwaytocontrolthesepinsisto
usetheRPi.GPIOPythonlibrary.ThelibrarycomespreinstalledwiththelatestRaspbian
OS.Inanycase,welllearnhowtoinstallthelibrary,justincaseyoufinditmissing.After
thispost,youshouldbeabletoperformsimpleI/OoperationsusingyourRPisGPIOpins.

Contents
RaspberryPiPinConfiguration
TheRPi.GPIOPythonLibrary
Installation
HelloWorldwithRaspberryPiLEDBlinky
Alittlebackground
Circuit
UsingRPi.GPIOLibrary
TimingConsiderations
LetsCode!

Video
ALevelup:ReadingInputs
Algorithm
LetsCode!
Test:DesignaCounter
Whatnow?
Summary

RaspberryPiPinConfiguration
Asmentionedearlier,RPimodelsA/BandB+arepincompatible.Thefollowingimage
(sourceraspberrypispy.co.uk)showsthepinlayoutofmodelsA/B(rev2)andB+.

RPiPinLayoutforModelBRev2andModelB+(Imagesource
raspberrypispy.co.uk)

ModelBhadtworevisionsinwhichthepinconfigurationchangedalittle.TheRPimodelB
consistsofpins1through26,ofwhichonly17ofthemcanbeusedasGPIO.The
remainingpinsconsistofpowersupply(5vand3.3v),groundandserialpins.TheRPi
modelB+consistsofallthepinsshownabove,outofwhich26canbeusedasGPIO.
Thelabelsmentionedontheleftandrightofthepinsrefertothepinnumbersonthe
BCM2835CPU.Forinstance,pinGPIO16ofBCM2835CPUisconnectedtopin36ofRPi
B+.Makessense?Whatdifferencedoesitmaketoyouwellseeinawhile!:)

TheRPi.GPIOPythonLibrary
Nowletsgettothepoint.InordertocontroltheGPIOpinsoftheRPi,welluse
theRPi.GPIOPythonlibrary.Startingversion0.5.6,thelibraryhassupportforRPimodel
B+aswell.WhilethelibraryisthebestwaytoaccessandcontroltheGPIOpins,itstill
lackssupportforSPI,I2C,hardwarePWMandserialfunctionality,whichareplannedtobe
added(thisiswithrespecttoversion0.5.6.Infuture,thismightchange).
ThisisareallysimplelibrarywhichallowsyoutoreadtoandwritefromanyGPIOpinby
variousmeans(likepolling,triggers,events,etc).Inthispost,welldiscussthepolling
method(dontworryaboutthename,welldealwithitlater.Theconceptisrathersimple),
whereasIlldealwiththeothermethodsinmynextpost.

Installation
Method1InstallfromRepositories
TheRPi.GPIOlibrarycomespreinstalledwiththelatestversionofRaspbian.Incaseit
doesnt,allyouneedtodoistoinstallthelatestversionfromtherepositoriesbyrunning
thefollowingintheterminal(holdsgoodforRaspbianonly)
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install python-rpi.gpio python3-rpi.gpio
Thatsallyouneedtodo!Simple,eh?!:)
Method2BuildfromSource
Ifyouwanttobuildfromthesource,firstdownloadthelibraryfromhere.Once
downloaded,youneedtoextractit.Openuptheterminal,browsetothedirectorywhere
youdownloadedthelibraryandtypeinthefollowingtoextract(replacethenameofthefile
withtheonethatyoudownloaded)

tar zxvf RPi.GPIO-0.5.6.tar.gz

tar zxvf RPi.GPIO-0.5.6.tar.gz


Thenenterintotheextractedfolder.
cdRPi.GPIO-0.5.6
Beforeweproceedtowardsinstallation,makesurePythonisinstalledinyoursystem
(whichshouldbesinceitcomespreinstalledinallOSimages).IncasetheresnoPython
installed,typethefollowingtoinstall
sudo apt-get install python-dev python3-dev
Andthen,installthepackagebytyping
sudo python setup.py install
##or
sudo python3 setup.py install
Thatshouldbeit!YoureallsettoblinksomeLEDs!:)

HelloWorldwithRaspberryPiLEDBlinky
AHelloworldprogramisatypicallyoneofthesimplestprogramsthatonecanpossibly
writetoillustratethebasicfunctionalityofanydevice.IncaseofRaspberryPi,itis,likeany
otherembeddedsystem,blinkinganLED.Thisnotonlygivesbeginnersanideaofhow
thingsgenerallywork,butalsomakessurethatallthetoolsanddevicesareproperlyset
upandworkingproperly.
Inthispost,wellprograminPython.Itcanbeprogrammedinatonotherlanguagesas
well,butwellsticktoPythonfornowbecauseofitssimplicity.Illdedicateanotherposton
howtodothesameusingC,andmaybeanotherpostonhowtowriteyourownLinux
kernelmodulestocontroltheGPIO.:)

Alittlebackground
Forthosewhoarenotfamiliarwithcircuits,thismightseemachallengingtask.Soheresa
littlebackgroundontheconceptofblinkingLEDs.Ifyouarenotalreadyfamiliar,LEDsare
littledevicesthatglowandemitlightofsomecolor(red,blue,green,yellow,white,etc)
uponprovidingapositivevoltageacrossitspins(forwardbias).Ifyoureversethepolarity,
theLEDdoesnotglow.IntheadjoiningfigureofanLED,youmustmakesurethatthe
voltagedropacrosstheLED(from+vetovepin)ispositivetomakeitglow.
Ifyouconnecta5voltssupplyacrossanLEDdirectly,itllsimplyblowupsinceitexceeds
thevoltageratingoftheLED.Topreventthat,weusuallyconnectacurrentlimitingresistor
inserieswiththeLEDtodividethevoltagedrop,sothatyourLEDissafeandkeepson
glowing.Usuallyanyresistorhavingvalueinbetween100ohmsand1kohmswillwork

goodforthis.Butdontconnectaresistorhavingtoohighresistance.
ThiswillnotleaveenoughvoltageacrosstheLEDtomakeitglow.
TheGPIOpinsofyourRPiarecapableofgeneratingthesedifferent
voltagelevels.ThisiswhyyouprogramtheRPitogeneratea
particularvoltagelevelonaparticularpin.
Alright,nowletsgettothecircuitdiagram.

Circuit
Disclaimer:WeABSOLUTELYDONOTtakeanyresponsibilityof
youmessingthingsup.Thecircuitshownbelowistestedand
worksjustfine,howeverifyoumakewrongconnectionsand/or
DetailedDiagram
shorttheboardanddamageyourRaspberryPi,itsallonyou.In
ofanLED
short,PROCEEDATYOUROWNRISK.Also,bewareof
ELECTROSTATICDISCHARGE.TheGPIOpinsofyourRaspberryPi
areconnecteddirectlytotheBCM2835CPUspins.Thereisnoprotection.Sodontmess
around.Ifyoudontfeelconfident,tryusingsomethinglikeaGertboardasanintermediate
interface.
Wellbeusingasolderlessbreadboardtomakethecircuit.Ifyoudontknowhowtomake
circuitsonabreadboard,trywatchingthisvideofirst.Thingsthatwellneedare
RaspberryPiandaccessories
F/Mjumperwires(acombinationofF/FandM/Mwillalsowork)
AnLED(3mmor5mm)
Two330ohmsresistor
Onepushbutton
Checkoutthefollowingcircuit.Wellimplementtheregionmarkedinredfornow,whichis
theLEDblinky.Noticethatpin7ofRPiisconnectedtothepositiveendofthecircuitand
pin6(whichisground)isconnectedtothenegativeendofthecircuit.
Thismeansthatwhenpin7isdrivenhigh,ahighvoltagelevel(usually5v)isgeneratedat
pin7,whichglowstheLED.Andwhenpin7isdrivenlow,alowvoltagelevel(usually0v)
isgeneratedatpin7,whichturnsofftheLED.
Cool!Onceyouredonemakingthecircuitintheredregion,proceedtothenextsection
wherewelearnhowtoprogramyourRPiusingtheRPi.GPIOlibrary.

RaspberryPiGPIOExampleCircuit.TheREDregionistheLEDblinkycircuit.

Herearesomepicturesofhowthecircuitshouldlooklikeonabreadboard

LEDBlinkyBreadboardCircuit

RaspberryPiLEDBlinky

UsingRPi.GPIOLibrary
ImportingModule
TheRPi.GPIOpackageallowsustocontroltheGPIOpinsbymeansofclasses.Westart
byimportingthemodulesbytyping
import RPi.GPIO as GPIO
ThisallowsustoreferthemodulebysimplymentioningGPIOinsteadofitsfullname
RPi.GPIO.
SpecifyModeofOperation
Thenextstepistospecifythemodeinwhichwellbeusingthemodule.Rememberthat
wementionedthatRPi(BOARD)andtheCPU(BCM)havedifferentpinnumbers?Thisis
wherethismatters.Youneedtochoosebetweenthetwosystems.Youcandosoby
typing
GPIO.setmode(GPIO.BOARD) # for RPi numbering
# or
GPIO.setmode(GPIO.BCM) # for CPU numbering
SetupaChannel
Nextweneedtosetupthedesiredchannelaseitherinputoroutput.Thiscanbedoneby
typing

GPIO.setup(channel, GPIO.IN) # input channel


# or
GPIO.setup(channel, GPIO.OUT) # output channel
Forinstance,fortheLEDblinky,weconnectedpin7ontheboardtotheLED.Thismeans
thatwemustconfigurethatpinasanoutputchannel.Also,recallthatthatpin7onboard
ismappedtoGPIO4oftheCPU.Sothisishowyoudo
GPIO.setup(7, GPIO.OUT) # if BOARD numbering system is used
# or
GPIO.setup(4, GPIO.OUT) # if BCM numbering system is used
ItisrecommendedthatyoufollowtheBOARDnumberingsystemsinceitiseasierto
follow.Intheenditdoesntmatterwhichoneyoufollow,justchooseoneandsticktoit.
DriveaChannel
Nextstepistodrivethechannelhighorlow.Thiscanbedonebytyping
GPIO.output(channel, state)
Forinstance,todrivepin7high,wetypeanyofthefollowing
GPIO.output(7, True)
# or
GPIO.output(7, GPIO.HIGH)
# or
GPIO.output(7, 1)
Todrivethesamepin7low,wetype
GPIO.output(7, False)
# or
GPIO.output(7, GPIO.LOW)
# or
GPIO.output(7, 0)
ReadaChannel
InordertoreadthevalueofanyGPIOpin,simplytype
GPIO.input(channel)
Welllearnhowtouseinlaterinthistutorial.WedontneeditforLEDblinkysinceallour
pinsareoutputpins.
Cleanup
AndoncewearedonewithalltheGPIOoperations,weneedtocleanupandfreeany

resourcesthatwemighthaveused.Thisisnotrequiredbutisconsideredagood
programmingpractice.Allyouneedtodoistotype
GPIO.cleanup()

TimingConsiderations
Anotherthingthatyouneedtoknowistheconceptofdelay.Thethingisthatwhenthe
LEDblinks,youactuallywanttoseeitblink.Itshouldntblinksofastthatyoualwaysseeit
on,anditshouldntblinksoslowthatyoualwaysseeitoff/on.Also,youneedtocontrolthe
rateatwhichtheLEDblinks(sayyouwanttheLEDtoblinkeveryquarterofasecond).So
herestheflowhowitgoes
1.TurnLEDon.
2.Waitforawhile.
3.TurnLEDoff.
4.Waitforawhile.
5.Repeatsteps14.
Inordertoachievesteps2and4mentionedabove,Pythonhasatimelibrarywhichhasa
functioncalledsleep()whichdoesexactlythesamething!Hereshowweuseit
import time # import 'time' library
time.sleep(n) # sleep for 'n' seconds
Ithinkthatsallyouneedtoknowtostartprogramming.Iassumethatyourefamiliarwith
somebasicPythonprocedures.Ifnot,pleaselearnthemfirstandthencomeback!

LetsCode!
Alrightfellas,timetogetourhandsdirtyandstartprogramming!Wearegoingtouse
Python2.7.3towritethecode.Towritethecode,openupyourfavoritetexteditor(like
gedit,Geany,etc).UsuallyforPython,weprefertouseIDLE.Sogototheterminaland
type
sudo idle
WeneedtorunIDLEassuperusersinceRPi.GPIOlibraryneedsthoseprivilegesto
controlthehardwarepins.DonotopenIDLE3,werenotusingPython3.
Next,typeinthefollowingcode
1
2
3
4
5

import RPi.GPIO as GPIO


import time

pin = 7
GPIO.setmode(GPIO.BOARD)

## Import GPIO Library


## Import 'time' library (for 'slee
## We're working with pin 7
## Use BOARD pin numbering

5
6
7
8
9
10
11
12
13

GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.OUT)

GPIO.output(pin, GPIO.HIGH)
time.sleep(1)
GPIO.output(pin, GPIO.LOW)
time.sleep(1)

GPIO.cleanup()

## Use BOARD pin numbering


## Set pin 7 to OUTPUT
##
##
##
##

Turn
Wait
Turn
Wait

on GPIO pin (HIGH)


1 second
off GPIO pin (LOW)
1 second

## Cleanup

Onceyouaredone,savethefileandgiveitanynameyouwish(likeblinky.py).Once
youaredone,runitbyhittingF5.Ifyouhavetypedanythingwrong,youwillseetheerror
boxpoppedup.Ifitsayssomekindofsyntaxerror,doublecheckthatyouarerunning
IDLEandnotIDLE3.Ifitsaysinsufficientpermission,makesurethatyouarerunning
IDLEasasuperuser(byusingsudo).
Youcanalsorunitfromtheterminalbytypingthefollowingfromtheworkingdirectory
sudo python blinky.py
Whatdidyousee?DidyourLEDblink?Ifeverythingwentokay,yourLEDwouldhave
blinked,butjustonce.Thatsbecausewehaventimplementedtheloopyet!Letsmodify
thecodeas
1
2
3
4
5
6
7
8
9
10
11
12
13
14

import RPi.GPIO as GPIO


import time

pin = 7
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.OUT)

for i in range (0, 20):


GPIO.output(pin, GPIO.HIGH)
time.sleep(1)
GPIO.output(pin, GPIO.LOW)
time.sleep(1)

GPIO.cleanup()

## Import GPIO Library


## Import 'time' library (for 'slee
## We're working with pin 7
## Use BOARD pin numbering
## Set pin 7 to OUTPUT
##
##
##
##
##

Repeat 20 times
Turn on GPIO pin (HIGH)
Wait 1 second
Turn off GPIO pin (LOW)
Wait 1 second

## Cleanup

MakesureyouindentyourcodeproperlyusingTABratherthanspaces.Python
dependsheavilyuponproperindentationofcode.Saveitandrunit.Whatdoyousee?Did
theLEDblink20times?!Woah,thatsabigdeal!Goodjob!:)
Nowtryplayingaround!Changethenumberoftimestheloophastorepeat,changethe
delay,etc.
Butwhyblinkitonly20times?Whatifyouwanttoblinkitforever?!Forthat,youwould
needtoreplacetheforstatementwiththefollowing
while
#
#
#

True:
loop code goes here
This loop iterates infinitely
since the condition of the

You might also like