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,[Link]!
Nowwhat?YoudidntbuyaRaspberryPijusttoreplaceyourcomputer,didyou?Well,
RaspberryPicandoalotmoremuchmorethanyourcomputercando!
Didyounoticethattherearelotsoftiny
littlepinsononecornerofyourRPi?
ThesearecalledGeneralPurposeInput
Outputpins(orGPIOpins).Thesepins
allowyourRPitobeconnectedtothe
[Link]
Bhave26pins(17GPIO)whereasthe
modelsB+andB2comewith40pins(26
GPIO).ThemodelsB+andB2arepin
compatiblewithmodelsAandB.
RaspberryPiModelA/BGPIO
Theeasiestwaytocontrolthesepinsisto
[Link]
[Link],welllearnhowtoinstallthelibrary,[Link]
thispost,youshouldbeabletoperformsimpleI/OoperationsusingyourRPisGPIOpins.
Contents
RaspberryPiPinConfiguration
[Link]
Installation
HelloWorldwithRaspberryPiLEDBlinky
Alittlebackground
Circuit
[Link]
TimingConsiderations
LetsCode!
Video
ALevelup:ReadingInputs
Algorithm
LetsCode!
Test:DesignaCounter
Whatnow?
Summary
RaspberryPiPinConfiguration
Asmentionedearlier,RPimodelsA/BandB+[Link]
([Link])showsthepinlayoutofmodelsA/B(rev2)andB+.
RPiPinLayoutforModelBRev2andModelB+(Imagesource
[Link])
[Link]
consistsofpins1through26,[Link]
remainingpinsconsistofpowersupply(5vand3.3v),[Link]
modelB+consistsofallthepinsshownabove,outofwhich26canbeusedasGPIO.
Thelabelsmentionedontheleftandrightofthepinsrefertothepinnumbersonthe
[Link],pinGPIO16ofBCM2835CPUisconnectedtopin36ofRPi
B+.Makessense?Whatdifferencedoesitmaketoyouwellseeinawhile!:)
[Link]
[Link],welluse
[Link].Startingversion0.5.6,thelibraryhassupportforRPimodel
B+[Link],itstill
lackssupportforSPI,I2C,hardwarePWMandserialfunctionality,whichareplannedtobe
added([Link],thismightchange).
ThisisareallysimplelibrarywhichallowsyoutoreadtoandwritefromanyGPIOpinby
variousmeans(likepolling,triggers,events,etc).Inthispost,welldiscussthepolling
method(dontworryaboutthename,[Link]),
whereasIlldealwiththeothermethodsinmynextpost.
Installation
Method1InstallfromRepositories
[Link]
doesnt,allyouneedtodoistoinstallthelatestversionfromtherepositoriesbyrunning
thefollowingintheterminal(holdsgoodforRaspbianonly)
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install [Link] [Link]
Thatsallyouneedtodo!Simple,eh?!:)
Method2BuildfromSource
Ifyouwanttobuildfromthesource,[Link]
downloaded,[Link],browsetothedirectorywhere
youdownloadedthelibraryandtypeinthefollowingtoextract(replacethenameofthefile
withtheonethatyoudownloaded)
HelloWorldwithRaspberryPiLEDBlinky
AHelloworldprogramisatypicallyoneofthesimplestprogramsthatonecanpossibly
[Link],itis,likeany
otherembeddedsystem,[Link]
thingsgenerallywork,butalsomakessurethatallthetoolsanddevicesareproperlyset
upandworkingproperly.
Inthispost,[Link]
well,[Link]
howtodothesameusingC,andmaybeanotherpostonhowtowriteyourownLinux
kernelmodulestocontroltheGPIO.:)
Alittlebackground
Forthosewhoarenotfamiliarwithcircuits,[Link]
[Link],LEDsare
littledevicesthatglowandemitlightofsomecolor(red,blue,green,yellow,white,etc)
uponprovidingapositivevoltageacrossitspins(forwardbias).Ifyoureversethepolarity,
[Link],youmustmakesurethatthe
voltagedropacrosstheLED(from+vetovepin)ispositivetomakeitglow.
Ifyouconnecta5voltssupplyacrossanLEDdirectly,itllsimplyblowupsinceitexceeds
[Link],weusuallyconnectacurrentlimitingresistor
inserieswiththeLEDtodividethevoltagedrop,sothatyourLEDissafeandkeepson
glowing.Usuallyanyresistorhavingvalueinbetween100ohmsand1kohmswillwork
[Link].
ThiswillnotleaveenoughvoltageacrosstheLEDtomakeitglow.
TheGPIOpinsofyourRPiarecapableofgeneratingthesedifferent
[Link]
particularvoltagelevelonaparticularpin.
Alright,nowletsgettothecircuitdiagram.
Circuit
Disclaimer:WeABSOLUTELYDONOTtakeanyresponsibilityof
[Link]
worksjustfine,howeverifyoumakewrongconnectionsand/or
DetailedDiagram
shorttheboardanddamageyourRaspberryPi,[Link]
ofanLED
short,[Link],bewareof
[Link]
[Link]
[Link],tryusingsomethinglikeaGertboardasanintermediate
interface.
[Link]
circuitsonabreadboard,[Link]
RaspberryPiandaccessories
F/Mjumperwires(acombinationofF/FandM/Mwillalsowork)
AnLED(3mmor5mm)
Two330ohmsresistor
Onepushbutton
[Link],whichis
theLEDblinky.Noticethatpin7ofRPiisconnectedtothepositiveendofthecircuitand
pin6(whichisground)isconnectedtothenegativeendofthecircuit.
Thismeansthatwhenpin7isdrivenhigh,ahighvoltagelevel(usually5v)isgeneratedat
pin7,whichglowstheLED.Andwhenpin7isdrivenlow,alowvoltagelevel(usually0v)
isgeneratedatpin7,whichturnsofftheLED.
Cool!Onceyouredonemakingthecircuitintheredregion,proceedtothenextsection
[Link].
[Link].
Herearesomepicturesofhowthecircuitshouldlooklikeonabreadboard
LEDBlinkyBreadboardCircuit
RaspberryPiLEDBlinky
[Link]
ImportingModule
[Link]
byimportingthemodulesbytyping
import [Link] as GPIO
ThisallowsustoreferthemodulebysimplymentioningGPIOinsteadofitsfullname
[Link].
SpecifyModeofOperation
[Link]
wementionedthatRPi(BOARD)andtheCPU(BCM)havedifferentpinnumbers?Thisis
[Link]
typing
[Link]([Link]) # for RPi numbering
# or
[Link]([Link]) # for CPU numbering
SetupaChannel
[Link]
typing
[Link]
[Link]
[Link]()
TimingConsiderations
[Link]
LEDblinks,[Link]
on,anditshouldntblinksoslowthatyoualwaysseeitoff/[Link],youneedtocontrolthe
rateatwhichtheLEDblinks(sayyouwanttheLEDtoblinkeveryquarterofasecond).So
herestheflowhowitgoes
[Link].
[Link].
[Link].
[Link].
5.Repeatsteps14.
Inordertoachievesteps2and4mentionedabove,Pythonhasatimelibrarywhichhasa
functioncalledsleep()whichdoesexactlythesamething!Hereshowweuseit
import time # import 'time' library
[Link](n) # sleep for 'n' seconds
[Link]
[Link],pleaselearnthemfirstandthencomeback!
LetsCode!
Alrightfellas,timetogetourhandsdirtyandstartprogramming!Wearegoingtouse
[Link],openupyourfavoritetexteditor(like
gedit,Geany,etc).UsuallyforPython,[Link]
type
sudo idle
[Link]
controlthehardwarepins.DonotopenIDLE3,werenotusingPython3.
Next,typeinthefollowingcode
1
2
3
4
5
pin = 7
[Link]([Link])
5
6
7
8
9
10
11
12
13
[Link]([Link])
[Link](pin, [Link])
[Link](pin, [Link])
[Link](1)
[Link](pin, [Link])
[Link](1)
[Link]()
Turn
Wait
Turn
Wait
## Cleanup
Onceyouaredone,savethefileandgiveitanynameyouwish([Link]).Once
youaredone,[Link],youwillseetheerror
[Link],doublecheckthatyouarerunning
[Link],makesurethatyouarerunning
IDLEasasuperuser(byusingsudo).
Youcanalsorunitfromtheterminalbytypingthefollowingfromtheworkingdirectory
sudo python [Link]
Whatdidyousee?DidyourLEDblink?Ifeverythingwentokay,yourLEDwouldhave
blinked,[Link]!Letsmodify
thecodeas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
pin = 7
[Link]([Link])
[Link](pin, [Link])
[Link]()
Repeat 20 times
Turn on GPIO pin (HIGH)
Wait 1 second
Turn off GPIO pin (LOW)
Wait 1 second
## Cleanup
[Link]
[Link]?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