Using The Raspberry Pi GPIO With Python MaxEmbedded
Using The Raspberry Pi GPIO With Python 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)
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
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
pin = 7
GPIO.setmode(GPIO.BOARD)
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()
Turn
Wait
Turn
Wait
## 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
pin = 7
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.OUT)
GPIO.cleanup()
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