GettingStartedwithRaspberryPiZero
TableofContents
GettingStartedwithRaspberryPiZero
Credits
AbouttheAuthor
AbouttheReviewer
www.PacktPub.com
eBooks,discountoffers,andmore
Whysubscribe?
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Downloadingthecolorimagesofthisbook
Errata
Piracy
Questions
1.GettingStartedwithRaspberryPiZero
SettinguptheRaspberryPiZero
Poweringtheboard
Hookingupakeyboard,mouse,anddisplay
Installingtheoperatingsystem
AddingInternetaccess
AccessingyourRaspberryPiZerofromyourhostPC
Summary
2.ProgrammingRaspberryPiZero
PoweringupRaspberryPiZerowithLinux
Creating,editing,andsavingfiles
CreatingandrunningPythonprograms
BasicprogrammingconstructsonRaspberryPiZero
Theifstatement
Thewhilestatement
Workingwithfunctions
Libraries/modulesinPython
Summary
3.AccessingtheGPIOPinsonRaspberryPiZero
TheGPIOcapabilityofRaspberryPiZero
SimpleGPIOdigitalvoltageoutput
RaspberryPiZeroandLEDcode
Addingasonarsensor
RaspberryPiZeroandthesonarsensorcode
ConnectingadigitalcompasstoRaspberryPiZero
Accessingthecompassprogrammatically
Summary
4.BuildingandControllingaSimpleWheeledRobot
Thebasicplatform
ControllinganH-bridgeinterfacetotheDCmotors
ControllingyourmobileplatformprogrammaticallyusingtheRaspberryPiZero
ControllingthespeedofyourmotorswithPWM
UsingamotorcontrollerboardtocontroltheDCmotors
ControllingthevehicleusingtheRaspberryPiZeroinPython
Planningyourpath
Summary
5.BuildingaRobotThatCanWalk
Robotsthatcanwalk
Howservomotorswork
Buildingthequadrupedplatform
Usingaservocontrollertocontroltheservos
CommunicatingbetweentheservocontrollerandaPC
ConnectingtheservocontrollertotheRaspberryPiZero
CreatingaprograminLinuxtocontrolyourquadruped
Summary
6.AddingVoiceRecognitionandSpeech–AVoiceActivatedRobot
CommunicationbetweentheRaspberryPiZeroandtherobot
Givingyourrobotvoicecommands
UsingeSpeaktoallowyourrobottorespondwithanaudiblevoice
Usingpocketsphinxtoacceptyourvoicecommands
Interpretingcommandsandinitiatingactions
Summary
7.AddingRaspberryPiZerotoanRCVehicle
ConfiguringandcontrollinganRCcarwithRaspberryPiZero
ControllingtheRCcarinPython
AccessingtheRCcarremotely
Connectingawebcam
Summary
8.PlayingRock,Paper,orScissorswithRaspberryPiZero
Arobotichand
Movingtherobotichand
ConnectingtheservocontrollertotheRaspberryPiZero
CreatingaprogramonRaspberryPiZerosothatyoucancontrolyourhand
InstallingaUSBcameraonRaspberryPiZero
DownloadingandinstallingOpenCV–afullyfeaturedvisionlibrary
Gesturedetection
Summary
9.AddingRaspberryPiZerotoaQuadcopter
Constructingtheplatform
Missionplanningsoftware
Summary
Index
GettingStartedwithRaspberryPiZero
GettingStartedwithRaspberryPiZero
Copyright©2016PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,
ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthe
publisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyofthe
informationpresented.However,theinformationcontainedinthisbookissoldwithout
warranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,andits
dealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecaused
directlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthe
companiesandproductsmentionedinthisbookbytheappropriateuseofcapitals.
However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:March2016
Productionreference:1210316
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78646-946-5
www.packtpub.com
Credits
Author
RichardGrimmett
Reviewer
DavidWhale
CommissioningEditor
KartikeyPandey
AcquisitionEditor
TusharGupta
ContentDevelopmentEditor
MerintThomasMathew
TechnicalEditor
SaurabhMalhotra
CopyEditors
KevinMcGowan
SnehaSingh
ProjectCoordinator
FrancinaPinto
Proofreader
SafisEditing
Indexer
PriyaSane
Graphics
DishaHaria
ProductionCoordinator
ShantanuN.Zagade
CoverWork
ShantanuN.Zagade
AbouttheAuthor
RichardGrimmetthasalwaysbeenfascinatedbycomputersandelectronicssincehis
veryfirstprogrammingprojectthatusedFortranonpunchcards.Hehasabachelor’sand
master’sdegreeinelectricalengineeringandaPhDinleadershipstudies.Healsohas26
yearsofexperienceintheradarandtelecommunicationsindustries,andevenhasoneof
theoriginalbrickphones.Henowteachescomputerscienceandelectricalengineeringat
theBrighamYoungUniversity,Idaho,wherehisofficeisfilledwithhisnumerousrobotics
projects.
ThisbookistheresultofworkingwiththewonderfulstudentsatBYU-Idaho.Italso
wouldn’tbepossiblewithoutthehelpofmywonderfulwife,Jeanne.
AbouttheReviewer
DavidWhaleisasoftwaredeveloperlivinginEssex,UK.Hestartedcodingasa
schoolboyaged11,inspiredbytheschoolsciencetechniciantobuildhisowncomputer
fromakitandquicklyprogressedtowritingmachinecodeprogramsbecausetheywere
“smallandfast”.Theseearlyexperimentsledtosomeofhiscodebeingusedinsidea
saleableeducationalwordgamewhenhewasonly13.
Hehasbeendevelopingsoftwareprofessionallyeversince,mainlywritingsmallandfast
codethatgoesintoelectronicproducts,includingautomatedmachinery,electriccars,
mobilephones,energymeters,andwirelessdoorbells.
Thesedays,herunshisownsoftwareconsultancycalledThinkingBinariesandspends
nearlyhalfofhistimehelpingtodesignthenextwaveoftheInternetcalledTheInternet
ofThings,byconnectingelectronicdevicestoit.Therestofthetimehevolunteersfor
TheInstitutionofEngineeringandTechnology,runningtrainingcoursesforteachers,
designingandrunningworkshopsandclubsforschoolchildren,andbeingbusywithhis
RaspberryPi,BBCmicro:bitandArduino.
HewasthetechnicaleditorforthebookAdventuresinRaspberryPiandtheco-authorof
thebookAdventuresinMinecraft,andisaregularreviewerandeditoroftechnicalbooks
fromanumberofbookpublishers.
Iwasreallypleasedtobeaskedtoreviewthisgreatnewbookofprojectsusingthe
RaspberryPiZero.ThesizeofthePiZeromakesitidealforbuildingintootherproducts.
Inthisbook,RichardGrimmetttakesusonanamazingjourneyofcircuitbending,coding,
andinnovatingusingthistinycomputer!Butdon’tstophere;theprojectsinthisbookwill
giveyoutheskillsyouneedandinspireyoutocomeupwithmanynewideasyourself!
www.PacktPub.com
eBooks,discountoffers,andmore
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFand
ePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandas
aprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwith
usat<>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signup
forarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooks
andeBooks.
/>DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigital
booklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.
Whysubscribe?
FullysearchableacrosseverybookpublishedbyPackt
Copyandpaste,print,andbookmarkcontent
Ondemandandaccessibleviaawebbrowser
Preface
Formanyyears,robotsandotheradvancedelectronicwonderscouldonlybeseenonthe
television,movies,orinuniversityormilitarylabs.Inrecentyears,however,the
availabilityofnewandinexpensivehardwareandalsofreeandopensourcesoftware,has
providedtheopportunityforalmostanyonewithalittletechnicalknowledgeand
imaginationtobuildthesetechnicalwonders.Thefirstwaveofprojectswerefueledby
Arduino,aninexpensiveandsimple-to-programmicrocontroller.Thenextwavewas
carriedfurtherbytheintroductionoftheRaspberryPi,anevenmorecapableprocessor
poweredbytheLinuxoperatingsystem.
Nowthereisanevenlessexpensive,powerfulmicroprocessor:theRaspberryPiZero.
ThislittleprocessorpacksaprocessorpowerfulenoughtorunLinuxintoasmallandeven
lessexpensivepackage.Thiscapability,coupledwithsomeadditionalpower,inexpensive
hardware,andfreeopensourcesoftwareprovidesaplatformforprojectsthatrangefrom
simplewheeledrobotstoadvancedflyingmachines.
Whatthisbookcovers
Chapter1,SettingStartedwithRaspberryPiZero,isdesignedtogothroughthedetailsof
settingupausefuldevelopmentenvironmentonRaspberryPiZero.Thechapterbegins
withadiscussionofhowtoconnectpowerandcontinuesthroughsettingupafullsystem,
configuredandreadytobeconnectedtoanyoftheamazingdevicesandSWcapabilities
todevelopadvancedroboticsapplications.
Chapter2,ProgrammingRaspberryPiZero,reviews,forthosewhoarealreadyfamiliar,
basicLinux,editing,andprogrammingtechniquesthatwillbeusefulthroughtherestof
thebook.You’lllearnhowtointeractfromthecommandline,howtocreateandeditafile
usinganeditor,andbasicPythonprogramming.
Chapter3,AccessingtheGPIOPinsonRaspberryPiZero,discussestheGPIO
capabilitiesofRaspberryPiZerobybuildingandcontrollingsomesimpleLEDcircuits.
Chapter4,BuildingandControllingaSimpleWheeledRobot,discussesoneofthe
amazingthingsyoucandowithRaspberryPiZero,controllingasimplewheeledrobot.
Thischapterwillshowyouhowtoaddmotorcontrol,soyoucanbuildyourveryown
autonomousmobilerobot.
Chapter5,BuildingaRobotThatCanWalk,tellsusaboutanotherimpressiverobotic
project,anautonomousrobotthatcanwalk.Thisisdoneusingservoswhosepositioncan
becontrolledusingRaspberryPiandsomeadditionalUSB-controlledhardware.
Chapter6,AddingVoiceRecognitionandSpeech–AVoiceActivatedRobot,tellsusabout
avoice-activatedrobot.Oneofthesignificantnewfeaturesoftoday’scomputersystemis
theabilitytoinputcommandsandprovideoutputwithoutascreenorkeyboard.Afew
yearsago,theconceptofacomputerthatcantalkandlistenwassciencefiction,buttoday
itisbecomingastandardpartofnewcellphones.ThischapterintroduceshowRaspberry
PiZerocanbothlistentospeechandalsorespondinkind.Thisisnotaseasyasitsounds
(punintended)andyou’llbeexposedtosomebasicfunctionality,whilealso
understandingsomeofthekeylimitations.You’lltakeastandardtoyandturnitintoa
responsiverobot.
Chapter7,AddingRaspberryPiZerotoanRCVehicle,tellsusaboutanotherastounding
capabilityofRaspberryPiZero,theabilitytoadd“sight”toyouprojects.RaspberryPi
ZeromakesthisveryeasybysupportingopensourcesoftwareandreadilyavailableUSB
webcams.Byaddingthisandaremotecontrol,youcanbuildaremotecontrolvehiclethat
cangoaroundcorners,intorooms,whereveryou’dliketogo.
Chapter8,PlayingRock,Paper,orScissorswithRaspberryPiZero,tellsusabouthowwe
canuseourtoolkittobuildandcontrolarobotichandthatcanseeandrespondtothe
worldaroundit.Inthiscase,you’llprogramyourhandtoplayrock,paper,andscissors.
Chapter9,AddingRaspberryPiZerotoaQuadcopter,talksaboutthefactthatbuildinga
robotthatcanwalk,talk,orplayairhockeyiscool,butonethatcanflyistheultimate
goal.
Whatyouneedforthisbook
YouneedaRaspberryPiZero.Youcanrefertothesoftwarelistalongwiththecode
bundleofthebook.