0% found this document useful (0 votes)
198 views11 pages

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
198 views11 pages

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link]

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)

tar zxvf [Link]

tar zxvf [Link]


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

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](channel, [Link]) # input channel


# or
[Link](channel, [Link]) # output channel
Forinstance,fortheLEDblinky,[Link]
[Link],recallthatthatpin7onboard
[Link]
[Link](7, [Link]) # if BOARD numbering system is used
# or
[Link](4, [Link]) # if BCM numbering system is used
ItisrecommendedthatyoufollowtheBOARDnumberingsystemsinceitiseasierto
[Link],justchooseoneandsticktoit.
DriveaChannel
[Link]
[Link](channel, state)
Forinstance,todrivepin7high,wetypeanyofthefollowing
[Link](7, True)
# or
[Link](7, [Link])
# or
[Link](7, 1)
Todrivethesamepin7low,wetype
[Link](7, False)
# or
[Link](7, [Link])
# or
[Link](7, 0)
ReadaChannel
InordertoreadthevalueofanyGPIOpin,simplytype
[Link](channel)
[Link]
pinsareoutputpins.
Cleanup
AndoncewearedonewithalltheGPIOoperations,weneedtocleanupandfreeany

[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

import [Link] as GPIO


import time

pin = 7
[Link]([Link])

## 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

[Link]([Link])
[Link](pin, [Link])

[Link](pin, [Link])
[Link](1)
[Link](pin, [Link])
[Link](1)

[Link]()

## 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([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

import [Link] as GPIO


import time

pin = 7
[Link]([Link])
[Link](pin, [Link])

for i in range (0, 20):


[Link](pin, [Link])
[Link](1)
[Link](pin, [Link])
[Link](1)

[Link]()

## 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

[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

You might also like