Make: Getting Started with Raspberry Pi: Electronic

Make: Getting Started with Raspberry Pi: Electronic
GettingStartedwithRaspberryPi
MattRichardsonandShawnWallace
SecondEdition
GettingStartedwithRaspberryPi
byMattRichardsonandShawnWallace
Copyright©2015MattRichardsonandShawnWallace.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyMakerMedia,Inc.,1005GravensteinHighwayNorth,Sebastopol,CA
95472.
MakerMediabooksmaybepurchasedforeducational,business,orsalespromotionaluse.
Onlineeditionsarealsoavailableformosttitles(http://safaribooksonline.com).Formore
information,contactourdistributor’scorporate/institutionalsalesdepartment:[email protected]
Editor:BrianJepson
ProductionEditor:MelanieYarbrough
Copyeditor:JasmineKwityn
Proofreader:AmandaKersey
Indexer:WordCoIndexingServices
InteriorDesigner:RonBilodeauandNellieMcKesson
CoverDesigner:BrianJepson
Illustrator:MarcdeVinck
December2012:FirstEdition
October2014:SecondEdition
RevisionHistoryfortheSecondEdition:
2014-10-13:FirstRelease
Seehttp://oreilly.com/catalog/errata.csp?isbn=9781457186127forreleasedetails.
Make:,MakerShed,andMakerFaireareregisteredtrademarksofMakerMedia,Inc.The
MakerMedialogoisatrademarkofMakerMedia,Inc.GettingStartedwithRaspberryPi
andrelatedtradedressaretrademarksofMakerMedia,Inc.
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproducts
areclaimedastrademarks.Wherethosedesignationsappearinthisbook,andMaker
Media,Inc.wasawareofatrademarkclaim,thedesignationshavebeenprintedincapsor
initialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthisbook,thepublisherand
authorsassumenoresponsibilityforerrorsoromissions,orfordamagesresultingfromthe
useoftheinformationcontainedherein.
978-1-457-18612-7
[LSI]
Preface
It’seasytounderstandwhypeoplewereskepticaloftheRaspberryPiwhenitwasfirst
announced.Acredit-card–sizedcomputerfor$35seemedlikeapipedream.Whichis
why,whenitstartedshipping,theRaspberryPicreatedafrenzyofexcitement.
Demandoutstrippedsupplyformonthsandthewaitlistsfortheseminicomputerswere
verylong.Besidestheprice,whatisitabouttheRaspberryPithatteststhepatienceofthis
hardware-hungrymassofpeople?BeforewegetintoeverythingthatmakestheRaspberry
Pisogreat,let’stalkaboutitsintendedaudience.
EbenUptonandhiscolleaguesattheUniversityofCambridgenoticedthattoday’s
studentsapplyingtostudycomputersciencedon’thavetheskillsthattheydidinthe
1990s.
Theyattributethisto—amongotherfactors—the“riseofthehomePCandgames
consoletoreplacetheAmigas,BBCMicros,SpectrumZXandCommodore64machines
thatpeopleofanearliergenerationlearnedtoprogramon.”1
Becausethecomputerhasbecomeimportantforeverymemberofthehousehold,itmay
alsodiscourageyoungermembersfromtinkeringaroundandpossiblyputtingsucha
criticaltooloutofcommissionforthefamily.
Butmobilephoneandtabletprocessorshaverecentlybecomelessexpensivewhilegetting
morepowerful,clearingthepathfortheRaspberryPi’sleapintotheworldofultra-cheapyet-serviceablecomputerboards.
AsLinusTorvalds,thefounderofLinux,saidinaninterviewwithBBCNews,Raspberry
Pimakesitpossibleto“affordfailure.”2
WhatCanYouDowithIt?
OneofthegreatthingsabouttheRaspberryPiisthatthere’snosinglewaytouseit.
WhetheryoujustwanttowatchvideosandsurftheWeb,oryouwanttohack,learn,and
makewiththeboard,theRaspberryPiisaflexibleplatformforfun,utility,and
experimentation.HerearejustafewofthedifferentwaysyoucanuseaRaspberryPi:
General-purposecomputing
It’simportanttorememberthattheRaspberryPiisacomputerandyoucan,infact,use
itasone.AfteryougetitupandrunninginChapter1,youcanchoosetohaveitboot
intoagraphicaldesktopenvironmentwithawebbrowser,whichisalotofwhatweuse
computersforthesedays.GoingbeyondtheWeb,youcaninstallawidevarietyoffree
software,suchastheLibreOfficeproductivitysuite,whichallowsyoutoworkwith
documentsandspreadsheetswhenyoudon’thaveanInternetconnection.
Learningtoprogram
BecausetheRaspberryPiismeantasaneducationaltooltoencouragekidsto
experimentwithcomputers,itcomespreloadedwithinterpretersandcompilersfor
manydifferentprogramminglanguages.Forthebeginner,there’sScratch,agraphical
programminglanguagefromMIT,whichwecoverinChapter6.Ifyou’reeagertojump
intowritingcode,thePythonprogramminglanguageisagreatwaytogetstarted,and
wecoverthebasicsofitinChapter4.Butyou’renotlimitedtoonlyScratchand
Python.YoucanwriteprogramsforyourRaspberryPiinmanydifferentprogramming
languages,includingC,Ruby,Java,andPerl.
Projectplatform
TheRaspberryPidifferentiatesitselffromaregularcomputernotonlyinitspriceand
size,butalsobecauseofitsabilitytointegratewithelectronicsprojects.Startingin
Chapter8,we’llshowyouhowtousetheRaspberryPitocontrolLEDsandAC
devices,andyou’lllearnhowtoreadthestateofbuttonsandswitches.
Productprototyping
MoreandmoreelectronicsproductsuseLinuxcomputersinside,andnowthisworldof
embeddedLinuxismoreaccessiblethanever.Let’ssayyoucreatesomethingwithyour
RaspberryPithatwouldmakeagreatproductfortheeverydayconsumer.Withthe
RaspberryPiComputeModule(asmallerversionoftheboardthatwe’lldiscusslater),
itbecomespossibletocreateaproductwithaRaspberryPiatheart.
RaspberryPiforMakers
Asmakers,wehavealotofchoiceswhenitcomestoplatformsonwhichtobuild
technology-basedprojects.Lately,microcontrollerdevelopmentboardsliketheArduino
havebeenapopularchoicebecausethey’vebecomeveryeasytoworkwith.Butsystem
onachipplatformsliketheRaspberryPiarealotdifferentthantraditional
microcontrollersinmanyways.Infact,theRaspberryPihasmoreincommonwithyour
computerthanitdoeswithanArduino.
ThisisnottosaythataRaspberryPiisbetterthanatraditionalmicrocontroller;it’sjust
different.Forinstance,ifyouwanttomakeabasicthermostat,you’reprobablybetteroff
usinganArduinoUnoorsimilarmicrocontrollerforpurposesofsimplicity.Butifyou
wanttobeabletoremotelyaccessthethermostatviatheWebtochangeitssettingsand
downloadtemperaturelogfiles,youshouldconsiderusingtheRaspberryPi.
Choosingbetweenoneortheotherwilldependonyourproject’srequirements,andin
fact,youdon’tnecessarilyhavetochoosebetweenthetwo.InChapter7,we’llshowyou
howtousetheRaspberryPitoprogramtheArduinoandgetthemcommunicatingwith
eachother.
Asyoureadthisbook,you’llgainabetterunderstandingofthestrengthsoftheRaspberry
Piandhowitcanbecomeanotherusefultoolinthemaker’stoolbox.
ButWait…There’sMore!
There’ssomuchyoucandowiththeRaspberryPi,wecouldn’tfititallintoonebook.Hereareseveralotherways
youcanuseit:
Mediacenter
BecausetheRaspberryPihasbothHDMIandcompositevideooutputs,it’seasytoconnecttotelevisions.Italso
hasenoughprocessingpowertoplayfullscreenvideoinhighdefinition.Toleveragethesecapabilities,
contributorstothefreeandopensourcemediaplayerXBMChaveportedtheirprojecttotheRaspberryPi.XBMC
canplaymanydifferentmediaformats,anditsinterfaceisdesignedwithlargebuttonsandtextsothatitcanbe
easilycontrolledfromthecouch.XBMCmakestheRaspberryPiafullycustomizablehomeentertainmentcenter
component.
“Baremetal”computerhacking
Mostpeoplewhowritecomputerprogramswritecodethatrunswithinanoperatingsystem,suchasWindows,
MacOS,or—inthecaseofRaspberryPi—Linux.Butwhatifyoucouldwritecodethatrunsdirectlyonthe
processorwithouttheneedforanoperatingsystem?Youcouldevenwriteyourownoperatingsystemfrom
scratchifyouweresoinclined.TheUniversityofCambridge’sComputerLaboratoryhaspublishedafreeonline
coursewhichwalksyouthroughtheprocessofwritingyourownOSusingassemblycode.
LinuxandRaspberryPi
Yourtypicalcomputerisrunninganoperatingsystem,suchasWindows,OSX,orLinux.
It’swhatstartsupwhenyouturnyourcomputeron,anditprovidesyourapplications
accesstohardwarefunctionsofyourcomputer.Forinstance,ifyou’rewritingan
applicationthataccessestheInternet,youcanusetheoperatingsystem’sfunctionstodo
so.Youdon’tneedtounderstandandwritecodeforeverysingletypeofEthernetorWiFi
hardwareoutthere.
Likeanyothercomputer,theRaspberryPialsousesanoperatingsystem,andthe“stock”
OSisaflavorofLinuxcalledRaspbian.LinuxisagreatmatchforRaspberryPibecause
it’sfreeandopensource.Ononehand,itkeepsthepriceoftheplatformlow,andonthe
other,itmakesitmorehackable.
Andyou’renotlimitedtojustRaspbian,astherearemanydifferentflavors,or
distributions,ofLinuxthatyoucanloadontotheRaspberryPi.Thereareevenseveral
non-LinuxOSoptionsavailableoutthere.Throughoutthisbook,we’llbeusingthe
standardRaspbiandistributionthat’savailablefromRaspberryPi’sdownloadpage.
Ifyou’renotfamiliarwithLinux,don’tworry,Chapter2willequipyouwiththe
fundamentalsyou’llneedtoknowtogetaround.
WhatOthersHaveDonewithIt
Whenyouhaveaccesstoanexcitingnewtechnology,itcanbetoughdecidingwhattodo
withit.Ifyou’renotsure,there’snoshortageofinterestingandcreativeRaspberryPi
projectsouttheretogetinspirationfrom.AseditorsforMake:,we’veseenalotof
fantasticusesoftheRaspberryPicomeourwayandwewanttosharesomeofour
favorites:
ArcadeGameCoffeeTable
Instructablesusergrahamgeldinguploadedastep-by-steptutorialonhowtomakea
coffeetablethatdoublesasaclassicarcadegameemulatorusingtheRaspberryPi.To
getthegamesrunningonthePi,heusedMAME(MultipleArcadeMachineEmulator),
afree,opensourcesoftwareprojectthatletsyourunclassicarcadegamesonmodern
computers.Withinthetableitself,hemounteda24-inchLCDscreenconnectedtothe
RaspiberryPiviaHDMI,classicarcadebuttons,andajoystickconnectedtothePi’s
GPIOpinstobeusedasinputs.
RasPod
AneeshDogra,ateenagerinIndia,wasoneoftherunnersupinRaspberryPi
Foundation’s2012SummerCodingContest.HecreatedRaspod,aRaspberryPi–based,
web-controlledMP3audioplayer.BuiltwithPythonandawebframeworkcalled
Tornado,RaspodletsyouremotelylogintoyourRaspberryPitostartandstopthe
music,changethevolume,selectsongs,andmakeplaylists.Themusiccomesoutofthe
RaspberryPi’saudiojack,soyoucanuseitwithapairofcomputerspeakers,oryou
canconnectittoastereosystemtoenjoythetunes.
RaspberryPiSupercomputer
Manysupercomputersaremadeofclustersofstandardcomputerslinkedtogether,and
computationaljobsaredividedamongallthedifferentprocessors.Agroupof
computationalengineersattheUniversityofSouthamptonintheUnitedKingdom
linked64RaspberryPistocreateaninexpensivesupercomputer.Whileit’snowhere
nearthecomputationalpowerofthetop-performingsupercomputersoftoday,it
demonstratestheprinciplesbehindengineeringsuchsystems.Bestofall,therack
systemusedtoholdalltheseRaspberryPiswasbuiltwithLegobricksbytheteam
leader’ssix-year-oldson.
IfyoudosomethinginterestingwithyourRaspberryPi,we’dlovetohearaboutit.You
cansubmityourprojectstotheMake:editorialteamthroughourcontributeformon
Makezine.com.
ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:
Italic
Indicatesnewterms,URLs,emailaddresses,filenames,andfileextensions.
Constantwidth
Usedforprogramlistings,aswellaswithinparagraphstorefertoprogramelements
suchasvariableorfunctionnames,databases,datatypes,environmentvariables,
statements,andkeywords.
Constantwidthbold
Showscommandsorothertextthatshouldbetypedliterallybytheuser.
Constantwidthitalic
Showstextthatshouldbereplacedwithuser-suppliedvaluesorbyvaluesdetermined
bycontext.
Note
Thisiconsignifiesatip,suggestion,orgeneralnote.
Warning
Thisiconindicatesawarningorcaution.
UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,youmayusethecodeinthis
bookinyourprogramsanddocumentation.Youdonotneedtocontactusforpermission
unlessyou’rereproducingasignificantportionofthecode.Forexample,writinga
programthatusesseveralchunksofcodefromthisbookdoesnotrequirepermission.
SellingordistributingaCD-ROMofexamplesfromMake:booksdoesrequire
permission.Answeringaquestionbycitingthisbookandquotingexamplecodedoesnot
requirepermission.Incorporatingasignificantamountofexamplecodefromthisbook
intoyourproduct’sdocumentationdoesrequirepermission.
Weappreciate,butdonotrequire,attribution.Anattributionusuallyincludesthetitle,
author,publisher,andISBN.Forexample:“GettingStartedWithRaspberryPibyMatt
RichardsonandShawnWallace(MakerMedia).Copyright2015MattRichardsonand
ShawnWallace,978-1-4493-4421-4.”
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseorthepermissiongivenhere,
[email protected]
Safari®BooksOnline
SafariBooksOnlineisanon-demanddigitallibrarythatdeliversexpertcontentinboth
bookandvideoformfromtheworld’sleadingauthorsintechnologyandbusiness.
Technologyprofessionals,softwaredevelopers,webdesigners,andbusinessandcreative
professionalsuseSafariBooksOnlineastheirprimaryresourceforresearch,problem
solving,learning,andcertificationtraining.
SafariBooksOnlineoffersarangeofplansandpricingforenterprise,government,
education,andindividuals.
Membershaveaccesstothousandsofbooks,trainingvideos,andprepublication
manuscriptsinonefullysearchabledatabasefrompublisherslikeMakerMedia,O’Reilly
Media,PrenticeHallProfessional,Addison-WesleyProfessional,MicrosoftPress,Sams,
Que,PeachpitPress,FocalPress,CiscoPress,JohnWiley&Sons,Syngress,Morgan
Kaufmann,IBMRedbooks,Packt,AdobePress,FTPress,Apress,Manning,NewRiders,
McGraw-Hill,Jones&Bartlett,CourseTechnology,andhundredsmore.Formore
informationaboutSafariBooksOnline,pleasevisitusonline.
HowtoContactUs
Pleaseaddresscommentsandquestionsconcerningthisbooktothepublisher:
Make:
1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheUnitedStatesorCanada)
707-829-0515(internationalorlocal)
707-829-0104(fax)
Make:unites,inspires,informs,andentertainsagrowingcommunityofresourcefulpeople
whoundertakeamazingprojectsintheirbackyards,basements,andgarages.Make:
celebratesyourrighttotweak,hack,andbendanytechnologytoyourwill.TheMake:
audiencecontinuestobeagrowingcultureandcommunitythatbelievesinbettering
ourselves,ourenvironment,oureducationalsystem—ourentireworld.Thisismuch
morethananaudience,it’saworldwidemovementthatMake:isleading—wecallitthe
MakerMovement.
FormoreinformationaboutMake:,visitusonline:
Make:magazine:http://makezine.com/magazine/
MakerFaire:http://makerfaire.com
Makezine.com:http://makezine.com
MakerShed:http://makershed.com/
Wehaveawebpageforthisbook,wherewelisterrata,examples,andanyadditional
information.Youcanaccessthispageathttp://bit.ly/gs_with_raspberry_pi.
Tocommentorasktechnicalquestionsaboutthisbook,sendemailto
[email protected]
Acknowledgments
We’dliketothankafewpeoplewhohaveprovidedtheirknowledge,support,advice,and
feedbacktoGettingStartedwithRaspberryPi:
BrianJepson
FrankTeng
AnnaFrance
MarcdeVinck
EbenUpton
TomIgoe
ClayShirky
JohnSchimmel
PhillipTorrone
LimorFried
KevinTownsend
AliSajjadi
AndrewRossi
1AboutRaspberryPi.
2LeoKelion,“LinusTorvalds:LinuxSucceededThankstoSelfishnessandTrust,”BBC
News,June12,2012.
Chapter1.GettingUpandRunning
AfewwordscomeupoverandoverwhenpeopletalkabouttheRaspberryPi:small,
cheap,hackable,educationoriented.However,itwouldbeamistaketodescribeitasplug
andplay,eventhoughitiseasyenoughtoplugitintoaTVsetandgetsomethingto
appearonthescreen.Thisisnotaconsumerdevice,anddependingonwhatyouintendto
dowithyourRaspberryPi,you’llneedtomakeanumberofdecisionsaboutperipherals
andsoftwarewhengettingupandrunning.
Ofcourse,thefirststepistoactuallyacquireaRaspberryPi.Chancesareyouhaveoneby
now,butifnot,theRaspberryPiFoundationhasarrangementswithafewmanufacturers
fromwhomyoucanbuyaPidirectlyatthewell-known$25-$35pricerange.Theyare:
PiSwag
Thefoundation’sonlinestore
PremierFarnell/Element14
ABritishelectronicsdistributorwithmanysubsidiariesallovertheworld(suchas
NewarkandMCMintheUnitedStates)
RSComponents
AnotherUK-basedglobalelectronicsdistributor(andparentofAlliedElectronicsinthe
UnitedStates))
TheRaspberryPi’slowpriceisobviouslyanimportantpartofthestory.Enablingthe
generalpublictogodirectlytoadistributorandordersmallquantitiesforthesameprice
offeredtoresellersisanunusualarrangement.Alotofpotentialresellerswereconfounded
bytheoriginalannouncementsofthepricepoint;itwashardtoseehowtherecouldbe
anyprofitmargin.That’swhyyou’llseeresellersaddingaslightmarkuptothe$35price
(usuallyto$40orso).Thoughthegeneralpubliccanstillbuydirectfromthedistributors
mentionedherefortheoriginalprice,theretailersandresellersoftencanfulfillorders
faster.BothMake:’sownMakerShedaswellasAdafruitaretwocompanieswhosell
RaspberryPisandaccessoriesforaslightmarkup.
Enoughmicroeconomicgossip;let’sstartbytakingacloserlookattheRaspberryPi
board.
ATouroftheBoards
TherearefourdifferentversionsoftheRaspberryPiboard.ThefirstversionistheModel
B,whichwasfollowedbyasimplerandcheaperModelA.In2014,theRaspberryPi
Foundationannouncedasignificantrevision(andimprovement)inthePi’sboarddesign:
theB+.TheB+isthestandardreferencemodelfortheforeseeablefuture.TheFoundation
hasalsocreatedaversionforembeddingthePiinproductscalledtheComputeModule.
AllfourversionsarepicturedinFigure1-1.
Figure1-1.TherearefourversionsoftheRaspberryPi:theModelB+,
ModelB,ModelA,andComputeModule(clockwisefromtop).TheModel
B+isthestandardreferencedesign.ModelAphotocourtesyofSparkFun
Electronics(CCBY2.0).
Let’sstartwithatourofwhatyou’llseewhenyoutakeitoutofthebox.
It’stemptingtothinkofRaspberryPiasamicrocontrollerdevelopmentboardlike
Arduinoorasalaptopreplacement.Infact,itismoreliketheexposedinnardsofamobile
devicewithmaker-friendlyheadersforvariousportsandfunctions.Figure1-2showsthe
partsoftheboard.
Figure1-2.AmapofthehardwareinterfaceoftheRaspberryPi
Here’sadescriptionofeachpart:
A:TheProcessor
AttheheartoftheRaspberryPiisthesamekindofprocessoryouwouldhavefoundin
theiPhone3GandtheKindle2,soyoucanthinkofthecapabilitiesoftheRaspberryPi
ascomparabletothosepowerfullittledevices.Thischipisa32-bit,700MHzsystem
onachip,whichisbuiltontheARM11architecture.ARMchipscomeinavarietyof
architectureswithdifferentcoresconfiguredtoprovidedifferentcapabilitiesatdifferent
pricepoints.TheModelBandB+have512MBofRAMandtheModelAhas256MB.
(ThefirstbatchofModelBshadonly256MBofRAM.)
B:Compositevideoandanalogaudioout
OntheModelB+,analogaudioandvideooutputsareavailableonastandard3.5mm4Poleplugconnector.Onesideoftheconnectingcableisafour-connectorminijack,and
theothersideisthreeRCAplugsforstereoaudio(redandwhite)andcompositeNTSC
orPALvideo(yellow).TheModelAandBPihasanRCA-typejackforcomposite
videoandaseparate3.5mmminijackforanalogaudio.
C:StatusLEDs
FiveindicatorLEDsprovidevisualfeedback(Table1-1).OntheModelB+,the
networkLEDsareontheethernetjackitself.
Table1-1.ThefivestatusLEDs
ACT Green
LightswhentheSDcardisaccessed(markedOKonearlierboards)
PWR Red
Hookedupto3.3Vpower
FDX Green
Onifnetworkadapterisfullduplex
LNK Green
Networkactivitylight
100
Yellow Onifthenetworkconnectionis100Mbps(someearlyboardshavea10Mmisprint)
D:ExternalUSBports
OntheModelB+,therearefourUSB2.0ports.TheModelBhastwo,andtheModelA
hasonlyone.SomeoftheearlyRaspberryPiboardswerelimitedintheamountof
currentthattheycouldprovide.SomeUSBdevicescandrawup500mA.Theoriginal
Piboardsupported100mAorso,butthenewerrevisionsareuptothefullUSB2.0
spec.Onewaytocheckyourboardistoseeifyouhavetwopolyfuseslimitingthe
current.TheModelB+addedbetterhotplugsupportandovercurrentprotection.You
canuseapoweredexternalhubifyouhaveaperipheralthatneedsmorepower.
E:Ethernetport
ThemodelB+andBhaveastandardRJ45Ethernetport.TheModelAdoesnot,but
canbeconnectedtoawirednetworkbyaUSBEthernetadapter(theportontheModel
BisactuallyanonboardUSBtoEthernetadapter).WiFiconnectivityviaaUSBdongle
isanotheroption.
F:HDMIconnector
TheHDMIportprovidesdigitalvideoandaudiooutput.Fourteendifferentvideo
resolutionsaresupported,andtheHDMIsignalcanbeconvertedtoDVI(usedbymany
monitors),composite(analogvideosignalusuallycarriedoverayellowRCA
connector),orSCART(aEuropeanstandardforconnectingaudio-visualequipment)
withexternaladapters.
G:Powerinput
Oneofthefirstthingsyou’llrealizeisthatthereisnopowerswitchonthePi.This
microUSBconnectorisusedtosupplypower(thisisn’tanadditionalUSBport;it’s
onlyforpower).MicroUSBwasselectedbecausetheconnectorischeapandUSB
powersuppliesareeasytofind.
H:TheSecureDigital(SD)cardslot
You’llnoticethere’snoharddriveonthePi;everythingisstoredonamicroSDcard.
Onereasonyou’llwantsomesortofprotectivecasesoonerthanlateristhatthesolder
jointsontheSDsocketmayfailiftheSDcardisaccidentallybent.TheModelB+hasa
slimmerprofilemicroSDslot,whichisabigimprovementovertheModelB’sfriction
fitslot.
Figure1-3showsallofthepowerandinput/output(I/O)pinsontheRaspberryPi.
Figure1-3.ThepinsandheadersontheRaspberryPi
Here’sadescriptionofthepinsandheadersshown:
A:General-purposeinput/output(GPIO)andotherpins
TheModelB+hasa2×20pinheaderandisthereferencestandardforthePi’sGPIO
header.Chapters8and9showhowtousethesepinstoreadbuttonsandswitchesand
controlactuatorslikeLEDs,relays,ormotors.TheolderModelBandAhadmostof
thesamepinspulledoutbutonthreeseparateheaders:a2x13pinheader,a2x4header,
anda1x8header.
B:TheCameraSerialInterface(CSI)connector
Thisportallowsacameramoduletobeconnecteddirectlytotheboard(seeFigure1-4)
.
C:TheDisplaySerialInterface(DSI)connector
Thisconnectoracceptsa15pinflatribboncablethatcanbeusedtocommunicatewith
anLCDorOLEDdisplayscreen.
Figure1-4.The5MegapixelRaspberryPicameramoduleconnects
directlytotheCSIconnector.Althoughthecameramoduleisvery
afforableat$25,thelackoffocusingoptics(andsensitivitytostatic)may
ormaynotbethebestfitforyourproject.SeeChapter11forafull
discussionofcameraandthePi.
TheProperPeripherals
Nowthatyouknowwhereeverythingisontheboard,you’llneedtoknowafewthings
abouttheproperperipheralstousewiththePi.Thereareabunchofprepackagedstarter
kitsthathavewell-vettedpartslists;thereareafewcaveatsandgotchaswhenfittingout
yourRaspberryPi.There’sadefinitivelistofsupportedperipheralsonthemainwiki,but
thesearethemostbasic:
Apowersupply
Thisisthemostimportantperipheraltogetright;youshoulduseamicroUSBadapter
thatcanprovide5Vandatleast700mAofcurrent(500mAfortheModelAorB+).A
cellphonechargerwon’tnecessarilycutit,evenifithasthecorrectconnector.Atypical
cellphonechargeronlyprovides400mAofcurrentorless,butchecktheratingmarked
ontheback.AnunderpoweredPimaystillseemtoworkbutwillbeflakyandmayfail
unpredictably.TheexceptionisifyouarerunningthePiheadless(i.e.,withoutmonitor
orkeyboard).AheadlessPiwillrunona500mAsupply,suchaswhenconnectedtoa
laptop.Therearealsoanumberofbattery-packsolutionsforthePi;thesamerules
applythere.
Note
WiththecurrentversionofthePiboard,itispossibletopowerthePifromaUSBhubthat
feedspowerbackintooneofthetwoexternalUSBports.However,thereisn’tmuch
protectioncircuitry,soitmaynotbethebestideatopoweritovertheexternalUSBports.
Thisisespeciallytrueifyou’regoingtobedoingelectronicsprototypingwhereyoumay
accidentallycreateshortsthatmaydrawalotofcurrent.
AmicroSDcard
You’llneedatleast4GB,anditshouldbeaClass4card.Class4cardsarecapableof
transferringatleast4MB/sec.SomeoftheearlierRaspberryPiboardshadproblems
withClass6orhighercards,whicharecapableoffasterspeedsbutarelessstable.
HighercapacitySDHCcardsarecompatibleaswell.TheolderModelBboardsaccept
thelargerSDcard;anadapterformicroSDcardsworkswiththeseboards.
AnHDMIcable
Ifyou’reconnectingtoamonitor,you’llneedthis,oranappropriateadapterforaDVI
monitor.YoucanalsorunthePiheadless,asdescribedlaterinthischapter.HDMI
cablescanvarywildlyinprice.Ifyou’rejustrunningacablethreetosixfeettoa
monitor,there’snoneedtospendmorethan$3onanHDMIcable.Ifyouarerunning
longlengths,youshoulddefinitelyresearchthehigherqualitycablesandavoidthe
cheapgenerics.
Ethernetcable
YourhomemaynothaveasmanywiredEthernetjacksasitdidfiveyearsago.Because
everythingiswirelessthesedays,youmightfindthewiredporttobeabitofahurdle;
seethesection“RunningHeadless”forsomealternativestopluggingtheEthernet
directlyintothewallorahub.
IfyouwanttodoalotmorewithyourRaspberryPi,thereareafewotherperipheralsand
add-onsthatyou’llwant,whichwe’lltalkaboutinChapter6.Youmayalsowantto
considersomeofthefollowingadd-ons(seetheeLinuxwebsiteforalistofperipherals
thatareknowntowork):
ApoweredUSBhub
AUSB2.0hubisrecommended.
Heatsink
Aheatsinkisasmallpieceofmetal,usuallywithfinstocreatealotofsurfaceareato
dissipateheatefficiently.Heatsinkscanbeattachedtochipsthatgethot.ThePi’s
chipsetwasdesignedformobileapplications,soaheatsinkisn’tnecessarymostofthe
time.However,aswe’llseelater,therearecaseswhereyoumaywanttorunthePiat
higherspeeds,orcrunchnumbersoveranextendedperiodandthechipmayheatupa
bit.Somepeoplehavereportedthatthenetworkchipcangetwarmaswell.
Real-timeclock
Youmaywanttoaddareal-timeclockchip(liketheDS1307)forloggingorkeeping
timewhenoffline.
Cameramodule
A$25,5megapixelRaspberryPicameramoduleisavailableasanofficialperipheral.
YoucanalsouseaUSBwebcam(moreonthisinChapter11).
LCDdisplay
ManyLCDscanbeusedviaafewconnectionsontheGPIOheader.LookforaTFT
(thin-film-transistor)displaythatcancommunicatewiththePiusingtheSPI(Serial
PeripheralInterface)pinsontheheader.LCDsthatusetheDSIinterfacemaybe
availableinthefuture.
WiFiUSBdongle
Many802.11WiFiUSBdonglesworkwiththePi.WiFiusesalotofpower,soyouwill
needtomakesureyouhaveanadequatepowersupply;a2AsupplyorapoweredUSB
hubisagoodchoice.IfyouarehavingproblemswithaWiFidongle,powerisalmost
alwaystheproblem.
Soundcards
You’llprobablyfindthatthebuilt-inanalogaudioisinadequateformostofyour
projects.Ifyouwanthigh-qualitysoundoutput(orinput)fromthePi,you’llneeda
soundcard.ManyUSBsoundcardsalsoworkwellwiththePi;theBehringer’sUControldevicesareapopular,inexpensiveoption.
Laptopdock
Severalpeoplehavemodifiedlaptopdocksintendedforcellphones(liketheAtrix
lapdock)toworkasadisplay/basefortheRaspberryPi.
TheComputeModule
TheComputeModule(Figure1-5)isnottechnicallyanadd-onboard,butrathera
redesignoftheRaspberryPi.Itistheheart,brain,andgutsofaRaspberryPi
reconfiguredasacomponentthatwillplugintoaDIMM-styleconnector,thesame
connectorusedformemorymodules.Themoduleisdesignedformakerswhowantto
incorporatethePiinamorefinishedprojectorproduct.TousetheComputeModule,
you’llneedtodesignacustomPCBandperipherals,oryoucanusetheofficial
ComputeModuleI/OBoard.
Figure1-5.TheComputeModuleallowsyoutoeasilyembedaRaspberry
Piintoaproductdesign
HATsandshields
Anumberofvendorsandopenhardwarefolkshavereleasedadd-ondaughterboards
thatsitontopofthePiandconnectviatheGPIOheader.Theseboardsaddcapabilities
likedrivingLCDs,motors,oranalogsensorinputs.SomeuseArduinoterminologyand
callthesedaughterboards“shields,”buttheRaspberryPiFoundationhasareference
designthattheycallHATs(HardwareAttachedonTop).TheHATformfactorisshown
inFigure1-6andisonlycompatiblewiththeB+.
TheCase
You’llquicklyfindthatyou’llwantacaseforyourRaspberryPi.Thestiffcablesonall
sidesmakeithardtokeepflat,andsomeofthecomponentsliketheSDcardslotcanbe
mechanicallydamagedeventhroughnormaluse.
Figure1-6.ARaspberryPiHATisanadd-onboardthatconformstoa
certainsize(65×56mm)andhasanEEPROMonboardtohelpthePi
autodetectthefunctionalityoftheboard,amongotherrequirements.The
fullspecisavailableontheRaspberryPiFoundations’sGitHubpage.
ThePicontainssixlayersofconductivetracesconnectingvariouscomponents,unlikea
lotofsimplemicrocontrollerPCBsthatjusthavetracesonthetopandthebottom.There
arefourlayersofthintracessandwichedinbetweenthetopandbottom;iftheboardgets
flexedtoomuch,youcanbreaksomeofthosetracesinamannerthatisimpossibleto
debug.Thesolution:getacase.
Thereareabunchofpremadecasesavailable,buttherearealsoalotofcasedesigns
availabletodownloadandfabricateonalasercutteror3Dprinter.Ingeneral,avoid
tabbedcaseswherebrittleacrylicisusedatrightangles.ThelayeredacrylicofthePibow
isacolorfuloption(Figure1-7).
Itshouldprobablygowithoutsaying,butit’soneofthoseobviousmistakesyoucanmake
sometimes:makesureyoudon’tputyourRaspberryPionaconductivesurface.Flipover
theboardandlookatthebottom;therearealotofcomponentsthereandalotofsolder
jointsthatcanbeeasilyshorted.Anotherreasonwhyit’simportanttocaseyourPi!
Figure1-7.ThecolorfulPibowcasefromPimoroni
ChooseYourDistribution
TheRaspberryPirunsLinuxforanoperatingsystem.Linuxistechnicallyjustthekernel,
butanoperatingsystemismuchmorethanthat—it’sthetotalcollectionofdrivers,
services,andapplicationsthatmakestheOS.Avarietyofflavorsordistributionsofthe
LinuxOShaveevolvedovertheyears.Someofthemostcommonondesktopcomputers
areUbuntu,Debian,Fedora,andArch.Eachhasitsowncommunitiesofusersandis
tunedforparticularapplications.
BecausethePiisbasedonamobiledevicechipset,ithasdifferentsoftwarerequirements
thanadesktopcomputer.TheBroadcomprocessorhassomeproprietaryfeaturesthat
requirespecial“binaryblob”devicedriversandcodethatwon’tbeincludedinany
standardLinuxdistribution.And,whilemostdesktopcomputershavegigabytesofRAM
andhundredsofgigabytesofstorage,thePiismorelimitedinbothregards.SpecialLinux
distributionsthattargetthePihavebeendeveloped.
Inthisbook,wewillconcentrateontheofficialRaspbiandistributionfromthe
Foundation,basedonDebian).Notethatraspbian.orgisacommunitysite,notoperated
bytheFoundation.Ifyou’relookingfortheofficialdistribution,visittheRaspberryPi
Foundation’sdownloadspage.OtherspecializeddistributionsareexploredinChapter3.
FlashtheSDCard
ManyvendorssellSDcardswiththeoperatingsystempreinstalled;forsomepeople,this
maybethebestwaytogetstarted.Evenifitisn’tthelatestrelease,youcaneasilyupgrade
onceyougetthePibootedupandontheInternet.
TheeasiestwaytogettheOSontheSDCardistousetheNOOBStool.Don’ttake
offense;nooneisquestioningyourcomputeracumen.NOOBSstandsforNewOutOfthe
BoxSoftwareandisaconfigurationtoolthatwillhelpinstalltheOS.You’llneedanSD
card(atleast4GB)andreader,thenfollowthesesteps:whenyoubootupthePi,you’ll
seeaconfigurationscreenwithanumberofOSoptions.SelectRaspbianandhitthe
Installbutton;that’sallthereistoit!
ForAdvancedUsers:CreateYourOwnDiskImage
Thefirstthingyou’llneedtodoisdownloadoneofthedistributionsfromtheRaspberry
PiFoundation’sdownloadspageoroneofthesitesinChapter3.Notethatyoucan’tjust
dragthediskimageontotheSDcard;you’llneedtomakeabit-for-bitcopyoftheimage.
You’llneedacardwriterandadiskimageutility;anyinexpensivecardwriterwilldo.The
instructionsvarydependingontheOSyou’rerunning.Unziptheimagefile(youshould
endupwitha.imgfile),thenfollowtheappropriatedirectionsdescribedinAppendixA.
FasterDownloadswithBitTorrent
You’llseeanoteonthedownloadsiteaboutdownloadingatorrentfileforthemostefficientwayofdownloading
Raspbian.Thetorrentfileisadecentralizedwayofdistributingfiles;itcanbemuchfasterbecauseyou’llbepulling
bitsofthedownloadfrommanyothertorrentclientsratherthanasinglecentralserver.You’llneedaBitTorrentclient
ifyouchoosethisroute.
SomepopularBitTorrentclientsare:
Vuze
Integratedtorrentsearchanddownload
Miro
Opensourcemusicandvideoplayerthatalsohandlestorrents
MLDonkey
WindowsandLinux-onlyfilesharingtool
Transmission
LightweightMacandLinux-onlyclient;alsousedinembeddedsystems
BootingUp
FollowthesestepstobookupyourRaspberryPiforthefirsttime:
1. PlugtheSDcardintothesocket.
2. PluginaUSBkeyboardandmouse.OntheModelA,plugthemintoapoweredhub,
thenplugthehubintothePi.
3. PlugtheHDMIoutputintoyourTVormonitor.Makesureyourmonitorison.
4. Pluginthepowersupply.Ingeneral,trytomakesureeverythingelseishookedup
beforeconnectingthepower.
Ifallgoeswell,youshouldseeabunchofstartuplogentriesappearingonyourscreen.If
thingsdon’tgowell,skipaheadtothetroubleshootingsectionattheendofthischapter.
TheselogmessagesshowalloftheprocessesthatarelaunchingasyoubootupthePi.
You’llseethenetworkinterfacebeinitialized,andyou’llseeallofyourUSBperipherals
beingrecognizedandlogged.Youcanseetheselogmessagesafteryouloginbytyping
dmesgonthecommandline.
Theveryfirsttimeyoubootup,you’llbepresentedwiththeraspi-configtool(see
Figure1-8).Thereareafewkeysettingsyou’llneedtotweakhere;chancesaregoodthat
yourRaspberryPiwon’tworkexactlythewayyouwantrightoutofthebox.Ifyouneed
togetbacktothisconfigurationtoolatanytime,typethefollowingatthecommandline:
sudoraspi-config
Figure1-8.TheRaspi-configtoolmenu
GettingOnline
You’vegotafewdifferentwaystoconnecttotheInternet.Ifyou’vegoteasyaccesstoarouter,switch,orEthernet
jackconnectedtoarouter,justpluginusingastandardEthernetcable.IfyouhaveaWiFiUSBdongle,youcan
connectwirelessly;there’saniconontheDesktoptosetupyourwirelessconnection.Notalldongleswillwork;
checktheverifiedperipheralslistforasupportedone.
Ifyou’vegotalaptopnearby,orifyou’rerunningthePiinaheadlessconfiguration,youcansharetheWiFionyour
laptopwiththePi(Figure1-9).ItissupersimpleontheMac:justenableInternetSharingInyourSharingsettings,
thenuseanEthernetcabletoconnectthePiandyourMac.InWindows,enable“Allowothernetworkusersto
connectthroughthiscomputer’sInternetconnection”inyourInternetConnectionSharingproperties.ThePishould
automaticallygetanIPaddresswhenconnectedandbeonline.
Youwillprobablyneedacross-overcableforaWindows-basedPC,butyoucanuseanyEthernetcableonApple
hardware,asitwillautodetectthetypeofcable.
Figure1-9.Ahandytrickistoshareyourlaptop’sWiFiconnectionwith
thePi.YoucanalsorunthePiheadless(see“RunningHeadless”),whichis
convenientifyou’reusingyourRaspberryPiontherun.
ConfiguringYourPi
Next,we’llwalkthroughthestepsandshowyouwhichconfigurationoptionsareessential
andwhichyoucancomebacktoifyouneedthem.Whensettingoptionsinthetool,use
theupanddownarrowstomovearoundthelist,thespacebartoselectsomething,andtab
tochangefieldsormovethecursortothebuttonsatthebottomofthewindow.Let’sgoin
theorderofthemenuoptionsintheconfigurationtool:
Expandrootfs
Youshouldalwayschoosethisoption;thiswillenlargethefilesystemtoletyouusethe
wholeSDcard.
Overscan
Leavetheoverscanoptiondisabledatfirst.Ifyouhaveahigh-definitionmonitor,you
mayfindthattextrunsoffthesideofthescreen.Tofixthis,enabletheoverscanand
changethevaluestofittheimagetothescreen.Thevaluesindicatetheamountof
overscansothedisplaysoftwarecancorrect;usepositivevaluesiftheimagegoesoff
thescreenandnegativeifthereareblackbordersaroundtheedgeofthedisplay.
Keyboard
ThedefaultkeyboardsettingsareforagenerickeyboardinaUK-stylelayout.Ifyou
wanttheykeystodowhatthey’relabeledtodo,you’lldefinitelywanttoselecta
keyboardtypeandmappingthatcorrespondstoyoursetup.Luckily,thekeyboardlistis
veryrobust.Notethatyourlocalesettingscanaffectyourkeyboardsettingsaswell.
Password
It’sagoodideatochangethedefaultpasswordfrom“raspberry”tosomethingalittle
stronger.
Changelocale
Ifyou’reoutsidetheUK,youshouldchangeyourlocaletoreflectyourlanguageand
characterencodingpreferences.ThedefaultsettingisforUKEnglishwithastandard
UTF-8characterencoding(en_GB.UTF-8).Selecten_US.UTF-8ifyou’reintheUnited
States.
Changetimezone
You’llprobablywanttosetthis.
Memorysplit
ThisoptionallowsyoutochangetheamountofmemoryusedbytheCPUandtheGPU.
Leavethedefaultsplitfornow.
Overclock
Withthisoption,youcannowruntheprocessoratspeedshigherthan700MHz.For
yourfirsttimebooting,leavethedefaultsettingsortryMediumorModest.Youmay
wanttoreturntothislater(Turbomodecanrunat1,000MHz).
SSH
ThisoptionturnsontheSecureShell(SSH)server,whichwillallowyoutologintothe
RaspberryPiremotelyoveranetwork.Thisisreallyhandy,soyoushouldturniton.
Desktopbehavior
ThisoptionletsyoubootstraighttothegraphicaldesktopenvironmentandissettoYes
bydefault.IfyouselectNo,you’llgetthecommandlinewhenyoubootup,andyou’ll
havetologinandstartthegraphicalinterfacemanuallylikethis:
1. Whenyou’reinthegraphicaldesktop,yourcommandpromptwilldisappear.You
canopenaterminalprogramtogetacommandpromptwhileyou’reinthe
graphicaldesktop.
2. Clickthedesktopmenuinthelowerleft,thenchooseAccessories→LXTerminal.
Update
Finally,ifyou’reconnectedtotheInternet,you’llbeabletoupdatetheconfigutility
withthisoption.Don’tupdatetheOSonyourfirsttimearound;you’llseeotherwaysto
dothisinChapter2.
Whenyou’redone,selectFinishandyou’llbedumpedbacktothecommandline.Type:
[email protected]~$sudoreboot
andyourPiwillrebootwithyournewsettings.Ifallgoeswell(andifyouchosethe
optiontobootstraighttothegraphicaldesktopenvironment),youshouldseetheOpenbox
windowmanagerrunningontheLightweightX11DesktopEnvironment(LXDE).You’re
upandrunning!
ShuttingDown
There’snopowerbuttonontheRaspberryPi(althoughthereisaheaderforaresetswitch
onnewerboards).TheproperwaytoshutdownisthroughtheLogoutmenuonthe
graphicaldesktop;selectShutdowntohaltthesystem.
Youcanalsoshutdownfromthecommandlinebytyping:
[email protected]~$sudoshutdown-hnow
Besuretodoacleanshutdown(anddon’tjustpulltheplug).Insomecases,youcan
corrupttheSDcardifyouturnoffpowerwithouthaltingthesystem.
RunningHeadless
IfyouwanttoworkontheRaspberryPiwithoutplugginginamonitor,keyboard,and
mouse,therearesomewaystosetituptorunheadless.Ifallyourequireistogetintothe
commandline,youcansimplyhooktheRaspberryPiuptothenetworkanduseanSSH
clienttoconnecttoit(username:pi,password:raspberry).TheSSHutilityonMacor
Linuxwilldo;usePuTTYonWindows(orLinux).TheSSHserverontheRaspberryPiis
enabledbydefault(runraspi-configagainifforsomereasonitdoesn’tlaunchat
startup).
AnotherwaytoconnecttothePioveranetworkconnectionistorunaVirtualNetwork
Computing(VNC)serveronthePiandconnecttoitusingaVNCclient.Thebenefitof
thisisthatyoucanrunacompleteworkinggraphicaldesktopenvironmentinawindowon
yourlaptopordesktop.Thisisagreatsolutionforaportabledevelopmentenvironment.
SeetheRaspberryPiHubforextensiveinstructionsonhowtoinstallTightVNC,a
lightweightVNCserver.
AthirdwayofloggingintothePiwithoutakeyboardormonitorisviasomepinsonthe
GPIOheader.ThedefaultRaspbiandistributionbootsupwithaserialmonitorprogram
running,whichlistensforaconnectionontheGPIOheader.Youcanconnectaspecial
cablefromFTDIthatallowsyoutoconnecttothatmonitoroveraUSBcable.TheFTDI
cablehasfourwiresthatconnecttoground,pin6andpin10ontheheader.Alternatively,
youcouldusetheBUBIfromModernDevice,whichisabreakoutboardfortheFTDI
chipwithaprototypingareathatallowsyoutoreroutethesignals.
Troubleshooting
Ifthingsaren’tworkingthewayyouthinktheyshould,thereareafewcommonmistakes
andmissedsteps.Besuretocheckallofthefollowingsuggestions:
IstheSDcardintheslot,andisitmakingagoodconnection?Areyouusingthe
correcttypeofSDcard?
Wasthediskimagewrittencorrectlytothecard?Trycopyingitagainwithanother
cardreader.
IsthewriteprotectenabledonSDcard?Thisisalittleswitchonthesidethatcan
easilygettoggledthewrongway.
Checktheintegrityofyouroriginaldiskimage.YoucandothisbyrunningaSecure
HashAlgorithm(SHA)checksumutilityonthediskimageandcomparingtheresultto
the40-characterhashpublishedonthedownloadpage.
IsthePirestartingorhavingintermittentproblems?Checkyourpowersupply;an
underpoweredboardmayseemtoworkbutactflaky.
Doyougetakernelpaniconstartup?AkernelpanicistheequivalentofWindows’
BlueScreenofDeath;it’smostoftencausedbyaproblemwithadeviceontheUSB
hub.TryunpluggingUSBdevicesandrestarting.
Ifthatallfails,headovertotheRaspberryPiHub’stroubleshootingpageforsolutionsto
allsortsofproblemspeoplehavehad.
WhichBoardDoYouHave?
Ifyou’reaskingforhelpinanemailoronaforum,itcanbehelpfultothoseassistingyouifyouknowexactlywhat
versionoftheoperatingsystemandwhichboardyou’reusing.TofindouttheOSversion,openLXTerminaland
type:
cat/proc/version
Tofindyourboardversion,type:
cat/proc/cpuinfo
GoingFurther
TheRaspberryPiHub
Hostedbyelinux.org,thisisamassivewikiofinformationonthePi’shardwareand
configuration.
ListofVerifiedPeripherals
ThedefinitivelistofperipheralsknowntoworkwiththeRaspberryPi.
Chapter2.GettingAroundLinuxontheRaspberryPi
Ifyou’regoingtogetthemostoutofyourRaspberryPi,you’llneedtolearnalittleLinux.
Thegoalofthischapteristopresentawhirlwindtouroftheoperatingsystemandgive
youenoughcontextandcommandstogetaroundthefilesystem,installpackagesfromthe
commandlineordesktopenvironment,andpointoutthemostimportanttoolsyou’llneed
daytoday.
RaspbiancomeswiththeLightweightX11DesktopEnvironment(LXDE)graphical
desktopenvironmentinstalled(Figure2-1).Thisisatrimmed-downdesktopenvironment
fortheXWindowSystemthathasbeenpoweringtheGUIsofUnixandLinuxcomputers
sincethe1980s.SomeofthetoolsyouseeontheDesktopandinthemenuarebundled
withLXDE(theLeafpadtexteditorandtheLXTerminalshell,forinstance).
RunningontopofLXDEisOpenbox,awindowmanagerthathandlesthelookandfeelof
windowsandmenus.Ifyouwanttotweaktheappearanceofyourdesktop,gotothe
Openboxconfigurationtools(clickthedesktopmenuinthelowerleft,thenchoose
Preferences→OpenboxConfigurationManager).UnlikeOSXorWindows,itisrelatively
easytocompletelycustomizeyourdesktopenvironmentorinstallalternativewindow
managers.SomeoftheotherdistributionsforRaspberryPihavedifferentenvironments
tunedforapplicationslikesettopmediaboxes,phonesystems,ornetworkfirewalls.See
http://elinux.org/RPi_DistributionsandChapter3formore.
Figure2-1.Thegraphicaldesktop
Afewdesktopapplicationsmaybealittledifferentthanotherdesktopenvironments:
TheFileManager
Ifyouprefernottomovefilesaroundusingthecommandline(moreonthatina
moment),selecttheFileManagerfromtheAccessoriesmenu.You’llbeabletobrowse
thefilesystemusingiconsandfoldersthewayyou’reprobablyusedtodoing.
Thewebbrowser
ThedefaultwebbrowserisMidori,designedtoworkwellwithlimitedresources.It’s
easytoforgethowmuchworkwebbrowsersdothesedays.BecauseRaspbianis
designedtobeaverylightweightOSdistribution,thereareanumberoffeaturesyou
mayexpectinawebbrowserthatarenotavailable.Forexample,FlashandtheJava
plug-inarenotinstalled(sonoYouTube),andMidoridoesnotsupportHTML5video.
Later,we’lllookathowtoinstallnewsoftware(likeJava).Lookfortoolsandmenu
itemsinthepull-downmenuintheupper-rightcornerofthewindow(seeFigure2-2).
Thereareacoupleofotherbrowseroptions,notablyNetSurfandDillo.
Videoandaudio
Multimediaplaybackishandledbyomxplayer,whichiscomplicatedbutpowerful.Itis
onlyavailableasacommand-lineutility.Omxplayerisspeciallydesignedtoworkwith
theGraphicsProcessingUnit(GPU)ontheprocessor;otherfreesoftwarelikeVLCand
mPlayerwon’tworkwellwiththeGPU.
Note
Tokeepthepricedown,certainvideolicenseswerenotincludedwiththeRaspberryPi.If
youwanttowatchrecordedTVandDVDsencodedintheMPEG-2format(orMicrosoft’s
VC-1format),you’llneedtopurchasealicensekeyfromtheFoundation’sonlineshop.A
licenseforH.264(MPEG-4)decodingandencodingisincludedwiththeRaspberryPi.
Figure2-2.Thepull-downmenuinthewebbrowser
WolframandMathematica
BundledwithRaspbianisapilotreleaseoftheWolframLanguageandMathematica.In
fact,you’llnoticeiconsforbothonthedesktop.Mathematicaisthefrontendinterface
fortheWolframprogramminglanguage.Together,they’recommonlyusedforcomplex
computationsinmath,science,andengineeringfields.ToseewhatWolframand
Mathematicaarecapableof,theWolframLanguageandSystemDocumentationisa
greatplacetostart.
PiStore
Youcanbrowseasmallcollectionofdownloadablesoftwareanddocumentationfor
yourRaspberryPiinthePiStore(Figure2-3),whichalsohasanicononthedesktop.
However,it’slikelythatyou’llinstallmostsoftwarepackagesthroughthecommandlineutilityapt-get,whichyou’lllearnaboutin“InstallingNewSoftware”.
Texteditor
Leafpadisthedefaulttexteditor,whichisavailableunderthemainmenu.Forediting
textfilesoutsidethedesktopenvironment,youcanuseNano,whichisaneasy-to-learn,
bare-bonestexteditor.Vimisalsoinstalled;executeitwiththecommandvi.Other
commonUnixtexteditorslikeEmacsarenotinstalledbydefault,butcanbeeasily
added(see“InstallingNewSoftware”).
Figure2-3.Withinthedesktopenvironment,youcanbrowsethesoftware
fromthePiStore
Copyandpaste
Copyandpastefunctionsworkbetweenapplicationsprettywell,althoughyoumayfind
someoddballprogramsthataren’tconsistent.Ifyourmousehasamiddlebutton,you
canselecttextbyhighlightingitasyounormallywould(clickanddragwiththeleft
mousebutton)andpasteitbypressingthemiddlebuttonwhileyouhavethemouse
cursoroverthedestinationwindow.
Theshell
Alotoftasksaregoingtorequireyoutogettothecommandlineandruncommands
there.TheLXTerminalprogramprovidesaccesstothecommandlineorshell.The
defaultshellonRaspbianistheBourne-againshell(bash),whichisverycommonon
Linuxsystems.There’salsoanalternativecalleddash.Youcanchangeshellsviathe
programmenuorwiththechshcommand.
UsingtheCommandLine
Ifithelps,youcanthinkofusingthecommandlineasplayingatextadventuregame,but
withthefilesandthefilesysteminplaceofgruesandmazes.Ifthatmetaphordoesn’thelp
you,don’tworry:allthecommandsandconceptsinthissectionarestandardLinuxand
arevaluabletolearn.
Beforeyoustart,openuptheLXTerminalprogram(Figure2-4).Therearetwotricksthat
makelifemucheasierintheshell:autocompleteandcommandhistory.Oftenyouwill
onlyneedtotypethefirstfewcharactersofacommandorfilename,thenhitTab.The
shellwillattempttoautocompletethestringbasedonthefilesinthecurrentdirectoryor
programsincommonlyuseddirectories(theshellwillsearchforexecutableprogramsin
placeslike/binor/usr/bin/).Ifyouhittheuparrowonthecommandline,you’llbeableto
stepbackthroughyourcommandhistory,whichisusefulifyoumistypedacharacterina
longstringofcommands.
Figure2-4.LXTerminalgivesyouaccesstothecommandline(orshell)
FilesandtheFilesystem
Table2-1showssomeoftheimportantdirectoriesinthefilesystem.Mostofthesefollow
theLinuxstandardofwherefilesshouldgo;acouplearespecifictotheRaspberryPi.The
/sysdirectoryiswhereyoucanaccessallofthehardwareontheRaspberryPi.
Table2-1.ImportantdirectoriesintheRaspbianfilesystem
Directory
Description
/
/bin
Programsandcommandsthatalluserscanrun
/boot
Allthefilesneededatboottime
/dev
Specialfilesthatrepresentthedevicesonyoursystem
/etc
Configurationfiles
/etc/init.d
Scriptstostartupservices
/etc/X11
X11configurationfiles
/home
Userhomedirectories
/home/pi
HomedirectoryforPiuser
/lib
Kernelmodules/drivers
/media
Mountpointsforremovablemedia
/proc
VirtualdirectorywithdetailsaboutrunningprocessesandtheOS
/sbin
Programsforsystemmaintenance
/sys
AspecialdirectoryontheRaspberryPithatrepresentsthehardwaredevices
/tmp
Spaceforprogramstocreatetemporaryfiles
/usr
Programsanddatausablebyallusers
/usr/bin
Mostoftheprogramsintheoperatingsystemresidehere
/usr/games
Yes,games
/usr/lib
Librariestosupportcommonprograms
/usr/local
Softwarethatmaybespecifictothismachinegoeshere
/usr/sbin
Moresystemadministrationprograms
/usr/share
Supportingfilesthataren’tspecifictoanyprocessorarchitecture
/usr/src
Linuxisopensource;here’sthesource!
/var
Systemlogsandspoolfiles
/var/backups Backupcopiesofallthemostvitalsystemfiles
/var/cache
Programssuchasapt-getcachetheirdatahere
/var/log
Allofthesystemlogsandindividualservicelogs
/var/mail
Alluseremailisstoredhere,ifyou’resetuptohandleemail
/var/spool
Datawaitingtobeprocessed(e.g.,incomingemail,printjobs)
You’llseeyourcurrentdirectorydisplayedbeforethecommandprompt.InLinux,your
homedirectoryhasashorthandnotation:thetilde(~).WhenyouopentheLXTerminal,
you’llbedroppedintoyourhomedirectoryandyourpromptwilllooklikethis:
[email protected]~$
Here’sanexplanationofthatprompt:
[email protected] raspberrypi ~ $
Yourusername,pi,followedbytheat(@)symbol.
Thenameofyourcomputer(raspberrypiisthedefaulthostname).
Thecurrentworkingdirectoryoftheshell.Youalwaysstartoutinyourhomedirectory
(~).
Thisistheshellprompt.Anytextyoutypewillappeartotherightofit.PressEnteror
Returntoexecuteeachcommandyoutype.
Note
Laterinthebook,[email protected]~portionofthepromptandjust
showyouthe$insomeexamplestokeepthemlesscluttered.
Usethecd(changedirectory)commandtomovearoundthefilesystem.Thefollowingtwo
commandshavethesameeffect(changingtothehomedirectory)forthePiuser:
cd/home/pi/
cd~
Ifthedirectorypathstartswithaforwardslash,itwillbeinterpretedasanabsolutepathto
thedirectory.Otherwise,thedirectorywillbeconsideredrelativetothecurrentworking
directory.Youcanalsouse.and..torefertothecurrentdirectoryandthecurrent
directory’sparent.Forexample,tomoveuptothetopofthefilesystem:
[email protected]~$cd..
[email protected]/home$cd..
Youcouldalsogettherewiththeabsolutepath/:
[email protected]~$cd/
Onceyou’vechangedtoadirectory,usethelscommandtolistthefilesthere:
[email protected]/$ls
bindevhomelost+foundmntprocrunselinuxsysusr
bootetclibmediaoptrootsbinsrvtmpvar
Mostcommandshaveadditionalparameters,orswitches,thatcanbeusedtoturnon
differentbehaviors.Forexample,the-lswitchwillproduceamoredetailedlisting,
showingfilesizes,dates,andpermissions:
[email protected]~$ls-l
total8
drwxr-xr-x2pipi4096Oct1214:26Desktop
drwxrwxr-x2pipi4096Jul2014:07python_games
The-aswitchwilllistallfiles,includinginvisibleones:
[email protected]~$ls-la
total80
drwxr-xr-x11pipi4096Oct1214:26.
drwxr-xr-x3rootroot4096Sep1807:48..
-rw-------1pipi25Sep1809:22.bash_history
-rw-r--r--1pipi220Sep1807:48.bash_logout
-rw-r--r--1pipi3243Sep1807:48.bashrc
drwxr-xr-x6pipi4096Sep1901:19.cache
drwxr-xr-x9pipi4096Oct1212:57.config
drwx------3pipi4096Sep1809:24.dbus
drwxr-xr-x2pipi4096Oct1214:26Desktop
-rw-r--r--1pipi36Sep1809:35.dmrc
drwx------2pipi4096Sep1809:24.gvfs
drwxr-xr-x2pipi4096Oct1212:53.idlerc
-rw-------1pipi35Sep1812:11.lesshst
drwx------3pipi4096Sep1901:19.local
-rw-r--r--1pipi675Sep1807:48.profile
drwxrwxr-x2pipi4096Jul2014:07python_games
drwx------4pipi4096Oct1212:57.thumbnails
-rw-------1pipi56Sep1809:35.Xauthority
-rw-------1pipi300Oct1212:57.xsession-errors
-rw-------1pipi1391Sep1809:35.xsession-errors.old
Usethemvcommandtorenameafile.Thetouchcommandcanbeusedtocreateanempty
dummyfile:
[email protected]~$touchfoo
[email protected]~$ls
fooDesktoppython_games
[email protected]~$mvfoobaz
[email protected]~$ls
bazDesktoppython_games
Removeafilewithrm.Toremoveadirectory,youcanusermdirifthedirectoryisempty,
orrm-rifitisn’t.The-risaparametersenttothermcommandthatindicatesitshould
recursivelydeleteeverythinginthedirectory.
Ifyouwanttofindoutalltheparametersforaparticularcommand,usethemancommand
(oryoucanoftenusethe--helpoption):
[email protected]~$mancurl
[email protected]~$rm--help
Tocreateanewdirectory,usemkdir.Tobundleallofthefilesinadirectoryintoasingle
file,usethetarcommand,originallycreatedfortapearchives.You’llfindalotofbundles
offilesorsourcecodearedistributedastarfiles,andthey’reusuallyalsocompressed
usingthegzipcommand.Trythis:
[email protected]~$mkdirmyDir
[email protected]~$cdmyDir
[email protected]~$touchfoobarbaz
[email protected]~$cd..
[email protected]~$tar-cfmyDir.tarmyDir
[email protected]~$gzipmyDir.tar
You’llnowhavea.tar.gzarchiveofthatdirectorythatcanbedistributedviaemailorthe
Internet.
MoreLinuxCommands
OneofthereasonsthatLinux(andUnix)issosuccessfulisthatthemaindesigngoalwas
tobuildaverycomplicatedsystemoutofsmall,simplemodularpartsthatcanbechained
together.You’llneedtoknowalittlebitabouttwopiecesofthispuzzle:pipesand
redirection.
Pipesaresimplyawayofchainingtwoprogramstogether,sotheoutputofonecanserve
astheinputtoanother.AllLinuxprogramscanreaddatafromstandardinput(often
referredtoasstdin),writedatatostandardoutput(stdout),andthrowerrormessagesto
standarderror(stderr).Apipeletsyouhookupstdoutfromoneprogramtostdinof
another(Figure2-5).Usethe|operator,asinthisexample:
[email protected]~$ls-la|less
(Pressqtoexitthelessprogram.)
Figure2-5.Pipesareawayofchainingsmallerprogramstogetherto
accomplishbiggertasks
Now(forsomethingalittlemoreoutthere)try:
[email protected]~$sudocat/boot/kernel.img|aplay
Youmaywanttoturnthevolumedownabitfirst;thiscommandreadsthekernelimage
andspitsallofthe1sand0sattheaudioplayer.That’swhatyourkernelsoundslike!
Insomeoftheexampleslaterinthebook,we’llalsobeusingredirection,wherea
commandisexecutedandthestdoutoutputcanbesenttoafile.Asyou’llseelater,many
thingsinLinuxaretreatedasordinaryfiles(suchasthePi’sgeneral-purposeinput/output
pins),soredirectioncanbequitehandy.Toredirectoutputfromaprogram,usethe>
operator:
[email protected]~$ls>directoryListing.txt
SpecialControlKeys
Inadditiontothekeysforautocomplete(Tab)andcommandhistory(uparrow)previouslymentioned,thereareafew
otherspecialcontrolkeysyou’llneedintheshell.Hereareafew:
Ctrl-C
Killstherunningprogram.Maynotworkwithsomeinteractiveprogramssuchastexteditors.
Ctrl-D
Exitstheshell.Youmusttypethisatthecommandpromptbyitself(don’ttypeanythingafterthe$beforehitting
Ctrl-D).
Ctrl-A
Movesthecursortothebeginningoftheline.
Ctrl-E
Movesthecursortotheendoftheline.
Thereareothers,butthesearethecorekeyboardshortcutsyou’lluseeveryday.
Sometimesyou’llwanttodisplaythecontentsofafileonthescreen.Ifit’satextfileand
youwanttoreaditonescreenatatime,useless:
[email protected]~$ls>flob.txt
[email protected]~$lessflob.txt
Ifyouwanttojustdumptheentirecontentsofafiletostandardoutput,usecat(shortfor
concatenate).Thiscanbehandywhenyouwanttofeedafileintoanotherprogramor
redirectitsomewhere.
Forexample,thisistheequivalentofcopyingonefiletoanotherwithanewname(the
secondlineconcatenatesthetwofilesfirst):
[email protected]~$ls>wibble.txt
[email protected]~$catwibble.txt>wobble.txt
[email protected]~$catwibble.txtwobble.txt>wubble.txt
Tolookatjustthelastfewlinesofafile(suchasthemostrecententryinalogfile),use
tail(toseethebeginning,usehead).Ifyouaresearchingforastringinoneormorefiles,
usethevenerableprogramgrep:
[email protected]~$grepPuzzle*/*
grepisapowerfultoolbecauseoftherichlanguageofregularexpressionsthatwas
developedforit.Regularexpressionscanbeabitdifficulttoread,andmaybeamajor
factorinwhateverreputationLinuxhasforbeingopaquetonewcomers.
Processes
EveryprogramonthePirunsasaseparateprocess;atanyparticularpoint,you’llhave
dozensofprocessesrunning.Whenyoufirstbootup,about75processeswillstart,each
onehandlingadifferenttaskorservice.Toseealltheseprocesses,runthetopprogram,
whichwillalsodisplayCPUandmemoryusage.topwillshowyoutheprocessesusing
themostresources;usethepscommandtolistalltheprocessesandtheirIDnumbers(see
Figure2-6).Try:
[email protected]~$psaux|less
Sometimesyoumaywanttokillarogueorunresponsiveprocess.Todothat,usepsto
finditsID,thenusekilltostopit:
[email protected]~$kill95689
Inthecaseofsomesystemprocesses,youwon’thavepermissiontokillit(thoughyoucan
circumventthiswithsudo,coveredinthenextsection).
Figure2-6.Thepscommandshowsasnapshotofalloftheprocesses
currentlyrunningonyourPi
SudoandPermissions
Linuxisamultiuseroperatingsystem;thegeneralruleisthateveryoneownstheirown
filesandcancreate,modify,anddeletethemwithintheirownspaceonthefilesystem.The
root(orsuper)usercanchangeanyfileinthefilesystem,whichiswhyitisgoodpractice
tonotloginasrootonaday-to-daybasis.
Warning
Asthepiuser,there’snotmuchdamageyoucandotothesystem.Assuperuser,youcan
wreakhavoc,accidentallyorbydesign.Becarefulwhenusingsudo,especiallywhen
movingordeletingfiles.Ofcourse,ifthingsgobadly,youcanalwaysmakeanewSD
cardimage(seeAppendixA).
Therearesometoolslikesudothatallowuserstoactlikesuperusersforperformingtasks
likeinstallingsoftwarewithoutthedangers(andresponsibilities)ofbeingloggedinas
root.You’llbeusingsudoalotwheninteractingwithhardwaredirectly,orwhenchanging
system-wideconfigurations.
Eachfilebelongstooneuserandonegroup.Usechownandchgrptochangethefile’s
ownerorgroup.Youmustberoottouseeither:
[email protected]~$sudochownpigarply.txt
[email protected]~$sudochgrpstaffplugh.txt
Eachfilealsohasasetofpermissionsthatshowwhetherafilecanberead,written,or
executed.Thesepermissionscanbesetfortheownerofthefile,thegroup,orfor
everyone(seeFigure2-7).
Figure2-7.Filepermissionsforowner,group,andeveryone
Yousettheindividualpermissionswiththechmodcommand.Theswitchesforchmodare
summarizedinTable2-2.
Table2-2.The
switchesthatcanbe
usedwithchmod
u User
g Group
o Othersnotinthegroup
a All/everyone
r Readpermission
w Writepermission
x Executepermission
+ Addpermission
- Removepermission
Hereareafewexamplesofhowyoucancombinetheseswitches:
chmodu+rwx,g-rwx,o-rwxwibble.txt
chmodg+wxwobble.txt
chmod-rw,+rwubble.txt
Allowonlytheusertoread,write,andexecute
Addpermissiontowriteandexecutetoentiregroup
Makereadonlyforeveryone
Theonlythingprotectingyouruserspaceandfilesfromotherpeopleisyourpassword,so
youbetterchooseastrongone.Usethepasswdcommandtochangeit,especiallyifyou’re
puttingyourPionanetwork.
TheNetwork
Onceyou’reonanetwork,thereareanumberofLinuxutilitiesthatyou’llbeusingona
regularbasis.Whenyou’retroubleshootinganInternetconnection,useifconfig,which
displaysallofyournetworkinterfacesandtheIPaddressesassociatedwiththem(see
Figure2-8).
Figure2-8.Theifconfigcommandgivesyouinformationaboutallofyour
networkinterfaces
Thepingcommandisactuallythemostbasictoolfortroubleshootingnetwork
connections.Youcanuseping(thinksonar)totestwhetherthereisatwo-wayconnection
betweentwoIPaddressesonthenetworkorInternet.Notethatmanywebsitesblockping
traffic,soyoumayneedtopingmultiplesitestoaccuratelytestaconnection:
pingyahoo.com
pingaltavista.com
pinglycos.com
pingnetscape.com
Failhappenshere
Tologintoanothercomputerremotely(andsecurely,withencryptedpasswords),youcan
usetheSecureShell(SSH).ThecomputerontheremotesideneedstoberunninganSSH
serverforthistowork,buttheSSHclientcomesbuiltintoRaspbian.Infact,thisisagreat
waytoworkonyourRaspberryPiwithoutamonitororkeyboard,asdiscussedlaterin
“RunningHeadless”.
RelatedtoSSHisthesftpprogram,whichallowsyoutosecurelytransferfilesfromone
computertoanother.Roundingoutthesetisscp,whichyoucanusetocopyfilesfrom
onecomputertoanotheroveranetworkortheInternet.Thekeytoallofthesetoolsisthat
theyusetheSecureSocketsLayer(SSL)totransferfileswithencryptedlogin
information.ThesetoolsareallstandardstalwartLinuxtools.
/etc
The/etcdirectoryholdsallofthesystem-wideconfigurationfilesandstartupscripts.
Whenyourantheconfigurationscriptsthefirsttimeyoustartedup,youwerechanging
valuesinvariousfilesinthe/etcdirectory.You’llneedtoinvokesuperuserpowerswith
sudotoeditfilesin/etc;ifyoucomeacrosssometutorialthattellsyoutoedita
configurationfile,useatexteditortoeditandlaunchitwithsudo:
[email protected]~$sudonano/etc/hosts
SettingtheDateandTime
Atypicallaptopordesktopwillhaveadditionalhardwareandabackupbattery(usuallya
coincell)tosavethecurrenttimeanddate.TheRaspberryPidoesnot,butRaspbianis
configuredtoautomaticallysynchronizeitstimeanddatewithaNetworkTimeProtocol
(NTP)serverwhenpluggedintoanetwork.
Havingthecorrecttimecanbeimportantforsomeapplications(seetheexamplein
Chapter8usingcrontocontrolalamp).Tosetthetimeanddatemanually,usethedate
program:
$sudodate--set="SunNov181:55:16EDT2012"
IfthetimewassetautomaticallyviatheInternetwithNTP,youmaywanttoupdateyour
timezone.Inordertodothis,gototheInternationalisationSettingswithintheraspiconfigutility(see“BootingUp”).
InstallingNewSoftware
OneoftheareasthatLinuxcompletelytrouncesotheroperatingsystemsisinsoftware
packagemanagement.Packagemanagershandlethedownloadingandinstallationof
software,andtheyautomaticallyhandledownloadingandinstallingdependencies.
Keepingwiththemodularapproach,manysoftwarepackagesonLinuxdependonother
piecesofsoftware.Thepackagemanagerkeepsitallstraight,andthepackagemanagers
onLinuxareremarkablyrobust.
Raspbiancomeswithaprettyminimalsetofsoftware,soyouwillsoonwanttostart
downloadingandinstallingnewprograms.Theexamplesinthisbookwillallusethe
commandlineforthis,becauseitisthemostflexibleandquickestwayofinstalling
software.
Theprogramapt-getwiththeinstalloptionisusedtodownloadsoftware.apt-getwill
evendownloadanyextrasoftwareorlibrariesrequiredsoyoudon’thavetogohunting
aroundfordependencies.Softwarehastobeinstalledwithsuperuserpermissions,so
alwaysusesudo(thiscommandinstallstheEmacstexteditor):
[email protected]~$sudoapt-getinstallemacs
TakingaScreenshot
Oneofthefirstthingsweneededtofigureoutwhenwritingthisbookwashowtotake
screenshotsonthePi.Wefoundaprogramcalledscrot(anabbreviationfor
SCReenshOT).AnotheroptiontocapturescreenshotsistoinstalltheGNUImage
ManipulationProgram(Gimp)orImageMagick,butscrotworkedforus.Toinstallscrot,
type:
sudoapt-getinstallscrot
SoundinLinux
RaspberryPihasthebuilt-incapabilitytoplaysound.Thismakesitapopularplatformfor
DIYprojectsthatplaysoundeffectsorstreammusicfromtheInternet.Raspbianusesthe
AdvancedLinuxSoundArchitecture,orALSA,forlow-levelcontrolofaudiodevices.You
cantestitwithapre-loadedsoundfileandthesoundplaybackutilityaplay:
$aplay/usr/share/scratch/Media/Sounds/Human/PartyNoise.wav
Ifyou’reusinganHDMIdisplay,bydefault,thesoundwillbeplayedthroughHDMI.To
forceyourRaspberryPitoplaythroughtheanalogoutputjack,runsudoraspi-config
andchooseAdvancedOptions→Audio→Force3.5mm(headphone)jack.
Toadjustthevolumeoutput,runalsamixeranduseyourarrowkeystochangethegain.
You’renotlimitedtotheonboardsound;youcanalsoaddUSBaudiodevices.ManyUSB
audiodevicesevenhaveanaudioinputsothatyoucanuseyourRaspberryPitorecord
audioinadditiontoplayingit.
ToenableaUSBaudiodevice,you’llneedtoedittheALSAconfigurationfile:
$sudonano/etc/modprobe.d/alsa-base.conf
Findthelinethatsays:
optionssnd-usb-audioindex=-2
Andchangeitto:
optionssnd-usb-audioindex=0
SavethefileandrebootyourRaspberryPi.NowyourRaspberryPiwilldefaulttousing
theUSBaudiodevice.
UpgradingYourFirmware
SomeofyourRaspberryPi’sfirmwareisstoredontheSDcardandincludesmuchofthe
low-levelinstructionsthatneedtobeexecutedbeforethebootprocessishandedoverto
youroperatingsystem.
Whileit’stypicallynotnecessary,ifyourunintosomestrangebehavior,youmaywanttry
toupdatethefirmwareonyourSDcard.WithanInternet-connectedRaspberryPi,thisis
veryeasytodo:
$sudorpi-update
Ifyou’dliketoseewhat’sbeingupdatedwhenyouruntheutility,youcanreviewthe
latestchangesinRaspberryPi’sfirmwarerepositoryonGitHub.
ToviewwhatversionoftheRaspberryPifirmwareyoucurrentlyhave,runvcgencmd
version:
$vcgencmdversion
Aug1201418:08:57
Copyright(c)2012Broadcom
version158db03216ab9f49243655d4d325da3264567104(tainted)(release)
GoingFurther
There’smuchmoretoLinuxandmanyplacestocontinuelearningaboutit.Somegood
startingpointsare:
LinuxPocketGuide,byDanielJ.Barrett
Handyasaquickreference.
LinuxinaNutshell,byEllenSiever,StephenFiggins,RobertLove,andArnoldRobbins
Moredetailed,butstillaquickreferenceguide.
TheDebianWiki
RaspbianisbasedonDebian,soalotoftheinfoontheDebianwikiappliestoRaspbian
aswell.
EricS.Raymond’s“TheJargonFile”
AlsopublishedastheNewHacker’sDictionary,thiscollectionofdefinitionsandstories
isrequiredreadingontheUnix/Linuxsubculture.
Chapter3.SpecializedDistributions
ThestockRaspbianoperatingsystemisgreatforgeneral-purposecomputing,but
sometimesyoumaywanttotailorthePitoaspecificpurposelikeastandalonemedia
centerorguitareffectspedal.TheLinuxecosystemisrichinsoftwareforevery
imaginableapplication.Anumberoffolkshavespentthetimetobundlealltheright
softwaretogethersoyoudon’thavetodoit.Thischapterwillhighlightjustafewofthe
morespecializeddistributionstogetyoustarted.
Whenweusetheterm“distribution,”we’reusuallytalkingaboutthreethingstogether:
TheLinuxkernelanddrivers
Preinstalledsoftwareforaparticularapplication
Specialconfigurationtoolsortoolspreconfiguredforaparticulartask(e.g.,tobootup
intoaparticularprogram)
AsyousawinChapter1,thereareessentiallythreepopulargeneral-purposedistributions
(threethatareoptionsintheNOOBSinstalleratleast):
Raspbian
TherecommendeddistributionfromtheFoundationtostartwith;basedonDebian.
ArchLinux
ArchLinuxspecificallytargetsARM-basedcomputers,sotheysupportedthePivery
earlyon.
Pidora
PidoraisaversionoftheFedoradistributiontunedforthePi.
Therestofthischapterpointstoanumberofotherinterestingspecializeddistributions.
WhynotUbuntu?
Ubuntuisoneofthemostpopularand(arguably)slickestdistributionsofLinux,sowhynotuseitontheRaspberry
Pi?Thatwasinitiallytheplanofthedevelopers,butitturnsoutUbuntuonlysupportsARMv7orgreaterprocessors.
DistributionsforHomeTheater
ThemostpopularprograminthisareaisXBMC,whichbeganasamediacenterprojectto
runontheXbox.Overtheyears,however,XBMChasmorphedtobecomeamoregeneral
entertainmentcenterplatformandhappenstoworkverywellonthePi.Inthesummerof
2014,theXBMCFoundationrenamedthesoftwareKoditobringtheevolutionofthe
projectintofocus,becauseitdoesn’tevenrunonthenewerXboxversions.Therearea
coupleofPidistributionsthatmakeiteasytoputXBMCinyourlivingroom:
Raspbmc
AnoptioninNOOBS,sothismightbethefirstonetotry(Figure3-1).
Figure3-1.XBMC/Kodiforastandalonemediacenter
OpenELEC
TheOpenEmbeddedLinuxEntertainmentCenterisapared-downversionofXBMC
thatmayappealtomoreasceticPiusers.
DistributionsforMusic
It’scheapanditcanfitinaguitareffectsstompbox,soofcoursetheelectronicmusic
worldhasbeenexcitedaboutthePisinceitsrelease.Herearesomeexamples:
SatelliteCCRMA
ThisdistributionfromStanford’sCenterforComputerResearchinMusicandAcoustics
(CCRMA)isgearedtowardembeddedmusicalinstrumentsandartinstallations,aswell
aseffectspedals.Itcanrunothersoftware,butthecoreisPureDataExtended,Faust,
JackTrip,andChucK.TheoriginalrationaleisdescribedinEdgarBerdahlandWendy
Ju’spaper“SatelliteCCRMA:AMusicalInteractionandSoundSynthesisPlatform”.
Volumio
Amusicplayerforaudiophiles.ThisprojectevolvedfromRaspyFi.
Alsoonthemusicfront,youmaywanttocheckoutPhilAtkin’sPIANAPisynthesizer.
HardwareHackingwithOccidentalis
AdafruitIndustriescreatedaforkofthemainRaspbian/WheezyLinuxdistributionand
addeddriversandsoftwarethatmakeelectronicsprototypingeasierrightoutofthebox.
TheresultistheAdafruitRaspberryPiEducationalLinuxDistro,codenamedOccidentalis
fromthespeciesnameoftheblackraspberry.
Occidentalisisaninterestingexampleoftheopensourcemodelinaction;theLinux
ecosystemhasalonghistoryofforkeddistributionsthatarespeciallytunedfora
particularapplication.Oftentheseforksareprovinggroundsfortargetedimprovements
thatcanbemergedbackintootherdistributions.
Manyoftheimprovementsandadditionsinthedistributionareaimedatsupporting
popularsensorsandsomeAdafruitproductswithouthavingtoinstalladditionalsoftware.
Therearealsosomelow-levelimprovementsthatmakeiteasiertoperformpulse-width
modulationandcontrolservomotorsdirectlyfromtheRaspberryPi.
SeetheoverviewpageforalistoffeaturesandtheAdafruittutorialsforexamplesofhow
touseOccidentalis.
RetrocomputingandRetrogaming
ThePiwasinspiredbytheinexpensivepersonalcomputersofthe1980s,soitseems
fittingthatthereareanumberofdistributionsaimedatnostalgicretrocomputingor
gaming:
RISCOS
BootsstraightintoBASIC!
Plan9
BellLabs’experimentalsuccessortoUnix,featuringoneofthemoreadorableOS
mascots,GlendathePlan9Bunny.
Commodore64
Bootintoanemulatorofthisclassicbox.
Retropie
AnSDcardimageandGPIOhardwareboardthatmakesiteasiertobuildretrogaming
consoles.
PiPlay
AprebuiltdistributionforgamingandemulationbasedonMAME(formerly
PiMAME).
OtherUsefulDistributions
Hereareafewotherdistributionsofnote:
QtonPi
AnOSbundleaimedatdevelopersofstandalone“single-purposeappliances”usingthe
QtGUIframework.
Webkiosk
FormakingInternetkiosksanddigitalsignage.
Openwrt
TurnyourPiintoapowerfulrouterwiththisopensourcerouterplatform.
GoingFurther
ListofLinuxdistributionsthatworkwithRaspberryPi
ThisisthedefinitivelistattheRaspberryPiHub.
Chapter4.PythononthePi
Pythonisagreatfirstprogramminglanguage;it’sclearandeasytogetupandrunning.
Moreimportant,therearealotofotheruserstosharecodewithandaskquestions.
GuidovanRossumcreatedPython,andveryearlyonrecognizeditsuseasafirstlanguage
forcomputing.In1999,vanRossumputtogetherawidelyreadproposalcalled
“ComputerProgrammingforEverybody”thatlaidoutavisionforanambitiousprogram
toteachprogramminginelementaryandsecondaryschoolsusingPython.Morethana
decadelater,itlookslikeitisactuallyhappeningwiththecomingoftheRaspberryPi.
Pythonisaninterpretedlanguage,whichmeansthatyoucanwriteaprogramorscriptand
executeitdirectlyratherthancompilingitintomachinecode.Interpretedlanguagesarea
bitquickertoprogramwith,andyougetafewsidebenefits.Forexample,inPythonyou
don’thavetoexplicitlytellthecomputerwhetheravariableisanumber,alist,orastring;
theinterpreterfiguresoutthedatatypeswhenyouexecutethescript.
ThePythoninterpretercanberunintwoways:asaninteractiveshelltoexecuteindividual
commands,orasacommand-lineprogramtoexecutestandalonescripts.Theintegrated
developmentenvironment(IDE)bundledwithPythonandtheRaspberryPiiscalledIDLE
(seeFigure4-1).
ThePythonVersionConundrum
ThereasonyouseetwoversionsofIDLEisthattherearetwoversionsofPythoninstalledonthePi.Thisiscommon
practice(thoughabitconfusing).Asofthiswriting,Python3isthenewest,butchangesmadetothelanguage
betweenversions2and3madethelatternotbackwardcompatible.EventhoughPython3hasbeenaroundforyears,
ittookawhileforittobewidelyadopted,andlotsofuser-contributedpackageshavenotbeenupgradedtoPython3.
ItgetsevenmoreconfusingwhenyousearchthePythondocumentation;makesureyou’relookingattheright
version!
TheexamplesinthisbookwillworkwithPython2.7or3.X,unlessotherwisenoted.
Figure4-1.PythonoptionsontheRaspbianDesktop:theIDLEintegrated
developmentenvironmentforPython2.0(left),IDLEforPython3.0
(middle),andacollectionofsamplegamesimplementedinPygamefrom
inventwithpython.com(right)
Hello,Python
ThebestwaytostartlearningPythonistojumprightin.Althoughyoucanuseanytext
editortostartscripting,we’llstartoutusingtheIDE.OpenuptheIDLE3application.To
runIDLE,double-clicktheIDLE3icononthedesktop,orclickthedesktopmenuinthe
lowerleft,andchooseProgramming→IDLE3.
IDLEcantakeseveralsecondstostartup,butwhenitappears,you’llseeawindowwith
theinteractiveshell.Thetriplechevron(>>>)istheinteractiveprompt;whenyouseethe
prompt,itmeanstheinterpreteriswaitingforyourcommands.Attheprompt,typethe
following:
>>>print("SalutonMondo!")
HitEnterorReturn.Pythonexecutesthatstatementandyou’llseetheresultintheshell
window.Notethattheprint()commandisoneofthethingsthatchangedinPython3.0;
ifyougetasyntaxerror,checktomakesureyou’rerunningthe3.0versionofIDLE.
Youcanusetheshellasakindofcalculatortotestoutstatementsorcalculations:
>>>3+4+5
12
Thinkofthestatementsexecutedintheinteractiveshellasaprogramthatyou’rerunning
onelineatatime.Youcansetupvariablesorimportmodules:
>>>importmath
>>>(1+math.sqrt(5))/2
1.618033988749895
TheimportcommandmakesallofPython’smathfunctionsavailabletoyourprogram
(moreaboutmodulesin“ObjectsandModules”).Tosetupavariable,usetheassignment
operator(=):
>>>importmath
>>>radius=20
>>>radius*2*math.pi
1256.6370614359173
Ifyouwanttoclearallvariablesandstartinafreshstate,selectShell→RestartShellto
startover.Youcanalsousetheinteractiveshelltogetinformationabouthowtousea
particularstatement,module,orotherPythontopicswiththehelp()command:
help("print")
Togetalistingofallofthetopicsavailable,try:
help("topics")
help("keywords")
help("modules")
ThePythoninterpreterisgoodfortestingstatementsorsimpleoperations,butyouwill
oftenwanttorunyourPythonscriptasyouwouldastandaloneapplication.Tostartanew
Pythonprogram,selectFile→NewWindow,andIDLEwillgiveyouascriptediting
window(seeFigure4-2).
Figure4-2.TheIDLEinteractiveshell(left)andaneditorwindow(right)
TrytypingalineofcodeandselectingRun→RunModule.You’llgetawarningthat
“SourceMustBeSavedOKToSave?”.Saveyourscriptinyourhomedirectoryas
SalutonMondo.pyandyou’llseeitexecuteintheshell.
SometimesyoumaynotwanttousetheIDLEenvironment.Torunascriptfromthe
commandline,openuptheLXTerminalandtype:
pythonSalutonMondo.py
That’sreallyallofthebasicmechanicsyouneedtoknowtogetupandrunningwiththe
environment.Next,you’llneedtostartlearningthelanguage.
CommandLineversusIDLE
OnethingyouwillnoticeisthattheoutputofIDLEisveryslowwhenrunningexamplecodethatprintstotheshell.
Togetanideaofjusthowslowitis,keepIDLEopenandopenanewLXTerminalalongside.Savethescriptas
CountEvens.pyinIDLEandtypethefollowingatthecommand-lineprompt:
pythonCountEvens.py
Actually,beforeyoudothat,runthesamescriptinIDLEusingRunModule;itwillneedtheheadstart.You’ll
quicklygetanideaoftheoverheadfromusingtheIDEonthefairlylimitedresourcesofthePi.Theexampleslaterin
thebookwillallbeexecutedfromthecommandline,butIDLEcanstillbeusedasaneditorifyoulike.
ABitMorePython
Ifyou’recomingtoPythonfromtheArduinoworld,you’reusedtowritingprograms
(knownassketchesinArduino,butoftencalledscriptsinPython)inasetup/loopformat,
wheresetup()isafunctionrunonceandloop()isafunctionthatexecutesoverand
over.ThefollowingexampleshowshowtoachievethisinPython.SelectNewWindow
fromtheshellinIDLE3andtypethefollowing:
#Setup
n=0
#Loop
whileTrue:
n=n+1
#The%isthemodulooperator
if((n%2)==0):
print(n)
SelectRunModuleandgiveyourscriptaname(suchasEvenIntegers.py).Asitruns,you
shouldseeallevenintegersprinted(pressCtrl-Ctointerrupttheoutput,becauseitwillgo
onforever).
Youcouldalsoimplementthisusingaforloopthatjustcountsthefirst100evenintegers:
forninrange(0,100):
if((n%2)==0):
print(n)
Note
Intheprecedingexample,youmaynotnoticethateachlevelofindentationisfourspaces,
notatab(butyoucanpresstabinIDLEanditwilldutifullyinsertspacesforyou).
IndentationhasstructuralmeaninginPython.Thisisoneofthebigstumblingblocksfor
beginners,orwhencopyingandpastingcode.Still,wefeelthatthemandatoryuseof
whitespacemakesPythonafairlyreadablelanguage.SeethePythonStyleGuidelinesfor
tipsonwritingreadablecode.
Itisimportanttowatchyourwhitespace;Pythonisahighlystructuredlanguagewherethe
whitespacedeterminesthestructure.Inthenextexample,everythingindentedonelevel
belowtheloop()functionisconsideredpartofthatfunction.Theendofaloopis
determinedbywheretheindentationmovesupalevel(orendofthefile).Thisdiffers
fromlanguageslikeCthatdelimitblocksofcodewithbracketsorothermarkers.
Usefunctionstoputchunksofcodeintoacodeblockthatcanbecalledfromotherplaces
inyourscript.Torewritethepreviousexamplewithfunctions,dothefollowing(when
yougotorunit,saveitasCountEvens.py):
#Declareglobalvariables
n=0
#Setupfunction
defsetup():
globaln
n=100
defloop():
globaln
n=n+1
if((n%2)==0):
print(n)
#Main
setup()
whileTrue:
loop()
Inthisexample,theoutputwillbeeveryevennumberfrom102on.Here’showitworks:
First,thevariablenisdefinedasaglobalvariablethatcanbeusedinanyblockinthe
script.
Here,thesetup()functionisdefined(butnotyetexecuted).
Similarly,here’sthedefinitionoftheloop()function.
Inthemaincodeblock,setup()iscalledonce,thenloop().
Theuseoftheglobalkeywordinthefirstlineofeachfunctionisimportant;ittellsthe
interpretertousetheglobalvariablenratherthancreateasecond(local,orprivatetothat
function)nvariableusableonlyinthefunction.
ThistutorialistooshorttobeacompletePythonreference.Toreallylearnthelanguage,
youmaywanttostartwithThinkPythonandthePythonPocketReference(O’Reilly).The
restofthischapterwillgiveyouenoughcontexttogetupandrunningwiththelater
examplesandwillmapoutthebasicfeaturesandmodulesavailable.Chapter5coversthe
PyGameframework,agoodwaytocreatemultimediaprogramsonthePi.
ObjectsandModules
You’llneedtounderstandthebasicsyntaxofdealingwithobjectsandmodulestoget
throughtheexamplesinthisbook.Pythonisacleanlanguage,withjust34reserved
keywords(seeTable4-1).Thesekeywordsarethecorepartofthelanguagethatletyou
structureandcontroltheflowofactivityinyourscript.Prettymucheverythingthatisn’ta
keywordcanbeconsideredanobject.Anobjectisacombinationofdataandbehaviors
thathasaname.Youcanchangeanobject’sdata,retrieveinformationfromit,andeven
manipulateotherobjects.
Table4-1.Pythonhasjust34reservedkeywords
Conditionals Loops
Built-infunctions Classes,modules,functions Errorhandling
if
for
print
class
try
else
in
pass
def
def
elif
while
del
global
finally
not
break
break
raise
or
as
nonlocal
assert
and
continue
yield
with
is
import
True
return
False
from
None
InPython,strings,lists,functions,modules,andevennumbersareobjects.APython
objectcanbethoughtofasanencapsulatedcollectionofattributesandmethods.Youget
accesstotheseattributesandmethodsusingasimpledotsyntax.Forexample,typethisat
theinteractiveshellprompttosetupastringobjectandcallthemethodthattellsitto
capitalizeitself:
>>>myString="quux"
>>>myString.capitalize()
'Quux'
Orusereverse()torearrangealistinreverseorder:
>>>myList=['a','man','a','plan','a','canal']
>>>myList.reverse()
>>>print(myList)
['canal','a','plan','a','man','a']
Note
BothStringandListarebuilt-inmodulesofthestandardlibrary,whichareavailablefrom
anyPythonprogram.Ineachcase,theStringandListmoduleshavedefinedabunchof
functionsfordealingwithstringsandlists,includingcapitalize()andreverse().
Someofthestandardlibrarymodulesarenotbuilt-in,andyouneedtoexplicitlysay
you’regoingtousethemwiththeimportcommand.Tousethetimemodulefromthe
standardlibrarytogainaccesstohelpfulfunctionsfordealingwithtimingand
timestamps,use:
importtime
Youmayalsoseeimportasusedtorenamethemoduleinyourprogram:
importtimeasmyTime
Orfromimportusedtoloadselectfunctionsfromamodule:
fromtimeimportclock
Here’sashortexampleofaPythonscriptusingthetimeanddatetimemodulesfromthe
standardlibrarytoprintthecurrenttimeonceeverysecond:
fromdatetimeimportdatetime
fromtimeimportsleep
whileTrue:
now=str(datetime.now())
print(now)
sleep(1)
Thesleepfunctionstopstheexecutionoftheprogramforonesecond.Onethingyouwill
noticeafterrunningthiscodeisthatthetimewilldriftabiteachtime.
That’sfortworeasons:
Thecodedoesn’ttakeintoaccounttheamountoftimeittakestocalculatethecurrent
time(.9secondswouldbeabetterchoice).
OtherprocessesaresharingtheCPUandmaytakecyclesawayfromyourprogram’s
execution.Thisisanimportantthingtoremember:whenprogrammingonthe
RaspberryPi,youarenotexecutinginareal-timeenvironment.
Ifyou’reusingthesleep()function,you’llfindthatitisaccuratetomorethan5msonthe
Pi.
Next,let’smodifytheexampletoopenatextfileandperiodicallylogsomedatatoit.
Everythingisastringwhenhandlingtextfiles.Usethestr()functiontoconvertnumbers
tostrings(andint()tochangebacktoaninteger):
fromdatetimeimportdatetime
fromtimeimportsleep
importrandom
log=open("log.txt","w")
foriinrange(5):
now=str(datetime.now())
#Generatesomerandomdataintherange0-1024
data=random.randint(0,1024)
log.write(now+""+str(data)+"\n")
print(".")
sleep(.9)
log.flush()
log.close()
Note
Inarealdata-loggingapplication,you’llwanttomakesureyou’vegotthecorrectdate
andtimesetuponyourRaspberryPi,asdescribedinChapter1.
Here’sanotherexample(ReadFile.py)thatreadsinafilenameasanargumentfromthe
commandline(runitfromtheshellwithpython3ReadFile.pyfilename.Theprogram
opensthefile,readseachlineasastring,andprintsit.Notethatprint()actslike
println()doesinotherlanguages;itaddsanewlinetothestringthatisprinted.Theend
argumenttoprint()suppressesthenewline:
#Openandreadafilefromcommand-lineargument
importsys
if(len(sys.argv)!=2):
print("Usage:pythonReadFile.pyfilename")
sys.exit()
scriptname=sys.argv[0]
filename=sys.argv[1]
file=open(filename,"r")
lines=file.readlines()
file.close()
forlineinlines:
print(line,end='')
EvenMoreModules
OneofthereasonsPythonissopopularisthatthereareagreatnumberofusercontributedmodulesthatbuildonthestandardlibrary.ThePythonPackageIndex(PyPI)
isthedefinitivelistofpackages(ormodules);someofthemorepopularmodulesthatare
particularlyusefulontheRaspberryPiareshowninTable4-2.You’llbeusingsomeof
thesemoduleslateron,especiallytheGPIOmoduletoaccessthegeneralinputsand
outputsoftheRaspberryPi.
Table4-2.SomepackagesofparticularinteresttoPiusers
Module
Description
URL
Packagename
RPi.GPIO AccesstoGPIOpins
sourceforge.net/projects/raspberry-gpio-python python-rpi.gpio
Pygame
Gamingframework
pygame.org
python-pygame
SimpleCV EasyAPIforComputerVision
simplecv.org
Nopackage
Scipy
Scientificcomputing
www.scipy.org
python-scipy
Numpy
ThenumericalunderpiningsofScipy
numpy.scipy.org
python-numpy
Flask
Microframeworkforwebdevelopment flask.pocoo.org
python-flask
Feedparser AtomandRSSfeedparser
pypi.python.org/pypi/feedparser
Nopackage
Requests
“HTTPforHumans”
docs.python-requests.org
python-requests
PIL
Imageprocessing
www.pythonware.com/products/pil/
python-imaging
wxPython GUIframework
wxpython.org
python-wxgtk2.8
PySerial
Accesstoserialport
pyserial.sourceforge.net
python-serial
pyUSB
FTDI-USBinterface
bleyer.org/pyusb
Nopackage
Touseoneofthese,you’llneedtodownloadthecode,configurethepackage,andinstall
it.Theserialmodule,forexample,canbeinstalledasfollows:
sudoapt-getinstallpython-serial
Ifapackagehasbeenbundledbyitscreatorusingthestandardapproachtobundling
modules(withPython’sdistutilstool),allyouneedtodoisdownloadthepackage,
uncompressit,andtype:
pythonsetup.pyinstall
EasyModuleInstallswithPip
Manymodulescanbeinstalledwithapt-get.YoumayalsowanttolookatthePippackageinstaller,atoolthatmakes
itquiteeasytoinstallpackagesfromthePyPI.InstallPipusingapt-get:
sudoapt-getinstallpython-pip
ThenyoucaninstallmostmodulesusingPiptomanagethedownloadsanddependencies.Forexample:
pipinstallflask
Inlaterchapters,you’lluseapplication-specificmodulesextensively,buthere’sone
examplethatshowshowpowerfulsomemodulescanbe.TheFeedparsermoduleisa
universalparserthatletsyougrabRSSorAtomfeedsandeasilyaccessthecontent.
BecausemoststreamsofinformationontheWebhaveRSSorAtomoutput,Feedparseris
oneofseveralwaystogetyourRaspberryPihookedintotheInternetofThings.
First,installtheFeedparsermoduleusingPip(see“EasyModuleInstallswithPip”):
sudopipinstallfeedparser
Touseit,simplygivetheparsefunctiontheURLofanRSSfeed.Feedparserwillfetch
theXMLofthefeedandparseit,andturnitintoaspeciallistdatastructurecalleda
dictionary.APythondictionaryisalistofkey/valuepairs,sometimescalledahashor
associativearray.Theparsedfeedisadictionary,andtheparseditemsinthefeedarealso
adictionary,asshowninthisexamplewhichgrabsthecurrentweatherinProvidence,RI,
fromhttp://weather.gov:
importfeedparser
feed_url="http://w1.weather.gov/xml/current_obs/KPVD.rss"
feed=feedparser.parse(feed_url)
RSSitems=feed["items"]
foriteminRSSitems:
weather=item["title"]
printweather
LaunchingOtherProgramsfromPython
PythonmakesitfairlyeasytotriggerotherprogramsonyourPiwiththesys.subprocess
module.Trythefollowing:
fromdatetimeimportdatetime
fromtimeimportsleep
importsubprocess
forcountinrange(0,60):
filename=str(datetime.now())+".jpg"
subprocess.call(["fswebcam",filename])
sleep(60)
Thisisasimpletime-lapsescriptthatwillsnapaphotofromawebcamonceaminutefor
anhour.CamerasarecoveredingreaterdetailinChapter11,butthisprogramshould
workwithaUSBcameraconnectedandthefswebcamprograminstalled;runthis
commandfirsttoinstallit:
sudoapt-getinstallfswebcam
Thesubprocess.callfunctiontakesalistofstrings,concatenatesthemtogether(with
spacesbetween)andattemptstoexecutetheprogramspecified.Ifitisavalidprogram,the
RaspberryPiwillspawnaseparateprocessforit,whichwillrunalongsidethePython
script.Thecommandintheprecedingexampleisthesameasifyoutypedthefollowingat
aterminalprompt:
fswebcam20140812.jpg
Toaddmoreparameterstotheprograminvocation,justaddstringstothelistinthe
subprocess.callfunction:
subprocess.call(["fswebcam","-r","1280x720",filename])
Thiswillsendthefswebcamprogramaparametertochangetheresolutionofthesnapped
image.
RunningaPythonScriptAutomaticallyatStartup
BecausethePicanactasastandaloneappliance,acommonquestionishowtolaunchaPythonscriptautomatically
whenthePibootsup.Theansweristoaddanentrytothe/etc/rc.localfile,whichisusedforexactlythisintheLinux
world.Justeditthefile:
sudonano/etc/rc.local
andaddacommandtoexecuteyourscriptbetweenthecommentedsectionandexit0.Somethinglike:
python/home/pi/foo.py&
Theampersandattheendwillrunthescriptasabackgroundprocess,whichwillallowalltheotherservicesofthePi
tocontinuebootingup.
TroubleshootingErrors
Inevitably,you’llrunintotroublewithyourcodeandyou’llneedtotrackdownand
squashabug.TheIDLEinteractivemodecanbeyourfriend;theDebugmenuprovides
severaltoolsthatwillhelpyouunderstandhowyourcodeisactuallyexecuting.Youalso
havetheoptionofseeingallyourvariablesandsteppingthroughtheexecutionlineby
line.
Syntaxerrorsaretheeasiesttodealwith;usuallythisisjustatypooramisunderstood
aspectofthelanguage.Semanticerrors—wheretheprogramiswellformedbutdoesn’t
performasexpected—canbehardertofigureout.That’swherethedebuggercanreally
helpunwindatrickybug.Effectivedebuggingtakesyearstolearn,buthereisaquick
cheatsheetofthingstocheckwhenprogrammingthePiinPython:
Useprint()toshowwhentheprogramgetstoaparticularpoint.
Useprint()toshowthevaluesofvariablesastheprogramexecutes.
Double-checkwhitespacetomakesureblocksaredefinedthewayyouthinktheyare.
Whendebuggingsyntaxerrors,rememberthattheactualerrormayhavebeen
introducedwellbeforetheinterpreterreportsit.
Double-checkallofyourglobalandlocalvariables.
Checkformatchingparentheses.
Makesuretheorderofoperationsiscorrectincalculations;insertparenthesesifyou’re
notsure.Forexample,3+4*2and(3+4)*2yielddifferentresults.
Afteryou’recomfortableandexperiencedwithPython,youmaywanttolookatthecode
andloggingmodulesformoredebuggingtools.
GoingFurther
ThereisalotmoretoPython,andherearesomeresourcesthatyou’llfinduseful:
ThinkPython,byAllenDowney
Thisisaclearandfairlyconciseapproachtoprogramming(thathappenstouse
Python).
PythonPocketReferencebyMarkLutz
Becausesometimesflippingthroughabookisbetterthanclickingthroughadozen
StackOverflowposts.
StackOverflow
Thatsaid,StackOverflowisanexcellentsourceofcollectiveknowledge.Itworks
particularlywellifyou’researchingforaspecificsolutionorerrormessage;chances
aresomeoneelsehashadthesameproblemandpostedhere.
LearnPythontheHardWay,byZedShaw
Agreatbookandonlineresource;attheveryleast,readtheintroduction“TheHard
WayIsEasier.”
PythonForKidsbyJasonR.Briggs
Again,moreofageneralprogrammingbookthathappenstousePython(andwritten
foryoungerreaders).
Chapter5.PygameforAnimationandMultimedia
PygameisalightweightframeworkforcreatingsimplegamesinPython.Youcanalso
thinkofitasatoolforgeneralmultimediaprogramming;it’saconvenientwaytojust
drawgraphicsonthescreen,playsounds,orhandlekeyboardandmouseevents.
PygameisasoftwarewrapperaroundanotherlibrarycalledtheSimpleDirectMediaLayer
(SDL).SDLhandlesallofthelow-levelaccesstothePi’skeyboard,mouse,and
audio/videodrivers.PygamesimplifiesSDLevenfurther.
ThefocusofthischapterismoreonthebasicmultimediacapabilitiesofPygame,rather
thanatutorialongameprogramming.Otherresourcesforgameprogrammingare
providedattheend.
Hello,Pygame
PygamecomespreinstalledonyourRaspberryPi.There’saversionofPygamethatworks
withPython3.0,buttheversionthatcomeswithRaspbianonlyworkswithversion2.7.
Youcaneitherswitchovertothenon-3.0versionofIDLE(justdouble-clicktheIDLE
iconinsteadoftheIDLE3icon),orjustrunyourscriptfromthecommandline,andthe
2.7interpreterwillbeused.
ThefollowingexampleshowstheminimalnumberofstepstocreateaPygameprogram;it
drawsaredcircleinanewwindow:
importpygame
width=640
height=480
radius=100
stroke=1
pygame.init()
window=pygame.display.set_mode((width,height))
window.fill(pygame.Color(255,255,255))
whileTrue:
pygame.draw.circle(window,
pygame.Color(255,0,0),
(width/2,height/2),
radius,stroke)
pygame.display.update()
ImportthePygamemodule,whichmakesallofthePygameobjectsandfunctions
availableforuse.
Setupsomeglobalvariableshere.
Alwayscalltheinit()functionfirst;thisperformssomestepsneededtoinitialize
Pygamebeforeyouuseit,andwillalsocalltheinit()functionforallofthePygame
submodules.
Setupthewindow:aPygameSurfaceobject—anareaonwhichtodraw.
Fillthewindowwithwhite.
Loopforever.Youcanthinkofeachiterationofthisloopasasingleframeofaninfinite
animation.
Drawacircleinredatthecenterofthewindow.
Allofthedrawingcommandsintheloopmakeuponeframeoftheanimationandare
drawnintoanoffscreenbufferthatishidden.Whenyou’redonedrawingtheframe,call
display.update()toupdatetheimageonthescreen.
Note
Inalloftheseexamples,you’llhavetouseControl-Conthecommandlinetokillthe
scriptwhenyou’redone.IfyouwanttoenabletheclosebuttononthePygamewindow,
addthefollowingcodetotheendofthewhileloop:
ifpygame.QUITin[e.typeforeinpygame.event.get()]:
break
Thatwillcatchtheeventtriggeredwhenthebuttonispressed.Formoreonevents,see
“HandlingEventsandInputs”.
Pygameconsistsofacollectionofsubmodulesandobjects;thebasicsofhowtheyare
usedaredescribedintherestofthischapter.
PygameSurfaces
APygameSurfaceisjustarectangularimage;Surfacesarecombinedandlayeredto
createeachsceneinaframeofthegameoranimation.ThepixelsofaSurfaceare
representedbyasequenceofthree8-bitRGBnumbers(e.g.,(0,255,0)represents
green).Addafourthnumberfortransparency:(0,255,0,127)is50%transparent.
ThedisplaywindowisthebaseSurfaceonwhichallotherSurfacesaredrawn.The
pygame.displaymodulecontrolsandprovidesinformationaboutthedisplaywindow.Use
theset_mode()functiontocreateanewdisplaywindow,andtheupdate()function
redrawthedisplayeveryframe.
ToloadanimagefromafileintoaSurfacetobedisplayed,usetheload()functionfrom
thepygame.imagemodule.OnceyouhaveadisplaySurface,youcanaddimagestoitby
creatinganewSurfaceobjectandusingtheblit()functiontocombinethem:
importpygame
pygame.init()
screen=pygame.display.set_mode((450,450))
background=pygame.image.load("background.png")
background.convert_alpha()
screen.blit(background,(0,0))
whileTrue:
pygame.display.update()
LoadsabackgroundimagethatneedstobeinthesamedirectoryasthePython
program.
Theconvert_alpha()functionchangestheformatoftheSurfacetomatchthecurrent
display.Thisisn’trequired,butissuggested,asitwillspeedimagecompositing.
Bydefault,thescreenSurfacewillbeblack.Theblit()functioncombinesthe
backgroundSurfacewithablackbackground.
Here’sanexampleofcombiningtwoimages(seeFigure5-1):
importpygame
pygame.init()
screen=pygame.display.set_mode((450,450))
background=pygame.image.load("background.png").convert_alpha()
theremin=pygame.image.load("theremin.png").convert_alpha()
screen.blit(background,(0,0))
screen.blit(theremin,(135,50))
whileTrue:
pygame.display.update()
Figure5-1.Blittingtwoimagestogether
Thepygame.transformmoduleprovidesfunctionsforrotatingandscalingsurfaces.You
cangetaccesstotheindividualpixelsofaSurfaceusingthefunctionsofthe
pygame.surfarraymodule.
Surfacesarealwaysrectangularimageswhencreated;eventhoughthetransparentareasof
thepreviousexampleSurfacewerecombinedtomakeitlooknonrectangular,theSurface
isstillarectangle.IfyouwantaSurfacewithanonrectangularboundary(forpixel-perfect
collisiondetection,forexample),youcansetamaskfromanothersurfacewiththe
pygame.maskmodule.Masksaredescribedinmoredetailinthegameprogramming
resourcesattheendofthechapter.
DrawingonSurfaces
Yousawanexampleofthepygamecircledrawingfunctionpreviously;thepygame.draw
moduleprovidesseveralmorefordrawingrectangles,lines,arcs,andellipses.The
pygame.gfxdrawmoduleisanotherwayofdrawingshapes.Itprovidesafewmore
options,butisconsideredexperimentalandtheAPImaychange.
Todrawtextonthescreen,youfirstcreateanewFontobject(providedbythe
pygame.fontmodule),thenusethattoloadafontandrenderthetext.Tofindalistofall
ofthefontsavailableonyourRaspberryPi,usethepygame.font.get_fonts()function:
importpygame
pygame.init()
forfontnameinpygame.font.get_fonts():
printfontname
Asyoucansee,therearefewfontsavailablewiththebaseRaspbiandistribution.Usethe
SysFontobjecttorendersometextusingthefreeseriffont:
importpygame
pygame.init()
screen=pygame.display.set_mode((725,92))
font=pygame.font.SysFont("freeserif",72,bold=1)
textSurface=font.render("1ThereminPerChild!",1,
pygame.Color(255,255,255))
screen.blit(textSurface,(10,10))
whileTrue:
pygame.display.update()
Note
Ifyouwantmorefonts,try:
sudoapt-getinstallttf-mscorefonts-installer
sudoapt-getinstallttf-liberation
HandlingEventsandInputs
InPygame,user-initiatedeventslikepressingakeyorclickingormovingthemouseare
allcapturedasanEventobjectandputintheeventqueue,wheretheyaccumulateuntil
yourprogramdoessomethingwiththem.Thepygame.eventmoduleprovidesfunctions
forhandlingalltheeventsthathavepiledupsincethelasttimeyoulookedatthequeue.
Youcanevencreateyourowneventtypestoimplementamessagingsystem.Let’slookat
asimpleexamplethatusestheeventqueuetoexpandontheredcircleprogram;ineach
frame,thecircleisredrawnatthecurrentmouselocationandtheradiusgetslargerthe
closeritistotheedgeofthewindow(seeFigure5-2).
Figure5-2.OutputofthePygameeventsexample
HereisthecodethatgeneratestheimageshowninFigure5-2:
importpygame
frompygame.localsimport*
width,height=640,640
radius=0
mouseX,mouseY=0,0
pygame.init()
window=pygame.display.set_mode((width,height))
window.fill(pygame.Color(255,255,255))
fps=pygame.time.Clock()
whileTrue:
foreventinpygame.event.get():
ifevent.type==MOUSEMOTION:
mouseX,mouseY=event.pos
ifevent.type==MOUSEBUTTONDOWN:
window.fill(pygame.Color(255,255,255))
radius=(abs(width/2-mouseX)+abs(height/2-mouseY))/2+1
pygame.draw.circle(window,
pygame.Color(255,0,0),
(mouseX,mouseY),
radius,1)
pygame.display.update()
fps.tick(30)
Thepygame.localsmoduledefinesanumberofconstantslikeMOUSEMOTION.Importing
ithereallowsustousetheseconstantswithoutprependingpygame.tothem.
Variablestostorethemousecoordinates.
Thisfunctioninitializesanobjectthatwe’lluseasaframecounter.Withthisfps
(framespersecond)variable,youcanwaitacertainamountineachframetoachievea
regularframerate.
Loopforever;eachtimethroughtheloopisoneframe.
Loopthroughtheeventqueue.Eachtimethrough,theeventvariablewillholdthenext
eventinthequeue.
Iftheeventisamousemovement,updatethevariableholdingthemouselocation.
Iftheeventisamouseclick,clearthescreen.
Varytheradiusbasedonhowfarawayfromthecenterthemouseis.
Drawthecircle.
Waitsothattheframerateis30fps.
Othermodulesthatarehandyfordealingwitheventsanduserinputare:
pygame.time
Amoduleformonitoringtime.
pygame.mouse
Amoduletogetinformationaboutthemouse.
pygame.key
Amoduletogetinformationaboutthekeyboard,andmanyconstantsrepresentingthe
keys.
pygame.joystick
Amoduleforworkingwithajoystick.
GoingFullScreen
Torunyourprograminawindowthattakesoverthewholescreen,setthepygame.FULLSCREENflagwhenyousetthe
displaymode.Wheninfullscreenmode,makesuretohavesomewayofgettingoutofthescript,asyouwon’tbe
abletokillitwithCtrl-C:
importpygame
importrandom
fromtimeimportsleep
running=True
pygame.init()
screen=pygame.display.set_mode((0,0),pygame.FULLSCREEN)
whilerunning:
pygame.draw.circle(
screen,
pygame.Color(int(random.random()*255),
int(random.random()*255),
int(random.random()*255)),
(int(random.random()*1500),
int(random.random()*1500)),
int(random.random()*500),0)
pygame.display.update()
sleep(.1)
foreventinpygame.event.get():
ifevent.type==pygame.KEYDOWN:
running=False
pygame.quit()
Thescriptwillexitwhenanykeyonthekeyboardispressed.
Sprites
Youwillhandlemostofthemovableandcontrollablegraphicalelementsofagamewith
sprites.Thepygame.spritemoduleprovidesallofthebasicfunctionstodrawspriteson
thescreenandhandlecollisionsbetweenthem.Youcanalsogroupspritessothatyoucan
controlandupdatethemtogether.Acompleteworkinggameusingspritesisbeyondthe
scopeofthisbook(“GoingFurther”hassomeresourcestogetyouheadedintheright
direction).
Spritesarebestusedwhenyou’llbecreatingseveralscreenelementsthatsharealotofthe
samecode.Hereisanexampleofhowtohandlecreatingandupdatingacoupleofsprites;
theresultistwoballsthatbounceoffthesidesofthescreen.Youcanaddotherballsby
creatinganewspritewithadifferentstartingcoordinate,direction,andspeed:
importpygame
classBall(pygame.sprite.Sprite):
def__init__(self,x,y,xdir,ydir,speed):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface([20,20])
self.image.fill(pygame.Color(255,255,255))
pygame.draw.circle(self.image,
pygame.Color(255,0,0),
(10,10),10,0)
self.rect=self.image.get_rect()
self.x,self.y=x,y
self.xdir,self.ydir=xdir,ydir
self.speed=speed
defupdate(self):
self.x=self.x+(self.xdir*self.speed)
self.y=self.y+(self.ydir*self.speed)
if(self.x<10)|(self.x>490):
self.xdir=self.xdir*-1
if(self.y<10)|(self.y>490):
self.ydir=self.ydir*-1
self.rect.center=(self.x,self.y)
pygame.init()
fps=pygame.time.Clock()
window=pygame.display.set_mode((500,500))
ball=Ball(100,250,1,1,5)
ball2=Ball(400,10,-1,-1,8)
whileTrue:
ball.update()
ball2.update()
window.fill(pygame.Color(255,255,255))
window.blit(ball.image,ball.rect)
window.blit(ball2.image,ball2.rect)
pygame.display.update()
fps.tick(30)
Theclassstatementcreatesanewobject(aball)thatisbasedontheSpriteobject.You
canthendefineyourownfunctionsfordrawingthesprite,andhowthespritebehaves
eachtimeitisupdated.
ThisfunctioniscalledwhentheBall()functioniscalledtocreateanewball.
ThesevariablesarestoredaspartofeachinstanceofBall.EachBallinessencecarries
arounditsownsetofvariables.
Theupdate()functioniscalledwitheachframe.Thesavedpositionismovedbasedon
thesaveddirectionandspeed,thentestedtoseeifithascomeneartheedge.Ifso,the
directiononthatparticularaxisisreversed.
Createtwoballswithdifferentstartinglocations,directions,andspeeds.
Updatetheballwithanewlocationbasedonitssavedposition,direction,andspeed.
Drawtheballatitscurrentlocation.
PlayingSound
Youcanloadsoundfilesandplaythembackusingthepygame.mixermodule,oryoucan
usethepygame.midimoduletosendMIDIeventstoothersoftwarerunningonthePior
MIDIhardwarehookeduptotheUSBport.ThefollowingexampleplaysbackaWAVformattedsoundsample(whichyoucandownloadfromtheInternetArchive):
importpygame.mixer
fromtimeimportsleep
pygame.mixer.init(48000,-16,1,1024)
sound=pygame.mixer.Sound("WilhelmScream.wav")
channelA=pygame.mixer.Channel(1)
channelA.play(sound)
sleep(2.0)
Anaudiofile(intheWAVformat)isloadedandassociatedwithachannel.Themixer
actuallyplaysbackeachchannelinaseparateprocess,somultiplesoundswillplayatthe
sametime.Thesleep()attheendisneededsothemainprocessdoesn’tendbeforethe
soundhasfinishedplaying.
ThemixerapproachforplayingbacksoundfilesisdiscussedfurtherinChapter9inthe
SimpleSoundboardexample.TheMIDIcapabilitiesofPygamehaveintriguing
possibilities;forexample,youcaneasilycreateacustomMIDIcontroller.Asofthis
writing,thestateofsoftwaresynthesizersthatworkonRaspbianiskindofrough,andthe
analogaudiooutputisnotasgoodastheHDMIaudiooutput.Thatwillimprove,however,
andyoucanalwaysuseanexternalUSBMIDIdevice.Tofindinformationaboutthe
MIDIdevicesconnectedtoyourRaspberyPi,use:
importpygame
importpygame.midi
pygame.init()
pygame.midi.init()
foridinrange(pygame.midi.get_count()):
printpygame.midi.get_device_info(id)
Themidimoduleisnotimportedwiththebasepygamemodule.
Italsomustbeinitializedseparately.
Theget_count()functionreturnsthenumberofMIDI-capabledevicesconnectedto
thePieitherbyUSB,softwaresynthesizers,orothervirtualMIDIdevices.
Printsinformationaboutthedevice.
IfyoupluginanexternalMIDIkeyboard,you’llgetsomethingthatlookslikethisfor
output:
('ALSA','MidiThroughPort-0',0,1,0)
('ALSA','MidiThroughPort-0',1,0,0)
('ALSA','USBUnoMIDIInterfaceMIDI1',0,1,0)
('ALSA','USBUnoMIDIInterfaceMIDI1',1,0,0)
Thefirststringtellsyouthatyou’reusingtheAdvancedLinuxSoundArchitecture
(ALSA),andtheseconddescribeseachMIDIport.Thelastthreenumbersindicate
whethertheportisaninputoroutputdevice,andwhetheritisopenornot.Youcanthink
oftheprecedingexampleasfourdifferentMIDIportslabeled0through3:
MidiThroughPort-0(0,1,0)
Port0,anoutputusedtotalktoanysoftwaresynthesizersyoumayhaverunningonthe
Pi.
MidiThroughPort-0(1,0,0)
Port1,aninputusedtotakeMIDIcontrolsfromanysoftwarecontrollersyoumayhave
runningonthePi.
USBUnoMIDIInterfaceMIDI1(0,1,0)
Port2,anoutputtoanexternalUSBMIDIinterfacehookeduptoakeyboard.
USBUnoMIDIInterfaceMIDI1(1,0,0)
Port3,aninputfromanexternalUSBMIDIinterfacehookeduptoakeyboard.
Withthisinmind,youcanhookupanexternalkeyboardwithaUSBinterfaceanduse
Pygametocontrolit,asinthefollowingexample:
importpygame
importpygame.midi
fromtimeimportsleep
instrument=0
note=74
volume=127
pygame.init()
pygame.midi.init()
port=2
midiOutput=pygame.midi.Output(port,0)
midiOutput.set_instrument(instrument)
fornoteinrange(0,127):
midiOutput.note_on(note,volume)
sleep(.25)
midiOutput.note_off(note,volume)
delmidiOutput
pygame.midi.quit()
TheseareMIDIvalues,typicallyintherange0to127.
Openport2,theoutputassociatedwiththeUSBMIDIcontrolledkeyboard.
Sendanoteoncontrolsignal,wait,thenturnthenoteoff.
It’sclearthattheRaspberryPihasalotofpotentialasaplatformformusicmaking.
PlayingVideo
Pygamecanalsobeusedtoplayvideosusingthethepygame.moviemodule.Videofiles
mustbeencodedintheMPEG1format.Ifyouhaveavideoinadifferentformat,trythe
ffmpegutilitytoconvertbetweenformats(you’llhavetorunsudoapt-getinstall
ffmpegfirst).Toplayitback,simplycreateanewMovieobjectandcalltheplay()
function:
importpygame
fromtimeimportsleep
pygame.init()
screen=pygame.display.set_mode((320,240))
movie=pygame.movie.Movie("foo.mpg")
movie.play()
whileTrue:
ifnot(movie.get_busy()):
print("rewind")
movie.rewind()
movie.play()
ifpygame.QUITin[e.typeforeinpygame.event.get()]:
break
Ifthevideohasanaudiotrack,you’llneedtoclosePygame’saudiomixerbeforeplaying
themovie.Totellthemixertoquit,includethislinebeforeyouplay:
pygame.mixer.quit()
EvenMoreExamples
There’sawholePygamemodulededicatedtomorecompleteexampleprograms:
pygame.examples.Youcanfindthesourcecodefortheseexamplesinthe
/usr/share/pyshared/pygame/examplesdirectory.
GoingFurther
Pygameofficialdocumentation
Theofficialdocumentationisabitsparseinplaces,buthopefullyyou’llbeableto
navigateitafterreadingthischapter.
MakingGameswithPython&PygameandInventYourOwnComputerGameswith
Python,byAlSweigart
TwoCreativeCommons-licensedbooks;thegamesdevelopedinthesebooksare
bundledwiththeRaspberryPi.
Chapter6.ScratchonthePi
ScratchwasdevelopedbytheMITMediaLab’sLifelongKindergartengroupasanew
wayofteachingprogrammingtoyoungpeople.Programsareconstructedfromcolorful
blocks,eachofwhichperformsanoperation.Theself-containedblockseliminatethe
syntaxproblemsthatstymiemanyfirsttimersusingtext-basedprogramminglanguages.
TosaythatScratchisnotapowerfulprogramminglanguagemissesthepoint,whichis
thatitisafriendlyenvironmentforcreatingandmakingthingshappenquickly.Ayoung
programmercanseetheblocksofcodehighlightasthey’reexecuted,andblockscanbe
changedandtheeffectsseeninrealtime.
Asyou’llsee,allScratchprogramsareaimedatmanipulatingspritesonastage.There’sa
largecommunityofScratchusers,andtheabilitytosharespritesandcodewiththe
communityisbakedrightintotheplatform.
Hello,Scratch
ToshowhoweasyitistogetstartedprogramminginScratch,we’llstartrightinwitha
verysimple“catinthebox”program.WhenyouopenupScratch,you’llseeasingle
windowopenwithseveralpanes.TheroleofeachpaneislabelledinFigure6-1.Youcan
startScratchbydouble-clickingitsdesktopicon,orbyclickingthedesktopmenuinthe
lowerleftandchoosingEducation→Scratch.
EveryScratchprograminvolvesspritesinteractingonthestage.Spritesarecontrolledby
scriptsthatarebuiltwithacollectionofblocksthatarepulledfromtheblockpalette.
Whenyouopenanewdocument,you’llgetthedefaultScratchcatsprite.Ifyoudon’t
wantthecat,youcandeleteit(right-clickonthespriteintheSpriteListforthemenu),
thendrawyourownorgrabarandomsurprisespritecreatedbysomeoneelseinthe
Scratchcommunity.
Figure6-1.TheScratchenvironment;everythingiscontainedinone
window,withsubpanelsfortheblockpalettes,thescriptingandcostume
area,thespritelist,andthestage
Thescriptingareashowsthescriptbelongingtotheselectedsprite.Clickonthecatinthe
spritelistandyou’llseeanemptyscriptingareaforthesprite.Youcanbuildascript
anywhereinthisframe.Ifyoucreateanothersprite,you’llneedtoclickonittodisplayits
script.
Scriptsarebuiltupbydraggingblocksfromthepalettetothescriptingarea.Manyblocks
cancontainotherblocks,andhowtheyfittogetherisindicatedbytheirshape.Thereare
threetypesofblocksinScratch,asshowninFigure6-2:
Hatblocks
Thewhengreenflagclickedblockisanexampleofahatblock,whichsitsatthetopof
astackofblocksandwaitsforaneventtohappen.
Stackableblocks
Blockswithanindentationontopand/orbumponthebottomfittogetherwithother
stackableblocks.Theblocksareexecutedintop-downorder.
Reporterblocks
Reporterblockshaveroundedorpointededgesandfitinsidetheinputareasofother
blocks.Reporterblocksmaybevariablesormayprovideinformationlikethemouse
coordinatesorsomecondition.
Figure6-2.TherearethreetypesofblocksinScratch:hatblocks(left),
stackableblocks(center),andreporterblocks(right)
StartanewscriptbyselectingtheControlblockpalette,anddragtheblockshownhereto
thescriptingarea:
Thenextstepistousethestackableforeverblockthatwillexecuteallofthecommands
containedwithinitoverandoverunderthescriptisstopped:
Besuretopracticereorganizingtheblocks.Whenyoupickupablock,youalsopickup
alloftheblocksattachedafterit.Toseparateablock,youwilloftenhavetoseparatea
wholestackofblocks,thengrabthechildrenoftheblockyouwanttoremove.Youcan
alsoright-clickonablocktoduplicateit(anditschildren)andgethelp.
Next,selecttheMotionpalette,anddragaturnblockandplaceitintheforeverloop:
Atthispoint,youcanclickthegreenflagintheupperrightofthestageandstart
executingthescript.OneoftheneatthingsaboutScratchisthatyoucanmakechangeson
theflyandseethemimmediatelytakeeffectonstage.Thisisareallygoodwaytodebug
yourprogramonthefly.
Note
Whenyouclickthegreenflag,amessageissenttoallscriptsintheprojecttostart
running(similarly,thestopsignsendsastopsignal).
Ifyoulookattheturnblock,you’llseethatthenumberofdegreestorotateisinarounded
rectangleshapedblock.Youcanedittheangledirectly,oryoucanreplaceitwithanother
blockofthesameshape.Youcanhavethespriteperformarandomwalkbymakingsome
changes.
First,replacethedefaultvaluewiththepickrandomblockfromtheOperatorspalette.
Afteryouplacetheblock,changethevaluessotheyselectarandomnumberbetween–10
and10:
NowaddamoveblockfromtheMotionpalette,whichwillmovethespriteanumberof
pixelsinthedirectionitiscurrentlyfacing.Thedirectionisshownasanumberandablue
lineintheinfobarabovethescriptingarea.Assoonasyouplacetheblock,thespritewill
startmovinginarandomwalk:
Finally,tokeepthespriteonthestage,addaifonedge,bounceblockfromthemotion
palette:
That’sallthereistowritingaScratchscript!
TheStage
Thestageistheframeintheupper-rightcorner,whereallofyourspritescarryouttheir
actionsandinteractions.Likesprites,thestagecanhavescriptsthatchangeitsappearance
orbehavior.YoucanalsopaintbackgroundsintheBackgroundstabofthescriptingarea.
ThecoordinatesysteminScratchisalittledifferentthanothermultimediaenvironments
likePygame;itfollowsmoreofamath-classmodel,wheretheorigin(0,0)isactuallyin
thecenterofthestage.Thevisiblepartofthestageextendsfrom(–240,180)to(240,–
180),asshowninFigure6-3.Spritescancontinueoffstageifyouletthem,however;if
youselectasprite,you’llseethecurrentpositionatthetopofthescriptarea,andthe
locationofthecursoratthebottomofthestage.
Figure6-3.TheScratchcoordinatesystem,withtheorigininthecenterof
thestage
TwoMoreThingstoKnowaboutSprites
Therearetwoadditionaltabsinthescriptingareathatyou’llbeusing:Costumesand
Sounds.
Costumesareacollectionofimagesthatthespritecanchangeinto.Costumescanbeused
tocreateloopinganimationsortoshowdifferentstatesthatthespriteisin(e.g.,an
explodingspaceship).Forexample,createanewspritethatisanopeneye;we’lluse
changingcostumestomakeitblink.SelectPaintNewSprite(it’stheicontotherightof
“Newsprite”intheStatearea)anddrawsomethinglikethis,thenclickOK:
SelecttheCostumestab,whereyou’llseetheimageyoujustdrew.Changethenameof
thecostumetoopen.ClicktheCopybuttontocreateanewcostume.ClickEdittoerase
thepupilanddrawaclosedeyelid,thenclickOKandchangethenameofthiscostumeto
shut:
Next,selecttheScriptstabanddragtheseblockstocreateascriptthatwillblinktheeye
everysecond:
Finally,youcanaddsoundeffectstoaspriteintheSoundstab.Justhitrecordandyou’ll
getthebuilt-inSoundRecordertool.You’llneedanexternalUSBsoundcardor
microphonetobeabletorecordsound.Givethesoundeffectanameandyoucanplayit
backusingtheplaysoundorplaysounduntildoneblocks.
ABiggerExample:AstralTrespassers
InthegameAstralTrespassers,theplayermustshootatincomingalienspaceships;the
gameisoverwhenanalienhitstheplayer’splanetdefendingcannon.Thissimplegame
willshowhowallthepiecesfittogether.
First,selectFile→New,thensavethenewgamebyselectingFile→SaveAs.Next,you’ll
needtocreatesomesprites.Ctrl-clickorright-clickthecatintheSpritelistandselect
Deletefromthemenu.Thencreatenewspritesbypaintingyourownorloadingfroman
imagefile.WedrewthefivespritesinFigure6-4andscannedtheminasaPNG.
You’llseethatthespritesareaddedtothestageasyoucreatethem,andtheyareprobably
notthesizeyouwantthemtobe.SelecttheGrowSpriteorShrinkSpritetooljustabove
theStageandclickonthespritetomakeitlargerorsmaller.You’llalsowanttorename
thespritestousethenamesshowninFigure6-4.
Figure6-4.ThefivespritesforAstralTrespassers
Thealiensandthecannoneachhavetwostates:normalandexploded.We’llhandlethis
bycreatingacostumeforeachstate,asshowninFigure6-5.
Figure6-5.Createtwocostumesforeachsprite,oneforthenormalstate
andoneforanexplosion.Namethecostumesasshownhere.
Eachspritewillhaveitsownscriptthatwilldeterminehowitactsinthegame.Forclarity,
eachactionwillbeacompletestandalonescriptsthatwillallrunatthesametime.
Let’sstartwiththefirstalien.Selectthespriteanddragthefollowingblockstothe
scriptingarea:
Thisblockwillmovethespritetoitsstartinglocationandmakesureitisvisibleandinits
nonexplodedstate.
Next,dragandassemblethefollowingblockssomewhereinthescriptingarea:
Hitthegreenflag,andyou’llseethisisprettymuchthecat-in-the-boxexamplefromthe
beginningofthechapter.Becausetherearethreespriteshere,you’llneedtohandlewhat
happenswhenthespritescollide.Iftwoalienscollide,onewaytomakesuretheydon’t
overlapistoturn90degreesoncollision:
Ifthebulletistouchingthealien,wewantittoexplode:
Theexplosionishandledbychangingtotheexplosioncostume,applyingaspecialeffect
forashorttime,thenhidingthespritewhichtakesitoffthestage.Afterafewseconds,the
alienwillreturntoarandomlocationatthetopofthescreen.
That’sallthescriptingweneedforthealien.Ifyouhavemultiplespritesthatdothesame
(orsimilar)thing,youcancopycodebetweenspritesbyright-clickingonablockand
selectingduplicate.Dragtheduplicatedblockstothesecondalienandrepeatforeach
snippetofblocks.Nowselectthesecondalienandchangethestartinglocationandthe
collisiontest:
Next,selectthecannonsprite.First,moveitintopositionandmakesureitisvisibleandin
thenon-explodedstate:
Thecannoncanonlymoveleftandright,controlledbythekeyboardarrowkeys).Hereis
thecodetorespondtokeyboardpresses:
Testtoseeifthecannonistouchingeitheralienwiththetouchingblockfromthesensing
palette.Ifitis,makethecannonexplodeinasimilarmannertothealiens.Afterthe
explosion,thecannonwillbroadcastamessagetoalloftheotherspritesthatthegameis
over.ThismessagewillbepickedupbytheGameOversprite,whichwillstopallthe
scripts:
Moveontothebulletspriteandaddthesecodeblockstomoveitintoplace.Thebullet
willbehiddenuntilthespacebarispressed:
Eachtimethespacebarispressed,thebulletwillbemovedtothecannon’scurrent
location,madevisible,andthenwillmovetowardthetopofthescreenuntilittouchesthe
topedge.
Herearetheblockstohandlethespacebar:
ThefinalspriteistheGameOvermessage.Itsroleissimple:hideuntilitreceivesthe
GameOvermessage,atwhichpointitappearsandstopsallthescripts:
That’stheendofthegame!
ScratchandtheRealWorld
Ifyoupokearoundthesensingpalette,you’llnoticetwointerestingblocks:sensorand
sensorvalue.Theseblocksareusedtointeractwithanexternalsensoraccessorycalledthe
PicoBoard(seeFigure6-6).ThePicoBoardhasamicrocontrolleronboardthatreadsthe
sensorsandsendsthevaluestoScratchoveraUSBconnection.
ThePicoBoardprovidesabutton,aslider,asoundsensor,andjacksforfourarbitrary
analoginputs.Specialalligatorclipconnectorscanbeusedtotakeanalogsamplesfrom
manydifferentsources.
Figure6-6.ThePicoBoardisasensoraccessorythatisdesignedtowork
withScratch
ThePicoBoardsendsthesensorvaluestoScratchusingitsownPicoBoardprotocol.The
S4AProject(ScratchforArduino)hasimplementedthesameprotocolforArduino,soyou
canconnecttotherealworldthatwayaswell.S4ArequiresacustomversionofScratch
that’savailableontheirprojectpage.
SharingYourPrograms
OneofthereallyinterestingaspectsofScratchisthatthere’sacommunitybuiltrightinto
theprogram.BesidesRandomSpritetool(whichwillgrabrandomspritesfromother
Scratchusers),there’salsoasharingfeaturethatwillletyoupackageanduploadyour
programstoMIT’sScratchprojectpage.Atlastcount,therewereover1.2millionScratch
users,whohavesharedover2.8millionprograms.
Onereasontherearesomanysharedprojectsisthatitisveryeasytodoso.Onceyou
createanaccountatscratch.mit.edu,justselectShareThisProjectOnline…underthe
Sharemenu.You’llbepromptedforsomeinformation(Figure6-7),andyourprojectwill
beuploadedtothesite.There’sa10MBsizelimit,soyoumightneedtocompresssome
ofyourimagesorsoundsfirst(seetheoptionsundertheEditmenu).TheScratchproject
pageisagreatplacetogotoseewhatispossiblewiththeenvironment.
Figure6-7.Whenyou’vegotsomethinggood,shareitontheMITScratch
projectsiteusingthebuilt-insharingtool.Unfortunately,thewebsiteuses
Flash,soyouwon’tbeabletouseitdirectlyfromtheRaspberryPi.
GoingFurther
ThemainScratchwiki
MIT’srepositoryforScratchreferencematerial.
MIT’sScratchpage
ThisistheScratchcommunitysite,whichhasliterallymillionsofprojectsand
registeredmembers.
Chapter7.ArduinoandthePi
Asyou’llseeinthenextfewchapters,youcanusetheGPIOpinsontheRaspberryPito
connecttosensorsorthingslikeblinkingLEDsandmotors.Ifyouhaveexperienceusing
theArduinomicrocontrollerdevelopmentplatform,youcanalsousethatalongsidethe
RaspberryPi.
WhentheRaspberryPiwasfirstannounced,alotofpeopleaskedifitwasanArduino
killer.Foraboutthesameprice,youcangetmuchmoreprocessingpower:whyuse
ArduinowhenyouhaveaPi?Itturnsoutthetwoplatformsareactuallycomplementary,
andtheRaspberryPimakesagreathostfortheArduino.Thereareafewothercases
whereyoumightwanttoputtheArduinoandPitogether:
TherearelotsoflibrariesandsharableexamplesfortheArduino.
IfyoualreadyhaveagoodworkingArduinoprojectthatyouwanttosupplementwith
moreprocessingpower.Forexample,maybeyouhaveaMIDIcontrollerthatwas
hookeduptoasynthesizer,butnowyouwanttoupgradetosynthesizingthesound
directlyonthePi.
Whenyou’redealingwith5Vlogiclevels.ThePioperatesat3.3V,anditspinsarenot
tolerantof5V.
Youmaybeprototypingsomethingalittleoutofyourcomfortzoneandmaymake
somechip-damagingmistakes.We’veseenstudentstrytodrivemotorsdirectlyfroma
pinontheArduino(don’ttryit);itwaseasytoprythedamagedmicrocontrollerchip
outofitssocketandreplaceit(lessthan$10usually).NotsowiththeRaspberryPi.
Whenyouhaveaproblemthatrequiresexactcontrolinrealtime,suchasacontroller
fora3Dprinter.AswesawinChapter4,Raspbianisnotareal-timeoperatingsystem,
andprogramscan’tnecessarilydependonthesame“instructionperclockcycles”rigor
ofamicrocontroller.
TheexamplesinthissectionassumethatyouknowatleastthebasicsofusingtheArduino
developmentboardandintegrateddevelopmentenvironment(IDE).Ifyoudon’thavea
goodgraspofthefundamentals,GettingStartedwithArduinobyMassimoBanziisagreat
placetostart.TheofficialArduinotutorialsarequitegoodaswell,andprovidealotof
opportunitiestocutandpastegoodworkingcode.
Figure7-1.ArduinoandtheRaspberryPiareBFFs
InstallingArduinoinRaspbian
ToprogramanArduinodevelopmentboard,youneedtohookituptoacomputerwitha
USBcable,thencompileandflashaprogramtotheboardusingtheArduinoIDE.You
candothiswithanycomputer,oryoucanuseyourRaspberryPiasahosttoprogramthe
Arduino.
UsingtheRaspberryPitoprogramtheArduinowillbequickertodebug,butcompiling
willbealittlesloweronthePithanonamodernlaptopordesktopcomputer.It’snottoo
badthough,andyou’llfindthatcompilingwilltakelesstimeaftertheveryfirstcompile,
asArduinoonlycompilescodethathaschangedsincethelastcompilation.
ToinstalltheArduinoIDEontheRaspberryPi:
sudoapt-getupdate
sudoapt-getinstallarduino
Makesureyouhavethelatestpackagelist.
DownloadtheArduinopackage.
ThiscommandwillinstallJavaplusalotofotherdependencies.TheArduino
environmentwillappearundertheElectronicssectionoftheprogrammenu(don’tlaunch
itjustyetthough).
Ifyou’rerunningthePiheadless,youcanjustplugtheArduinointooneoftheopenUSB
ports.Ifyoudon’thaveanopenUSBport,youmaybeabletouseafreeportonyour
keyboard,orelseyou’llneedaUSBhub.TheUSBconnectionshouldbeabletoprovide
enoughpowerfortheArduino,butyoumightwanttopowertheArduinoseparatelyfor
goodmeasure.
Warning
Notethatyou’llneedtoplugtheArduinoUSBcableinaftertheRaspberryPihasbooted
up.Ifyouleaveitpluggedinatboottime,theRaspberryPimayhangasittriestofigure
outallthedevicesontheUSBbus.
WhenyoulaunchtheArduinoIDE,itpollsalltheUSBdevicesandbuildsalistthatis
shownintheTools→SerialPortmenu.Inordertoaccesstheserialport,you’llneedto
makesurethatthepiuserhaspermissiontodoso.Youcandothatbyaddingthepiuserto
thettyanddialoutgroups.You’llneedtodothisbeforerunningtheArduinoIDE:
sudousermod -a-G ttypi
sudousermod-a-Gdialoutpi
usermodisaLinuxprogramtomanageusers.
-a-Gputstheuser(pi)inthespecifiedgroup(tty,thendialout).
NowyoucanrunArduino.ClickTools→SerialPortandselecttheserialport(mostlikely
/dev/ttyACM0),thenclickTools→Board,andselectthetypeofArduinoBoardyouhave
(e.g.,Uno).ClickFile→Examples→01.Basics→Blinktoloadabasicexamplesketch.
ClicktheUploadbuttoninthetoolbarorchooseFile→Uploadtouploadthesketch,and
afterthesketchloads,theArduinolightwillstartblinking.
FindingtheSerialPort
If,forsomereason,/dev/ttyACM0doesn’twork,you’llneedtodoalittledetectivework.
TofindtheUSBserialportthattheArduinoispluggedintowithoutlookingatthemenu,
trythefollowingfromthecommandline.WithouttheArduinoconnected,type:
ls/dev/tty*
PluginArduino,thentrythesamecommandagainandseewhatchanged.Onmy
RaspberryPi,atfirstIhad/dev/ttyAMA0listed(whichistheonboardUSBhub).WhenI
pluggedintheArduino,/dev/ttyACM0poppedupinthelisting.
ImprovingtheUserExperience
Whileyou’regettingsetup,youmaynoticethatthequalityofthedefaultfontintheArduinoeditorislessthanideal.
YoucanimproveitbydownloadingtheopensourcefontInconsolata.Toinstall,type:
sudoapt-getinstallttf-inconsolata
ThenedittheArduinopreferencesfile:
nano~/.arduino/preferences.txt
andchangethefollowinglinesto:
editor.font=Inconsolata,medium,14
editor.antialias=true
WhenyourestartArduino,theeditorwillusethenewfont.
TalkinginSerial
TocommunicatebetweentheRaspberryPiandtheArduinooveraserialconnection,
you’llusethebuilt-inSeriallibraryontheArduinoside,andthePythonpySerialmodule
ontheRaspberryPiside.Toinstalltheserialmodule,runthefollowing:
sudoapt-getinstallpython-serialpython3-serial
OpentheArduinoIDEanduploadthiscodetotheArduino:
voidsetup(){
Serial.begin(9600);
}
voidloop(){
for(byten=0;n<255;n++){
Serial.write(n);
delay(50);
}
}
Thiscountsupwardandsendseachnumberovertheserialconnection.
Note
NotethatinArduino,Serial.write()sendstheactualnumber(i.e.,thestring“123”
insteadofthenumber123.)UsetheSerial.print()command.
Next,you’llneedtoknowwhichUSBserialporttheArduinoisconnectedto(see
“FindingtheSerialPort”).Here’sthePythonscript;iftheportisn’t/dev/ttyACM0,change
thevalueofport.(SeeChapter4formoreonPython).SaveitasSerialEcho.pyandrunit
withpythonSerialEcho.py:
importserial
port="/dev/ttyACM0"
serialFromArduino=serial.Serial(port,9600)
serialFromArduino.flushInput()
whileTrue:
if(serialFromArduino.inWaiting()>0):
input=serialFromArduino.read(1)
print(ord(input))
OpentheserialportconnectedtotheArduino.
Clearouttheinputbuffer.
Readonebytefromtheserialbuffer.
Changetheincomingbyteintoanactualnumberwithord().
Note
Youwon’tbeabletouploadtoArduinowhenPythonhastheserialportopen,somake
sureyoukillthePythonprogramwithCtrl-Cbeforeyouuploadthesketchagain.Youwill
beabletouploadtoanArduinoLeonardoorArduinoMicro,butdoingsowillbreakthe
connectionwiththePythonscript,soyou’llneedtorestartitanyhow.
TheArduinoissendinganumbertothePythonscript,whichinterpretsthatnumberasa
string.Theinputvariablewillcontainwhatevercharactermapstothatnumberinthe
ASCIItable.Togetabetteridea,tryreplacingthelastlineofthePythonscriptwiththis:
print(str(ord(input))+"=theASCIIcharacter"+input+".")
SettingtheSerialPortasanArgument
Ifyouwanttosettheportasacommand-lineargument,usethesysmoduletograbthefirstargument:
importserial,sys
if(len(sys.argv)!=2):
print("Usage:pythonReadSerial.pyport")
sys.exit()
port=sys.argv[1]
Afteryoudothis,youcanruntheprogramlikethis:
pythonSerialEcho.py/dev/ttyACM0
Thefirstsimpleexamplejustsentasinglebyte;thiscouldbefineifyouareonlysending
aseriesofeventcodesfromtheArduino.Forexample,iftheleftbuttonispushed,senda
1;iftheright,send2.That’sonlygoodfor255discreteevents,though;moreoftenyou’ll
wanttosendarbitrarilylargenumbersorstrings.Ifyou’rereadinganalogsensorswiththe
Arduino,forexample,you’llwanttosendnumbersintherange0to1,023.
Parsingarbitrarynumbersthatcomeinonebyteatatimecanbetrickierthanyoumight
thinkinmanylanguages.ThewayPythonandPySerialhandlestringsmakesitalmost
trivial,however.Asasimpleexample,updateyourArduinowiththefollowingcodethat
countsfrom0to1,024:
voidsetup(){
Serial.begin(9600);
}
voidloop(){
for(intn=0;n<1024;n++)
Serial.println(n,DEC);
delay(50);
}
}
Thekeydifferenceisintheprintln()command.Inthepreviousexample,the
Serial.write()functionwasusedtowritetherawnumbertotheserialport.With
println(),theArduinoformatsthenumberasadecimalstringandsendstheASCII
codesforthestring.Soinsteadofsendingthenumber254,itsendsthestring254\r\n.
The\rrepresentsacarriagereturnandthe\nrepresentsanewline(theseareconceptsthat
carriedoverfromthetypewriterintocomputing:carriagereturnmovestothestartofthe
line,newlinestartsanewlineoftext).
OnthePythonside,youcanusereadline()insteadofread(),whichwillreadallofthe
charactersupuntil(andincluding)thecarriagereturnandnewline.Pythonhasaflexible
setoffunctionsforconvertingbetweenthevariousdatatypesandstrings.Itturnsoutyou
canjustusetheint()functiontochangetheformattedstringintoaninteger:
importserial
port="/dev/ttyACM0"
serialFromArduino=serial.Serial(port,9600)
serialFromArduino.flushInput()
whileTrue:
input=serialFromArduino.readline()
inputAsInteger=int(input)
print(inputAsInteger*10)
Notethatitissimpletoadaptthisexamplesothatitwillreadananaloginputandsendthe
result;justchangetheloopto:
voidsetup(){
Serial.begin(9600);
}
voidloop(){
intn=analogRead(A0);
Serial.println(n,DEC);
delay(100);
}
AssumingyouchangethePythonscripttojustprintinputAsIntegerinsteadof
inputAsInteger*10,youshouldgetsomefloatingvaluesinthe200rangeifnothingis
connectedtoanalogpin0.Withsomejumperwire,connectthepintoGNDandthevalue
shouldbe0.Connectittothe3V3pinandyou’llseeavaluearound715,and1,023when
connectedtothe5Vpin.
UsingFirmata
Asyougofurther,manyprojectswilllookthesameasfarasthecodeforbasic
communicationgoes.Aswithanyformofcommunication,thingsgettrickyonceyouget
past“Hello,world”;you’llneedtocreateprotocols(orfindanexistingprotocoland
implementit)sothateachsideunderstandstheother.
OnegoodsolutionthatcomesbundledwithArduinoisHans-ChristophSteiner’sFirmata,
anall-purposeserialprotocolthatissimpleandhumanreadable.Itmaynotbeperfectfor
allapplications,butitisagoodplacetostart.Here’saquickexample:
1. SelectFile→Examples→Firmata→StandardFirmatainArduino;thiswillopenthe
sampleFirmatacodethatwillallowyoutosendandreceivemessagestothe
Arduinoandgetinformationaboutallofthepins.
2. UploadthatcodetotheArduinothesamewayyoudidinpreviousexamples.
3. You’llneedabitofPythoncodeonthePitosendcommandstotheArduinotoquery
orchangeitsstate.TheeasiestwayistousethePyfirmatamodule.Installitusing
pip(see“EasyModuleInstallswithPip”):
sudopipinstallpyfirmata
4. BecauseFirmataisaserialprotocol,youtalktotheArduinofromPythoninthe
samewayasinpreviousexamples,butusingPyfirmatainsteadofPyserial.Usethe
write()methodtomakeadigitalpinhighorlowontheArduino:
frompyfirmataimportArduino
fromtimeimportsleep
board=Arduino('/dev/ttyACM0')
while(1):
board.digital[13].write(1)
print("on")
sleep(1)
board.digital[13].write(0)
print("off")
sleep(1)
ThiscodeshouldblinktheLEDontheArduinoUnoboardthatisconnectedtopin
13.ThefullmoduleisdocumentedonthePyfirmataGitHubpage.
GoingFurther
Thenitty-grittyofserialprotocolsisbeyondthescopeofthisbook,buttherearealotof
interestingexamplesofhowotherpeoplehavesolvedproblemsinthe“Interfacingwith
Software”sectionoftheArduinoPlayground.Inaddition,youmaywanttotry:
MIDI
Ifyourprojectismusical,considerusingMIDIcommandsasyourserialprotocol.
MIDIis(basically)justserial,soitshouldjustwork.
Arduino-compatibleRaspberryPishields
Thereareafewdaughterboards(orshields)onthemarketthatconnecttheGPIOpins
ontheRaspberryPiwithanArduino-compatiblemicrocontroller.WyoLum’sAlaMode
shieldisagoodsolutionandoffersafewotheraccessories,includingareal-timeclock.
Talkoveranetwork
Finally,youcanditchtheserialconnectionaltogetherandtalktotheArduinoovera
network.AlotofreallyinterestingprojectsareusingtheWebSocketprotocolalong
withtheNode.jsJavaScriptplatform.TheNoduinoprojectisagoodplacetostart
exploringthistechnology.
UsingtheserialpinsontheRaspberryPiheader
TheheaderontheRaspberryPipullsoutanumberofinputandoutputpins,including
twothatcanbeusedtosendandreceiveserialdatabypassingtheUSBport.Todothat,
you’llneedtofirstcoverthematerialinChapter9,andmakesurethatyouhavealevel
shiftertoprotecttheRaspberryPi3.3VpinsfromtheArduino’s5Vpins.
Ifyou’relookingtogetdeeperintomakingphysicaldevicescommunicate,agoodstarting
pointisMakingThingsTalk,2ndEdition,byTomIgoe.
Chapter8.BasicInputandOutput
WhiletheRaspberryPiis,inessence,averyinexpensiveLinuxcomputer,thereareafew
thingsthatdistinguishitfromlaptopanddesktopmachinesthatweusuallyuseforwriting
email,browsingtheWeb,orwordprocessing.Oneofthemaindifferencesisthatthe
RaspberryPicanbedirectlyusedinelectronicsprojects,becauseithasgeneral-purpose
input/outputpinsrightontheboard,showninFigure8-1.
Figure8-1.RaspberryPi’sGPIOpins
TheseGPIOpinscanbeaccessedforcontrollinghardwaresuchasLEDs,motors,and
relays,whichareallexamplesofoutputs.Asforinputs,yourRaspberryPicanreadthe
statusofbuttons,switches,anddials,oritcanreadsensorsliketemperature,light,motion,
orproximitysensors(amongmanyothers).
Note
OneofthedrawbackstotheRaspberryPiisthatthere’snowaytodirectlyconnectanalog
sensors,suchaslightandtemperaturesensors.Doingsorequiresachipcalledananalogto-digitalconverterorADC.SeeChapter10forhowtoreadanalogsensorsusingan
ADC.
ThebestpartofhavingacomputerwithGPIOpinsisthatyoucancreateprogramstoread
theinputsandcontroltheoutputsbasedonmanydifferentconditions,aseasilyasyou’d
programyourdesktopcomputer.Unlikeatypicalmicrocontrollerboard,whichalsohas
programmableGPIOpins,theRaspberryPihasafewextrainputsandoutputs,suchas
yourkeyboard,mouse,andmonitor,aswellastheEthernetport,whichcanactasbothan
inputandanoutput.Ifyouhaveexperiencecreatingelectronicsprojectswith
microcontrollerboardsliketheArduino,youhaveafewmoreinputsandoutputsatyour
disposalwiththeRaspberryPi.Bestofall,they’rebuiltrightin;there’snoneedtowireup
anyextracircuitrytousethem.
Havingakeyboard,mouse,andmonitorisnottheonlyadvantagethatRaspberryPihas
overtypicalmicrocontrollerboards.Thereareafewotherkeyfeaturesthatwillhelpyou
inyourelectronicsprojects:
Filesystem
BeingabletoreadandwritedataintheLinuxfilesystemwillmakemanyprojectsmuch
easier.Forinstance,youcanconnectatemperaturesensortotheRaspberryPiandhave
ittakeareadingonceasecond.Eachreadingcanbeappendedtotheendofalogfile,
whichcanbeeasilydownloadedandparsedinagraphingprogram.Itcanevenbe
graphedrightontheRaspberryPiitself!
Linuxtools
PackagedintheRaspberryPi’sLinuxdistributionisasetofcorecommand-line
utilities,whichletyouworkwithfiles,controlprocesses,andautomatemanydifferent
tasks.Thesepowerfultoolsareatyourdisposalforallofyourprojects.Andbecause
thereisanenormouscommunityofLinuxusersthatdependonthesecoreutilities,
gettinghelpisusuallyonewebsearchaway.ForgeneralLinuxhelp,youcanusually
findanswersatStackOverflow.IfyouhaveaquestionspecifictoRaspberryPi,trythe
RaspberryPiForumortheRaspberryPisectionofStackOverflow.
Languages
Therearemanyprogramminglanguagesoutthere,andembeddedLinuxsystemslike
theRaspberryPigiveyoutheflexibilitytochoosewhicheverlanguageyou’remost
comfortablewith.TheexamplesinthisbookuseshellscriptingandPython,butthey
couldeasilybetranslatedtolanguageslikeC,Java,orPerl.
UsingInputsandOutputs
Thereareafewsuppliesthatyou’llneedinadditiontotheRaspberryPiitselfinorderto
tryoutthesebasicinputandoutputtutorials.Manyofthesepartsyou’llbeabletofindin
yourlocalRadioShack,ortheycanbeorderedonlinefromstoreslikeMakerShed,
SparkFun,Adafruit,Mouser,orDigi-Key.Hereareafewofthebasicparts:
Solderlessbreadboard
LEDs,assorted
Male-to-malejumperwires
Female-to-malejumperwires(thesearenotascommonastheirmale-to-male
counterpartsbutareneededtoconnecttheRaspberryPi’sGPIOpinstothebreadboard)
Pushbuttonswitch
Resistors,assorted
TomakeiteasiertoconnectbreadboardedcomponentstotheRaspberryPi’spins,wealso
recommendAdafruit’sPiCobblerBreakoutKit.Thiseliminatestheneedtousefemale-tomalejumperwires.Thekitcomesunassembled,soit’suptoyoutosolderthepartsonto
theboard,butit’seasyandAdafruit’stutorialwalksyouthroughtheprocessstepbystep.
ThePiCobblerBreakoutKitisincluded,alongwiththeothercomponentsjustlisted(with
theexceptionofthefemale-to-malejumperwires,whicharenotneededifyouhavethePi
CobblerBreakoutKit),inMAKE’sRaspberryPiStarterKit(MakerShedproductnumber
MSRPIK).
InFigure8-2,we’velabeledeachpinaccordingtoitsdefaultGPIOsignalnumber,which
ishowyou’llrefertoaparticularpininthecommandsyouexecuteandinthecodethat
youwrite.Theunlabeledpinsareassignedtootherfunctionsbydefault.
Note
YoumayhavenoticedthatoneofthepinshastwodifferentGPIOpinnumbersin
Figure8-2.InrecentversionsoftheModelB,GPIOpin21becameGPIOpin27.To
determinetheversionofyourboard,typecat/proc/cpuinfoonthecommandline.If
yourrevisionnumberislistedas0002or0003,youhavethefirstversionoftheboard.If
youhaveahighernumber,oraletter,youhavealaterversionoftheboard.
Figure8-2.ThedefaultGPIOpinsontheRaspberryPi.Inrecentrevisions
oftheboard,GPIOpin21wasswappedforGPIOpin27.TheModelB+
hasadditionalpinsbelowthese,butthepinassignmentsforthefirst26
pinsarethesameastheModelBv2.
DigitalOutput:LightingUpanLED
TheeasiestwaytouseoutputswiththeGPIOpinsisbyconnectinganLED,orlightemittingdiode.YoucanthenusetheLinuxcommandlinetoturntheLEDonandoff.
Onceyouhaveanunderstandingofhowthesecommandswork,you’reonestepcloserto
havinganLEDlightuptoindicatewhenyouhavenewemail,whenyouneedtotakean
umbrellawithyouasyouleaveyourhouse,orwhenit’stimetogotobed.It’salsovery
easytogobeyondabasicLEDandusearelaytocontrolalamponasetschedule,for
instance.
Beginner’sGuidetoBreadboarding
Ifyou’veneverusedabreadboard(Figure8-3)before,it’simportanttoknowwhich
terminalsareconnected.Inthediagram,we’veshadedtheterminalconnectionsona
typicalbreadboard.Notethatthepowerbusesontheleftsidearenotconnectedtothe
powerbusesontherightsideofthebreadboard.You’llhavetousemale-to-malejumper
cablestoconnectthemtoeachotherifyouneedgroundandvoltageonbothsidesofthe
breadboard.
Figure8-3.Breadboard
Herearetheinstructionsyoushouldfollow:
1. Usingamale-to-femalejumperwire,connectpin25ontheRaspberryPitothe
breadboard.RefertoFigure8-2forthelocationofeachpinontheRaspberryPi’s
GPIOheader.
2. Usinganotherjumperwire,connecttheRaspberryPi’sgroundpintothenegative
powerbusonthebreadboard.
3. Nowyou’rereadytoconnecttheLED(seeFigure8-4).Beforeyoudothat,it’s
importanttoknowthatLEDsarepolarized:itmatterswhichoftheLED’swiresis
connectedtowhat.OfthetwoleadscomingofftheLED,thelongeroneistheanode
andshouldbeconnectedtoaGPIOpin.Theshorterleadisthecathodeandshould
beconnectedtoground.Anotherwaytotellthedifferenceisbylookingfromthe
top.TheflatsideoftheLEDindicatesthecathode,thesidethatshouldbeconnected
toground.InserttheanodesideoftheLEDintothebreadboardinthesamechannel
asthejumperwirefrompin25,whichwillconnectpin25totheLED.Insertthe
cathodesideoftheLEDintothegroundpowerbus.
Figure8-4.ConnectinganLEDtotheRaspberryPi
4. Withyourkeyboard,mouse,andmonitorhookedup,poweronyourRaspberryPi
andlogin.Ifyou’reatacommandline,you’rereadytogo.Ifyou’reintheX
Windowenvironment,double-clicktheLXTerminalicononyourdesktop.Thiswill
bringupaterminalwindow.
5. Inordertoaccesstheinputandoutputpinsfromthecommandline,you’llneedto
runthecommandsasroot,thesuperuseraccountontheRaspberryPi.Tostart
runningcommandsasroot,typesudosuatthecommandlineandpressEnter:
[email protected]~$sudosu
[email protected]:/home/pi#
You’llnoticethatthecommandprompthaschangedfrom$to#,indicatingthat
you’renowrunningcommandsasroot.
Warning
Therootaccounthasadministrativeaccesstoallthefunctionsandfilesonthesystemand
thereisverylittleprotectingyoufromdamagingtheoperatingsystemifyoutypea
commandthatcanharmit,soexercisecautionwhenrunningcommandsasroot.Ifyoudo
messsomethingup,don’tworryaboutittoomuch;youcanalwaysreimagetheSDcard
withacleanLinuxinstall.Whenyou’redoneworkingwithintherootaccount,typeexit
toreturntoworkingwithinthepiuseraccount.
6. BeforeyoucanusethecommandlinetoturntheLEDonpin25onandoff,you
needtoexportthepintotheuserspace(inotherwords,makethepinavailablefor
useoutsideoftheconfinesoftheLinuxkernel),thisway:
[email protected]:/home/pi#echo25>/sys/class/gpio/export
Theechocommandwritesthenumberofthepinyouwanttouse(25)totheexport
file,whichislocatedinthefolder/sys/class/gpio.Whenyouwritepinnumbersto
thisspecialfile,itcreatesanewdirectoryin/sys/class/gpiothathasthecontrolfiles
forthepin.Inthiscase,itcreatedanewdirectorycalled/sys/class/gpio/gpio25.
7. Changetothatdirectorywiththecdcommandandlistthecontentsofitwithls:
[email protected]:/home/pi#cd/sys/class/gpio/gpio25
[email protected]:/sys/class/gpio/gpio25#ls
active_lowdirectionedgepowersubsystemueventvalue
Thecommandcdstandsfor“changedirectory.”Itchangestheworkingdirectoryso
thatyoudon’thavetotypethefullpathforeveryfile.lswilllistthefilesand
folderswithinthatdirectoryTherearetwofilesthatyou’regoingtoworkwithin
thisdirectory:directionandvalue.
8. Thedirectionfileishowyou’llsetthispintobeaninput(likeabutton)oran
output(likeanLED).BecauseyouhaveanLEDconnectedtopin25andyouwant
tocontrolit,you’regoingtosetthispinasanoutput:
[email protected]:/sys/class/gpio/gpio25#echoout>direction
9. ToturntheLEDon,you’llusetheechocommandagaintowritethenumber1tothe
valuefile:
[email protected]:/sys/class/gpio/gpio25#echo1>value
10. AfterpressingEnter,theLEDwillturnon!Turningitoffisassimpleasusingecho
towriteazerotothevaluefile:
[email protected]:/sys/class/gpio/gpio25#echo0>value
VirtualFiles
Thefilesthatyou’reworkingwitharen’tactuallyfilesontheRaspberryPi’sSDcard,butratherareapartofLinux’s
virtualfilesystem,whichisasystemthatmakesiteasiertoaccesslow-levelfunctionsoftheboardinasimplerway.
Forexample,youcouldturntheLEDonandoffbywritingtoaparticularsectionoftheRaspberryPi’smemory,but
doingsowouldrequiremorecodingandmorecaution.
Soifwritingtoafileishowyoucontrolcomponentsthatareoutputs,howdoyoucheck
thestatusofcomponentsthatareinputs?Ifyouguessed“readingafile,”thenyou’re
absolutelyright.Let’strythatnow.
DigitalInput:ReadingaButton
SimplepushbuttonswitchesliketheoneinFigure8-5aregreatforcontrollingbasic
digitalinputandbestofall,they’remadetofitperfectlyintoabreadboard.
Note
Thesesmallbuttonsareverycommonlyusedinelectronicsprojectsandunderstanding
what’sgoingoninsideofthemwillhelpyouasyouprototypeyourproject.Whenlooking
atthebuttonasitsitsinthebreadboard(seeFigure8-5),thetoptwoterminalsarealways
connectedtoeachother.Thesameistrueforthebottomtwoterminals;they’realways
connected.Whenyoupushdownonthebutton,thesetwosetsofterminalsareconnected
toeachother.
Figure8-5.Button
WhenyoureadadigitalinputonaRaspberryPi,you’recheckingtoseeifthepinis
connectedtoeither3.3voltsortoground.It’simportanttorememberthatitmustbeeither
oneortheother,andifyoutrytoreadapinthat’snotconnectedtoeither3.3voltsor
ground,you’llgetunexpectedresults.Onceyouunderstandhowdigitalinputwitha
pushbuttonworks,youcanstartusingcomponentslikemagneticsecurityswitches,arcade
joysticks,orevenvendingmachinecoinaccepters.Startbywiringupaswitchtoreadits
state:
1. Insertthepushbuttonintothebreadboardsothatitsleadsstraddlethemiddle
channel.
2. Usingajumperwire,connectpin24fromtheRaspberryPitooneofthetop
terminalsofthebutton.
3. Connectthe3V3pinfromtheRaspberryPitothepositivepowerbusonthe
breadboard.
Warning
Besurethatyouconnectthebuttontothe3V3pinandnotthe5Vpin.Usingmore
than3.3voltsonaninputpinwillpermanentlydamageyourRaspberryPi.
4. Connectoneofthebottomterminalsofthebuttontothepowerbus.Nowwhenyou
pushdownonthebutton,the3.3voltswillbeconnectedtopin24.
5. Rememberwhatwesaidabouthowadigitalinputmustbeconnectedtoeither3.3
voltsorground?Whenyouletgoofthebutton,pin24isn’tconnectedtoeitherof
thoseandisthereforefloating.Thisconditionwillcauseunexpectedresults,solet’s
fixthat.Usea10Kresistor(labeledwiththecoloredbands:brown,black,orange,
andthensilverorgold)toconnecttheinputsideoftheswitchtothegroundrail,
whichyouconnectedtotheRaspberryPi’sgroundintheoutputexample.Whenthe
switchisnotpressed,thepinwillbeconnectedtoground.
Electricityalwaysfollowsthepathofleastresistancetowardground,sowhenyou
presstheswitch,the3.3voltswillgotowardtheRaspberryPi’sinputpin,whichhas
lessresistancethanthe10Kresistor.Wheneverything’shookedup,itshouldlook
likeFigure8-6.
6. Nowthatthecircuitisbuilt,let’sreadthevalueofthepinfromthecommandline.If
you’renotalreadyrunningcommandsasroot,typesudosu.
7. Aswiththepreviousexample,youneedtoexporttheinputpintouserspace:
#echo24>/sys/class/gpio/export
8. Let’schangetothedirectorythatwascreatedduringtheexportoperation:
#cd/sys/class/gpio/gpio24
9. Nowsetthedirectionofthepintoinput:
#echoin>direction
Figure8-6.ConnectingabuttontotheRaspberryPi
10. Toreadthevalueoftheofthepin,you’llusethecatcommand,whichwillprintthe
contentsoffilestotheterminal.Thecommandcatgetsitsnamebecauseitcanalso
beusedtoconcatenate,orjoin,files.Itcanalsodisplaythecontentsofafileforyou:
#catvalue
0
11. Thezeroindicatesthatthepinisconnectedtoground.Nowpressandholdthe
buttonwhileyouexecutethecommandagain:
#catvalue
1
12. Ifyouseethenumber1,you’llknowyou’vegotitright!
Tip
Toeasilyexecuteacommandthatyou’vepreviouslyexecuted,hittheuparrowkey
untilyouseethecommandthatyouwanttorunandthenhitEnter.
NowthatyoucanusetheLinuxcommandlinetocontrolanLEDorreadthestatusofa
button,let’suseafewofLinux’sbuilt-intoolstocreateaverysimpleprojectthatuses
digitalinputandoutput.
Project:CronLampTimer
Let’ssayyou’releavingforalongvacationearlytomorrowmorningandyouwantto
wardoffwould-beburglarsfromyourhome.Alamptimerisagooddeterrent,but
hardwarestoresareclosedforthenightandyouwon’thavetimetogetonebeforeyour
flightinthemorning.However,becauseyou’reaRaspberryPihobbyist,youhaveafew
supplieslyingaround,namely:
RaspberryPiboard
Breadboard
Jumperwires,female-to-male
PowerSwitchTailIIrelay
Hookupwire
Withthesesupplies,youcanmakeyourownprogrammablelamptimerusingtwo
powerfulLinuxtools:shellscriptsandcron.
ScriptingCommands
Ashellscriptisafilethatcontainsaseriesofcommands(justliketheonesyou’vebeen
usingtocontrolandreadthepins).Takealookatthefollowingshellscriptandthe
explanationofthekeylines:
#!/bin/bash
echoExportingpin$1.
echo$1>/sys/class/gpio/export
echoSettingdirectiontoout.
echoout>/sys/class/gpio/gpio$1/direction
echoSettingpinhigh.
echo1>/sys/class/gpio/gpio$1/value
Thislineisrequiredforallshellscripts.
$1referstothefirstcommand-lineargument.
Insteadofexportingaspecificpinnumber,thescriptusesthefirstcommand-line
argument.
Noticethatthefirstcommand-lineargumentreplacesthepinnumberhereaswell.
Savethatasatextfilecalledon.shandmakeitexecutablewiththechmodcommand:
[email protected]:/home/pi#chmod+xon.sh
Note
Youstillneedtobeexecutingthesescommandsasroot.Typesudosuifyou’regetting
errorslike“Permissiondenied.”
Acommand-lineargumentisawayofpassinginformationintoaprogramorscriptby
typingitinafternameofthecommand.Whenyou’rewritingashellscript,$1referstothe
firstcommand-lineargument,$2referstothesecond,andsoon.Inthecaseofon.sh,
you’lltypeinthepinnumberthatyouwanttoexportandturnon.Insteadofhardcoding
pin25intotheshellscript,it’smoreuniversalbyreferringtothepinthatwastypedinat
thecommandline.Toexportpin25andturniton,youcannowtype:
[email protected]:/home/pi/#./on.sh25
Exportingpin25.
Settingdirectiontoout.
Settingpinhigh.
The./beforethefilenameindicatesthatyou’reexecutingthescriptinthedirectory
you’rein.
IfyoustillhavetheLEDconnectedtopin25fromearlierinthechapter,itshouldturnon.
Let’smakeanothershellscriptcalledoff.sh,whichwillturntheLEDoff.Itwilllooklike
this:
#!/bin/bash
echoSettingpinlow.
echo0>/sys/class/gpio/gpio$1/value
echoUnexportingpin$1
echo$1>/sys/class/gpio/unexport
Nowlet’smakeitexecutableandrunthescript:
[email protected]:/home/pi/temp#chmod+xoff.sh
[email protected]:/home/pi/temp#./off.sh25
Settingpinlow.
Unexportingpin25
Ifeverythingworked,theLEDshouldhaveturnedoff.
ConnectingaLamp
Ofcourse,atinylittleLEDisn’tgoingtogiveoffenoughlighttofoolburglarsinto
thinkingthatyou’rehome,solet’shookupalamptotheRaspberryPi:
1. RemovetheLEDconnectedtopin25.
2. Connecttwostrandsofhookupwiretothebreadboard,onethatconnectstopin25of
theRaspberryPiandtheothertothegroundbus.
3. Thestrandofwirethatconnectstopin25shouldbeconnectedtothe“+in”terminal
ofthePowerSwitchTail.
4. Thestrandofwirethatconnectstogroundshouldbeconnectedtothe“-in”terminal
ofthePowerSwitchTail.CompareyourcircuittoFigure8-7.
Figure8-7.ConnectingaPowerSwitchTailIItotheRaspberryPi
5. PlugthePowerSwitchTailintothewallandplugalampintothePowerSwitchTail.
Besurethelamp’sswitchisintheonposition.
6. Nowwhenyouexecute./on.sh25,thelampshouldturnonandifyouexecute
./off.sh25,thelampshouldturnoff!
Note
InsidethePowerSwitchTailthereareafewelectroniccomponentsthathelpyoucontrol
high-voltagedeviceslikealamporblenderbyusingalow-voltagesignalsuchastheone
fromtheRaspberryPi.The“click”youhearfromthePowerSwitchTailwhenit’sturned
onoroffistherelay,thecorecomponentofthecircuitinside.Arelayactslikeaswitch
forthehigh-voltagedevicethatcanbeturnedonoroffdependingonwhetherthelowvoltagecontrolsignalfromtheRaspberryPiisonoroff.
SchedulingCommandswithcron
Sonowyou’vepackagedupafewdifferentcommandsintotwosimplecommandsthat
canturnapinonoroff.AndwiththelampconnectedtotheRaspberryPithroughthe
PowerSwitchTail,youcanturnthelamponoroffwithasinglecommand.Nowyoucan
usecrontoschedulethelighttoturnonandoffatdifferenttimesofday.cronisLinux’s
jobscheduler.Withit,youcansetcommandstoexecuteonspecifictimesanddates,or
youcanhavejobsrunonaparticularperiod(forexample,onceanhour).You’regoingto
scheduletwojobs:oneofthemwillturnthelightonat8:00p.m.andtheotherwillturn
thelightoffat2:00a.m.
Note
Aswithothertime-dependentprograms,you’llwanttomakesureyou’vegotthecorrect
dateandtimesetuponyourRaspberryPi,asdescribedinChapter1.
Toaddthesejobs,you’llhavetoeditthecrontable(alistofcommandsthatLinux
executesatspecifiedtimes):
[email protected]:/home/pi/#crontab-e
Thiswilllaunchatexteditortochangeroot’scrontable(tochangetotherootusertype
sudosu).Atthetopofthefile,you’llseesomeinformationabouthowtomodifythecron
table.Useyourarrowkeystogettothebottomofthefileandaddthesetwoentriesatthe
endofthefile:
020***/home/pi/on.sh25
02***/home/pi/off.sh25
Note
cronwillignoreanylinesthatstartwiththehashmark.Ifyouwanttotemporarilydisable
alinewithoutdeletingitoraddacommenttothefile,putahashmarkinfrontoftheline.
PressCtrl-Xtoexit,pressytosavethefilewhenitpromptsyou,andhitEntertoaccept
thedefaultfilename.Whenthefileissavedandyou’rebackatthecommandline,it
shouldsayinstallingnewcrontabtoindicatethatthechangesyou’vemadearegoing
tobeexecutedbycron.
MoreAboutCron
Cronwillletyouschedulejobsforspecificdatesandtimesoronintervals.Therearefive
timefields(orsixifyouwanttoschedulebyyear),eachseparatedbyaspacefollowedby
anotherspacethenthecommandtoexecute;asterisksindicatethatthejobshouldexecute
eachperiod(Table8-1).
Table8-1.Cronentryforturninglightonat8:00p.m.everyday
0
20
*
*
*
/home/pi/on.sh25
Minute(:00) Hour(8p.m.) Everyday Everymonth Everydayoftheweek Pathtocommand
Let’ssayyouonlywantedthelamptoturnoneveryweekday.Table8-2showswhatthe
crontabentrywouldlooklike.
Table8-2.Cronentryforturninglightonat8:00p.m.everyweekday
0
20
*
*
1-5
/home/pi/on.sh25
Minute(:00) Hour(8p.m.) Everyday EveryMonth MondaytoFriday Pathtocommand
Asanotherexample,let’ssayyouhaveashellscriptthatchecksifyouhavenewmailand
emailsyouifyoudo.Table8-3showshowyou’dgetthatscripttoruneveryfiveminutes.
Table8-3.Cronentryforcheckingformaileveryfiveminutes
*/5
*
*
*
*
/home/pi/checkMail.sh
Everyfiveminutes Everyhour Everyday Everymonth Everydayoftheweek Pathtocommand
The*/5indicatesaperiodofeveryfiveminutes.
Asyoucansee,cronisapowerfultoolthat’satyourdisposalforschedulingjobsfor
specificdatesortimesandschedulingjobstohappenonaspecificinterval.
GoingFurther
eLinux’sRaspberryPiGPIOReferencePage
ThisisthemostcomprehensivereferenceguidetotheRaspberryPi’sGPIOpins.
Adafruit:MCP230xxGPIOExpanderontheRaspberryPi
Ifyoudon’thaveenoughpinstoworkwith,Adafruitoffersthisguidetousingthe
MCP23008chipfor8extraGPIOpinsandtheMCP23017for16extraGPIOpins.
Chapter9.ProgrammingInputsandOutputswithPython
AttheendofChapter8,youdidalittlebitofprogrammingwiththeRaspberryPi’sGPIO
pinsusingashellscript.Inthischapter,you’regoingtolearnhowtousePythontodothe
samething…andalittlemore.Muchlikewiththeshellscript,Pythonwillletyouaccess
thepinsbywritingcodetoreadandcontrolthepinsautomatically.
TheadvantagethatPythonhasovershellscriptingisthatthecodeiseasiertowriteandis
morereadable.There’salsoawholeslewofPythonmodulesthatmakeiteasyforyouto
dosomecomplexstuffwithbasiccode.SeeTable4-2foralistofafewmodulesthat
mightbeusefulinyourprojects.Bestofall,there’saPythonmodulecalledraspberrygpio-pythonthatmakesiteasytoreadandcontroltheGPIOpins.You’regoingtolearn
howtousethatmoduleinthischapter.
InstallingandTestingGPIOinPython
OnthemostrecentversionsoftheRaspbiandistributionofLinux,theGPIOmoduleis
alreadyinstalled.Ifyou’reusinganolderversionofRaspbian,youmayneedtoinstallit.
Tocheckifyouhaveit,you’llusePython’sinteractiveinterpreter(asyoulearnedin
Chapter4,theinteractiveinterpreterletsyoutypelinesofPythoncodetobeevaluated
immediately,asopposedtowritingthecodeintoafileandexecutingthefile):
1. GointothePythoninteractiveinterpreterasrootfromtheterminalprompt.(Because
raspberry-gpio-pythonrequiresrootaccesstoreadandcontrolthepins,youneedto
gointothePythoninteractiveinterpreterasrootwiththesudocommand.)
Here’showtodoit:
$sudopython
Python2.7.3rc2(default,May62012,20:02:25)
[GCC4.6.3]onlinux2
Type"help","copyright","credits"or"license"formoreinformation.
>>>
2. Whenyou’reatthe>>>prompt,tryimportingthemodule:
>>>importRPi.GPIOasGPIO
3. Ifyoudon’tgetanerror,you’reallset.
Otherwise,ifyoudogetanerrorwhenyoutrytoimporttheGPIOmodule,theinstallation
canbedoneinafewsimplestepsthankstoapt-get,thepackagemanageronthe
RaspberryPi.
So,ifyoudon’talreadyhaveraspberry-gpio-pythoninstalled,here’showtoinstallit:
1. Exitoutoftheinterpreter(pressCtrl-Dortypeexit()andpressReturn),updatethe
apt-getpackageindexes,andissuetheinstallationcommandforraspberry-gpiopython:
>>>exit()
$sudoapt-getupdate
$sudoapt-getinstallpython-rpi.gpio
2. Whenthat’sdone,gobackintothePythoninteractiveinterpreterandimportthe
module:
$sudopython
Python2.7.3rc2(default,May62012,20:02:25)
[GCC4.6.3]onlinux2
Type"help","copyright","credits"or"license"formoreinformation.
>>>importRPi.GPIOasGPIO
>>>
Note
Inthischapter,we’llbeusingPython2.7insteadofPython3becauseoneofthemodules
we’llbeusingisonlyinstalledforPython2.xontheRaspberryPi.Whenyoutypepython
atthecommandpromptontheRaspberryPi,itrunsPython2.7bydefault.Thisbehavior
couldchangeinthefuture(youcanrunPython2.7explicitlybytypingpython2.7instead
ofpython).
Oneimportantdifferencebetweenthetwoversionsishowyouprinttexttotheconsole.
You’lluseprint"Hello,world!"inPython2.x,butyou’duseprint("Hello,
world!")inPython3.
Ifyoudon’tgetanyerrorsafterenteringtheimportcommand,youknowyou’rereadyto
tryitoutforthefirsttime:
1. Beforeyoucanusethepins,youmusttelltheGPIOmodulehowyourcodewill
refertothem.InChapter8,thepinnumbersweuseddidn’tcorrelatetothewaythat
they’rearrangedontheboard.Youwereactuallyusingtheon-boardBroadcom
chip’ssignalnameforeachpin.WiththisPythonmodule,youcanchoosetoreferto
thepinseitherway.Tousethenumberingfromthephysicallayout,use
GPIO.setmode(GPIO.BOARD).Butlet’sstickwiththepinnumberingthatyouusedin
Chapter8(GPIO.setmode(GPIO.BCM)),whichiswhatAdafruit’sPiCobblerand
similarbreakoutboardsuseforlabels:
>>>GPIO.setmode(GPIO.BCM)
2. Setthedirectionofpin25tooutput:
>>>GPIO.setup(25,GPIO.OUT)
3. ConnectanLEDtopin25likeyoudidin“Beginner’sGuidetoBreadboarding”.
4. TurnontheLED:
>>>GPIO.output(25,GPIO.HIGH)
5. TurnofftheLED:
>>>GPIO.output(25,GPIO.LOW)
6. ExitthePythoninteractiveinterpreter:
>>>exit()
$
Note
InChapter8,youlearnedthatdigitalinputandoutputsignalsontheRaspberryPimustbe
either3.3voltsorground.Indigitalelectronics,werefertothesesignalsashighorlow,
respectively.Keepinmindthatnotallhardwareoutthereuses3.3voltstoindicatehigh;
someuse1.8voltsor5volts.IfyouplanonconnectingyourRaspberryPitodigital
hardwarethroughitsGPIOpins,it’simportantthattheyalsouse3.3volts.
ThosestepsgaveyouaroughideaofhowtocontroltheGPIOpinsbytypinginPython
statementsdirectlyintotheinteractiveinterpreter.Justlikehowyoucreatedashellscript
toturnthepinsonandoffinChapter8,you’regoingtocreateaPythonscripttoreadand
controlthepinsautomatically.
BlinkinganLED
ToblinkanLEDonandoffwithPython,you’regoingtousethestatementsthatyou
alreadytriedintheinteractiveinterpreterinadditiontoafewothers.Forthenextfew
steps,we’llassumeyou’reusingthedesktopenvironment(asshowninFigure9-1),but
feelfreetousethecommandlinetowriteandexecutethesePythonscriptsifyouprefer.
Figure9-1.Creatinganewfileinthehomedirectory
Here’showtoblinkanLEDwithaPythonscript:
1. OpentheFileManagerbyclickingitsiconinthetaskbar.
2. Besureyou’reinthehomedirectory,thedefaultbeing/home/pi.Ifnot,clickonthe
homeiconunderthePlaceslisting.
3. Createafileinyourhomedirectorycalledblink.py.Dothisbyright-clickinginthe
homedirectorywindow,goingto“CreateNew”andthenclicking“BlankFile,”as
showninFigure9-1.Namethefileblink.py.
4. Double-clickonblink.pytoopenitinLeafpad,thedefaulttexteditor.
5. Enterthefollowingcodeandsavethefile:
importRPi.GPIOasGPIO
importtime
GPIO.setmode(GPIO.BCM)
GPIO.setup(25,GPIO.OUT)
whileTrue:
GPIO.output(25,GPIO.HIGH)
time.sleep(1)
GPIO.output(25,GPIO.LOW)
time.sleep(1)
ImportthecodeneededforGPIOcontrol.
Importthecodeneededforforthesleepfunction.
Usethechip’ssignalnumbers.
Setpin25asanoutput.
Createaninfiniteloopconsistingoftheindentedcodebelowit.
TurntheLEDon.
Waitforonesecond.
TurntheLEDoff.
Waitforonesecond.
Note
Don’tforgetthatindentationmattersinPython.
6. OpenLXTerminal,thenusethesecommandstomakesuretheworkingdirectoryis
yourhomedirectory,andexecutethescript:
[email protected]~/Development$cd~
[email protected]~$sudopythonblink.py
7. YourLEDshouldnowbeblinking!
8. PressCtrl-Ctostopthescriptandreturntothecommandline.
TrymodifyingthescripttomaketheLEDblinkfasterbyusingdecimalsinthe
time.sleep()functions.YoucanalsotryaddingafewmoreLEDsandgettingthemto
blinkinapattern.YoucanuseanyofthededicatedGPIOpins:4,17,18,21,22,23,24,or
25,asshowninFigure8-2.
ReadingaButton
Ifyouwantsomethingtohappenwhenyoupressabutton,onewaytodothatistousea
techniquecalledpolling.Pollingmeanscontinuallycheckingoverandoveragainforsome
condition.Inthiscase,itwillbepollingwhetherthebuttonisconnectingtheinputpinto
3.3voltsortoground.Tolearnaboutpolling,you’llcreateanewPythonscriptthatwill
displaytextonscreenwhentheuserpushesabutton:
1. Connectabuttonthesamewayasin“DigitalInput:ReadingaButton”,usingpin24
astheinput.Don’tforgetthepull-downresistor,whichgoesbetweengroundandthe
inputpin.
2. Createafileinyourhomedirectorycalledbutton.pyandopenitintheeditor.
3. Enterthefollowingcode:
importRPi.GPIOasGPIO
importtime
GPIO.setmode(GPIO.BCM)
GPIO.setup(24,GPIO.IN)
count=0
whileTrue:
inputValue=GPIO.input(24)
if(inputValue==True):
count=count+1
print("Buttonpressed"+str(count)+"times.")
time.sleep(.01)
Setpin24asaninput.
Createavariablecalledcountandstore0init.
Savethevalueofpin24intoinputValue.
CheckifthatvalueisTrue(whenthebuttonispressed).
Ifitis,incrementthecounter.
Printthetexttotheterminal.
Waitbriefly,butletotherprogramshaveachancetorunbynothoggingtheprocessor’s
time.
4. GobacktoLXTerminalandexecutethescript:
$sudopythonbutton.py
5. Nowpressthebutton.Ifyou’vegoteverythingright,you’llseeafewlinesof“The
buttonhasbeenpressed”foreachtimeyoupressthebutton.
Theprecedingcodechecksforthestatusofthebutton100timespersecond,whichiswhy
you’llseemorethanonesentenceprinted(unlessyouhaveincrediblyfastfingers).The
Pythonstatementtime.sleep(.01)iswhatcontrolshowoftenthebuttonischecked.
Butwhynotcontinuallycheckthebutton?Ifyouweretoremovethetime.sleep(.01)
statementfromtheprogram,theloopwouldindeedrunincrediblyfast,soyou’dknow
muchmorequicklywhenthebuttonwaspressed.Thiscomeswithafewdrawbacks:
you’dbeusingtheprocessorontheboardconstantly,whichwillmakeitdifficultforother
programstofunction,anditwouldincreasetheRaspberryPi’spowerconsumption.
Becausebutton.pyhastoshareresourceswithotherprograms,youhavetobecarefulthat
itdoesn’thogthemallup.
Nowaddafewlinestothecodetomakeitalittlebitbetteratregisteringasinglebutton
press:
importRPi.GPIOasGPIO
importtime
GPIO.setmode(GPIO.BCM)
GPIO.setup(24,GPIO.IN)
count=0
whileTrue:
inputValue=GPIO.input(24)
if(inputValue==True):
count=count+1
print("Buttonpressed"+str(count)+"times.")
time.sleep(.3)
time.sleep(.01)
Helpsabuttonpressregisteronlyonce.
Thisadditionallineofcodewillhelptoensurethateachbuttonpressisregisteredonly
once.Butit’snotaperfectsolution.Tryholdingdownthebutton.Anothercountwillbe
registeredanddisplayedthreetimesasecond,eventhoughyou’reholdingthebutton
down.Trypushingthebuttonrepeatedlyveryquickly.Itdoesn’tregistereverybutton
pressbecauseitwon’trecognizedistinctbuttonpressesmorefrequentlythanthreetimesa
second.
Thesearechallengesthatyou’llfacewhenyou’reusingpollingtocheckthestatusofa
digitalinput.Onewaytogetarroundthesechallengesistouseaninterrupt,whichisa
wayofsettingaspecifiedblockofcodetorunwhenthehardwaresensesachangeinthe
stateofthepin.ThereiscurrentlyexperimentalsupportforinterruptsinRPi.GPIO,and
youcanreadabouthowtousethisfeatureinthelibrary’sdocumentation.
Project:SimpleSoundboard
NowthatyouknowhowtoreadtheinputsontheRaspberryPi,youcanusethePython
modulePygame’ssoundfunctionstomakeasoundboard.Asoundboardletsyouplay
smallsoundrecordingswhenyoupushitsbuttons.Tomakeyourownsoundboard,you’ll
needthefollowinginadditiontoyourRaspberryPi:
Threepushbuttonswitches
Female-to-malejumperwires
Standardjumperwiresorhookupwire,cuttosize
Solderlessbreadboard
Threeresistors,10Kohm
Computerspeakers,oranHDMImonitorthathasbuilt-inspeakers
You’llalsoneedafewuncompressedsoundfiles,in.wavformat.Forpurposesoftesting,
thereareafewsoundfilespreloadedontheRaspberryPithatyoucanuse.Onceyouget
thesoundboardworking,it’seasytoreplacethosefileswithanysoundsyouwant,though
youmayhavetoconvertthemto.wavfromotherformats.Startoffbybuildingthecircuit:
1. Usingafemale-to-malejumperwire,connecttheRaspberryPi’sgroundpintothe
negativerailonthebreadboard.
2. Usingafemale-to-malejumperwire,connecttheRaspberryPi’s3.3Vpintothe
positiverailonthebreadboard.
3. Insertthethreepushbuttonswitchesinthebreadboard,allstraddlingthecenter
trench.
4. Usingstandardjumperwiresorsmallpiecesofhookupwire,connectthepositive
railofthebreadboardtothetoppinofeachbutton.
5. Nowaddthepull-downresistors.Connectthebottompinofeachbuttontoground
witha10Kresistor.
6. Usingfemale-to-malejumperwires,connecteachbutton’sbottompin(theonewith
the10Kresistor)totheRaspberryPi’sGPIOpins.Forthisproject,weusedpins23,
24,and25.
Figure9-2showsthecompletedcircuit.WecreatedthisdiagramwithFritzing,anopen
sourcetoolforcreatinghardwaredesigns.
Figure9-2.Completedcircuitforthesoundboardproject
Nowthatyouhavethecircuitbreadboarded,it’stimetoworkonthecode:
1. Createanewdirectoryinyourhomedirectorycalledsoundboard.
2. Openthatfolderandcreateafiletherecalledsoundboard.py.
3. Opensoundboard.pyandtypeinthefollowingcode:
importpygame.mixer
fromtimeimportsleep
importRPi.GPIOasGPIO
fromsysimportexit
GPIO.setmode(GPIO.BCM)
GPIO.setup(23,GPIO.IN)
GPIO.setup(24,GPIO.IN)
GPIO.setup(25,GPIO.IN)
pygame.mixer.init(48000,-16,1,1024)
soundA=pygame.mixer.Sound("/usr/share/sounds/alsa/Front_Center.wav")
soundB=pygame.mixer.Sound("/usr/share/sounds/alsa/Front_Left.wav")
soundC=pygame.mixer.Sound("/usr/share/sounds/alsa/Front_Right.wav")
soundChannelA=pygame.mixer.Channel(1)
soundChannelB=pygame.mixer.Channel(2)
soundChannelC=pygame.mixer.Channel(3)
print"SoundboardReady."
whileTrue:
try:
if(GPIO.input(23)==True):
soundChannelA.play(soundA)
if(GPIO.input(24)==True):
soundChannelB.play(soundB)
if(GPIO.input(25)==True):
soundChannelC.play(soundC)
sleep(.01)
exceptKeyboardInterrupt:
exit()
Initializepygame’smixer.
Loadthesounds.
Setupthreechannels(oneforeachsound)sothatwecanplaydifferentsounds
concurrently.
Lettheuserknowthesoundboardisready(usingPython2syntax).
Ifthepinishigh,executethefollowingline.
Playthesound.
Don’t“peg”theprocessorbycheckingthebuttonsfasterthanweneedto.
ThiswillletusexitthescriptcleanlywhentheuserhitsCtrl-C,withoutshowingthe
tracebackmessage.
4. Gotothecommandlineandnavigatetothefolderwhereyou’vesaved
soundboard.pyandexecutethescriptwithPython2:
[email protected]~/soundboard$sudopythonsoundboard.py
5. Afteryousee“SoundboardReady,”startpushingthebuttonstoplaythesound
samples.
Note
WhilePygameisavailableforPython3,ontheRaspberryPi’sdefaultinstallation,it’s
onlyinstalledforPython2.
DependingonhowyourRaspberryPiissetup,yoursoundmightbesentviaHDMIto
yourdisplay,oritmaybesenttothe3.5mmanalogaudiooutputjackontheboard.To
changethat,exitoutofthescriptbypressingCtrl-Candexecutingthefollowing
commandtousetheanalogaudiooutput:
[email protected]~/soundboard$sudoamixercsetnumid=31
TosendtheaudiothroughHDMItothemonitor,use:
[email protected]~/soundboard$sudoamixercsetnumid=32
Ofcourse,thestocksoundsaren’tveryinteresting,butyoucanreplacethemwithanyof
yourownsounds:applause,laughter,buzzers,anddings.Addthemtothesoundboard
directoryandupdatethecodetopointtothosefiles.Ifyouwanttousemoresoundson
yoursoundboard,addadditionalbuttonsandupdatethecodeasnecessary.
GoingFurther
RPi.GPIO
BecausetheRPi.GPIOlibraryisstillunderactivedevelopment,youmaywanttocheck
thehomepagefortheprojecttofindthelatestupdates.
Chapter10.AnalogInputandOutput
InChapter8,youlearnedaboutdigitalinputsandoutputswithbuttons,switches,LEDs,
andrelays.Eachofthesecomponentswasalwayseitheronoroff,neveranythingin
between.However,youmightwanttosensethingsintheworldthatarenotnecessarily
oneortheother—forinstance,temperature,distance,lightlevels,orthestatusofadial.
Theseallcomeinarangeofvalues.
Oryoumaywantputsomethinginastatethat’snotjustonoroff.Forexample,ifyou
wantedtodimanLEDorcontrolthespeedofamotorratherthanjustturningitonoroff.
Tomakeananalogyforanaloganddigital,youcanthinkofatypicallightswitchversusa
dimmerswitch,aspicturedinFigure10-1.
Figure10-1.Digitalisliketheswitchontheleft:itcanbeeitheronoroff.
Analog,ontheotherhand,canbesetatarangeofvaluesbetweenfullyon
andcompletelyoff.
Output:ConvertingDigitaltoAnalog
JustlikeinChapter9,you’llusetheGPIOPythonmodulealreadyinstalledinthemost
recentversionsofRaspbianLinux.Themodulehasexperimentalfunctionsforcontrolling
theGPIOpins,sortoflikeadimmerswitch.
Wesaythatit’s“sortof”likeadimmerswitchbecausethemoduleusesamethodcalled
pulse-widthmodulation,orPWM,tomakeitseemlikethere’sarangeofvoltagescoming
outofitsoutputs.Whatit’sactuallydoingispulsingitspinsonandoffreallyquickly.So
ifyouwantthepintobeasthoughit’sathalfvoltage,thepinwillbepulsedsothatitison
50%ofthetimeandofffor50%ofthetime.Ifyouwantthepintobeasthoughit’sat
20%power,itwillturnthepinon20%ofthetimeandoff80%ofthetime.The
percentageoftimethatit’sonversustotaltimeofthecycleiscalledthedutycycle
(Figure10-2).WhenyouconnectanLEDtothesepinsandinstructtheRaspberryPito
changethedutycycle,itcangivetheeffectofdimmingtheLED.
Figure10-2.Thedutycyclerepresentshowmuchtimethepinisturnedon
overthecourseofanon-offcycle
TestDrivingPWM
Forthenextfewsteps,we’llassumeyou’reusingthedesktopenvironment,butfeelfreeto
usethecommandlinetowriteandexecutethesePythonscriptsifyouprefer:
1. ConnectanLEDtopin25likeyoudidin“Beginner’sGuidetoBreadboarding”.
2. OpentheFileManagerbyclickingitsiconinthetaskbar.
3. Besureyou’reinthehomedirectory,thedefaultbeing/home/pi.Ifnot,clickonthe
homeiconunderthePlaceslisting.
4. Createafileinyourhomedirectorycalledblink.py.Dothisbyright-clickinginthe
homedirectorywindow,goingto“CreateNew”andthenclicking“BlankFile.”
Namethefilefade.py.
5. Double-clickonfade.pytoopenitinLeafpad,thedefaulttexteditor.
6. Enterthefollowingcodeandsavethefile:
importRPi.GPIOasGPIO
importtime
GPIO.setmode(GPIO.BCM)
GPIO.setup(25,GPIO.OUT)
p=GPIO.PWM(25,50)
p.start(0)
whileTrue:
fordcinrange(0,100,5):
p.ChangeDutyCycle(dc)
time.sleep(0.05)
fordcinrange(100,0,-5):
p.ChangeDutyCycle(dc)
time.sleep(0.05)
CreateaPWMobjectcalledpandsetittoGPIOpin25withafrequencyof50Hz.
StartPWMonp.
Runtheindentedcodebelow,eachtimeincrementingthevalueofdcby5fromstarting
at0andgoingto100.
Setthedutycycleofptothevalueofdc.
Runtheindentedcodethatfollows,eachtimedecrementingthevalueofdcby5from
startingat100andgoingto0.
7. OpenLXTerminal,thenusethesecommandstomakesuretheworkingdirectoryis
yourhomedirectory,andexecutethescript:
[email protected]~/Development$cd~
[email protected]~$sudopythonfade.py
8. YourLEDshouldnowbefadingupanddown!
9. PressCtrl-Ctostopthescriptandreturntothecommandline.
Note
Ifyou’reaccustomedtousingPWMonamicrocontrollerliketheArduino,you’llfindthat
—unlikeArduino—thereisunsteadinessinthePWMpulsesfromtheRaspberryPi.This
isbecauseinthisexample,you’reusingtheCPUtoturnonandofftheLED.Becausethat
CPUisusedformultiplethingsatonetime,itmaynotalwayskeepperfecttime.Youcan
alwaysreachforotherhardwarelikeAdafruit’sPWM/ServoDriverifyouneedtohave
moreprecisecontrol.
TakingPWMFurther
Withtheabilitytousepulse-widthmodulationtofadeLEDsupanddown,youcouldalso
connectanRGBLEDandcontrolthecolorbychangingthebrightnessofitsred,green,
andblueelements.
Pulse-widthmodulationcanalsobeusedtocontrolthespeedofadirectcurrentmotor
that’sconnectedtoyourRaspberryPithroughtransistors.Thepositionoftheshaftona
hobbyservomotors(thekindthatsteerRCcars)canalsocontrolledwithspecificpulses
ofelectricity.Though,keepinmindthatyoumayneedadditionalhardwareandpowerin
ordertocontrolthesemotorswithaRaspberryPi.
Input:ConvertingAnalogtoDigital
JustlikeyoucontrolledtheoutputofaGPIOpinonascaleof0to100,it’salsopossible
toreadsensorsthatcanoffertheRaspberryPiarangeofvalues.Ifyouwanttoknowthe
temperatureofaroom,thelightlevel,ortheamountofpressureonapad,youcanuse
varioussensors.OnamicrocontrollerliketheArduino,there’sspecialhardwaretoconvert
theanalogvoltageleveltodigitaldata.Unfortunately,yourRaspberryPidoesn’thave
havethishardwarebuiltin.
Toconvertfromanalogtodigital,thissectionwillshowyouhowtouseanADC,or
analog-to-digitalconverter.ThereareafewdifferentmodelsofADCsoutthere,butthis
chapterwillusetheADS1115fromTexasInstruments.ThepackageoftheADS1x15chip
istoosmallforyourstandardbreadboard,soAdafruitIndustrieshascreatedabreakout
boardforit,showninFigure10-3.Onceyou’vesolderedheaderpinstothebreakout
board,youcanprototypewiththischipinyourbreadboard.Thechipusesaprotocol
calledI2Cfortransmittingtheanalogreadings.Luckily,wedon’tneedtounderstandthe
protocolinordertouseit.AdafruitprovidesanexcellentopensourcePythonlibraryto
readthevaluesfromtheADS1115anditslittlebrother,theADS1015,viaI2C.
Figure10-3.TheADS1115analog-to-digitalconverterbreakoutfrom
Adafruit
ToconnecttheADS1115breakouttoyourRaspberryPi:
1. Connectthe3.3voltpinfromtheRaspberryPitothepositiverailofthebreadboard.
RefertoFigure8-2forpinlocationsontheRaspberryPi’sGPIOheader.
2. ConnectthegroundpinfromtheRaspberryPitothenegativerailofthebreadboard.
3. InserttheADS1115intothebreadboardandusejumperwirestoconnectitsVDD
pintothepositiverailanditsGNDpintothenegativerail.
4. ConnecttheSCLpinontheADS1115totheSCLpinontheRaspberryPi.TheSCL
pinonthePiistheonepairedwiththegroundpinontheGPIOheader.
5. ConnecttheSDApinontheADS1115totheSDApinontheRaspberryPi.TheSDA
pinisinbetweenthetheSCLpinandthe3.3voltpin.
Nowyou’llneedtoconnectananalogsensortotheADS1115.Therearemanytochoose
from,butforthiswalk-through,you’llusea2Kpotentiometersothatwecanhaveadial
inputforyourRaspberryPi.Apotentiometer,orpot,isessentiallyavariablevoltage
divider,andcancomeintheformofadialorslider.
Note
Thevalueofthepotentiometeryouusedoesn’thavetobe2K.Ifyouonlyhavea10Kor
1Mpotentiometer,itwillworkjustfine.
ToconnectapotentiometertotheADS1115:
1. Insertthepotentiometerintothebreadboard.
2. Thepothasthreepins.ConnectthemiddlepintopinA0inontheADS1115.
3. Oneoftheoutsidepinsshouldconnecttothepositiverailofthebreadboard.For
now,itdoesn’tmatterwhich.
4. Connecttheotheroutsidepintothenegativerailofthebreadboard.
TheconnectionsshouldlookasshowninFigure10-4.
Beforeyoucanreadthepotentiometer,you’llneedtoenableI2Candinstallacouple
libraries:
1. Onthecommandline,openuptheraspi-blacklist.conffileasroot:
$sudonano/etc/modprobe.d/raspi-blacklist.conf
InordertoremoveI2Cfromthisblacklist,putahashmarkinfrontofthelinethat
saysblacklisti2c-bcm2708.Itshouldlooklikethis:
#blacklistspiandi2cbydefault(manyusersdon'tneedthem)
blacklistspi-bcm2708
#blacklisti2c-bcm2708
2. PressCtrl-Xtoexitandthenpressytosavethefile.
3. Next,open/etc/modules:
$sudonano/etc/modules
4. Addi2c-devtotheendofthefile,onitsownline.Thefileshouldlooklikethis:
#/etc/modules:kernelmodulestoloadatboottime.
#
#Thisfilecontainsthenamesofkernelmodulesthatshouldbeloaded
#atboottime,oneperline.Linesbeginningwith"#"areignored.
#Parameterscanbespecifiedafterthemodulename.
snd-bcm2835
i2c-dev
Figure10-4.UsingtheADS1115toconnectapotentiometertothe
RaspberryPi
5. PressCtrl-Xtoexitandthenpressytosavethefile.
6. Updateyourlistofpackages:
$sudoapt-getupdate
7. Installi2c-toolstoolsandpython-smbus:
$sudoapt-getinstalli2c-toolspython-smbus
8. RestartyourRaspberryPi.
9. Afteryou’verestartedyourRaspberryPi,testthattheRaspberryPicandetectthe
ADS1115.Onrevision1boards,usethecommand:
$sudoi2cdetect-y0
Onrevision2boards,usethecommand:
$sudoi2cdetect-y1
10. Iftheboardisrecognized,you’llseethenumberinthegridthatisdisplayed:
0123456789abcdef
00:—--—--—--—--—--—--—10:—--—--—--—--—--—--—--—-20:—--—--—--—--—--—--—--—--
30:—--—--—--—--—--—--—--—-40:—--—--—--—--48—--—--—--—50:—--—--—--—--—--—--—--—-60:—--—--—--—--—--—--—--—-70:—--—--—--—--
11. NowthatweknowthatthedeviceisconnectedandisrecognizedbyourPi,it’stime
tostartreadingthepotentiometer.Todoso,downloadtheRaspberryPiPython
librariesfromAdafruit’scoderepositoryintoyourhomefolder.Typethefollowing
commandattheshellprompt,allononelinewithnospacesintheURL:
wgethttps://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/archive/master.zip
12. Unzipit:
$unzipmaster.zip
13. Changetothelibrary’sADS1x15directory:
$cdAdafruit-Raspberry-Pi-Python-Code-master/Adafruit_ADS1x15
14. Runoneoftheexamplefiles:
$sudopythonads1x15_ex_singleended.py
0.734625
Note
TheexamplePythonscriptads1x15_ex_singleended.pydefaultstolookingforan
ADS1115.Ifyou’reusinganADS1015,you’llneedtoeditthelineinthescriptthat
saysadc=ADS1x15=(ic=ADS1115),replacingADS1115withADS1015.
15. Turnthepotentiometerallthewayinonedirectionandrunitagain.Noticethe
changeinthevalue:
$sudopythonads1x15_ex_singleended.py
3.290750
16. Turnthepotentiometerallthewayintheotherdirectionandrunitonemoretime:
$sudopythonads1x15_ex_singleended.py
0.000500
Asyoucansee,turningthedialonthepotentiometerchangesthevoltagecominginto
channel0oftheADS1115.Thecodeintheexampledoesalittlebitofmathtodetermine
thevoltagevaluefromthedatacomingfromtheADC.Ofcourse,yourmathwillvary
dependingonwhatkindofsensoryouuse.
AsshowninExample10-1,trycreatinganewfileinthesamedirectorywiththe
followingcode.
Example10-1.RepeatedlyreadingtheADC
fromAdafruit_ADS1x15importADS1x15
fromtimeimportsleep
adc=ADS1x15()
whileTrue:
result=adc.readADCSingleEnded(0)
printresult
sleep(.5)
ImportAdafruit’sADS1x15library.
CreateanewADS1x15objectcalledadc.
GetareadingfromchannelA0ontheADS1115andstoreitinresult.
Whenyourunthiscodeasroot,itwilloutputoutrawnumbersforeachreadingtwicea
second.Turningthepotentiometerwillmakethevaluesgoupordown.
Onceyougetitallsetup,theAdafruitADS1x15librarydoesallthehardworkforyou
andmakesiteasytouseanalogsensorsinyourprojects.Forinstance,ifyouwanttomake
yourownPong-likegame,youcouldreadtwopotentiometersandthenusePygameto
drawonthegameonscreen.FormoreinformationaboutusingPygame,seeChapter4.
VariableResistors
Whiletherearemanythatdo,notallanalogsensorsworklikethepotentiometerdoes,
whichprovidesavariablevoltagebasedonsomefactor(suchastheamountthedialon
thepotisturned).
Somesensorsaresimplyvariableresistorsthatresisttheflowofelectricitybasedonsome
factor.Forinstance,aphotocellliketheoneinFigure10-5willactlikearesistorthat
changesvaluesbasedontheamountoflighthittingthecell.Addmorelightandthe
resistancegoesdown.Takeawaylightandtheresistancegoesup.Theforce-sensitive
resistordecreasesitsresistanceasyouputpressureonthepad.
Figure10-5.Thephotocellandforce-sensitiveresistorsactasvariable
resistorsandcanbeusedasanaloginputs
Inordertoreadsensorslikethesewithanaloginputpins,you’llneedtoincorporatea
voltagedividercircuit.
VoltageDividerCircuit
Whenyou’reworkingwithsensorsthatoffervariableresistance,thepurposeofavoltage
divideristoconvertthevariableresistanceintoavariablevoltage,whichiswhatthe
analoginputpinsaremeasuring.First,takealookatasimplevoltagedivider.
InFigure10-6,you’llseetworesistorsofthesamevalueinseriesbetweenthepositive
andgroundandonewireconnectedtoanaloginput0betweenthetworesistors.Because
bothresistorsare10Kohms,there’sabout1.65voltsgoingtoanaloginput0,halfof3.3
volts.
Withoutgettingboggeddowninthemathinvolved,ifyouremovedthe10Kresistor
connectedto3.3voltsandreplaceditwitharesistorofahighervalue,thevoltagegoing
intotheanalogpinwoulddecrease.Ifyouremovedthat10Kresistorandreplaceditwith
oneofalowervalue,thevoltagegoingintotheanalogpinwouldincrease.Wecanuse
thisprinciplewithsensorsthatarevariableresistorsinordertoreadthemwiththeanalog
inputpins.You’llsimplyreplaceoneoftheresistorswithyoursensor.
Totrythecircuitout,you’llwireupatypeofvariableresistorcalledaforce-sensitive
resistor,orFSR.
Figure10-6.Withtwoofthesamevalueresistorsbetweenvoltageand
ground,thevoltagebetweenthetwowouldbehalfofthetotalvoltage
Force-SensitiveResistor
Aforce-sensitiveresistorisavariableresistorthatchangesbasedontheamountof
pressureplacedonitspad.Whenthere’snopressureonthepad,thecircuitisopen.When
youstartplacingpressureonit,theresistancedrops.
TheexactfigureswilldependonyourparticularFSR,buttypicallyyou’llsee100Kohms
ofresistancewithlightpressureand1ohmofresistancewithmaximumpressure.Ifyou
haveamultimeter,youcanmeasurethechangesinresistancetoseeforyourself,oryou
canlookatthecomponent’sdatasheet,whichwilltellyouwhattoexpectfromthesensor.
Ifyou’regoingtoreplacetheresistorconnectedto3.3voltsinFigure10-6withavariable
resistorlikeanFSR,you’llwantthevalueoftheotherresistortobesomewherein
betweentheminimumandmaximumresistancesothatyoucangetthemostrangeoutof
thesensor.ForatypicalFSR,trya10Kohmresistor.Togivetheforce-sensitiveresistora
testdrive:
1. WireupanFSRtotheADCasshowninFigure10-7.
2. ExecutethecodeinExample10-1again.
3. WatchthereadingsonthescreenasyousqueezetheFSR.
Ifeverythingisworkingcorrectly,youshouldseethevaluesriseasyouincreasingly
squeezeharderontheFSR.Asyoupressharder,you’rereducingtheresistancebetween
thetwoleadsontheFSR.Thishastheeffectofsendinghighervoltagetotheanaloginput.
You’llencountermanyanalogsensorsthatusethisverysameprinciple,andasimple
voltagedividercircuit,alongwithananalog-to-digitalconverter,willallowyour
RaspberryPitocapturethatsensordata.
Figure10-7.Wiringupaforce-sensitiveresistortotheADCrequiresa
voltagedividercircuit
GoingFurther
ControllingaDCMotorwithPWM
AdafruithasanexcellentguidethatteachesyouhowtousePWMtocontrolthespeed
ofaDCmotor.
ReadingResistiveSensorswithRCTiming
Adafruitalsoshowsyouhowtouseasimplecircuittoreadresistiveanalogsensors
withoutananalog-to-digitalconverter.
Chapter11.WorkingwithCameras
OneoftheadvantagestousingaplatformliketheRaspberryPiforDIYtechnology
projectsisthatitsupportsawiderangeofperipheraldevices.Notonlycanyouhookupa
keyboardandmouse,butyoucanalsoconnectaccessorieslikeprinters,WiFiadapters,
thumbdrives,additionalmemorycards,cameras,andharddrives.Inthischapter,we’re
goingtoshowafewwaysthatyoucanuseacamerainyourRaspberryPiprojects.
Whilenotquiteascommonasakeyboardandmouse,thewebcamhasalmostbecomea
standardperipheralfortoday’smoderncomputers.Mostlaptopssoldthesedayshavea
tinycamerabuiltintothebezelofthedisplay.Andifnot,aaUSBwebcamfromawellknownbrandcanbepurchasedforaslittleas$25.Youcanevenfindwebcamsformuch
lessifyoutakeachanceonanunknownbrand.
ThefolksattheRaspberryPiFoundationhavecreatedtheirowncameraperipheralthatis
designedtoworkwithRaspberryPi(Figure11-1).UnlikeaUSBwebcam,it’sunlikely
you’lltobeabletofindtheofficialRaspberryPicameramoduleinabasicelectronics
store,butyoushouldbeabletobuyitwhereverRaspberryPisaresoldforaround$25.
Figure11-1.RaspberryPi’scameramodule
UnlikeaUSBwebcam,thecameraboardconnectstoRaspberryPi’scameraserial
interfaceconnector(Figure11-2).BecausetheBroadcomchipatthecoreoftheRaspberry
Piismeantformobilephonesandtablets,theCSIconnectionishowamobiledevice
manufacturerwouldconnectacameratothechip.Throughoutthischapter,we’llusethe
officialcameraboard,butmanyoftheprojectsandtutorialscanalsobedonewithaUSB
webcam(Figure11-3).
Figure11-2.RaspberryPi’scameraserialinterface
Figure11-3.AtypicalUSBwebcam
ConnectingandTestingtheCameraModule
Connectingtheofficialcameramoduleisn’tasstraightforwardasconnectingaUSB
device,butonceyougetitworking,itshouldbeapieceofcake.
Warning
MakesuretheRaspberryPiispowereddownbeforeyoudothis.
Herearethestepsyou’llneedtotake:
1. PulluponedgesoftheCSIconnector,whichisrightnexttotheEthernetport.A
pieceoftheconnectorwillslideupandleanbacktowardtheEthernetport.(See
Figure11-4.)
Figure11-4.Openingthecameraserialinterfaceconnectorlocking
mechanism
2. Insertthecameramodule’sribboncableintotheCSIconnectorsothatitsmetal
contactsarefacingawayfromtheEthernetport.
3. HoldtheribboncableintotheCSIconnectorandpressthemovingpartoftheCSI
connectordowntolockandholdtheribboncableinplace.You’llstillseepartofthe
metalcontactsontheribboncable.(SeeFigure11-5.)
4. LaunchtheRaspberryPiSoftwareConfigurationToolfromthecommandline:
$sudoraspi-config
5. Select“EnableCamera”toenablethecamera.
6. SelectfinishandreboottheRaspberryPi.
7. Afteryourebootandyoulogin,testthecamerawith:
$raspistill-otest.jpg
Ifeverythingworks,you’llseeapreviewimagefromthecameraappearonscreenfora
fewseconds.Afteritdisappears,aJPEGfileofthecapturedimagewillbesavedinyour
currentdirectory.
Figure11-5.Afterplacingtheribboncableintothecameraserialinterface
connectorandlockingitdown,youmaystillseemetalcontactsonthe
ribboncable
raspistillisapowerfulprogramwithalotofoptions.Toseewhat’spossiblewithit,
viewallthecommand-lineoptionsbyrunningtheprogramandpipingtheoutputthrough
less:
$raspistill2>&1|less
Usetheupanddownarrowkeystoscrollthroughtheoptions,andpressqwhenyouwant
togetbacktothecommandline.
Project:MakingaGIF
Oneofthefeaturesofraspistillisthatitcantakeaseriesofphotosonaparticular
interval.Wecanusethisfeaturealongwiththecommand-linevideoconvertersoftware
ffmpegtocreatefunanimatedGIFswiththeRaspberryPi:
1. First,installffmpeg:
$sudoapt-getinstallffmpeg
2. Createanewdirectorytoholdtheimagesyoucaptureandswitchtothatdirectory:
$mkdirgif-test
$cdgif-test
3. Withyourcameraready,executeraspistilltorunfornineseconds,takinga640×
480resolutionimageeverythreeseconds,namingeachfilewithanincrementing
filename:
$raspistill-t9000-tl3000-oimage%02d.jpg-w640-h480
4. Next,inputthosefilesintoffmpegoutputtingasthefiletest.gif:
ffmpeg-iimage%02d.jpg-pix_fmtrgb24test.gif
5. Nowopenthetest.giffilewithinMidoriinthedesktopenvironment,andyou’llsee
theGIFyoumade!
CapturingVideo
There’salsoacommand-lineutilitycalledraspividtocapturevideofromtheofficial
RaspberryPicameramodule.Trycapturingafive-secondvideoandsavingittoafile:
$raspivid-t5000-ovideo.h264
Youcanplaythatfilebackwith:
$omxplayervideo.h264
Andjustlikeraspistill,raspividisapowerfulprogramwithalotofoptions.Tosee
what’spossiblewithit,viewallthecommand-lineoptionsbyrunningtheprogramand
pipingtheoutputthroughless:
$raspivid2>&1less
TestingUSBWebcams
Withallthedifferentmodelsofwebcamsoutthere,there’snoguaranteethatacamerawill
workrightoutofthebox.Ifyou’repurchasingawebcamforusewiththeRaspberryPi,
searchonlinetomakesurethatothershavehadsuccesswiththemodelthatyou’re
purchasing.YoucanalsocheckthewebcamsectionofeLinux.org’spageofperipherals
thathavebeenverfiedtoworkwiththeRaspberryPi.
Beawarethatyou’llneedtoconnectapoweredUSBhubtoyourRaspberryPisothatyou
canconnectyourwebcaminadditiontoyourkeyboardandmouse.Thehubshouldbe
poweredbecausetheRaspberryPionlyletsalimitedamountofelectricalcurrentthrough
itsUSBports,andit’slikelyitwillbeunabletoprovideenoughpowerforyourkeyboard,
mouse,andwebcam.ApoweredUSBhubplugsintothewallandprovideselectrical
currenttotheperipheralsthatconnecttoitsothattheydon’tmaxoutthepoweronyour
RaspberryPi.
Ifyouhaveawebcamthatyou’rereadytotestoutwiththeRaspberryPi,useapt-getin
theterminaltoinstallasimplecameraviewingapplicationcalledluvcview:
$sudoapt-getinstallluvcview
Afterapt-getfinishestheinstallation,runtheapplicationbytypingluvcviewina
terminalwindowwhileyou’reinthedesktopenvironment.Awindowwillopenshowing
theviewofthefirstvideosourceitfindsinthe/devfolder,likely/dev/video0.Notethe
framesizethatisprintedintheterminalwindow.Ifthevideoseemsalittlechoppy,you
canfixthisbyreducingthedefaultsizeofthevideo.Forexample,ifthedefaultvideosize
is640×480,closeluvcviewandreopenitathalfthevideosizebytypingthefollowingat
thecommandline:
$luvcview-s320x240
Ifyoudon’tseevideocomingthrough,you’llwanttotroubleshootherebeforemovingon.
Onewaytoseewhat’swrongisbydisconnectingthewebcam,reconnectingit,and
runningthecommanddmesg,whichwilloutputdiagnosticmessagesthatmightgiveyou
someclues.
InstallingandTestingSimpleCV
InordertoaccessthewebcamwithPythoncode,we’lluseSimpleCV(Figure11-6),
whichisafeature-packedopensourcecomputervisionlibrary.SimpleCVmakesitreally
easytogetimagesfromthewebcam,displaythemonscreen,orsavethemasfiles.But
whatmakesSimpleCVreallystandoutareitscomputervisionalgorithms,whichcando
someprettyamazingthings.Besidesbasicimagetransformations,itcanalsotrack,detect,
andrecognizeobjectsinanimageorvideo.Lateroninthischapter,we’lltrybasicface
detectionwithSimpleCV(“FaceDetection”).
Figure11-6.SimpleCVlogo
ToinstallSimpleCVforPython,you’llneedtostartbyinstallingtheotherlibrariesit
dependson.Forthose,youcanuseapt-get:
$sudoapt-getinstallpython-opencvpython-scipypython-numpypython-pip
It’sabiginstall,anditmaytakeawhilebeforetheprocessiscomplete.Next,you’ll
installtheactualSimpleCVlibrarywiththefollowingcommand:
$sudopipinstallhttps://github.com/ingenuitas/SimpleCV/zipball/master
Whenit’sdone,checkthattheinstallationworkedbygoingintothePythoninteractive
interpreterandimportingthelibrary:
$python
Python2.7.3rc2(default,May62012,20:02:25)
[GCC4.6.3]onlinux2
Type"help","copyright","credits"or"license"formoreinformation.
>>>importSimpleCV
>>>
Ifyougetnoerrorsafterimportingthelibrary,youknowyou’vegotSimpleCVinstalled
correctly.Ifyou’reusingaUSBwebcam,youcanjumpaheadto“DisplayinganImage”.
Ifyou’reusingtheRaspberryPicameramodule,thereareafewextrasteps,whichwe’ll
covernow.
AdditionalStepsfortheRaspberryPiCameraModule
BecauseSimpleCVusessomethingcalledtheVideo4Linux(V4L)driverframeworkto
accessUSBwebcams,we’llneedtomaketheRaspberryPicameramoduleaccessible
throughV4L.AdevelopernamedLucaRisoliahascreateddriverssothatyoucanusethe
officialRaspberryPicameramodulewithSimpleCV.Again,ifyou’reusingaregular
USBwebcam,youcanskipthesesteps:
1. Fromthecommandline,runthefollowingtwocommandssothatyoucanadd
Luca’ssoftwarerepositorytoapt-get:
$wgethttp://www.linux-projects.org/listing/uv4l_repo/lrkey.asc
$sudoapt-keyadd./lrkey.asc
2. Thenextstepistoaddthetherepository’sURLtoyourlistofrepositories.Open
yourlistofrepositoriesinnano:
$sudonano/etc/apt/sources.list
3. Addthefollowinglinetothatfile:
debhttp://www.linux-projects.org/listing/uv4l_repo/raspbian/wheezymain
4. ExitnanobypressingCtrl-Xfollowedbyytosavethefilewhenitpromptsyou.
5. Downloadandinstallthedrivers:
$sudoapt-getupdate
$sudoapt-getinstalluv4luv4l-raspicamuv4l-raspicam-extras
6. Whentheinstallationisdone,you’llneedtorebootyourRaspberryPi.
Note
Atthetimeofwritingthisbook,thedriverisunderdevelopmentandnotallthingswill
workasexpected.TheremainderofthischapterusesaUSBwebcam,butifyouusethe
RaspberryPicameramodule,youmayneedtoreplacethelinesthatreadmyCamera=
Camera(prop_set={'width':320,'height':240})withmyCamera=Camera(0).
DisplayinganImage
Formanyoftheexamplesinthischapter,you’llneedtoworkinthedesktopenvironment
sothatyoucandisplayimagesonscreen.YoucanworkinIDLE,orsaveyourcodeas.py
filesfromLeafpadandexecutethemfromtheterminalwindow.
We’regoingtostartyouoffwithsomeSimpleCVbasicsusingimagefiles,andthenyou’ll
workyourwayuptoreadingimagesfromthewebcam.Onceyou’vegotimagescoming
infromthewebcam,itwillbetimetotrysomefacedetection:
1. Createanewdirectorywithinyourhomedirectorycalledsimplecv-test.
2. OpenMidoriandsearchforanimagethatinterestsyou.Weusedaphotographof
raspberriesfromWikipediaandrenameditraspberries.jpg.
3. Right-clickontheimageandclick“SaveImage.”
4. Savetheimagewithinthesimplecv-testfolder.
5. Inthefilemanager(ontheAccessoriesmenu),openthesimplecv-testfolderand
right-clickinthefolder.ChooseCreateNew→BlankFile.
6. Namethefileimage-display.py.
7. Double-clickonthenewlycreatedimage-display.pyfiletoopenitinLeafpad.
8. EnterthecodeinExample11-1.
9. Savetheimage-display.pyfileandrunitfromtheterminalwindow.Ifyou’vegot
everythingright,you’llseeaphotoinanewwindowasinFigure11-7.Youcan
closethewindowitself,orintheTerminal,pressCtrl-Ctoendthescript.
Figure11-7.Theraspberryphotodisplayedinawindow
Example11-1.Sourcecodeforimage-display.py
fromSimpleCVimportImage,Display
fromtimeimportsleep
myDisplay=Display()
raspberryImage=Image("raspberries.jpg")
raspberryImage.save(myDisplay)
whilenotmyDisplay.isDone():
sleep(0.1)
ImportSimpleCV’simageanddisplayfunctions.
Createsanewwindowobject.
Loadstheimagefileraspberries.jpgintomemoryastheobjectimage.
Displaytheimageinthewindow.
Preventthescriptfromendingimmediatelyafterdisplayingtheimage.
ModifyinganImage
Nowthatyoucanloadanimageintomemoryanddisplayitonthescreen,thenextstepis
tomodifytheimagebeforedisplayingit(doingthisdoesnotmodifytheimagefileitself;
itsimplymodifiesthecopyoftheimagethat’sheldinmemory):
1. Savetheimage-display.pyfileassuperimpose.py.
2. MaketheenhancementstothecodethatareshowninExample11-2.
3. Savethefileandrunitfromthecommandline.
4. Youshouldseethesameimage,butnowsuperimposedwiththeshapeandthetext.
Example11-2.Sourcecodeforsuperimpose.py
fromSimpleCVimportImage,Display,DrawingLayer,Color
fromtimeimportsleep
myDisplay=Display()
raspberryImage=Image("raspberries.jpg")
myDrawingLayer=DrawingLayer((raspberryImage.width,raspberryImage.height))
myDrawingLayer.rectangle((50,20),(250,60),filled=True)
myDrawingLayer.setFontSize(45)
myDrawingLayer.text("Raspberries!",(50,20),color=Color.WHITE)
raspberryImage.addDrawingLayer(myDrawingLayer)
raspberryImage.applyLayers()
raspberryImage.save(myDisplay)
whilenotmyDisplay.isDone():
sleep(0.1)
ImportSimpleCV’sdrawinglayerandcolorfunctions,inadditiontotheimageand
displayfunctionsyouimportedpreviously.
Createanewdrawinglayerthat’sthesamesizeastheimage.
Onthelayer,drawarectanglefromthecoordinates50,20to250,60andmakeitfilled.
Onthelayer,writethetext“Raspberries!”at50,20inthecolorwhite.
AddmyDrawingLayertoraspberryImage.
MergethelayersthathavebeenaddedintoraspberryImage(Figure11-8showsthe
newimage).
Figure11-8.Themodifiedraspberryphoto
Insteadofdisplayingtheimageonscreen,ifyouwantedtosimplysaveyour
modificationstoafile,Example11-3showshowthecodewouldlook.
Example11-3.Sourcecodeforsuperimpose-save.py
fromSimpleCVimportImage,DrawingLayer,Color
fromtimeimportsleep
raspberryImage=Image("raspberries.jpg")
myDrawingLayer=DrawingLayer((raspberryImage.width,raspberryImage.height))
myDrawingLayer.rectangle((50,20),(250,60),filled=True)
myDrawingLayer.setFontSize(45)
myDrawingLayer.text("Raspberries!",(50,20),color=Color.WHITE)
raspberryImage.addDrawingLayer(myDrawingLayer)
raspberryImage.applyLayers()
raspberryImage.save("raspberries-titled.jpg")
Savethemodifiedimageinmemorytoanewfiledcalledraspberries-titled.jpg.
Becausethiscodedoesn’tevenopenupawindow,youcanuseitfromthecommandline
withoutthedesktopenvironmentrunning.Youcouldevenmodifythecodetowatermark
batchesofimageswithasinglecommand.
Andyou’renotlimitedtotextandrectangles.Hereareafewoftheotherdrawing
functionsavailabletoyouwithSimpleCV(theirfulldocumentationisavailablefrom
SimpleCV):
Circle
Ellipse
Line
Polygon
Beziercurve
AccessingtheWebcam
Luckily,gettingawebcam’svideostreamintoSimpleCVisn’tmuchdifferentthan
accessingimagefilesandloadingthemintomemory.Totryitout,youcanmakeyourown
basicwebcamviewer:
1. Createanewfilenamedbasic-camera.pyandsavethecodeshowninExample11-4
init.
2. Withyourwebcampluggedin,runthescript.Youshouldseeawindowpopupwith
aviewfromthewebcam,asinFigure11-9.
3. Toclosethewindow,pressCtrl-CintheTerminal.
Figure11-9.Outputtingwebcaminputtothedisplay
Example11-4.Sourcecodeforbasic-camera.py
fromSimpleCVimportCamera,Display
fromtimeimportsleep
myCamera=Camera(prop_set={'width':320,'height':240})
myDisplay=Display(resolution=(320,240))
whilenotmyDisplay.isDone():
myCamera.getImage().save(myDisplay)
sleep(.1)
Createanewcameraobjectandsettheheightandwidthoftheimageto320x240for
betterperformance.
Setthesizeofthewindowtobe320x240aswell.
Looptheindentedcodebelowuntilthewindowisclosed.
Getaframefromthewebcamanddisplayitinthewindow.
Waitone-tenthofasecondbetweeneachframe.
YoucanevencombinethecodefromthelasttwoexamplestomakeaPythonscriptthat
willtakeapicturefromthewebcamandsaveitasa.jpgfile:
fromSimpleCVimportCamera
fromtimeimportsleep
myCamera=Camera(prop_set={'width':320,'height':240})
frame=myCamera.getImage()
frame.save("camera-output.jpg")
FaceDetection
OneofthepowerfulfunctionsthatcomesalongwithSimpleCViscalled
findHaarFeatures.It’sanalgorithmthatletsyousearchwithinanimageforpatternsthat
matchaparticularprofile,orcascade.ThereareafewcascadesincludedwithSimpleCV,
suchasface,nose,eye,mouth,andfullbody.Alternatively,youcandownloadorgenerate
yourowncascadefileifneedbe.findHaarFeaturesanalyzesanimageformatches,and
ifitfindsatleastone,thefunctionreturnsthelocationofthosematcheswithintheimage.
Thismeansthatyoucandetectobjectslikecars,animals,orpeoplewithinanimagefileor
fromthewebcam.TotryoutfindHaarFeatures,youcandosomebasicfacedetection:
1. Createanewfileinthesimplecv-testdirectorycalledface-detector.py.
2. EnterthecodeshowninExample11-5.
3. Withyourwebcampluggedinandpointedataface,runthescriptfromthe
commandline.
4. Intheterminalwindow,you’llseethelocationofthefacesthatfindHaarFeatures
finds.Trymovingaroundandwatchingthesenumberschange.Tryholdingupa
photoofafacetothecameratoseewhathappens.
Example11-5.Sourcecodeforface-detector.py
fromSimpleCVimportCamera,Display
fromtimeimportsleep
myCamera=Camera(prop_set={'width':320,'height':240})
myDisplay=Display(resolution=(320,240))
whilenotmyDisplay.isDone():
frame=myCamera.getImage()
faces=frame.findHaarFeatures('face')
iffaces:
forfaceinfaces:
print"Faceat:"+str(face.coordinates())
else:
print"Nofacesdetected."
frame.save(myDisplay)
sleep(.1)
Lookforfacesintheimageframeandsavethemintoafacesobject.
IffindHaarFaturesdetectedatleastoneface,executetheindentedcodebelow.
Foreachfaceinfaces,executethecodebelow(theprintstatement)withfaceasan
individualface.
Ifyourmugisonscreenbutyoustillgetthemessage“Nofacesdetected,”tryafew
troubleshootingsteps:
Doyouhaveenoughlight?Ifyou’reinadarkroom,itmaybehardforthealgorithmto
detectyourface.Tryaddingmorelight.
ThisparticularHaarcascadeismeanttofindfacesthatareintheirnormalorientation.
Ifyoutiltyourheadtoomuchorthecameraisn’tlevel,thiswillaffectthealgorithm’s
abilitytofindfaces.
Project:RaspberryPiPhotobooth
YoucancombinedifferentlibrariestogethertomakePythonapowerfultooltodosome
fairlycomplexprojects.WiththeGPIOlibrary,youlearnedaboutinChapter9and
SimpleCV,youcanmakeyourownRaspberryPi-basedphotobooththat’ssuretobeabig
hitatyournextparty(seeFigure11-10).AndwiththefindHaarFeaturesfunctionin
SimpleCV,youcanenhanceyourphotoboothwithaspecialextrafeature,theabilityto
automaticallysuperimposefunvirtualpropslikehats,monocles,beards,andmustacheson
thepeopleinthephotobooth.ThecodeinthisprojectisbasedontheMustacheinator
projectinPracticalComputerVisionwithSimpleCVbyKurtDemaagd,AnthonyOliver,
NathanOostendorp,andKatherineScott(O’Reilly).
Figure11-10.OutputoftheRaspberryPiPhotobooth
Here’swhatyou’llneedtoturnyourRaspberryPiintoaphotobooth:
AUSBwebcam
Amonitor
Abutton,anykindyoulike
Hookupwire,cuttosize
1resistor,10Kohm
Beforeyougetstarted,makesurethatboththeRPi.GPIOandSimpleCVPythonlibraries
areinstalledandworkingproperlyonyourRaspberryPi.See“InstallingandTesting
GPIOinPython”and“InstallingandTestingSimpleCV”formoredetails.
1. LikeyoudidinChapter9,connectpin24tothebutton.Onesideofthebutton
shouldbeconnectedto3.3V,theothertopin24.Don’tforgettousea10Kpulldownresistorbetweengroundandthesideoftheswitchthatconnectstopin24.
2. Findorcreateasmallimageofablackmustacheonawhitebackgroundandsaveit
asmustache.pnginanewfolderonyourRaspberryPi.Youcanalsodownloadour
premademustachefileinthech09subdirectoryofthedownloads(see“Howto
ContactUs”).
3. Inthatfolder,createanewfilecalledphotobooth.py,typeinthecodelistedin
Example11-6,andsavethefile.
Example11-6.Sourcecodeforphotobooth.py
fromtimeimportsleep,time
fromSimpleCVimportCamera,Image,Display
importRPi.GPIOasGPIO
myCamera=Camera(prop_set={'width':320,'height':240})
myDisplay=Display(resolution=(320,240))
stache=Image("mustache.png")
stacheMask=\
stache.createBinaryMask(color1=(0,0,0),color2=(254,254,254))
stacheMask=stacheMask.invert()
GPIO.setmode(GPIO.BCM)
GPIO.setup(24,GPIO.IN)
defmustachify(frame):
faces=frame.findHaarFeatures('face')
iffaces:
forfaceinfaces:
print"Faceat:"+str(face.coordinates())
myFace=face.crop()
noses=myFace.findHaarFeatures('nose')
ifnoses:
nose=noses.sortArea()[-1]
print"Noseat:"+str(nose.coordinates())
xmust=face.points[0][0]+nose.x-(stache.width/2)
ymust=face.points[0][1]+nose.y+(stache.height/3)
else:
returnframe
frame=frame.blit(stache,pos=(xmust,ymust),mask=stacheMask)
returnframe
else:
returnframe
whilenotmyDisplay.isDone():
inputValue=GPIO.input(24)
frame=myCamera.getImage()
ifinputValue==True:
frame=mustachify(frame)
frame.save("mustache-"+str(time())+".jpg")
frame=frame.flipHorizontal()
frame.show()
sleep(3)
else:
frame=frame.flipHorizontal()
frame.save(myDisplay)
sleep(.05)
Createamaskofthemustache,selectingallbutblacktobetransparent(thetwo
parameters,color1andcolor2,aretherangeofcolorsasRGBvaluesfrom0to255).
Invertthemasksothatonlytheblackpixelsintheimagearedisplayedandallother
pixelsaretransparent.
Createafunctionthattakesinaframeandoutputsaframewithasuperimposed
mustacheifitcanfindthefaceandnose.
Createasubimageofthefacesothatsearchingforanoseisquicker.
Iftherearemultiplenosecandidatesontheface,choosethelargestone.
Setthexcoordinatesofthemustache.
Settheycoordinatesofthemustache.
Ifnonoseisfound,justreturntheframe.
Usetheblitfunction(shortforBLockImageTransfer)tosuperimposethemustache
ontheframe.
Returnthe“mustachified”frame.
Ifnofaceisfound,justreturntheframe.
Passtheframeintothemustachifyfunction.
SavetheframeasaJPEGwiththecurrenttimeinthefilename.
Beforeshowingtheimage,flipithorizontallysothatit’samirrorimageofthesubject.
Holdthesavedimageonscreenforthreeseconds.
Ifthebuttonisn’tpressed,simplyfliptheliveimageanddisplayit.
Nowyou’rereadytogiveitatry.Makesureyourwebcamisconnected.Next,gotothe
terminal,andchangetothedirectorywherethemustacheillustrationandphotobooth.py
areandthenrunthescript:
$sudophotobooth.py
Theoutputofthewebcamwillappearonscreen.Whenthebuttonispressed,itwill
identifyanyfaces,addamustache,andsavetheimage.(Alltheimageswillbesavedin
thesamefolderwiththescript.)
GoingFurther
PracticalComputerVisionwithSimpleCV
ThisbookbyKurtDemaagd,AnthonyOliver,NathanOostendorp,andKatherineScott
isacomprehensiveguidetousingSimpleCV.Itincludesplentyofexamplecodeand
projectstolearnmoreaboutworkingwithimagesandcomputervisioninPython.
Chapter12.PythonandtheInternet
Pythonhasaveryactivecommunityofdeveloperswhooftensharetheirworkintheform
ofopensourcelibrariesthatsimplifycomplextasks.Someoftheselibrariesmakeit
relativelyeasyforustoconnectourprojectstotheInternettodothingslikegetdataabout
theweather,sendanemailortextmessage,followtrendsonTwitter,oractasaweb
server.
Inthischapter,we’regoingtotakealookatafewwaystocreateInternet-connected
projectswiththeRaspberryPi.We’llstartoffbyshowingyouhowtofetchdatafromthe
InternetandthenmoveintohowyoucancreateyourownRaspberryPi-basedwebserver.
DownloadDatafromaWebServer
WhenyoutypeanaddressintoyourwebbrowserandhitEnter,yourbrowseristheclient.
Itestablishesaconnectionwiththeserver,whichrespondswithawebpage.Ofcourse,a
clientdoesn’thavetobeawebbrowser,itcanalsobeamailapplication,aweatherwidget
onyourphoneorcomputer,oragamethatuploadsyourhighscoretoagloballeader
board.Inthefirstpartofthischapter,we’regoingtofocusonprojectsthatusethe
RaspberryPitoactasaclient.Thecodeyou’llbeusingwillconnecttoInternetserversto
getinformation.Beforeyoucandothat,you’llneedtoinstallapopularPythonlibrary
calledRequeststhatisusedforconnectingtowebserversviahypertexttransferprotocol,
orHTTP.Fromtheterminal,here’showyouinstallit:
$sudoapt-getinstallpython-requests
ToconfirmthatRequestsisinstalled:
$python
Python2.7.3rc2(default,May62012,20:02:25)
[GCC4.6.3]onlinux2
Type"help","copyright","credits"or"license"formoreinformation.
>>>importrequests
>>>
Ifyoudon’tgetanerrormessage,you’llknowRequestshasbeeninstalledproperlyandis
nowimportedinthisPythonsession.Nowyoucantryitout:
>>>r=requests.get('http://www.google.com/')
>>>
Youmaybeabitdisappointedatfirstbecauseitseemslikenothinghappened.But
actually,allthedatafromtherequesthasbeenstoredintheobjectr.Here’showyoucan
displaythestatuscode:
>>>r.status_code
200
TheHTTPstatuscode200meansthattherequestsucceeded.ThereareafewotherHTTP
statuscodesinTable12-1.
Table12-1.Common
HTTPstatuscodes
Code Meaning
200
OK
301
Movedpermanently
307
Movedtemporarily
401
Unauthorized
404
Notfound
500
Servererror
Ifyouwanttoseethecontentsoftheresponse(whattheserversendsbacktoyou),trythe
following:
>>>r.text
Ifeverythingworkedcorrectly,whatwillfollowisalargeblockoftext;youmaynotice
somehuman-readablebitsinthere,butmostofitwillbehardtounderstand.Thisisthe
HTMLofGoogle’slandingpage,whichismeanttobeinterpretedandrenderedonscreen
byawebbrowser.
However,notallHTTPrequestsaremeanttoberenderedbyawebbrowser.Sometimes
onlydataistransmitted,withnoinformationabouthowitshouldbedisplayed.Manysites
makethesedataprotocolsavailabletothepublicsothatwecanusethemtofetchdata
fromandsenddatatotheirserverswithoutusingawebbrowser.Whetherit’spublicor
not,adataprotocolspecificationiscommonlycalledanapplicationprogramming
interfaceorAPI.APIsletdifferentpiecesofsoftwaretalktoeachotherandarepopular
forsendingdatafromonesitetoanotherovertheInternet.
Forexample,let’ssayyouwanttomakeaprojectthatwillsitbyyourdoorandremind
youtotakeyourumbrellawithyouwhenrainisexpectedthatday.Insteadofsettingup
yourownweatherstationandfiguringouthowtoforecasttheprecipitation,youcanget
theday’sforecastfromoneofmanyweatherAPIsoutthere.
FetchingtheWeatherForecast
Inordertodeterminewhetherornotitwillraintoday,we’llshowyouhowtousetheAPI
fromWeatherUnderground.
Note
KeepinmindthatnotallAPIsarecreatedequalandyou’llhavetoreviewtheir
documentationtodetermineifit’stherightoneforyourproject.Also,mostAPIslimitthe
amountofrequestsyoucanmakeandsomeevenchargeyoutousetheirservices.Many
times,theAPIprovidershaveafreetierforasmallamountofdailyrequests,whichis
perfectforexperimentationandpersonaluse.
TousetheAPI,takethefollowingsteps:
1. Inawebbrowser,gotoWeatherUnderground’sAPIhomepageandenterinyour
informationtosignup.
2. Afteryou’veloggedintoyouraccount,clickKeySettings.
3. Noticethatthere’salongstringofcharactersintheAPIkeyfield(Figure12-1).This
isauniqueidentifierforyouraccountthatyou’llneedtoprovideineachrequest.If
youabusetheirserversbysendingtoomanyrequests,theycansimplyshutoffthis
APIkeyandrefusetocompleteanyfurtherrequestsuntilyoupayforahighertierof
service.
4. ClickDocumentationandthenForecastsoyoucanseewhatkindofdatayouget
whenyoumakeaforecastrequest.AtthebottomofthepageisanexampleURLfor
gettingtheforecastforSanFrancisco,CA.NoticethatintheURLisyourAPIkey:
http://api.wunderground.com/api/YourAPIkey/forecast/q/CA/San_Francisco.json
Figure12-1.Matt’sWeatherUndergroundAPIaccount,withtheAPIkey
intheupperright
5. Tomakesureitworks,gotothisURLintoyourwebbrowser,andyoushouldsee
theweatherforecastdatainaformatcalledJSON,orJavaScriptObjectNotation(see
Example12-1).Noticehowthedataisstructuredhierarchically.
Note
EventhoughtheJstandsforJavaScript,JSONisusedinmanyprogramminglanguages,
especiallyforcommunicatingbetweenapplicationsviaanAPI.
6. Tostartoff,trytogettoday’slocaltextforecastfromwithinthisdatastructure.
ChangetheURLsothatitmatchesyourstateandtownandputitinanewPython
scriptcalledtext-forecast.py(Example12-2).
7. Asyouseefromthecode,inordertogetthetextforecastfortoday,we’llhaveto
fetchtherightfieldfromthehierarchyofthedatastructure(seeExample12-1).The
textforecastcanbefoundinforecast→txt_forecast→forecastday→0(thefirst
entry,whichistoday’sforecast)→fcttext.
8. Whenyourunthescriptfromthecommandline,theoutputshouldbeyourlocal
weatherforecastfortoday,suchasthis:“Clear.Highof47F.WindsfromtheNEat5
to10mph.”
Example12-1.PartialJSONresponsefromWeatherUnderground’sAPI
"response":{
"version":"0.1",
"termsofService":
"http://www.wunderground.com/weather/api/d/terms.html",
"features":{
"forecast":1
}
},
"forecast":{
"txt_forecast":{
"date":"10:00AMEST",
"forecastday":[
{
"period":0,
"icon":"partlycloudy",
"icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",
"title":"Tuesday",
"fcttext":
"Partlycloudy.Highof48F.WindsfromtheNNEat5to10mph.",
"fcttext_metric":
"Partlycloudy.Highof9C.WindsfromtheNNEat10to15km/h.",
"pop":"0"
},
Forecastisthetop-levelparentofthedatawewanttoaccess.
Withinforecast,wewantthetextforecast.
Withinthetextforecastdataset,wewantthedailyforecasts.
fcttext,thetextoftheday’sforecast.
Example12-2.Sourcecodefortext-forecast.py
importrequests
key='YOURKEYHERE'
ApiUrl=\
'http://api.wunderground.com/api/'+key+'/forecast/q/NY/New_York.json'
r=requests.get(ApiUrl)
forecast=r.json
printforecast['forecast']['txt_forecast']['forecastday'][0]['fcttext']
ReplacethiswithyourAPIkey.
GettheNewYorkCityforecastfromWeatherUnderground(replacewithyourown
stateandcity).
TakethetextoftheJSONresponseandparseitintoaPythondictionaryobject.
“Reachinto”thedatahierarchytogettoday’sforecasttext.
SoyounowhaveaPythonscriptthatwilloutputthetextforecastwheneveryouneedit.
ButhowcanyourRaspberryPideterminewhetherornotit’ssupposedtoraintoday?On
onehand,youcouldparsetheforecasttexttosearchforwordslike“rain,”“drizzle,”
“thunderstorms,”“showers,”andsoon,butthere’sactuallyabetterway.Oneofthefields
inthedatafromWeatherUndergroundAPIislabeledpop,whichstandsforprobabilityof
precipitation.Withvaluesrangingfrom0to100%,itwillgiveyouasenseofhowlikelyit
willberainingorsnowing.
Forarainforecastindicator,let’ssaythatanyprobabilityofprecipitationvalueover30%
isadaythatwewanttohaveanumbrellahandy:
1. ConnectanLEDtopin25,asyoudidinFigure8-4.
2. Createanewfilecalledumbrella-indicator.pyandusethecodeinExample12-3.
Don’tforgettoputinyourownAPIkeyandthelocationintheWeather
UndergroundAPIURL.
3. Runthescriptasrootwiththecommandsudopythonumbrella-indicator.py.
Example12-3.Sourcecodeforumbrella-indicator.py
importrequests
importRPi.GPIOasGPIO
importtime
GPIO.setmode(GPIO.BCM)
GPIO.setup(25,GPIO.OUT)
key='YOURKEYHERE'
ApiUrl=\
'http://api.wunderground.com/api/'+key+'/forecast/q/NY/New_York.json'
whileTrue:
r=requests.get(ApiUrl)
forecast=r.json
popValue=forecast['forecast']['txt_forecast']['forecastday'][0]['pop']
popValue=int(popValue)
ifpopValue>=30:
GPIO.output(25,GPIO.HIGH)
else:
GPIO.output(25,GPIO.LOW)
time.sleep(180)#3minutes
Asbefore,changethistoyourAPIkey.
Gettoday’sprobabilityofprecipitationandstoreitinpopValue.
ConvertpopValuefromastringintoanintegersothatwecanevaluateitasanumber.
Ifthevalueisgreaterthan30,thenturntheLEDon.
Otherwise,turntheLEDoff.
WaitthreeminutesbeforecheckingagainsothatthescriptstayswithintheAPIlimitof
500requestsperday.
PressCtrl-Ctoquittheprogramwhenyou’redone.
TheWeatherUndergroundAPIisoneofaplethoraofdifferentAPIsthatyoucan
experimentwith.Table12-2listsafewothersitesandservicesthathaveAPIs.
Table12-2.Popularapplication
programminginterfaces
Site
APIReferenceURL
Facebook
https://developers.facebook.com
Flickr
http://www.flickr.com/services/api/
Foursquare https://developer.foursquare.com
Reddit
https://github.com/reddit/reddit/wiki/API
Twilio
http://www.twilio.com
Twitter
https://dev.twitter.com
YouTube
https://developers.google.com/youtube/
ServingPi(BeaWebServer)
NotonlycanyouusetheRaspberryPitogetdatafromserversviatheInternet,butyourPi
canalsoactasaserveritself.Therearemanydifferentwebserversthatyoucaninstallon
theRaspberryPi.Traditionalwebservers,likeApacheorlighttpd,servethefilesfrom
yourboardtoclients.Mostofthetime,serverslikethesearesendingHTMLfilesand
imagestomakewebpages,buttheycanalsoservesound,video,executableprograms,
andmuchmore.
However,there’sanewbreedoftoolsthatextendprogramminglanguageslikePython,
Ruby,andJavaScripttocreatewebserversthatdynamicallygeneratetheHTMLwhen
theyreceiveHTTPrequestsfromawebbrowser.Thisisagreatwaytotriggerphysical
events,storedata,orcheckthevalueofasensorremotelyviaawebbrowser.Youcan
evencreateyourownJSONAPIforanelectronicsproject!
FlaskBasics
We’regoingtouseaPythonwebframeworkcalledFlasktoturntheRaspberryPiintoa
dynamicwebserver.Whilethere’salotyoucandowithFlask“outofthebox,”italso
supportsmanydifferentextensionsfordoingthings,suchasuserauthentication,
generatingforms,andusingdatabases.Youalsohaveaccesstothewidevarietyof
standardPythonlibrariesthatareavailabletoyou.
InordertoinstallFlask,you’llneedtohavePipinstalled.Ifyouhaven’talreadyinstalled
pip,it’seasytodo:
$sudoapt-getinstallpython-pip
Afterpipisinstalled,youcanuseittoinstallFlaskanditsdependencies:
$sudopipinstallflask
Totesttheinstallation,createanewfilecalledhello-flask.pywiththecodefrom
Example12-4.Don’tworryifitlooksabitoverwhelmingatfirst;youdon’tneedto
understandwhateverylineofcodemeansrightnow.Theblockofcodethat’smost
importantistheonethatcontainsthestring“HelloWorld!”
Example12-4.Sourcecodeforhello-flask.py
fromflaskimportFlask
app=Flask(__name__)
@app.route("/")
defhello():
return"HelloWorld!"
if__name__=="__main__":
app.run(host='0.0.0.0',port=80,debug=True)
CreateaFlaskobjectcalledapp.
RunthecodebelowwhensomeoneaccessestherootURLoftheserver.
Sendthetext“HelloWorld!”totheclient.
Ifthisscriptwasrundirectlyfromthecommandline.
Havetheserverlistenonport80andreportanyerrors.
Note
Beforeyourunthescript,youneedtoknowyourRaspberryPi’sIPaddress(see“The
Network”).Analternativeistoinstallavahi-daemon(runsudoapt-getinstallavahidaemonfromthecommandline).ThisletsyouaccessthePionyourlocalnetworkthrough
theaddresshttp://raspberrypi.local.Ifyou’reaccessingtheRaspberryPiwebserverfrom
aWindowsmachine,youmayneedtoputBonjourServicesonitforthistowork.
Nowyou’rereadytoruntheserver,whichyou’llhavetodoasroot:
$sudopythonhello-flask.py
*Runningonhttp://0.0.0.0:80/
*Restartingwithreloader
FromanothercomputeronthesamenetworkastheRaspberryPi,typeyourRaspberry
Pi’sIPaddressintoawebbrowser.Ifyourbrowserdisplays“HelloWorld!”,youknow
you’vegotitconfiguredcorrectly.Youmayalsonoticethatafewlinesappearinthe
terminaloftheRaspberryPi:
10.0.1.100--[19/Nov/201200:31:31]"GET/HTTP/1.1"20010.0.1.100--[19/Nov/201200:31:31]"GET/favicon.icoHTTP/1.1"404-
ThefirstlineshowsthatthewebbrowserrequestedtherootURLandourserverreturned
HTTPstatuscode200for“OK.”Thesecondlineisarequestthatmanywebbrowsers
sendautomaticallytogetasmalliconcalledafavicontodisplaynexttotheURLinthe
browser’saddressbar.Ourserverdoesn’thaveafavicon.icofile,soitreturnedHTTP
statuscode404toindicatethattheURLwasnotfound.
IfyouwanttosendthebrowserasiteformattedinproperHTML,itdoesn’tmakealotof
sensetoputalltheHTMLintoyourPythonscript.Flaskusesatemplateenginecalled
Jinja2sothatyoucanuseseparateHTMLfileswithplaceholdersforspotswhereyou
wantdynamicdatatobeinserted.
Ifyou’vestillgothello-flask.pyrunning,pressCtrl-Ctokillit.
Tomakeatemplate,createanewfilecalledhello-template.pywiththecodefrom
Example12-5.Inthesamedirectorywithhello-template.py,createasubdirectorycalled
templates.Inthetemplatessubdirectory,createafilecalledmain.htmlandinsertthecode
fromExample12-6.AnythingindoublecurlybraceswithintheHTMLtemplateis
interpretedasavariablethatwouldbepassedtoitfromthePythonscriptviathe
render_templatefunction.
Example12-5.Sourcecodeforhello-template.py
fromflaskimportFlask,render_template
importdatetime
app=Flask(__name__)
@app.route("/")
defhello():
now=datetime.datetime.now()
timeString=now.strftime("%Y-%m-%d%H:%M")
templateData={
'title':'HELLO!',
'time':timeString
}
returnrender_template('main.html',**templateData)
if__name__=="__main__":
app.run(host='0.0.0.0',port=80,debug=True)
Getthecurrenttimeandstoreitinnow.
Createaformattedstringusingthedateandtimefromthenowobject.
Createadictionaryofvariables(asetofkeys,suchastitlethatareassociatedwith
values,suchasHELLO!)topassintothetemplate.
Returnthemain.htmltemplatetothewebbrowserusingthevariablesinthe
templateDatadictionary.
Example12-6.Sourcecodefortemplates/main.html
<!DOCTYPEhtml>
<head>
<title>{{title}}</title>
</head>
<body>
<h1>Hello,World!</h1>
<h2>Thedateandtimeontheserveris:{{time}}</h2>
</body>
</html>
UsethetitlevariableintheHTMLtitleofthesite.
Usethetimevariableonthepage.
Now,whenyourunhello-template.py(asbefore,youneedtousesudotorunit)andpull
upyourRaspberryPi’saddressinyourwebbrowser,youshouldseeaformattedHTML
pagewiththetitle“HELLO!”andtheRaspberryPi’scurrentdateandtime.
Note
Whileit’sdependentonhowyournetworkissetup,it’sunlikelythatthispageis
accessiblefromoutsideyourlocalnetworkviatheInternet.Ifyou’dliketomakethepage
availablefromoutsideyourlocalnetwork,you’llneedtoconfigureyourrouterforport
forwarding.Refertoyourrouter’sdocumentationformoreinformationabouthowtodo
this.
ConnectingtheWebtotheRealWorld
YoucanuseFlaskwithotherPythonlibrariestobringadditionalfunctionalitytoyoursite.
Forexample,withtheRPi.GPIOPythonmodule(seeChapter9),youcancreateawebsite
thatinterfaceswiththephysicalworld.Totryitout,hookupathreebuttonsorswitchesto
pins23,24,and25inthesamewayastheSimpleSoundboardprojectinFigure9-2.
Thefollowingcodeexpandsthefunctionalityofhello-template.py,socopyittoanewfile
calledhello-gpio.py.AddtheRPi.GPIOmoduleandanewrouteforreadingthebuttons,
aswe’vedoneinExample12-7.Thenewroutewilltakeavariablefromtherequested
URLandusethattodeterminewhichpintoread.
You’llalsoneedtocreateanewtemplatecalledpin.html(it’snotverydifferentfrom
main.html,soyoumaywanttocopymain.htmltopin.htmlandmaketheappropriate
changes,asinExample12-8):
Example12-7.Modifiedsourcecodeforhello-pgio.py
fromflaskimportFlask,render_template
importdatetime
importRPi.GPIOasGPIO
app=Flask(__name__)
GPIO.setmode(GPIO.BCM)
@app.route("/")
defhello():
now=datetime.datetime.now()
timeString=now.strftime("%Y-%m-%d%H:%M")
templateData={
'title':'HELLO!',
'time':timeString
}
returnrender_template('main.html',**templateData)
@app.route("/readPin/<pin>")
defreadPin(pin):
try:
GPIO.setup(int(pin),GPIO.IN)
ifGPIO.input(int(pin))==True:
response="Pinnumber"+pin+"ishigh!"
else:
response="Pinnumber"+pin+"islow!"
except:
response="Therewasanerrorreadingpin"+pin+"."
templateData={
'title':'StatusofPin'+pin,
'response':response
}
returnrender_template('pin.html',**templateData)
if__name__=="__main__":
app.run(host='0.0.0.0',port=80,debug=True)
Addadynamicroutewithpinnumberasavariable.
Ifthecodeindentedbelowraisesanexception,runthecodeintheexceptblock.
TakethepinnumberfromtheURL,convertitintoaninteger,andsetitasaninput.
Ifthepinishigh,settheresponsetexttosaythatit’shigh.
Otherwise,settheresponsetexttosaythatit’slow.
Iftherewasanerrorreadingthepin,settheresponsetoindicatethat.
Example12-8.Sourcecodefortemplates/pin.html
<!DOCTYPEhtml>
<head>
<title>{{title}}</title>
</head>
<body>
<h1>PinStatus</h1>
<h2>{{response}}</h2>
</body>
</html>
Insertthetitleprovidedfromhello-gpio.pyintothepage’stitle.
Placetheresponsefromhello-gpio.pyonthepageinsideHTMLheadingtags.
Withthisscriptrunning,whenyoupointyourwebbrowsertoyourRaspberryPi’sIP
address,youshouldseethestandard“HelloWorld!”pagewecreatedbefore.Butadd
/readPin/24totheendoftheURLsothatitlookssomethinglike
http://10.0.1.103/readPin/24.Apageshoulddisplayshowingthatthepinisbeing
readaslow.Nowholddownthebuttonconnectedtopin24andrefreshthepage;itshould
nowshowupashigh!
TrytheotherbuttonsaswellbychangingtheURL.Thegreatpartaboutthiscodeisthat
weonlyhadtowritethefunctiontoreadthepinonceandcreatetheHTMLpageonce,but
it’salmostasthoughthereareseparatewebpagesforeachofthepins!
Project:WebLamp
InChapter8,weshowedyouhowtouseRaspberryPiasasimpleACoutlettimerin
“Project:CronLampTimer”.NowthatyouknowhowtousePythonandFlask,youcan
nowcontrolthestateofalampovertheWeb.Thisbasicprojectissimplyastartingpoint
forcreatingInternet-connecteddeviceswiththeRaspberryPi.
AndjustlikehowthepreviousFlaskexampleshowedhowyoucanhavethesamecode
workonmultiplepins,you’llsetupthisprojectsothatifyouwanttocontrolmore
devicesinthefuture,it’seasytoadd:
1. Thehardwaresetupforthisprojectisexactlythesameasthe“Project:CronLamp
Timer”,soallthepartsyouneedarelistedthere.
2. ConnectthePowerSwitchTailIIrelaytothepin25,justasyoudidwithintheCron
LampTimerproject.
3. IfyouhaveanotherPowerSwitchTailIIrelay,connectittopin24tocontrola
secondACdevice.Otherwise,justconnectanLEDtopin24.We’resimplyusingit
todemonstratehowmultipledevicescanbecontrolledwiththesamecode.
4. CreateanewdirectoryinyourhomedirectorycalledWebLamp.
5. InWebLamp,createafilecalledweblamp.pyandputinthecodefromExample12-9
6. CreateanewdirectorywithinWebLampcalledtemplates.
7. Insidetemplates,createthefilemain.html.Thesourcecodeofthisfilecanbefound
inExample12-10.
Interminal,navigatetotheWebLampdirectoryandstarttheserver(besuretouseCtrl-C
tokillanyotherFlaskserveryouhaverunningfirst):
[email protected]~/WebLamp$sudopythonweblamp.py
Openyourmobilephone’swebbrowserandenteryourRaspberryPi’sIPaddressinthe
addressbar,asshowninFigure12-2.
Figure12-2.Thedeviceinterface,asviewedthroughamobilebrowser
Example12-9.Sourcecodeforweblamp.py
importRPi.GPIOasGPIO
fromflaskimportFlask,render_template,request
app=Flask(__name__)
GPIO.setmode(GPIO.BCM)
pins={
24:{'name':'coffeemaker','state':GPIO.LOW},
25:{'name':'lamp','state':GPIO.LOW}
}
forpininpins:
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin,GPIO.LOW)
@app.route("/")
defmain():
forpininpins:
pins[pin]['state']=GPIO.input(pin)
templateData={
'pins':pins
}
returnrender_template('main.html',**templateData)
@app.route("/<changePin>/<action>")
defaction(changePin,action):
changePin=int(changePin)
deviceName=pins[changePin]['name']
ifaction=="on":
GPIO.output(changePin,GPIO.HIGH)
message="Turned"+deviceName+"on."
ifaction=="off":
GPIO.output(changePin,GPIO.LOW)
message="Turned"+deviceName+"off."
ifaction=="toggle":
GPIO.output(changePin,notGPIO.input(changePin))
message="Toggled"+deviceName+"."
forpininpins:
pins[pin]['state']=GPIO.input(pin)
templateData={
'message':message,
'pins':pins
}
returnrender_template('main.html',**templateData)
if__name__=="__main__":
app.run(host='0.0.0.0',port=80,debug=True)
Createadictionarycalledpinstostorethepinnumber,name,andpinstate.
Seteachpinasanoutputandmakeitlow.
Foreachpin,readthepinstateandstoreitinthepinsdictionary.
Putthepindictionaryintothetemplatedatadictionary.
Passthetemplatedataintothetemplatemain.htmlandreturnittotheuser.
ThefunctionbelowisexecutedwhensomeonerequestsaURLwiththepinnumberand
actioninit.
ConvertthepinfromtheURLintoanint.
Getthedevicenameforthepinbeingchanged.
IftheactionpartoftheURLis“on,”executethecodeindentedbelow.
Setthepinhigh.
Savethestatusmessagetobepassedintothetemplate.
Readthepinandsetittowhateveritisn’t(i.e.,toggleit).
Foreachpin,readthepinstateandstoreitinthepinsdictionary.
Alongwiththepindictionary,putthemessageintothetemplatedatadictionary.
Example12-10.Sourcecodefortemplates/main.html
<!DOCTYPEhtml>
<head>
<title>CurrentStatus</title>
</head>
<body>
<h1>DeviceListingandStatus</h1>
{%forpininpins%}
<p>The{{pins[pin].name}}
{%ifpins[pin].state==true%}
iscurrentlyon(<ahref="/{{pin}}/off">turnoff</a>)
{%else%}
iscurrentlyoff(<ahref="/{{pin}}/on">turnon</a>)
{%endif%}
</p>
{%endfor%}
{%ifmessage%}
<h2>{{message}}</h2>
{%endif%}
</body>
</html>
Runthrougheachpininthepinsdictionary.
Printthenameofthepin.
Ifthepinishigh,printthatthedeviceisonandlinktoURLtoturnitoff.
Otherwise,printthatthedeviceisoffandlinktotheURLtoturniton.
Ifamessagewaspassedintothetemplate,printit.
Thebestpartaboutwritingthecodeinthiswayisthatyoucanveryeasilyaddasmany
devicesthatthehardwarewillsupport.Simplyaddtheinformationaboutthedevicetothe
pinsdictionary.Whenyourestarttheserver,thenewdevicewillappearinthestatuslist
anditscontrolURLswillworkautomatically.
There’sanothergreatfeaturebuiltin:ifyouwanttobeabletofliptheswitchonadevice
withasingletaponyourphone,youcancreateabookmarktotheaddress
http://ipaddress/pin/toggle.ThatURLwillcheckthepin’scurrentstateandswitchit.
GoingFurther
Requests
ThehomepageforRequestsincludesverycomprehensivedocumentationcompletewith
easy-to-understandexamples.
Flask
There’salotmoretoFlaskthatwedidn’tcover.TheofficialsiteoutlinesFlask’sfull
featureset.
FlaskExtensions
Flaskextensionsmakeiteasytoaddfunctionalitytoyoursite.
AppendixA.WritinganSDCardImage
WhilethisbookhasfocusedontheRaspbianoperatingsystem,therearemanyother
distributionsthatcanrunontheRaspberryPi.Withanyofthem,youneedtosimply
downloadthediskimageandthennot-so-simplycopythediskimageontotheSDcard.
Here’showtocreateanSDcardfromadiskimageonOSX,Windows,andLinux.
WritinganSDCardfromOSX
1. OpenyourTerminalutility(it’sin/Applications/Utilities)togetacommand-line
prompt.
2. Withoutthecardinyourcomputer’sSDcardreader,typedf-h.Thedfprogram
showsyourfreespace,butitalsoshowswhichdiskvolumesaremounted.
3. NowinserttheSDcardandrundf-hagain.
4. LookatthelistofmountedvolumesanddeterminewhichoneistheSDcardby
comparingittothepreviousoutput.Forexample,anSDcardmountsonour
computeras/Volumes/Untitled,andthedevicenameis/dev/disk3s1.Dependingon
theconfigurationofyourcomputer,thisnamemayvary.Namesareassignedas
devicesaremounted,soyoumayseeahighernumberifyouhaveotherdevicesor
diskimagesmountedintheFinder.Writethecard’sdevicenamedown.
5. Towritetothecardyou’llhavetounmountitfirst.Unmountitbytypingsudo
diskutilunmount/dev/disk3s1(usingthedevicenameyougotfromtheprevious
stepinsteadof/dev/disk3s1).NotethatyoumustusethecommandlineorDisk
Utilitytounmount.IfyoujustejectitfromtheFinder,you’llhavetotakeitoutand
reinsertit(andyou’llstillneedtounmountitfromthecommandlineorDisk
Utility).Ifthecardfailstounmount,makesuretocloseanyFinderwindowsthat
mightbeopenonthecard.
6. Next,you’llneedtofigureouttherawdevicenameofthecard.Takeyourdevice
nameandreplacediskwithrdiskandleaveoffthes1(whichisthepartition
number).Forexample,therawdevicenameforthedevice/dev/disk3s1is
/dev/rdisk3.
Warning
Itisreallyimportantthatyougettherawdevicenamecorrect!Youcanoverwriteyour
harddriveandlosedataifyoustartwritingtoyourharddriveinsteadoftheSDcard.Use
dfagaintodouble-checkbeforeyoucontinue.
7. Makesurethatthedownloadedimageisunzippedandsittinginyourhome
directory.You’llbeusingtheUnixutilityddtocopytheimagebitbybittotheSD
card.Belowisthecommand;justreplacethenameofthediskimagewiththeone
youdownloaded,andreplace/dev/rdisk3withtherawdevicenameoftheSDcard
fromstep6.
YoucanlearnmoreaboutthecommandlineinChapter3,butyou’reessentially
tellingddtorunasrootandcopytheinputfile(if)totheoutputfile(of):
sudoddbs=1mif=~/2012-09-18-wheezy-raspbian.imgof=/dev/rdisk3
8. Itwilltakeafewminutestocopythewholediskimage.Unfortunately,dddoesnot
provideanyvisualfeedback,soyou’lljusthavetowait.Whenit’sdone,itwillshow
yousomestatistics;ejecttheSDcardandyou’rereadytotryitonthePi.
WritinganSDCardfromWindows
1. DownloadtheWin32DiskImagerprogram.
2. InserttheSDcardinyourreaderandnotethedriveletterthatpopsupinWindows
Explorer.
3. OpenWin32DiskImagerandselecttheRaspbiandiskimage.
4. SelecttheSDcard’sdriveletter,thenclickWrite.IfWin32DiskImagerhasproblems
writingtothecard,tryreformattingitinWindowsExplorer.
5. EjecttheSDcardandputitinyourRaspberryPi;you’regoodtogo!
WritinganSDCardfromLinux
TheinstructionsforLinuxaresimilartothosefortheMac:
1. Openyouranewshellandwithoutthecardinthereader,typedf-htoseewhich
diskvolumesaremounted.
2. NowinserttheSDcardandrundf-hagain.
3. LookatthelistofmountedvolumesanddeterminewhichoneistheSDcardby
comparingittothepreviousoutput.Findthedevicename,whichshouldbe
somethinglike/dev/sdd1.Dependingontheconfigurationofyourcomputer,this
namemayvary.Writethecard’sdevicenamedown.
4. Towritetothecard,you’llhavetounmountitfirst.Unmountitbytypingumount
/dev/sdd1(usingthedevicenameyougotfromthepreviousstepinsteadof
/dev/sdd1).Ifthecardfailstounmount,makesureitisnottheworkingdirectoryin
anyopenshells.
5. Next,you’llneedtofigureouttherawdevicenameofthecard,whichisthedevice
namewithoutthepartitionnumber.Forexample,ifyourdevicenamewas
/dev/sdd1,therawdevicenameis/dev/sdd.
Warning
Itisreallyimportantthatyougettherawdevicenamecorrect!Youcanoverwriteyour
harddriveandlosedataifyoustartwritingtoyourharddriveinsteadoftheSDcard.Use
dfagaintodouble-checkbeforeyoucontinue.
6. Makesurethatthedownloadedimageisunzippedandsittinginyourhome
directory.You’llbeusingtheUnixutilityddtocopytheimagebitbybittotheSD
card.Hereisthecommand—justreplacethenameofthediskimagewiththeone
youdownloaded,andreplace/dev/sddwiththerawdevicenameoftheSDcard
fromstep5:
sudoddbs=1Mif=~/2012-09-18-wheezy-raspbian.imgof=/dev/sdd
Thiscommandtellsddtorunasrootandcopytheinputfile(if)totheoutputfile
(of).
8. Itwilltakeafewminutestocopythewholediskimage.Unfortunately,dddoesnot
provideanyvisualfeedback,soyou’lljusthavetowait.
Whenit’sdone,itwillshowyousomestatistics.ItshouldbeOKtoejectthedisk,
butjusttomakesureitissafe,runsudosync,whichwillflushthefilesystemwrite
buffers.
9. EjectthecardandinsertitinyourRaspberryPi.Goodtogo!
BerryBoot
AsecondwaytogettheOSontoanSDcardistousetheBerryBootutility.BerryBootispartoftheBerryTerminal
thinclientproject,andwillletyouputmultipleoperatingsystemsonasinglecard.YouputtheBerryBootimageon
anSDcard,bootitupontheRaspberryPi,andaninteractiveinstallerallowsyoutoselectanOSfromalist.Note
thatyou’llhavetobeconnectedtoanetworkforBerryBoottowork.
AbouttheAuthors
MattRichardsonisaBrooklyn-basedcreativetechnologistandcontributingeditorfor
MAKEmagazine.He’salsotheownerofAwesomeButtonStudios,atechnology
consultancy.HighlightsfromhisworkincludetheDescriptiveCamera(acamerawhich
outputsatextdescriptioninsteadofaphoto)andTheEnoughAlready(aDIYcelebritysilencingdevice).Matt’sworkhasbeenfeaturedatTheNevadaMuseumofArt,The
RomeInternationalPhotographyFestival,andMilanDesignWeek,andhasgarnered
attentionfromtheNewYorkTimes,Wired,andNewYorkMagazine.
ShawnWallacedesignsopenhardwarekitsandproductsatModernDevicein
Providence,RhodeIsland.HeisamemberoftheFluxamaartistcollectiveresponsiblefor
newiOSmusicalinstrumentssuchasNoisemusickandDR-OM.Hewasalsoaneditorat
O’ReillyMediaandMakerMediaandtaughtatthelocalchapteroftheFabAcademyin
theProvidenceFabLab.ForyearshewasthemanagingdirectoroftheAS220artspace
andisacofounderoftheSMTComputingSociety.
ThecoverimageisbyMarcDeVinck.ThecoverandbodyfontisBentonSans,the
headingfontisSerifa,andthecodefontisBitstreamVeraSansMono.
1. Preface
a. WhatCanYouDowithIt?
b. RaspberryPiforMakers
c. LinuxandRaspberryPi
d. WhatOthersHaveDonewithIt
e. ConventionsUsedinThisBook
f. UsingCodeExamples
g. Safari®BooksOnline
h. HowtoContactUs
i. Acknowledgments
2. 1.GettingUpandRunning
a. ATouroftheBoards
b. TheProperPeripherals
i. TheCase
c. ChooseYourDistribution
d. FlashtheSDCard
i. ForAdvancedUsers:CreateYourOwnDiskImage
e. BootingUp
f. ConfiguringYourPi
g. ShuttingDown
i. RunningHeadless
h. Troubleshooting
i. GoingFurther
3. 2.GettingAroundLinuxontheRaspberryPi
a. UsingtheCommandLine
i. FilesandtheFilesystem
b. MoreLinuxCommands
i. Processes
ii. SudoandPermissions
iii. TheNetwork
c. /etc
d. SettingtheDateandTime
e. InstallingNewSoftware
f. SoundinLinux
g. UpgradingYourFirmware
h. GoingFurther
4. 3.SpecializedDistributions
a. DistributionsforHomeTheater
b. DistributionsforMusic
c. HardwareHackingwithOccidentalis
d. RetrocomputingandRetrogaming
e. OtherUsefulDistributions
f. GoingFurther
5. 4.PythononthePi
a. Hello,Python
b. ABitMorePython
c. ObjectsandModules
d. EvenMoreModules
e. LaunchingOtherProgramsfromPython
f. TroubleshootingErrors
g. GoingFurther
6. 5.PygameforAnimationandMultimedia
a. Hello,Pygame
b. PygameSurfaces
c. DrawingonSurfaces
d. HandlingEventsandInputs
e. Sprites
f. PlayingSound
g. PlayingVideo
h. GoingFurther
7. 6.ScratchonthePi
a. Hello,Scratch
b. TheStage
c. TwoMoreThingstoKnowaboutSprites
d. ABiggerExample:AstralTrespassers
e. ScratchandtheRealWorld
f. SharingYourPrograms
g. GoingFurther
8. 7.ArduinoandthePi
a. InstallingArduinoinRaspbian
i. FindingtheSerialPort
b. TalkinginSerial
c. UsingFirmata
d. GoingFurther
9. 8.BasicInputandOutput
a. UsingInputsandOutputs
i. DigitalOutput:LightingUpanLED
ii. DigitalInput:ReadingaButton
b. Project:CronLampTimer
i. ScriptingCommands
ii. ConnectingaLamp
iii. SchedulingCommandswithcron
c. GoingFurther
10. 9.ProgrammingInputsandOutputswithPython
a. InstallingandTestingGPIOinPython
b. BlinkinganLED
c. ReadingaButton
d. Project:SimpleSoundboard
e. GoingFurther
11. 10.AnalogInputandOutput
a. Output:ConvertingDigitaltoAnalog
i. TestDrivingPWM
ii. TakingPWMFurther
b. Input:ConvertingAnalogtoDigital
i. VariableResistors
c. GoingFurther
12. 11.WorkingwithCameras
a. ConnectingandTestingtheCameraModule
i. Project:MakingaGIF
ii. CapturingVideo
b. TestingUSBWebcams
c. InstallingandTestingSimpleCV
i. AdditionalStepsfortheRaspberryPiCameraModule
d. DisplayinganImage
e. ModifyinganImage
f. AccessingtheWebcam
g. FaceDetection
h. Project:RaspberryPiPhotobooth
i. GoingFurther
13. 12.PythonandtheInternet
a. DownloadDatafromaWebServer
i. FetchingtheWeatherForecast
b. ServingPi(BeaWebServer)
i. FlaskBasics
c. ConnectingtheWebtotheRealWorld
d. Project:WebLamp
e. GoingFurther
14. A.WritinganSDCardImage
a. WritinganSDCardfromOSX
b. WritinganSDCardfromWindows
c. WritinganSDCardfromLinux
15. Index
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement