Vilros Raspberry Pi User Guide by Vilros

Vilros Raspberry Pi User Guide by Vilros
RaspberryPIUser’sGuide
Copyright©2014Vilros.Allrightsreserved.www.vilros.com
1-855-207-9254
ISBN:978-0-692-31936-9
Nopartofthispublicationmaybereproduced,distributed,ortransmittedinanyformorbyanymeans,including
photocopying,recording,orotherelectronicormechanicalmethods,withoutthepriorwrittenpermissionofthe
publisher,exceptinthecaseofbriefquotationsembodiedincriticalreviewsandcertainothernon-commercialuses
permittedbycopyrightlaw.
Trademarkednames,logos,andimagesmayappearinthisbook.Ratherthanuseatrademarksymbolwithevery
occurrenceofatrademarkedname,logo,orimage,thenames,logos,andimagesareusedonlyinaneditorialfashion
andtothebenefitofthetrademarkowner,withnointentionofinfringementofthetrademark.
Theinformationinthispublicationisprovidedonan“ASIS”basis.Vilrosmakesnowarranties,expressorimplied,
regardinguseoftheinformationaloneorincombinationwithyourproducts.Neithertheauthornorthepublishercan
acceptanylegalresponsibilityforanyerrorsoromissionsthatmaybemade.
ConventionsUsedinthisBook
Thefollowingtabledescribesthetextconventionsusedinthisbook.
ConventionMeaning
ItalicTextthatappearsinitalicsreferstofilenames,variableandfunctionnames,orothercode.Withinthecontextof
givinginstruction,italictextshouldbetypedexactlyasshown.
BoldWithinthecontextofgivinginstruction,itemsinboldtextareuserinterfaceelements,suchaskeystrokes,menu
items,orbuttonlabels.
MonospacefontAmonospacefontisusedforshellcommandsandPythoncodethatshouldbetypedinonthekeyboard.
Contents
1–GettingStarted51.1Introduction51.2TechnicalSpecifications71.3BasicSetup81.4SDCards14
2–IntroducingRaspbian162.1RaspbianandLinux162.2InstallationofRaspbianwithNOOBS162.3
InstallationofRaspbianusingaDiskImage202.4Raspi-config222.5Raspbian’sDesktopEnvironment262.6
CommonTasks372.7NetworkConnectionsandRemoteAccess402.8OtherOperatingSystems45
3–BuildingaMediaCenterwithXBMC473.1XBMC473.2Installation483.3FirstSteps513.4
MediaFilesandtheLibrary533.5NetworkDevicesandOtherComputers593.6Add-ons653.7RemoteControls66
4–ProgrammingwithScratch694.1TheUserInterface694.2Sprites754.3ArithmeticandVariables
814.4Decisions824.5Loops854.6Strings864.7Messages874.8SoundandMusic894.9ThePaintEditor894.10
AutomaticStartupofScratchProjects934.11SharingYourFinishedProjects94
5–BuildinganArcadeGameinScratch955.1TheTitleScreen955.2TheLevelBackgrounds995.3
ThePlayerSprite1055.4CollisionDetection1095.5Enemies1155.6MoreEnemies1275.7GameOver128
6–ProgramminginPython1296.1YourFirstPythonProgram1296.2Python1316.3Decisions1366.4
Loops1386.5Functions1396.6ClassesandObjects1416.7ModulesandPackages1446.8FileI/O1466.9Graphical
UserInterfaces(GUIs)149
7–ControllingInputandOutputPins1507.1ElectronicCircuits,VoltageandCurrent1507.2
SolderlessBreadboards1527.3TheGPIOHeader1537.4BasicOutput1557.5BasicInput1607.6Communication
between3.3Vand5VDevices1647.7SerialPeripheralInterface(SPI)1667.8I2CCommunication1717.9Serial
UARTs173
8–BuildinganIPCamera1768.1ThePiCameraModule1768.2Motion178
9–BuildingaSmarterDoorbell1849.1TheButtonCircuit1849.2Speakers1859.3ABasicDoorbell
1869.4AnEnhancedDoorbell188
10–MakingFreePhoneCallswithGoogleVoice19010.1SIPandSoftphones19010.2Google
Voice19210.3RasPBX19310.4SIPPhonesacrosstheInternet198
11–Accessories199
1–GettingStarted
1.1Introduction
TheRaspberryPiisasmallcomputer,averysmallcomputer.
Itconsistsofmostlythesamepartsasastandarddesktopcomputerorlaptop.Acentral
processingunit(CPU)actsasabrain,randomaccessmemory(RAM)andlong-term
storagedevicesareusedtoholddata,avideodisplayshowsyouwhatishappening,and
youinteractwithallofthisusingmice,keyboards,joysticks,andotheruniversalserialbus
(USB)devices.ThePimaybelesspowerfulthanyourWindowsPCorMacintosh,butit
isstillimpressivethatitfitsallofthisonaboardonlyslightlylargerthanacreditcard.
TheoriginalgoaloftheUK-basedRaspberryPiFoundationwastocreateadevicethat
wouldaddresstheirperceptionoffallingstandardsintheteachingofcomputerscience.As
computershaveevolved,theyhavebecomemoredifficulttowritesoftwareforata“lowlevel”–withcloseinteractionbetweenhardwareandsoftware.Andastheyhavebecome
moreintegratedinourdailylives,theconsequencesofbreakingyourcomputerby
experimentinghavebecomemoresevere…andexpensive.
So,unlikeconventionalsystems,thePiisamachinethatisdesignedtobeplayedwithand
usedforexperiments.Itsdiminutiveformfactorandrelativelylowcostmeanthatyoucan
dowhatyouwantwithit,andthisattractsfarmorediversegroupsofusersthanjust
studentsandteachers.
Itissuitableforawiderangeofapplications,including:
UsingthePiforGeneralComputing
YoucaninstallavarietyofoperatingsystemsonthePi,andmanyofthesehavefull
desktopenvironments.Withsupportforexternalhardwaredevices,Internetconnections,
anddownloadingandinstallingsoftware,youcanusetheRaspberryPiasaregular
computer.Itcandojustabouteverythingyourmainsystemcando…onlyalittleslower.
PlayingGames
TherangeofgamesavailableontheRaspberryPi’soperatingsystemsisextensive.But
youcanalsoinstall“emulators”,whicharepiecesofsoftwarethatallowprogramsfrom
othermachinestoberunonthePi.Thisgivesyouaccesstotitlesonclassicmachines
suchastheAtari2600,NintendoEntertainmentSystem,SegaGenesis,SharpX1,MSX,
Panasonic3DO,andmanymore.AllRaspberryPimodelssupportHDMIvideooutput
andUSBgamecontrollers,makingthePiapopularchoiceforfansofretrocomputingand
retrovideogames.
PlayingMovieFilesandMusiconYourTV
PutthePiinacase,connectittoatelevisionusinganHDMIcable,andinstallXBMC.
ThenyouhaveacapablemediacenterthatcanloadmoviefilesfromtheSDcard,USB
harddrives,oracrossyourlocalnetwork.
ProvidingNetworkServices
Asasmall,standalonedevicethatconnectstotheInternetandlocalnetworks,the
RaspberryPimakesanexcellentserver.Youcanuseittoservefilesandwebpages,
answerdomainnamesystem(DNS)requests,sharehardwaredevices(forexample,
printers)acrossanetwork,andalmostanythingelseyoumightneedaserverfor.
SettingupDevelopmentEnvironments
ThesimplenatureofthePi,anditssupportformanydifferentprogramminglanguages,
makeitanidealsystemtousewhenlearninghowtoprogram.ThePicontainsanARM
processor,andthesearepopularlyusedincellphones,tablets,gamesconsoles,andinthe
computer-controlledequipmentusedinmanufacturing.Theabilitytoprogramoneisa
skillthatisinhighdemand.
BuildingControllerBoardsandInteractionwithElectronicsItssmallsize,lowcost,
andeaseofprogrammingmaketheRaspberryPiveryusefulin“embedded”applications.
Inthesetypesofproject,thePiisusedalongwithotherelectronicscircuitstocreate
everythingfrom3Dprinters,tohomeautomationsystemsandrobots.
1.2TechnicalSpecifications
TheModelB+isarevisedversionoftheModelBthatwilleventuallyreplacetheearlier
model.Ithasmoregeneralpurposeinput/output(GPIO)pinsthanearliermodels,and
twiceasmanyUSBsockets.
ModelB+
CPUBroadcommicroprocessorrunningat700MHz(ARMv6architecture)
GPUBroadcomVideoCoreIV,250MHz
OpenGLES2.0
MPEG-2andVC-1,1080ph.264/MPEG-4AVCdecoder
Memory512MBVideoOutputVideoOutputpole3.5mmjack,LCDpanelsthroughDSI.AudioOutput4-pole3.5mm
jack,HDMI,I2SUSBPorts4(2dualsockets)Input/Output17xGPIO,UART,I2C,SPINetworking10/100Mb/s
Ethernet,USBdevicesStoragemicroSDcardslotPower5Vthroughmicro-USBsocketorGPIOheader
ThediagrambelowshowstheavailableconnectorsontheRaspberryPiModelB+.
Figure1.TheRaspberryPianditsconnectors
1Generalpurposeinput/output(GPIO)header–thesepinscanbecontrolledfromsoftware.
2Universalserialbus(USB)socketforattachingperipheraldevicessuchasmice,keyboards,ormemorysticks.Thisis
adualsocketandtwoUSBdevicescanbeconnectedatthesametime.
310/100Mb/sEthernet(RJ45)socketforconnectingtoanetworkrouter.
44-pole3.5mmoutputjackforaudioandvideo.
5Cameraserialinterface(CSI).
6High-definitionmultimediainterface(HDMI)videooutput.
7Powerinviamicro-USBsocket.
8Displayserialinterface(DSI)flexibleflatcableconnectorforliquidcrystaldisplays(LCDs).
9microSDsocket.Thecardsocketisattachedtotheundersideoftheboard.
1.3BasicSetup
TostartusingyourPi,youneedtoconnectitto:1.Power
2.AnSDcardwithanoperatingsystemor“bootable”programinstalled
Withoutthese,thePiwilldonothing,notevenoutputavideosignal.Fortheinitial
configuration,youmayalsoneedtoconnect:
1.Adisplay(usingHDMIorcompositevideo)
2.AUSBkeyboard
3.AnEthernetcableorUSBWi-Fi“dongle”
Thedisplay,andanyUSBdevicesyoumayconnect,canberemovedwhentheyarenotin
use.Forexample,aPiactingasafile/printservermayonlyacceptinputfromcomputers
onthenetworkanddoesnotalwaysneedakeyboardorscreen.
FittingaHeatSink
Whenthecomponentsinacomputersystemworkhard,theygenerateheat.Andabovea
certainlevel,thisheatcanreducethelifespanofthecomponentsorevenbreakthem
altogether.Aheatsinkisacarefullydesignedblockofmetalthattakestheheatawayfrom
theelectroniccomponentandthenpassesitintotheairsurroundingthedevice.
TherearethreechipsonaRaspberryPithatcangetveryhotifthedeviceisworkinghard:
thecentralprocessingunit(1),thechipthatcontrolstheEthernetandUSBports(2),and
thepowerregulator(3).
Toinstallaheatsink:
1.UnplugthePiandleaveittocoolbeforeattemptingtohandlethedevice.
2.Onthebottomoftheheatsink,peelawaytheplasticbackingthatcoverstheadhesive.
3.Presstheheatsinkdownfirmlyanddirectlyontothechip.Holdthepressureforafew
secondstoallowtheadhesivetowork.
IfyoubuyheatsinksforyourPi,onlyusethethermaladhesivethattheyarrivewith;
neveruseanyothertypeofadhesiveorstickyplastictoinstallaheatsinkonaRaspberry
Pi.Theadhesivemustbeaspecialcompoundsothatiteffectivelytransfersheatfromthe
chiponthePitothemetaloftheheatsink.
Figure2.Thethreeheat-outpointsonaPi(left);andinstallingaheatsinkontheCPU(right)
ConnectingPower
TheRaspberryPirequiresapowersupplyof5Vthatcanprovideatleast700mAof
current.BeforeconnectingthePiandturningiton,youshouldchecktheratingofthe
powersupplycarefully.
Manycellphonechargerswillwork,butsomesupplylesscurrentthanthePineeds.Using
inadequatepowersupplies,orevenpoweringthePifromtheUSBportofanother
computer,isnotrecommendedasthelackofcurrentmaymakethePiunstable.You
shouldcertainlyavoiddoingthisifyouneedtoconnectanyotherdevicestothePi.
PowercanbefedintothePithroughthemicro-USBsocketor,ifyouhaveasuitable
connector,throughthegeneralpurposeinputoutputpins.However,youshouldbeaware
thatprovidingpowerthroughtheGPIOheaderpinsbypassestheon-boardprotection
circuitrythatisdesignedtopreventdamagetothedevice.Forthisreason,itshouldonly
beattemptedbypeoplewhoareexperiencedinbuildingelectroniccircuits.
ItisworthnotingthattheRaspberryPidoesnothaveanon/offswitch.Someoperating
systemscanpowerdownthedeviceorputitintostandbymodebutwhenyouwanttoturn
itoff,youwilloftenhavetoremovethepowersupplyorswitchitoffatthewallsocket.
Therearetwoholesontheprintedcircuitboard(PCB)oftheModelB+.Theseholesarelabelled“RUN”andyou
cansolderaswitchacrossthesetwoconnectionstocreatearesetbutton.
ConnectingaDisplay
HDMIoffersahigh-qualityvideoandaudiosignal,andisthepreferredwayofconnecting
allmodelsofRaspberryPitoamoderntelevision.Toconnectahigh-definitiontelevision:
•PlugoneendofanHDMIcableintotheRaspberryPi’sHDMIsocket,andtheotherend
intoanHDMIinputonyourTV.
IfyourdisplaydoesnotsupportHDMI,youcanconnectthecompositevideoandaudio
outputstotheauxiliaryA/Vinputofmosttelevisions.Theseconnectionsarecolored
yellow,red,andmosttelevisions.Theseconnectionsarecoloredyellow,red,andpolejack
ononeend,andthreeRCAplugsontheother(oneyellow,onered,andonewhite).Touse
thesecables:
1.Plugthe4-pole3.5mmjackplugintothe3.5mmjacksocketontheRaspberryPi
ModelB+.
2.ConnecttheyellowcompositevideoplugtotheyellowvideoinputsocketonyourTV.
3.ConnecttheredRCAplugtotheredaudiosocketonyourTV.
4.ConnectthewhiteRCAplugtothewhiteaudiosocketonyourTV.
IfyourTVdoesnothavetheyellow,red,andwhiteauxiliaryinputs,youcanplugthe
compositeoutputsintoaSCARTadapterandconnectthattoyourTVinstead.
Whenusingthecompositevideo,youalwayshavetheoptionofconnectingthevideotoa
televisionandtheaudiooutput(theredandwhiteconnectors)tootherdevices,suchas
headphones,poweredspeakers,oramplifiers.
TouseacomputermonitorasthePi’sdisplay,youwillneedanHDMItoVGA,orHDMI
toDVIadaptor.However,whenconnectingtoamonitorusinganHDMItoVGA/DVI
adapter,youwillinitiallybeunabletoconnectspeakerstotheaudioconnector.Whenthe
HDMIcableisconnected,thecompositevideoandaudiooutputportsareturnedoff.This
canbechangedonceyouhaveanoperatingsystemrunningonthePi.
Althoughnotcoveredinthisbook,allRaspberryPimodelssupportDSIforconnectingLCDpanels.
Figure3.ConnectingadisplaytotheModelB+
ConnectingUSBDevices
WithmostoperatingsystemsthatyourunonthePi,humaninterfacedevices(HIDs)that
connectusingUSB(suchasmice,keyboards,andgamecontrollers),andstoragedevices
(suchasUSBmemorysticksandharddrives)willworkwithoutanyproblemsor
installationprocesses.Youmayneedtoinstalldrivers–piecesofsoftwarewrittentopass
messagesbetweentheoperatingsystemandthehardwaredevice–tousemore
complicatedperipheralslikesoundcards.
ToconnectaUSBdevice,insertitsUSBconnectorintoanavailablesocketonthe
RaspberryPi.YoucanusuallydothissafelywhetherornotthePiisturnedonand
running.
TheRaspberryPicanonlysupplyalimitedamountofpowertoUSBdevices.Itis
recommendedthatyoudonotconnectanydevicesthatdrawover100mA.Tousemore
power-hungrydevices,youcanuseapoweredUSBhub–adevicethatallowsmultiple
USBperipheralstobeconnectedtoasingleport,andthathasitsownpowersupply.This
alsoallowsyouattachmoredevicestothePi.
Figure4.ConnectingthePitoa4-portUSBhub
ConnectingtoaNetwork
TomakeawirednetworkconnectionbetweenthePiandanetworkrouter:
1.PlugoneendofaCAT5orCAT6EthernetcablewithRJ45connectorsintotheEthernet
socketontheRaspberryPi.
2.Plugtheotherendofthecableintoyournetworkrouter.
Theactualnetworkconnectionismadebythesoftwareoroperatingsystemrunningonthe
Pi.
Intheory,Wi-Fiisafastertechnologythanthe10/100Mb/sEthernetcircuitthatisbuilt-in
toModelB+.Inpractice,however,thisisnotalwaysthecase.AsthePicannotprocess
dataasquicklyasabrandnewdesktopcomputer,thedifferenceinspeedbetweenEthernet
andWi-Fiislessnoticeableandyoushouldusewhicheverismostconvenientforyou.
NotallWi-FiandEthernetadaptorsarecompatiblewiththeRaspberryPi.Beforebuying,checkthattheadaptor
isknowntobeworkingbylookingatthelistat
http://elinux.org/RPi_USB_Wi-Fi_Adapters
1.4SDCards
Inthenextchapter,youwilllearnaboutRaspberryPioperatingsystems(inparticularly,
RaspbianLinux)andhowtoinstallthemontoanSDcard.Thiswillcompletetheset-upof
thePi.
Unlikeconventionaldesktopcomputersystems,thePidoesnothaveaharddrivefrom
whichtoloadanoperatingsystem.Instead,itusesthecardsockettoloadfilesfroma
memorycard.
WhenthePiisfirstturnedon:1.ThemainARMprocessorandSDRAM(memory)are
disabled.
2.Thegraphicsprocessingunit(GPU)loadsthe“firststagebootloader”thatisbuilt-into
thePi,andthiscontainsallofthecodenecessarytoworkwithmemorycards.
3.Thefirst-stagebootloaderenablesSDRAM,detectsthepresenceofamemorycard,and
loadsthe“second-stagebootloader”fromit.
4.Thesecond-stagebootloaderloadstheoperatingsystemorbootableprogramfromthe
card.
InsertingandRemovingSDCards
Itislikelythatyouwillneedamemorycardwithatleast4GBcapacityifyouare
intendingtorunanoperatingsystemonthePi.4GBSDHCmicroSDcardsarewidely
availableandgenerallyverycost-effective.
ToinsertanSDcard:
1.EnsurethePiisunplugged.
2.LocatetheSDcardsocketontheundersideofthePi’sboard.
3.Whenlookingfromabove,theSDcard’scontactsshouldbefacingup.
4.Gently,butfirmly,pushtheSDcardintothesocketuntilitclicksintoplace.
Figure5.InsertingSDcardsintotheRaspberryPi
ToremovetheSDcard:
•FirstpushthemicroSDfurtherintothedeviceuntilitclicks.Thenpullthecardout.
WheninsertingandremovingSDcardsinothercomputers,itisnotalwaysnecessaryto
turnoffthedevice.However,asthememorycardcontainsitsoperatingsystem,thePi
mayaccessitatanytime.RemovingthecardwhilethePiisaccessingitcancorruptdata
and,inextremecases,maystopthecardworkingatall.
2–IntroducingRaspbian
2.1RaspbianandLinux
Anoperatingsystem(OS)isauniquetypeofapplicationthatyourunonyourcomputer.It
isanenvironmentinwhichmanyotherapplicationscanrunatthesametime,witha
consistentuserinterfaceandsharingthesameresources.MicrosoftWindowsandApple’s
MacOSXareprobablythetwomostwell-knownoperatingsystems,butthereareothers.
Linuxisoneofasmallgroupofoperatingsystemsthatare“free”.Itusuallydoesn’tcost
anythingtouseandpeoplecanmodifytheOS,repackageitwithothersoftware,distribute
theirversion,andgenerallydowhattheywantwithit.Becauseofthis,youcanfindLinux
runningonmosttypesofcomputer–fromlargeserversusedbycorporationssuchas
Google,tosmalldevicesliketheRaspberryPi.AbundleoftheLinuxcorewithother
applications(suchasdesktopenvironments,filemanagers,andwebbrowsers)iscalleda
“distribution”(or“distro”).
RaspbianisaLinuxdistributionthatisbasedonDebian,anotherpopularversionof
Linux.ItisdesignedfortheRaspberryPiandistheOSrecommendedbytheRaspberryPi
Foundation.AlthoughdifferentLinuxdistributionscanusuallyallrunthesame
applications,thisbookisfocusedonusingRaspbiananditmaybehelpfulforyoutorun
thisOSwhileyouarelearning.OnceyouarefamiliarwithRaspbian,youwillfindthat
youareabletouseothervarietiesofLinuxwithoutmuchhelp.
2.2InstallationofRaspbianwithNOOBS
NewoutofBoxSoftware(NOOBS)isatoolthatyoucanrunonyourRaspberryPiandit
willhelpyouinstallanOS.ItstaysontheSDcard,evenaftertheOSinstalled,andcan
alsobeusedtoeditthePi’smainconfigurationfileorreplacetheinstalledOSifproblems
occur.TheSDcardsuppliedwithyourPialreadycontainsNOOBS.
InstallingNOOBStoanSDCard
TherearetwoversionsofNOOBSavailable:NOOBSandNOOBSLite.NOOBSLiteis
quickertodownload,butdoesnotcomewiththeinstallationfilesforRaspbian.Instead,
yourPiconnectstotheInternettodownloadtherelevantfileswhenyoustartthe
installationprocess.ItdoesnotsupportUSBWi-Fiadapters,andthismeansthatyouwill
needanEthernetcablepluggedintoyourRaspberryPitouseNOOBSLite.
ThefullversionofthelatestversionofNOOBSonlycomeswiththefilesneededtoinstall
Raspbian.ToinstalladifferentOS,youneedanInternetconnection.
ThespacethatNOOBSoccupiesontheSDcardisnotavailableforusebytheOSthat
youareinstalling.Evena4GBSDcardwillsometimesnotbelargeenoughtohold
NOOBSandanOS,andstillhaveadequatespaceforyourfilesandprograms.
IfyoucannotuseNOOBS,youcaninstallanOS“diskimage”toyourSDcard.Thisis
describedinsection2.3InstallationofRaspbianusingaDiskImageonpage20.
TheprocessforinstallingNOOBStoanSDcardisthesamewhetheryouareusingthe
fullNOOBSpackage,orNOOBSLite.OnWindows(8/7/Vista/XP):
1.InserttheSDcardintoasuitablecardsocketorUSBcardreader.
2.PresstheWindowslogokey+R.TypeexplorerandpressEnter.
3.IntheWindowsFileExplorerwindow,right-clickthecarddevice(usuallylabelled
“SDHC”or“RemovableDisk”)andthenclickFormat.
4.IntheFilesystemlist,clickFAT32.
5.IntheAllocationunitsizelist,clickDefaultallocationsize.
6.ClickStart.
7.DownloadoneoftheNOOBSpackagesfromhttp://www.raspberrypi.org/downloads/
8.Findthe.zipfileyoudownloadedandright-clickit.PointtoOpenwithandthenclick
WindowsExplorer.
9.PressCtrl+A,toselectallofthefilesinthe.ziparchive.
10.PressCtrl+C,tocopytheselectedfilesintomemory.
11.IntheWindowsFileExplorerwindow,right-clickthecarddevice.
12.ClickPastetocopythefilestotheSDcard.13.IntheWindowsFileExplorer
window,right-clickthecarddevice.
14.ClickEject.
OnMacOSX:
1.InserttheSDcardintoasuitablecardsocketorUSBcardreader.
2.Onthedock,clickFinder.
3.Onthesidebar,clickApplications.
4.ClickUtilities,andthendouble-clickDiskUtility.
5.Intheleftpanel,clicktheSDcard(usuallylabelled“NONAME”ifthecardwasnot
formattedwithavolumename).
6.OntheErasetab,fromtheVolumeFormatlist,clickMS-DOSFileSystem.
7.ClickErase.
8.DownloadoneoftheNOOBSpackagesfromhttp://www.raspberrypi.org/downloads/
9.InFinder,locatethe.zipfileyoudownloaded.
10.Double-clicktheNOOBSzipfileanditwillunziptoanewfolder.Forexample,a
foldernamedNOOBS_lite_v1_3_9.1
11.Double-clickthefoldertoopenit.
12.PressCmd+Atoselectallofthefiles.
13.PressCmd+Ctocopythefilesintomemory.
14.Intheleftpanel,clicktheSDcard(usuallylabelled“NONAME”ifthecardwasnot
formattedwithavolumename).
15.PressCmd+VtocopythefilestotheSDcard.16.Intheleftpanel,clicktheEject
iconnexttothenameoftheSDcard.
InstallingRaspbian
ToinstallRaspbian,youwillneedtoconnectakeyboard,mouse,anddisplaytoyourPi.
First,ensurethePiiscompletelyoffandunplugged,andtheninserttheSDcardintothe
Pi’scardsocket.ReconnectthepowertoyourPi.ThePiwillstartandwillloadthe
NOOBStool.Wheneverythingisready,youshouldseeawindowsimilartoFigure1.
Figure1.NOOBSonaRaspberryPi
Thewindowshowsalistoftheoperatingsystemsthatyoucaninstall.
1.IfyouhavearchivingsoftwareinstalledonyourMac,theNOOBSfilemightopenwiththisinstead..
ToinstallRaspbian:1.Inthelist,clicktheboxnexttoRaspbian.
2.Onthetoolbar,clickInstall.
Whentheinstallationiscomplete,theRaspberryPirestartsandloadstheraspi-configtool.
Thishelpsyoutochangecertainimportantsettings.Formoreinformation,seesection2.4
Raspiconfigonpage22.
IfyouputtheSDcardbackintoaWindowsPCthenthecardwillappeartohaveshrunkincapacity.Ifyouwant
towipethecard,youcanusethecommand-linetooldiskparttodestroythepartitionsandcreateanew“primary”
partitionusingalloftheavailablespace.
2.3InstallationofRaspbianusingaDiskImage
Adiskimageisaspecialtypeoffileformakingacopyofstoragedevices,suchasfloppy
disks,CDs,harddrives,andmemorycards.Itnotonlycontainsallofthefilesfromthe
device,italsostoresalloftheinformationnecessarytorecreatethesamefilestructureand
physicallayoutonanotherdevice.
ManyoperatingsystemsthathavealreadybeenmadetoworkontheRaspberryPiare
availablefordownloadasdiskimages.TowritetheimagetoanSDcard,youcanusea
WindowsPC,MacorLinuxcomputer.1
DownloadtheRaspbiandiskimagefromhttp://
www.raspberrypi.org/downloads/–itisa.ziparchivethatyouneedtounzipbeforeitcan
beused.
TounzipthefileonWindows(8/7/Vista/XP):
1.Findthe.zipfileyoudownloadedandright-clickit.PointtoOpenwithandthenclick
WindowsExplorer.
1.OnlyinstructionsforWindowsandMacOSXarecoveredinthisguide.
2.Clickthe.imgfile,andthenpressCtrl+C.
3.Intheleftpanel,clickDesktop.
4.PressCtrl+Vtocopythe.imgfiletoyourDesktop.
TounzipthefileonMacOSX:
1.Onthedock,clickFinder.
2.Findthe.zipfileyoudownloaded.
3.Double-clickthe.zipfiletounzipittoanewfolder.
UsersofWindowswillneedtodownloadandinstallWin32DiskImagerfrom
http://sourceforge.net/projects/win32diskimager/beforecontinuing.UsersofMacOSX
shouldinstallApplePi-Bakerfromhttp://www.tweaking4all.com/hardware/raspberrypi/macosx-apple-pi-baker/
TowritetheRaspbiandiskimagetoanSDcardonWindows(8/7/Vista/XP):
1.InserttheSDcardintoasuitablecardsocketorUSBcardreader.
2.IfyouarerunningWindowsXP:ontheStartmenu,underagroupnamedImage
Writer,click
Win32DiskImager.
3.IfyouarerunningalaterversionofWindows:ontheStartmenu,underagroupnamed
ImageWriter,right-clickWin32DiskImager.ThenclickRunasadministrator.You
maybeaskedtoconfirmthisbyawindowtitled“UserAccessControl”.ClickYes.
4.InWin32DiskImager,underImageFile,clickthefoldericon.Intheleft-handsideof
theWindowtitled“Selectadiskimage”,clickDesktop,andthendouble-clickthe.img
filethatyouunzipped.
5.UnderDevice,ensurethatthedrivelettershownmatchestheonethatisdisplayedin
WindowsExplorernexttoyourSDcard.
6.ClickWrite.
7.Whentheprocessiscomplete,clickExit.
8.PresstheWindowslogokey+R.TypeexplorerandpressEnter.
9.IntheWindowsFileExplorerwindow,right-clickthecarddevice(usuallylabelled
“SDHC”or
“RemovableDisk”)andthenclickEject.
OnMacOSX:
1.InserttheSDcardintoasuitablecardsocketorUSBcardreader.
2.Onthedock,clickFinder.
3.Onthesidebar,clickApplications.
4.Intherightpanel,double-clickApplePi-Baker.
5.IfmultipleSDcardsarelistedunderPi-Crust:PossibleSD-Cards,clicktheoneyou
wanttowriteto.
6.UnderPi-Ingredients:IMGRecipe,clickIMGtoSD-Card.
7.Locatethe.imgfilethatyouunzipped,thenclickOpen.
8.EntertheadministratorpasswordforyourMac.
9.Whentheprocessiscomplete,clicktheClosebutton.TheninFinder,clicktheEject
buttonnexttotheSDcard.
EnsurethePiiscompletelyoff,andtheninserttheSDcardintothePi’smemorycard
socket.ReconnectthepowertoyourPi.
2.4Raspi-config
WhenRaspbianstartsforthefirsttime,itrunsatoolcalledraspiconfig.Youcanusethis
tochangeseveralconfigurationoptionsthataffecthowRaspbianoperates.Raspi-configis
acommandlineapplicationandiscontrolledusingthekeyboard:
•UsetheUpandDownArrowkeystohighlightmenu
items.
•PressEntertoactivatethehighlighteditem.
•PresstheTabkeytomovethehighlightdowntothetwooptionsatthebottomofthe
window–<Select>and<Finish>–andthenusetheLeftandRightArrowkeysto
choosebetweenthosetwooptions.
•Tomovebacktothemainmenu,presstheTabkeyagain.
Whenyouhavefinishededitingthesettings,highlighttheoption<Finish>andpress
Enter.
WhenRaspbian’sgraphicaldesktopisrunning,youcanaccesstheraspi-configtoolatanytimebydoubleclickingLXTerminalonyourdesktop.ThenenterthefollowingcommandandpressEnter:sudoraspi-config
ExploringtheSettingsinRaspi-config
Thetablebelowsummarizestheoptionsavailablefromthemainmenuinraspi-config:
MenuOptionDescription
ExpandFilesystemMakethefullcapacityoftheSDcardavailabletotheoperatingsystem–ifisnotalreadyavailable.
ChangeUserPassword
Changethepasswordforthedefaultuser(pi).
EnableBoottoDesktop/ScratchRaspbiancanautomaticallyloaddifferentapplicationswhenitstarts.Thissetting
changesthat.
InternationalisationOptions
Configurelanguage,keyboardandculturesettings(suchasdateformatandtimezone).
EnableCameraIfyouhaveaRaspberryPiCameramodule,youneedtoenableitusingthismenuoption.
AddtoRastrack
Rastrack(rastrack.co.uk)showsthelocationofRaspberryPidevicesaroundtheworld.UsethisoptiontoaddyourPito
themap.
OverclockOverclockingyourPimakesitrunfasterthanthe
manufacturerdesigneditto.However,thiscanalsocausethesystemtooverheatorbecomelessstable.
AdvancedOptionsSeebelow.About‘raspi-config’Displayinformationabouttheraspi-configtool.
SelectingAdvancedOptionsfromthemenutakesyoutoanothermenu:
MenuOptionDescription
OverscanThedisplayinmanyoldertelevisionsisslightly
largerthanthevisiblearea.IfyourPi’sdisplayrunsofftheedgeofthescreen,youcanenableblackborders(overscan)
toensurethatyoucanseeallofthepicture.
HostnameChangethenamegiventothePiwhenitis
connectedtoalocalnetwork.Thiscanbeusefulwhensearchingforthedevice,orwhenyouhaveseveralRaspberryPi
devices.
MemorySplitThePi’smemoryissharedbetweentheCPUandGPU.Youcanchangehowmuchmemoryisallocatedto
theGPUusingthissetting.
SSHEnableordisableSSHaccess.SPIWhenconnectingcertainSPIdevices,itcanbe
usefultoloadtheSPIkernelmodulewhenthePistarts.Usethissettingtochangewhetherthemoduleisloaded
automatically.
Audio
Usedtosendtheaudiosignaltotheaudiooutputconnector,evenwhenusinganHDMIcableforvideo.
UpdateConnectstotheInternetandupdatestheraspiconfigtooltothelatestversion.
Forsomeusers,thedefaultsettingsareok.However,therearethreesettingsinparticular
thatmanyusersmightwanttochangeatthisstage:
ChangingtheDefaultPassword
WhenRaspbianisinstalled,itcreatesanewusercalledpi.Thedefaultpasswordforthis
userisraspberry.
Tochangethis:
1.PresstheDownArrowkeytohighlightChangeUserPassword,andthenpressEnter.
2.PressEnteragaintoselect<OK>.
3.TypeanewpasswordandpressEnter.
4.Toconfirmthepassword,typeitagainandpressEnter.
5.PressEntertoselect<OK>.
IfyouconnectyourPitotheInternetandareunsurewhetheryournetworkrouterallows
incomingconnectionsthenitisagoodideatochangethispasswordsothatotherpeople
cannotlogintoyourdevice.
ExpandingtheFileSystem
IfyouinstalledRaspbiantotheSDcardusingadiskimage,itispossiblethattheOS
cannotusethefullcapacityofyourSDcard.
Tofixthis:
1.UsetheUpandDownArrowkeystohighlightExpandFilesystemandthenpress
Enter.
2.Whentheprocessiscomplete,pressEntertoselect<OK>.
3.PresstheTabkeyandthentheRightArrowkeytohighlight<Finish>.PressEnter,
andwhenyouarepromptedtorebootthePi,select<Yes>.
ChangingtheDefaultBootSequence
ThedefaultsettingisforRaspbiantofinishloadingandplaceyouatthecommandline.
Fromtheraspi-configtool,youcaninstructRaspbiantoloadthegraphicalenvironment
everytimetheRaspberryPistartsup.Todothis:
1.UsetheUpandDownArrowkeystohighlightEnableBoottoDesktop/Scratch,and
thenpressEnter.
2.PresstheDownArrowkeytohighlightDesktopLoginasuser‘pi’atthegraphical
desktop,andthenpressEnter.
2.5Raspbian’sDesktopEnvironment
Ifyouhavenotchangedthesettinginraspi-config,theRaspberryPiwillbootinto
Raspbian’scommandline.Tostartthedesktopenvironment:
1.Typepiastheusername,thenpressEnter.
2.Typeyourpassword,thenpressEnter.1
3.TypethefollowingcommandandpressEnter:
startx
Afterashortperiodofloading,youwillseeascreensimilartoFigure2.
1.Ifyouhavenotchangedthedefaultpassword,itisraspberry.
Figure2.Raspbian’sdesktopenvironment
Raspbian’sdesktopisacustomizedversionofLXDE,whichstandsforlightweightX11
desktopenvironment.ItissimilartoMicrosoftWindowsandmanyofthewaysthatyou
useitarethesame.
Thescreenisdividedintotwodistinctareas:thedesktop,andtheLXDEpanel.
Figure3.ElementsoftheRaspbiandesktopenvironment1Desktoparea.Hereyoucanfindfilesandlinks(shortcuts)to
applications.Double-clicktheiconstoopenthefileorapplicationthatitlinksto.
2LXDEpanel.Containsthemainmenu,shortcutstocommonly-usedapplications,thedesktoppager,andthesystem
tray.3Menu.TheLXDEmainmenuprovidesaccesstomanyofthesystemsettings,tools,andanyapplicationsthatyou
haveinstalled.4DesktopPager.Formoreinformation,seeSwitchingtheDesktoponpage29.
5Taskbar.Openapplicationsareshownasaniconanddescriptioninthisarea.Ifyouminimizeanapplicationwindow,
youcanclicktheiconintheLXDEpaneltorestorethewindowtofullview.
6SystemTray.Thisisusuallyusedbysystemprocessesandapplicationsthatruninthebackground,sothattheuserhas
somewayofinteractingwiththem.Bydefault,thesystemtraycontainstheCPUmonitor(whichshowshowbusyisthe
CPUis),thecurrenttime,andtheapplicationlaunchbar(anotherplaceyoucanstoreiconstoopencommonly-used
applications).Youcanusuallydouble-clicktheiconsinthisareatoopentheirwindow,orrightclicktheicontoaccess
theapplication’smenu.
OpeningandClosingApplications
Onthedesktop,andinthemenuthatyouaccessfromtheLXDEpanel,youcanseethat
manyapplicationsarealreadyinstalledonyoursystem.
ThereareseveralwaysofrunningapplicationsinRaspbian,butthethreemostcommon
are:clickingiconsonthedesktop,usingthemenu,andopeninganapplicationfromthe
commandline.
Forexample,toopenthewebbrowserMidori:
•Onthedesktop,double-clickMidori.
•OntheLXDEpanel,clicktheMenubutton.PointtoInternet,andthenclickMidori.
•Fromacommand-lineterminalrunninginthedesktopenvironment,typemidoriand
thenpressEnter.Ifyourunapplicationsfromthecommandline,youwillreturntothe
promptwhentheyarefinished.Withapplicationsthatopenawindowinthegraphical
environment,youcanclosetheminthreeways:
•PressAlt+F4onthekeyboard.
•ClicktheClosebuttoninthetop-rightofthewindow.Itlookslikeanx.
•Clicktheiconinthetop-leftofthewindow,andthenclickClose.
SwitchingtheDesktop
OnmostLinuxdesktopenvironments,youcanhavetwo(ormore)workspaces.A
workspaceiscollectionofthewindowsandfilesthatarecurrentlyopen.Switchingto
anotherworkspacehidesallofthewindowsthatarecurrentlyvisible,anddisplaysallof
thewindowsfromtheotherworkspace.InRaspbian,workspacesarealsocalled
“desktops”.
YoucanswitchbetweentheseusingthetwodesktopbuttonsthatmakeuptheDesktop
Pager.
Forexample:
1.Onthedesktop,double-clickMidori.
2.Dragthewindowtothetop-rightcornerofthedisplay.
3.Onthedesktop,double-clickLXTerminal.
4.OntheLXDEpanel,pointtothelightgraysquare.Afterafewmoments,thetext
“Desktop2”willappear.Clickthebutton.
5.Onthedesktop,double-clickPiStore.
6.Clickthe“Desktop1”button(totheleftofthe“Desktop2”button)toswitchbackto
thefirstdesktop.
7.Clickthe“Desktop2”buttontoswitchtotheseconddesktopagain.
Tomoveawindowtoanotherdesktop:clicktheiconinthetopleftofawindow,pointto
Sendtodesktop,andthenclickthenameofthedesktop.
Toincreasethenumberofdesktopsthatyoucanuse:
1.OntheLXDEpanel,right-clicktheDesktopPager.
2.Click“DesktopPager”Settings.
3.OntheDesktopstab,typeanumberintotheNumberofdesktopsbox,orusetheup
anddownarrowbuttonstoincreaseanddecreasethenumberofdesktops.
4.ClickClose.
UsingtheFileManager
YoucanusetheFileManagertocopy,rename,delete,andchangethepropertiesoffiles
thatarestoredontheSDcardoranyUSBstoragedevicesthatyouhaveattached.
Toopenthefilemanager:
•OntheLXDEpanel,clicktheFileManagerbutton–thesecondbuttonfromtheleft;or
•OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickFile
Manager.
1
2
3
45
6
Figure4.TheFileManager
1Applicationmenu.
2Toolbar–navigationbuttonsandaddressbar.
3Tabbar.
4Leftpanel–forselectingplaces,devices,andfiletrees.
5Rightpanel–forselectingfilesandfolders.
6Statusbar.
Likeawebbrowser,theFileManagerwindowcanopenmultiplefoldersatthesametime
byusingtabs.Toopenanewtab:
•Onthetoolbar,clickthefirstbuttonfromtheleft.
Thiswillcreateanewtabinthesamefolder,andwillshowthetabbar.Youcanusethe
tabbartoswitchbetweenthetabsthatarecurrentlyopen.
IfyouhaveusedtheWindowsExplorerinMicrosoftWindowsortheFinderinMacOS
X,youalreadyknowhowtocompletemanyofthemostcommontasks.However,the
tablebelowisabriefsummaryofhowtousetheRaspbianFileManager.
ToDoThis
Switchbetweenthe“Places”viewandthefulldirectorytree
Intheleftpanel,clickPlacesandthenclickDirectoryTree.
Changethewayiconsfilesandfoldersaredisplayedintherightpanel
Ontheapplicationmenu,clickView,andthenclickononeofthefourviewoptions–IconView,ThumbnailView,
CompactVieworDetailedListView.
OpenafolderIntheleftpanel,clickthenameofafolder.Intherightpanel,doubleclickfolder’sicon.
Openafolderusingafilepath
Intheaddressbar,typethefullfilepathandthenpressEnter.
ToDoThis
Openthecurrentuser’shomedirectory
Ontheapplicationmenu,clickGo,andthenclickHomeFolder;oronthetoolbar,clicktheHomebutton.
OpenthedesktopfolderOntheapplicationmenu,clickGo,andthenclickDesktop.
Openthecurrentfolderinthecommandline
Ontheapplicationmenu,clickTools,andthenclickOpenCurrentFolderinTerminal.
SelectafileorfolderIntherightpanel,clickanicon.SelectmultiplefilesorfoldersIntherightpanel,holdCtrland
clicktheiconsofthefilesandfoldersthatyouwanttoselect.DeleteafileorfolderRight-clickaniconandthenclick
Delete.
RenameafileorfolderRight-clickaniconandthenclickRename.
Viewthepropertiesofafileorfolder
Right-clickaniconandthenclickProperties.
OpenafileinitsdefaultapplicationDouble-clickafile’sicon.
Moveafileorfoldertoanewlocation
Right-clickaniconandthenclickCut.Browsetothefolderthatyouwanttomovetheitemto,right-clickintheright
panel,andthenclickPaste.
CopyafileRight-clickaniconandthenclick
Copy.Browsetothefolderwhereyouwantacopytobecreated,right-clickintherightpanel,andthenclickPaste.
Createanewfolder
Right-clickintherightpanel,pointtoCreateNew…,andthenclickFolder.
IfyouareusedtoMicrosoftWindows,theLinuxfilesystemmightseemalittlestrangeat
first.Itcontainsalargenumberoffolders,andmanyofthesehavespecificpurposes.The
keyonesare:
FolderDescription
homeContainsafolderforeachuseraccountonthesystem.Forexample,
/home/piisthehomefolderforthedefaultuseronRaspbianinstallations.Thisiswhereyoushouldstoreallofyour
personalfiles.
etcContainsmostoftheconfigurationfilesfortheoperatingsystem.
devLinuxcreatesfilesystementriesinthisfolderforhardwaredevicesthatareattachedtothesystem.Mediadevices
(forexample,DVDdrives)areplacedin/mntor/mediainstead.
mediaWhenstoragedevicessuchasCDs,memorycards,andUSBflashdrives,areinserted,thesystemcreatesa
“mountpoint”fortheminthisfolder.Mountpointsprovideaccesstothefilesystemonthedevice.
rootThisisthehomefolderforthesystemadministratoraccount.
tmpTemporaryfilesusedbythesystem.ThecontentsofthisfolderaredeletedwhenthePistarts.bootContainsfiles
neededtostartRaspbian.
varStoresvariableandtemporaryfilesthatarecreatedbytheuserorapplicationsrunningastheuser.
binContainsapplicationsthatareusedbyalluseraccounts,thesystem,andthesystemadministrator.
usrContainsapplicationsanddocumentationforalluserapplications.
sbinContainsapplicationsthatareonlyavailabletothesystemandthesystemadministrator.
FolderDescription
libContainslibraries–collectionsofcodeandinformation–thatmustbesharedamongallapplications.
mntSimilarto/media,thisfoldercontainsmountpointsfornon-removablemedia.
Ingeneral,trytokeepallofyourdatainthe/home/pifolder.Wheninstallingnew
softwareandhardwaredevices,theywillusethespecialfoldersiftheyneedto.
AccessingtheCommandLine
Whilemosttaskscanbecompletedusingthedesktopenvironment,therearestillsome
thingsthatyouwillhavetodofromthecommandline.
Toaccessthecommandlinefromthegraphicalenvironment:
•Onthedesktop,double-clickLXTerminal.
•OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclick
LXTerminal.
Inthecommandline,filesandfoldershavefilenamesandfilepaths.Thefilepath
includesthenamesofthefoldersandsubfoldersthatthefileisstoredin.Forexample,a
fileocr_pi.pnginthepiuser’shomefolderhasthefullfilepath:/home/pi/ocr_pi.png
Filepathsthatbeginwithaforwardslashstartfromthetop-levelfolder.Sotheexample
abovetellsthesystem:startatthetoplevelandmoveintothehomefolder,thenmoveinto
thepisubfolder,andthenfindthefileocr_pi.png.
Ifyouarealreadyinthehomefolder,youcanrefertothesamefileas:pi/ocr_pi.png
Andifyouareinasubfolderof/home/pi,youcanrefertothefileusingtwodotsthat
symbolizemovingtotheparentdirectory:../ocr_pi.png
Toruncommands:typethecommandusingthekeyboardandthenpressEnter.Thereare
alargenumberofcommandsavailable(toomanytolisthere),butthesearesomeofthe
mostcommon:
ToDoThis
Listthecontentsofthecurrentfolder
TypelsandthenpressEnter.
ListthecontentsofaspecificfolderTypelsfollowedbyaspaceandthenthenameofthefolder.ThenpressEnter.
MoveintoasubfolderTypecdfollowedbyaspaceandthenthenameofthefolder,andthenpressEnter.
MovetoaparentfolderTypecd..andthenpressEnter.CreateasubfolderTypemkdirfollowedbyaspaceandthenthe
nameofthefolder,andthenpressEnter.
DeleteafolderTypermdirfollowedbyaspaceandthenthenameofthefolder,andthenpressEnter.
DeleteafileTypermfollowedbyaspaceandthenthenameofthefile,andthenpressEnter.
CopyafileorfolderTypecpfollowedbyaspaceand
thenthename(orfullfilepath)ofthefiletobecopied.Typeanotherspaceandthenthename(orfullfilepath)tocall
thecopy.PressEnter.
RenameormoveafileorfolderTypemvfollowedbyaspaceand
thenthename(orfullfilepath)ofthefiletobecopied.Typeanotherspaceandthenthename(orfullfilepath)tocall
thecopy.PressEnter.
ClearthecommandlinewindowTypeclearandthenpressEnter.
Toclosethecommandline,dooneofthefollowing:
•PressAlt+F4onthekeyboard.
•ClicktheClosebuttoninthetop-rightofthewindow.
•Clicktheiconinthetop-leftofthewindow,andthenclickClose.
•Ontheapplicationmenu,clickFileandthenclickQuit.
•TypethefollowingcommandandthenpressEnter:
exit
IntheAccessoriesgroupoftheLXDEpanelmenu,thereisanotherterminal.Thisoneis
called“RootTerminal”.Whenyouopenthecommandlineusingthisapplication,youare
automaticallygrantedsystemadministratorprivileges.
Ifyouonlywanttorunasinglecommand,youcandothisfromtheRaspbianmenu.OntheLXDEpanel,click
theMenubuttonandthenclickRun.TypeyourcommandandthenpressEnter.
UnderstandingLinuxUsersandSuperusers
IfyouhaveusedmorerecentversionsofMicrosoftWindowsthenyoumaybeusedto
runningcertainapplicationsasanadministrator.ThisconceptisalsoinLinux.
Superusers(oftencalled“root”)havefullaccesstothesystem.Anyapplicationsyourun
asasuperuserwillalsohavefullaccesstothesystem.Toprotectthesystemfrom
accidentalormaliciousdamage,yourarelylogintoRaspbianasasuperuser.
NormalusershavelessaccesstothecorefilesneededbytheOS,andthismeansthatany
applicationsthattheyrunalsohavelessaccesstothesystem.InRaspbian,piistheuser
thatlogsintothedesktopenvironment,anditisanormaluser.
Whenyoudoneedtochangepartofthesystem,oraccomplishataskthatonlysuperuser
cando,youcan:
•OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickRoot
Terminal;or
•Fromthenormalcommandline,typesudofollowedbyaspacebeforethecommandthat
requiressuperuseraccessprivileges.
2.6CommonTasks
Inthissection,youcanfindinstructionsforsomeofmostcommontasksthatpeople
performafterinstallingRaspbian.Theseinstructionscontinueintothenextsection,2.7
NetworkConnectionsandRemoteAccessonpage40.
RestartingandShuttingDowntheRaspberryPiTorestartthePi:
1.OntheLXDEpanel,clicktheMenubuttonandthenclickRun.
2.TypethefollowingcommandandthenpressEnter:sudoshutdown–rnow
ToshutdownthePifromthedesktop:
1.Onthedesktop,double-clickShutdown.2.ClickYes.
ToshutdownthePifromthecommandline:
•TypethefollowingcommandandthenpressEnter:sudoshutdown–hnow
ConfiguringtheTVService
IfyouconnectyourPitoatelevisionusinganHDMIcable,Raspbianautomatically
selectsascreensizethatitdecideswillbethebestforyoursetup.However,thisisnot
alwaysthehighestresolution.
TheconfigurationsettingthatcontrolshowRaspbianselectsthescreensizeisinthefile
/boot/config.txtandyoucanadjustthissettingwithatexteditor:
1.OntheLXDEpanel,clicktheMenubutton,point
toAccessories,andthenclickRootTerminal.2.Typethefollowingcommandandthen
pressEnter:
tvservice–dedid
3.TypethefollowingcommandandthenpressEnter:
edidparseredid
4.Findthevideomodethatyouwanttouse,andmakenoteofthemodenumberand
whetheritsays“DMTmode”or“CEAmode”.
5.TypethefollowingcommandandpressEnter:nano/boot/config.txt
6.PresstheDownArrowkeyuntilyoufindthelinesthatbeginwith
#hdmi_group=
#hdmi_mode=
7.Removethe#fromthestartofbothofthoselines.8.IfthevideomodeisDMT,change
thehdmi_groupto2:
hdmi_group=2
9.IfthevideomodeisCEA,changethehdmi_group
to1:
hdmi_group=1
10.Typethemodenumberafterhdmi_mode=,for
example:
hdmi_mode=16
11.PressCtrl+X.
12.PressY,andthenpressEnter.
13.RestarttheRaspberryPi.
InstallingaGraphicalPackageManager
Wheninstallingnewapplications,thereareafewstepsthatneedtobetaken:
1.Findoutwhethertheapplicationiscompatiblewith
theOS.
2.Installanyotherpiecesofsoftwarethatthisnewapplicationrequires.
3.DownloadtheapplicationfromtheInternet.4.Installtheapplicationtothecorrect
folders.
InLinux,thepackagemanagerhandlesallofthisforyou.Youcanalsouseittouninstall
applicationsthatyoudonotwantanymore.Packagemanagersconnecttorepositories–
onlinelibrariesofsoftware.AndsinceLinuxisopen-source,mostofthesoftwareinthese
repositoriesisalsoopen-source(andfree).
Thepackagemanagerthatisbuilt-intoRaspbianisaccessedfromthecommandline.
However,youcanalsoinstallonethatrunsinthegraphicaldesktopenvironment.
OnesuchtoolisSynaptic.Toinstallit,usethecommand-linepackagemanager:
1.OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickRoot
Terminal.
2.TypethefollowingcommandandthenpressEnter:apt-getinstallsynaptic
3.Whentheprocessiscomplete,typethefollowingcommandandthenpressEnter:
exit
ToruntheSynapticpackagemanager:
•OntheLXDEpanel,clicktheMenubutton,pointtoPreferences,andthenclick
SynapticPackageManager.
2.7NetworkConnectionsandRemoteAccess
SettingupWi-Fi
BeforebuyingaUSBWi-FiadapterforusewiththeRaspberryPi,checkthattheadaptor
isknowntobeworkingbylookingatthelistathttp://elinux.org/RPi_USB_WiFi_Adapters
ToinstallaUSBWi-FiadapteronyourPiandconnecttoyournetwork:
1.InserttheUSBdeviceintoanavailableUSBsocketonthePi,oronaUSBhub.
2.Onthedesktop,double-clickWiFiConfig.
3.IntheAdapterlist,clickwlan0.Ifyouhavenoadaptersinthelist,yourUSBdeviceis
not
compatiblewiththeRaspberryPi.
4.ClickScantoopenthe“Scanresults”window.
5.ClickScan.
6.Double-clickthenameofyourWi-Finetwork.
7.CheckthattheAuthenticationandEncryptionsettingsmatchhowyourother
computersconnecttoyourrouter.
8.TypeyournetworkpasswordintothePSKbox.9.ClickAdd,andthenclickClose.
FindingtheIPAddress
ToconnecttothePifromanothercomputeronyournetwork,youwillneedtoknowitsIP
address.Tofindthis:
1.Onthedesktop,double-clickLXTerminal.
2.TypethefollowingcommandandthenpressEnter:ifconfig
Theaddressyouneediscalled“inetaddr”andconsistsoffournumbersseparatedbydots.
IfyouareconnectedtoyournetworkusinganEthernetcable,youcanfindtheaddressin
thesectionlabelled“eth0”.Ifyouareconnectedtoyournetworkusingawirelessadaptor,
youcanfindtheaddressinthesectionlabelled“wlan0”.
UsingaStaticIPAddress
WhenthePirestarts,orreconnectstothenetwork,yournetworkrouterwillgivethePian
IPaddress.However,thiscanchangeeverytime.
YoucanconfigurethePisothatitalwaysusesthesameIPaddress.Youneedafewpieces
ofinformationandyouwillneedtoeditaconfigurationfileinatexteditor.
Todothis:
1.Onthedesktop,double-clickLXTerminal.
2.TypethefollowingcommandandthenpressEnter:ifconfig
3.IfyouareusinganEthernetcable,inthesectionlabelled“eth0”,makeanoteofthe
values“inetaddr”,“Bcast”and“Mask”.
4.IfyouareusingWi-Fi,inthesectionlabelled“wlan0”,makeanoteofthevalues“inet
addr”,“Bcast”and“Mask”.
5.TypethefollowingcommandthenpressEnter:netstat-nr
6.Makeanoteofthevaluesin“Gateway”and“Destination”.Ifyoucanseetwoentriesin
thetable,ignorethevalues0.0.0.0andusethevaluefromtheotherline.
7.TypethefollowingcommandandthenpressEnter:sudonano/etc/network/interfaces
8.IfyouareusingWi-Fi,skiptostep12.
9.IfyouareusinganEthernetcable:changethelinethatreadsifaceeth0inetdhcpto
ifaceeth0inetstatic
10.Addthefollowinglines,startingonanewlineaftertheword“static”.Replacethe
valuesinangledbracketswiththevaluesfromtheprevioussteps:
address<inetaddr>
netmask<mask>
network<destination>
broadcast<bcast>
gateway<gateway>
11.Skiptostep14.
12.IfyouareusingWi-Fi:changethelinethatreadsifacewlan0inetdhcpto
ifacewlan0inetstatic
13.Addthefollowinglines,startingonanewlineafter
theword“static”.
address<inetaddr>
netmask<mask>
gateway<gateway>
14.PressCtrl+X.
15.PressY,andthenpressEnter.
16.RestarttheRaspberryPi.
TransferringFilestoandfromtheRaspberryPi
Youcanusesecurecopy(SCP)totransferfilesfromyourcomputertoaPi,ortocopy
filesfromthePitoanothercomputer.Raspbianalreadysupportsthis,andsoyouonly
needtoinstallaclientonyourmaincomputer.
OnWindows,WinSCPisverypopularapplicationfortransferringfiles.Youcan
downloaditforfreeathttp://winscp.net
OnMacOSX,youcanuseanapplicationcalledCyberduck.Thisisafreedownloadfrom
http://cyberduck.io/oryoucandownloaditfromtheMacAppStore.
ThedetailsyouneedtomakeaconnectiontothePiarelargelythesameregardlessof
whichSCPclientyouuse:
Server/Hostname:theIPaddressofyourPi
Username:pi
Password:thisisraspberryifyouhavenotyetchangedit.Protocol:SCP
TodownloadfilesfromthePi,dragtheiconsfromtheSCPclient’swindowtoaWindows
ExplorerorFinderwindow.TouploadfilestothePi,dragfilesfromaWindowsExplorer
orFinderwindowanddropthemontotheSCPclient’swindow.
ConnectingtothePiwithSSH
Secureshell(SSH)isawayoftalkingtoyourPioveranencryptedtransmission.Itis
typicallyusedwhenyouwanttoaccesstheRaspberryPi’scommandlinefromanother
computer.AslongasyourPihasanetworkconnection,youcanconnecttoitremotely
andtypecommands.
OnWindows,youwillneedanapplicationthatunderstandstheSSHprotocol.Thereare
manyoftheseavailable,butPuTTYisoneofthemorepopularones.Downloaditfrom
http://www.chiark.greenend.org.uk/~sgtatham/putty/
YoudonotneedanadditionalSSHclienttoconnecttothePionMacOSX.
ToconnecttoyourPioverSSHonWindows(8/7/Vista/XP):1.Locatethefileputty.exe
thatyoudownloaded,andthendouble-clickit.
2.IntheHostName(orIPaddress)box,typetheIPaddressofyourPi.
3.ClickOpen.
4.Attheloginprompt,typepi.
5.Atthepasswordprompt,typeyourpasswordandpressEnter.Thisisraspberryifyou
havenotchangedit.
ToconnecttoyourPioverSSHonMacOSX:
1.Onthedock,clickFinder.
2.Onthesidebar,clickApplications.
3.ClickUtilities,andthendouble-clickTerminal.
4.Typethefollowingcommand,replacing<IP>withtheIPaddressofyourRaspberryPi:
[email protected]<IP>
5.PressEnter.
6.Atthepasswordprompt,typeyourpasswordandpressEnter.Thedefaultpasswordis
raspberryifyouhavenotchangedit.
ConnectingtothePiwithRemoteDesktop
MicrosoftWindowscomeswithanapplicationcalled“RemoteDesktop”.Youcanusethis
toconnecttoyourRaspberryPiandusethedesktopenvironmentfromaWindows
computer.MacOSXusersneedtodownload“MicrosoftRemoteDesktop”fromtheMac
AppStore.
YoualsoneedtoinstallasmallsoftwareapplicationonthePibeforeyoucanconnect
usingRemoteDesktop.
Toinstallthesoftwarefromthecommandline:
1.OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickRoot
Terminal.2.TypethefollowingcommandandthenpressEnter:apt-getinstallxrdp
TostartaRemoteDesktopconnectionfromWindows(8/7/Vista/XP):
1.PresstheWindowslogokey+R.ThentypemstscandpressEnter.
2.IntheComputerbox,typetheIPaddressofyourRaspberryPi,andthenpressEnter.
3.Inthe“Logintoxrdp”window,intheusernamebox,typepi.
4.Inthepasswordbox,typeyourpassword.1
5.ClickOK.
BrowsingtheWeb
IfyouareusingthelatestversionofRaspbian,thewebbrowseriscalledEpiphanyandit
isinstalledwhenyouinstalltheOS.Inotherversions,thewebbrowserisMidori.
Toopenawebbrowser:
•OntheLXDEpanel,clicktheMenubutton,pointtoInternet,andthenclickMidorior
EpiphanyWebBrowser.
2.8OtherOperatingSystems
RaspbianLinuxisnottheonlyOSthatyoucanrunonaRaspberryPi.Manyvarietiesof
Linuxhavebeenrepackagedsothatyoucanusethem,andthereareseveralnon-Linux
operatingsystemsthatalsowork.
ArchLinux
ArchLinuxisanextremelylightweightversionofLinuxthatisidealforserversor
deviceswithunusualpurposes–wheremanyofthepackagesthatarenormallyinstalledto
createausabledesktopenvironmentarenotneeded.
YoucandownloadadiskimageofArchLinuxfromhttp://
www.raspberrypi.org/downloads/,oritcanbeinstalledusingNOOBS.
RISCOS
RISCOSisavailableathttp://www.raspberrypi.org/downloads/oryoucaninstallitusing
NOOBS.Ithasbeeninusesince1987,andwasdesignedforArchimedeslineof
computersmadebyAcornComputersLtd.ThesemachinesusedthefirstARM
processors.
1.Ifyouhavenotchangedthedefaultpassword,itisraspberry.
RetroPie
RetroPieisacustomizedversionofRaspbianthatrepackagestheOSwithavarietyof
emulatorsforclassiccomputersandvideogamesconsoles.Findoutmoreathttp://
blog.petrockblock.com/retropie/
Plan9
Plan9isdevelopedbyBellLabs,andhasitsoriginsinanOSthatwasreleasedinthe
1980s.Itisverylightonsystemresources,andquitedifferentfromtheoperatingsystems
thatpeopleareusedtotoday.YoucandownloadadiskimageofPlan9from
http://plan9.bell-labs.com/wiki/plan9/download/
AEROS
AROSisdesignedtobeasuccessortotheoperatingsystemAmigaOS,whichisitself
basedontheoperatingsystemusedbytheCommodoreAmigarangeof16-bitcomputers.
TheRaspberryPiversioniscalledAEROS.Thecurrentversionisonlyavailableto
registeredusers,butolderversionsareavailableathttp://www.aeros-os.org/styled11/index.html
Android
Androidisanoperatingsystemfortabletsandsmartphones,butitisnotyetfullyusable
ontheRaspberryPi.Thewebpageforthisprojectis
http://androidpi.wikia.com/wiki/Android_Pi_Wiki
NoOperatingSystem
Ifyouareanexperiencedsoftwaredeveloperandyoudonotneedtorunanyother
applications,thenyoumightbeabletorunyourcodewithoutinstallinganoperating
system.Thisiscalled“bare-metal”programmingandtherearevarioustutorialsand
samplesavailableonthewebtohelpyou.
3–BuildingaMediaCenterwithXBMC
3.1XBMC
XBMCisamediaplayerthatisdevelopedbytheXBMCFoundation.Asamultiplatform,highly-customizable,andopensourcesoftwarepackage,itisextremelypopular
andisusedonawidevarietyofdevices.
XBMCcanplayaudioandvideofilesinmanyformats,including:3GP,AAC,APE,AVI,
CDDA,FLV,MIDI,MKV,MP3,MP4,M4A,MPEG,OGG,WAV,WMA,WMV,and
manymore.1ItcanevenplayDVDsfromISOdiscimages.
ManypeoplehaveaRaspberryPispecificallyforthepurposeofrunningXBMC.ThePi’s
compactsize,lowcost,supportforUSBdevicesandnetworking,andbuilt-inHDMI
outputmakeitanexcellentchoiceforamediaplayerthatsitsnexttotheTVanddoesnot
takeupalotofspace.
ThecurrentversionofXBMCfortheRaspberryPiis13.2“Gotham”.WhentheXBMCFoundationrelease
version14ofthesoftware,theywillrenameXBMCto“Kodi”.
Inthischapter,youcanseehowtoinstallXBMConyourPi.Youwillalsolearnthebasics
ofhowtoworkwiththeuserinterface,andhowtoaddmediafilestothesystem.
Tocompletethistutorial,youneed:
•ARaspberryPi(anymodel)connectedtoyourlocalnetworkandwithaccesstothe
Internet.
•Akeyboardandmouse.
•AUSBstoragedevice,suchasamemorystickorharddrive.
1.ForthecompletelistofcontainerformatsandcodecsthatXBMCsupports,seehttp://wiki.xbmc.org/index.php?
title=Features_and_supported_formats
3.2Installation
IfyouhaveablankSDcardthatyouwillbeusingforyourmediacenterthenyoucan
installtheoperatingsystemandXBMCtogether.RaspBMCandOpenELECaretwo
LinuxdistributionsthatalreadycontainXBMC,andyoucaninstallthesefromNOOBS.
FormoreinformationaboutinstallingoperatingsystemsusingNOOBS,seesection2.2
InstallationofRaspbianwithNOOBSonpage16.
TostartNOOBSwhenanexistingOSisalreadyontheSDcard:turnoffthePi,andthen
holdtheShiftkeyasyouturnthePibackonanduntilyouseetheNOOBSwindow.
NOOBScaneitherremoveyourexistingOS,oraddRaspBMCorOpenELECasanadditionaloption.Toremove
anOS,unchecktheboxnexttoitbeforeyouclickInstall.IfyouleaveyourexistingOSontheSDcard,youwill
beaskedtochoosewhichoneyouwanttoloadwhentheRaspberryPistartsup.
IfyoucannotuseNOOBS,youcanalsodownloaddiskimagesofthedistributionsfrom
http://www.raspberrypi.org/downloads/andthenrefertosection2.3Installationof
RaspbianusingaDiskImageonpage20formoreinformationabouthowtowritethefile
toanSDcard.
IfRaspbianisalreadyinstalledonyourcardandyouwanttoaddXBMCtoit,installing
XBMCusuallyonlytakesafewminutes.Tobegin,youneedtoaddMichaelGorven’s
repositorytothelistofapplicationsourcesinLinux:
1.OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickRoot
Terminal.
2.TypethefollowingcommandandthenpressEnter:nano/etc/apt/sources.list.d/mene.list
3.Typethefollowingtextasthefirstlineinthefile:
debhttp://archive.mene.za.net/raspbianwheezycontrib
4.PressCtrl+O,andthenpressEnter.
5.PressCtrl+X.
6.Typethefollowingcommandononeline,andthenpressEnter:
apt-keyadv—keyserverkeyserver.ubuntu.com
-recv-key5243CDED
7.TypethefollowingcommandandthenpressEnter:apt-getupdate
ToinstallXBMCfromthecommandline:
•TypethefollowingcommandandthenpressEnter:apt-getinstallxbmc
XBMCdoesnotworkcorrectlyif64MBorlessmemoryisallocatedtotheGPU.Asthis
isthedefaultsettingforRaspbianinstallations,youneedtochangeitinraspi-config:
•IntheRootTerminal,typethefollowingcommandandthenpressEnter:
raspi-config
•or,ontheLXDEpanel,clicktheMenubutton,and
clickRun.Typethefollowingcommandandthen
pressEnter:
sudoraspi-config
WhentheRaspberryPiSoftwareConfigurationToolappears:
1.PresstheDownArrowkeyrepeatedlyuntilAdvancedOptionsishighlighted,and
thenpressEnter.
2.PresstheDownArrowkeytwicetoselectA3MemorySplit.PressEnter.
3.Changethevalueto128andthenpressEnter.4.PresstheRightArrowkeytwiceto
select<Finish>.ThenpressEnter.
5.PressEntertoselect<Yes>andrebootthePi.
RunningXBMC
XBMCisastandaloneapplicationanddoesnotrunthedesktopenvironment.Torunit,
youmustdropbacktothecommandline:pressCtrl+Alt+F1.Toreturntothedesktop
environment,pressAlt+F7.
TostartXBMC:
•TypethefollowingcommandandthenpressEnter:xbmc-standalone
However,startingXBMCthiswayreducestheamountofmemoryandsystemresources
availabletoit.IfyouwanttouseyourRaspberryPiasadedicatedmediaplayerand
automaticallyrunXBMCwhenitstartsup:
1.OnacommandlineorLXTerminal,enterthefollowingcommandandpressEnter:
sudonano/etc/default/xbmc
2.ChangeENABLED=0to
ENABLED=1
3.ChangeUSER=xbmcto
USER=pi
4.PressCtrl+X,thenpressY,andthenpressEnter.5.Typethefollowingcommandand
thenpressEnter:
sudoraspi-config
6.PresstheDownArrowkeytwicetohighlight
EnableboottoDesktop/Scratchandthenpress
Enter.
7.HighlightConsoleTextconsole,requiringlogin
(default)andthenpressEnter.
8.PresstheRightArrowkeytwicetohighlight
<Finish>,andthenpressEnter.
9.PressEntertoselect<Yes>.
3.3FirstSteps
OnceXBMCisfinishedloaded,youshouldseeascreensimilartoFigure1below.
Figure1.TheXBMChomescreen
1Recentvideos.WhentheMoviesorTVShowsmenuoptionishighlighted,XBMCwillshowthefilesthathavemost
recentlybeenaddedtoyourlibrary.Youcanclickoneoftheseitemstostartplaying.
2Mainmenu.
3Favorites.Clickthisbuttonforquickaccesstoitemsthatyouhaveplacedinyourfavoriteslist.Toaddanitemtoyour
favorites,rightclickittoopenitscontextmenu.
4Exit.TocloseXBMCandreturntotheLinuxcommandline,clicktheExitbutton,andthenclickExit.
AllofXBMC’sfeaturescanbeaccessedusingitsmouse-drivenmenusystem,you
generallyonlyneedtousethekeyboardfortypinginconfigurationsettings.
Tocontrolthehomescreenmenu:
•Movethemousepointertothefarleftandfarrightsidesofthemenutoscrollit.
•Pointtoamenuitemtobringupanyoptionsthatareavailableinthatcategory.
•Clickamenuitem(oroptionunderneath)toopenit.Mostmenuitemsopenadifferent
screenwhenyouclickthem.Tocontrolthesescreens:
•Clickwiththeleftmousebuttontoactivatemenuitemsandbuttons.
•Right-clickanareaofthescreenthatdoesnotcontainamenuitemorbuttontomoveto
thepreviousscreen.
•Right-clickamediafileorfoldertobringupacontextmenuwhichhasadditional
optionsthataffecttheselecteditem.
•Toopenthesidebar,movethemousepointerovertothetabontheleftsideofthescreen.
Toclosethesidebar,movethemousepointerawaytotheright.
•ClicktheBackbuttontoreturntothepreviousscreen.
•ClicktheHomebuttontoreturntothehomescreen.
Figure2.TheMoviesbrowserandthesidebar
XBMCdividesmediafilesintocategoriesdependingonwhethertheyareamoviefile,an
episodeofaTVshow,amusicfile,apictureorphoto,oraprogram.Thedifferenttypesof
fileareaccessedusingdifferentmenuitemsonthehomescreenmenu.
ChangingtheXBMCSkin
TheRaspberryPiversionofXBMCusesaninterfacetheme(or“skin”)called
“Confluence”.Ifyouwanttochangethis,youcandownloadnewskinsdirectlyfromthe
XBMCsystemsettings.
Todownloadandenableanewskin:
1.OntheXBMCHomescreen,clickSystem.
2.ClickAppearance,andthenclickthefirstitemintherightpanel.Thisitemhasthe
word“Skin”ononeside,and“Confluence”ontheorder.
3.ClickGetMore…
4.Pointtoeachskintoloadapreviewand
description.
5.Todownloadaskin,clickit,andthenclickInstall.6.Whenaskedifyouwanttoswitch
tothisskin,clickYes.
TochangetheskinbacktoConfluence:
1.OntheXBMCHomescreen,clickSystem.
2.ClickAppearance,andthenclickthefirstitemintherightpanel.
3.ClicktheConfluenceskin.
ThebasiccontrolsforusingXBMCdonotchangewithdifferentskins.However,the
layout,colors,andthewaymediafilesaredisplayedandpreviewedcanchange.
3.4MediaFilesandtheLibrary
UsingXBMC,youcanviewfilesfromUSBdevices(suchasmemorysticksandhard
drives)oroveryourlocalnetwork.
Inadditiontobrowsingforfileseachtimeyouwanttoplaysomething,youcanadd
devicesandnetworkfolderstoyourXBMClibrary.Thelibraryisalistofallofthefiles
thatyouhaveavailable,andusuallycontainsextrainformationsuchaspreviewimages
anddescriptions.
Notethatevenifyouaddafiletoyourlibrary,itisstillstoredontheoriginaldeviceand
willnotbeavailableifthatdeviceisunpluggedorturnedoff.
PlayingMediaFilesfromUSBDevices
KeepingyourmediafilesonUSBstoragedevicesmeansthatyouarenottakingupspace
ontheSDcardusedtorunXBMC.AndyoucanremoveUSBdevicesatanytime–
makingthisaconvenientwayoftransferringfilesfromyourPCtobeplayedonyour
mediabox.
Toplayafilewithoutaddingittoyourlibrary:
1.InserttheUSBdeviceintoafreeUSBslotonthePiorUSBhub.Youcandothiswhen
thePiisonandrunningXBMC.
2.OntheXBMCHomescreen,pointtoVideosandthenclickFiles.
3.ClicktheUSBdevicethatcontainsthefileyouwanttoplay.
4.Browsetothefileandthenclickit.
AddingFilestoyourLibrary
YourXBMClibraryismadeupofalistofsources,andinformationaboutthemediafiles
thatyouhaveonyoursystem.AsourceisXBMC’stermforafilepaththatitremembers
betweensessions,andthatitassociateswithaparticulartypeofcontent(forexample,a
movie).WhenXBMCupdatesyourlibrary,itopenseachsourcefolderandexaminesall
ofthecompatiblemediafilesinside.
Duringthisprocess,XBMCrunsspecialprogramscalled“scrapers”.Theseadd-onsfind
theinformationaboutthefilesinyourlibraryandforthistowork,thefilenamesof
moviesandTVshowsthatyouwanttoaddmustfollowasetpattern.Ifthescrapercannot
identifythefilefromthefilename,XBMCwillnotaddthefiletoyourlibrary.
Theinstructionsbelowareanexampletogetyoustarted;formoredetailedinformation,
seehttp://wiki.xbmc.org/index.php?title=Naming_video_files
IfyourUSBdevicecontainsmoviefilesandTVshows,createtwosubfoldersonthe
deviceanduseoneformovies,andtheotherfortheTVshowepisodes.
Whennamingmoviefiles,usethepattern:Title(Year).extForexample:HouseOn
HauntedHill(1999).mp4ToaddthemoviesfolderontheUSBdeviceasasource,and
loadthefilesintoyourlibrary:
1.InserttheUSBdeviceintoafreeUSBslotonthePiorUSBhub.Youcandothiswhen
thePiisonandrunningXBMC.
2.OntheXBMCHomescreen,pointtoVideosandthenclickFiles.
3.ClickAddVideos…andthenclickBrowse.
4.ClickRootfilesystem.
5.Clickmedia,andthenclickthe“name”oftheUSBdevice.
6.Clickthemoviesfolder,andthenclickOK.
7.ClickOK.
8.FromtheThisdirectorycontainslist,select(Movies).
9.UnderChooseaScraper,clickTheMovieDatabase(oranotherscraperifyouhave
alreadyinstalledone).
10.ClickOK.
11.Ifyouareaskedwhetheryouwanttorefreshinfoforallitems,clickYes.
IfTheMovieDatabasescrapercannotfindyourmovieinitslistings,XBMCwillnotaddthefiletoyourlibrary.
Thereareotherscrapersavailableandyoucaninstalltheminsection3.6Add-onsonpage65.
ToaddTVshowstoyourlibrary,itisadvisabletocreateadirectorystructureinsidethe
TVshowfolderontheUSBdevice.
CreateafolderforeachTVseries.Forexample,createafoldercalledTheAddams
Family.Thencreatesubfoldersinsidethatforeachseason.Forexample,TheAddams
Family/Season1andTheAddamsFamily/Season2.
Placethevideofilesforeachseasoninthecorrectsubfolder,andnameeachfilewiththe
pattern:AnythingIncludingSpaces_sXXeYY.ext.ReplaceXXwiththeseasonnumber,and
YYwiththeepisodenumber.Forexample:TheAddamsFamily_s01e01.mp4
ToaddtheTVshowsfolderontheUSBdeviceasasource,andloadthefilesintoyour
library:
1.InserttheUSBdeviceintoafreeUSBslotonthePiorUSBhub.Youcandothiswhen
thePiisonandrunningXBMC.
2.OntheXBMCHomescreen,pointtoVideosandthenclickFiles.
3.ClickAddVideos…andthenclickBrowse.
4.ClickRootfilesystem.
5.Clickmedia,andthenclickthe“name”oftheUSBdevice.
6.ClicktheTVshowsfolder,andthenclickOK.
7.ClickOK.
8.FromtheThisdirectorycontainslist,select(TVShows).
9.UnderChooseaScraper,clickTheTVDB(oranotherscraperifyouhavealready
installedone).
10.ClickOK.
11.Ifyouareaskedwhetheryouwanttorefreshinfoforallitems,clickYes.
Ifthescrapercannotfindyourfileinitslistings,XBMCwillnotaddthefiletoyourlibrary.Thereareother
scrapersavailableandyoucaninstalltheseusingtheAdd-onsmenu.
Playingandaddingmusicfilestoyourlibraryworksinthesameway.OntheHome
screen,pointtoMusicandthenclickFiles.
RemovingUSBDevices
MakesurethatyouproperlyejectUSBdevicesfromthesystem.Thisprocessstops
XBMCfromreadingorwritingtothedevicewhileyouunplugit,andensuresthatallof
thechangesthatneedtobemadetothefilesystemarecompleted.
TosafelyremoveaUSBdevice:
1.OntheXBMCHomescreen,pointtoVideosandthenclickFiles.
2.Right-clickthedevice,andthenclickRemovesafely.
3.RemovetheUSBdevicefromtheUSBsocket.
IftheUSBdevicecontainsthefilesforitemsinyourlibrary,thoseitemswillbe
unavailableuntilyouplugthedevicebackintoyourPi.
PlayingVideosfromYourLibrary
Onceyouhaveaddedsomevideostoyourlibrary,youcanaccessthemfromtheXBMC
homescreen.Toplayamovie,either:
•OntheXBMCHomescreen,pointtoMovies,andthenclickthepreviewofthefilethat
youwanttoplay;or
•OntheXBMCHomescreen,clickMoviestoloadthemoviebrowser.
Ifyouusethemoviebrowser,clickthenameofamovietostartplaying,orright-clickthe
movieandthenclickMovieinformationtobringupawindowcontainingallthe
informationthatthescrapercouldfindoutaboutthatfile.
Figure3.Themovieinformationdisplay
ToplayaTVshow,either:
•OntheXBMCHomescreen,pointtoTVShows,andthenclickthepreviewofthefile
thatyouwanttoplay;or
•OntheXBMCHomescreen,clickTVShowstoloadtheshowbrowser.
IfyouusetheTVshowbrowser,clickthenameofaseriestoloadtheepisodesorrightclickitandthenclickTVshowinformationtoviewthedetailsofthatseries.Clickan
episodetostartplaying,orright-clicktheepisodeandthenclickEpisodeinformationto
bringupawindowcontainingalltheinformationthatthescrapercouldfindoutaboutthat
particularepisode.
3.5NetworkDevicesandOtherComputers
ConnectingtoSMBShares
Servermessageblock(SMB)isanetworkingprotocolforsharingprinters,files,and
foldersbetweendevicesonalocalnetwork.Itisawell-establishedsystem,andsupport
foritisbuilt-inonmostpopularoperatingsystems.UsingSMB,XBMCcanaccess
foldersonyourWindows,MacOSX,orLinuxPCsasiftheywerelocaldevices.
SMBsharesmustbeaddedtoXBMCassources,andsoitisusuallyusefultohaveyour
movies,TVshows,music,andpicturesseparatedintodifferentfolders.
TocreateanewsharedfolderonWindows(8/7/Vista/XP):1.PresstheWindowslogokey
+R.TypeexplorerandthenpressEnter.
2.BrowsetoalocationonyourPCthateitheralluserscanaccess(suchasanextrahard
drivepartition)orthatbelongstotheuserthatiscurrentlyloggedin.
3.Right-clickintherightpanel,pointtoNew,andthenclickFolder.
4.Typeaname(forexample,Videos)andthenpressEnter.
5.Right-clickthefolder,andthenclickProperties.6.OntheSharingtab,under
NetworkFileandFolderSharing,clickShare.
7.IntheFileSharingwindow,clickShare.
8.ClickClose.
9.InWindowsExplorer,double-clickthefolder.Right-clickintherightpanel,pointto
NewandthenclickFolder.Typeaname(forexample,Movies)andthenpressEnter.
10.Right-clickintherightpanel,pointtoNewandthenclickFolder.Typeaname(for
example,TVShows)andthenpressEnter.
11.Copyormoveyourmoviefilesintothemoviesfolder,andTVshowepisodesintothe
TVshowsfolder.
TocreateanewsharedfolderonMacOSX(10.5orlater)usingGuestSharing:
1.Onthedock,clickFinder.
2.Browsetoyourhomefolder.
3.OntheFilemenu,clickNewFolder.Typeaname(forexample,Videos)andpress
Enter.
4.Clickthisfolder.
5.OntheFilemenu,clickNewFolder.Typeaname(forexample,Movies)andpress
Enter.
6.OntheFilemenu,clickNewFolder.Typeaname(forexample,TVShows)andpress
Enter.
7.Copyormoveyourmoviefilesintothemoviesfolder,andTVshowepisodesintothe
TVshowsfolder.
8.OntheApplemenu,clickSystemPreferences.
9.ClickSharing.
10.ClicktheboxnexttoFileSharing.
11.BelowtheSharedFolderslist,clickthe+button.
12.Browsetoyourvideosfolder,double-clickit,andthenclickAdd.
13.NexttoEveryone,clickReadOnly,andthenclickRead&Write.
14.ClickOptions.
15.ClicktheboxnexttoSharefilesandfoldersusingSMB.
16.ClickDone.
NowthatsharingisenabledandyouhavefoldersthatyouwantXBMCtolookat,addthe
SMBshareasanXBMCvideosource:
1.OntheXBMCHomescreen,clickVideos.
2.ClickAddVideos…andthenclickBrowse.
3.ClickAddnetworklocation…1
4.IntheProtocollist,clickWindowsnetwork(SMB).
5.NexttoServer,clickBrowse.
6.Clickthenameofyourworkgroup,andthenclickthenameoftheWindowsPCorMac.
7.IntheUsernamebox,typeyourWindows
username(orthenameofauseraccountthathasaccesstothesharedfolder.)Donotenter
ausernameifyouareusingGuestSharingonMacOSX10.5orlater.
8.InthePasswordbox,typethepasswordforthatuser.
9.ClickOK.
10.Clickthenewnetworklocation.Thisissmb://,followedbythenameofyourPCor
Mac.
11.Browsetoyourmoviesfolderandthenclickit.
12.ClickOK.
13.ClickOK.
14.FromtheThisdirectorycontainslist,select(Movies).
15.UnderChooseaScraper,clickTheMovie
Database(oranotherscraperifyouhavealreadyinstalledone).
16.ClickOK.
17.Ifyouareaskedwhetheryouwanttorefreshinfoforallitems,clickYes.
ToaddtheTVshowsfolder,repeatthisprocessbutselect(TVShows)fromtheThis
directorycontainslistandTheTVDBscraperfromtheChooseaScraperlist.
1.The“Addnetworklocation…“optionallowsformorecontrolovertheusernameandpasswordthanthe“Windows
network(SMB)”option.
XBMC’sscraperswillattempttoaddthefilesfromyoursourcestoyourlibrary.This
meansthatthefilesinyoursharedfoldermustfollowthenamingconventionsdescribedin
AddingFilestoyourLibraryonpage54.
Ifthescrapercannotfindinformationaboutthefile,XBMCdoesnotaddthefiletoyour
library.However,youcanstillusetheVideosfilebrowsertoaccessanyfilesthatwerenot
added.
ThemostcommoncauseofproblemswhencreatingSMBsharesandaddingthemto
XBMCisuserpermissions.Ifyoucannotconnecttoyourshare,orcannotseethefiles
insideit,thenchecktheuseraccountpermissionsonyourPCorMac.Ifnecessary,you
candeleteasourceandstartover.
Todeleteasource:1.OntheXBMCHomescreen,pointtoVideos,andthenclickFiles.
2.Right-clickasource,andthenclickRemovesource.
ConnectingtoUPnPDevices
Universalplugandplay(UPnP)isacollectionofnetworkingprotocolsthatallowsdevices
onalocalnetworktofindeachother,tofindoutwhattypeofservicesandfilesother
devicesoffer,andtosharethosefiles.
YoucansetupyourPCorMacsothatXBMContheRaspberryPicanplaythemediafiles
fromit.OnMacOSXandLinuxmachines,youwillneedtoinstallandconfigureaUPnP
mediaserver,suchasMediaTomb(http://www.mediatomb.cc).MicrosoftWindowshasa
built-inUPnPserver,butthisisusuallydisabledwhentheoperatingsystemisinstalled.
ToenabletheUPnPserveronWindows(8/7/Vista):
1.PresstheWindowslogokey+R.Typecontrol.exe/name
Microsoft.NetworkAndSharingCenterandthenpressEnter.
2.OnWindows8/7:clickChangeadvancedsharingsettings.OnWindowsVista:click
thearrowtotherightofNetworkDiscovery.
3.ClicktheboxnexttoTurnonnetworkdiscovery,andthenclickSavechanges(or
ApplyonVista).ToenabletheUPnPserveronWindowsXP:
1.PresstheWindowslogokey+R.Typeappwiz.cplandthenpressEnter.
2.ClickAdd/RemoveWindowsComponents.
3.ClickNetworkingServices,thenclickDetails.
4.Ifitisnotselected,clicktheboxnexttoInternetGatewayDeviceDiscoveryand
ControlClient.5.Ifitisnotselected,clicktheboxnexttoUPnPUserInterface.
6.ClickOK.
7.ClickNext.
8.PresstheWindowslogokey+R.Type
services.mscandthenpressEnter.
9.Double-clickSSDPDiscoveryService.
10.OntheGeneraltab,intheStartuptypelist,clickAutomatic.
11.ClickOK.
12.RestartyourPC.
UPnPdevicesandtheirfoldersshouldbeaddedtoXBMCassources.Althoughfiles
storedonthesetypesofdevicescannotbeaddedtotheXBMClibrary,theycanstillbe
accessedusingthevideosandmusicfilebrowsers.
Toaddavideosource:
1.OntheXBMCHomescreen,clickVideos.
2.ClickAddVideos…andthenclickBrowse.
3.ClickUPnPDevices,andthenclickthenameofyourdevice.
4.Browseintoafolder,ifyouwanttoadditanditssubfoldersonly.
5.ClickOK.
6.ClickOK.
Toaddamusicsource:
1.OntheXBMCHomescreen,clickMusic.
2.ClickAddMusic…andthenclickBrowse.
3.ClickUPnPDevices,andthenclickthenameofyourdevice.
4.Browseintoafolder,ifyouwanttoadditanditssubfoldersonly.
5.ClickOK.
6.ClickOK.
IfyourUPnPdeviceappearsintheUPnPDeviceslistbutyoucannotopenittobrowseits
content,thereareafewthingstocheck:
•IfyouarerunningafirewallonaWindowsPCwithUPnPenabled,youmayneedto
createanexceptionfortheWindowsMediaPlayerNetworkSharingServiceorUPnP
Framework.
•OnWindows,placeyourvideoandmusicfilesintheVideosandMusicfoldersofthe
userthatiscurrentlylogged-in.CheckthattheWindowsuserEveryoneisabletoread
fromthosefolders.
•Checkthatyournetworkrouterallowsdevicesonyournetworktotalktoeachother.
•Updateyouroperatingsystemtothelatestversion.
•UpdateXBMCtothelatestversion.
3.6Add-ons
Add-onsextendthefunctionalityofXBMCinuniqueways,andtherearemanyadd-ons
available.Thesevaryfrommakingsmallchangestotheinterface,tolettingyouwatchlive
TVandstreamvideosovertheInternet.
Todownloadandinstallanadd-on:1.OntheXBMCHomescreen,pointtoSystem,and
thenclickSettings.
2.ClickAdd-ons.
3.ClickGetAdd-ons,andthenclickXBMC.orgAddons.
4.Clickthetypeofadd-onthatyouwanttoinstall.Forexample,“VideoAdd-ons”add
newwaysofwatchingvideos.
5.Inthelistofavailableadd-ons,clickonetobringupadescription.
6.ClickInstalltodownloadandinstalltheadd-on.
InstallingMovieInformationAdd-ons
Movieinformationadd-onsareatypeofextensionforfindinginformationaboutthevideo
filesinyourlibrary.Bydefault,thescraperthatfindsinformationaboutyourmoviefiles
usesTheMovieDatabasewebsite.Toinstalladifferentmoviescraper,andconfigurea
videosourcetouseit:
1.OntheXBMCHomescreen,pointtoSystem,andthenclickSettings.
2.ClickAdd-ons.
3.ClickGetAdd-ons,andthenclickXBMC.orgAddons.
4.ClickMovieinformation,andthenclickUniversalMovieScraper.
5.ClickInstall.
6.OntheXBMCHomescreen,pointtoVideos,andthenclickFiles.
7.Right-clickyourvideosource,andthenclickChangecontent.
8.UnderChooseaScraper,clickUniversalMovieScraper.
9.ClickOK.
10.Ifyouareaskedwhetheryouwanttorefreshinfoforallitems,clickYes.
InstallingProgramAdd-ons
Programadd-onsarepowerfulextensionsthatincludeprogramsforaccessingtheweband
socialmediasites,clientsforfilesharingandfilehostingservices,backuputilities,and
eventorrentclients.
Toopenthelistofprogramadd-ons:
1.OntheXBMCHomescreen,pointtoSystem,andthenclickSettings.
2.ClickAdd-ons.
3.ClickGetAdd-ons,andthenclickXBMC.orgAddons.
4.ClickProgramAdd-ons.
3.7RemoteControls
XBMChasabuilt-inwebserverthatyoucanusetocontrolit.Thisturnsanydevicewith
awebbrowserintoaremotecontrolforXBMC.Therearealsoseveralremotecontrol
appsavailableforsmartphonesandtablets.TheseappsusuallytalktoXBMCusingthe
webserver.
Toenablethewebserver:
1.OntheXBMCHomescreen,clickSystem.
2.ClickServices.
3.ClickWebserver.
4.EnsureAllowcontrolofXBMCoverHTTPisselected.
5.InthePortbox,typeaportnumber.Thisnumbermustbeover1024.
6.IntheUsernamebox,typexbmc.
7.InthePasswordbox,typeapasswordthatyouwanttouse.
8.PresstheBackorHomebuttonstoleavethesystemsettings.
ToconnecttoXBMC,youneedtoknowitsIPaddressonyourlocalnetwork.TheIP
addressisshownintheSummaryandNetworktabsoftheSysteminfoscreen.Tofind
this:
•OntheXBMCHomescreen,pointtoSystem,andthenclickSysteminfo.
Testtheremotecontrolfeaturebyopeningawebbrowseronadeviceonyourlocal
network.Intheaddressbar,typehttp://followedbytheIPaddressoftheRaspberryPi,
thenacolon,andthentheportnumberthatissetintheXBMCsettings.
Forexample,toaccesstheremotecontrolwebinterfaceoverport8080onaPiwiththeIP
address192.168.0.9,typehttp://192.168.0.9:8080
Loginwiththeusernamexbmc,andthepasswordthatyousetintheXBMCsettings.
IfyoucannotconnecttoXBMC,firstcheckthattheRaspberryPihasanactivenetwork
connectionandthenverifythattheconnectionsettingsyouareusingmatchthosethatyou
enteredintheXBMCsettings.Ifyoustillcannotconnect,tryadifferentportnumber.
Figure4.TheXBMCwebinterface
Touseasmartphoneortabletapp,youwillneedthesamedetailsthatyouusedtoaccess
theremotecontrolwithawebbrowser.AppsareavailableforiOS,Android,and
WindowsPhone.However,theOfficialXBMCRemoteappisonlyavailableforiOSand
Androiddevices.
Atthetimeofwriting,thecurrentversionoftheOfficialXBMCRemotehasafew
problems.Butdevelopersupdateappsextremelyfrequently,andtheissuesmaybefixed
bythetimeyoureadthis.Ifyoucannotgettheofficialappworking,searchyourdevice’s
appstoreandyouwillfindmanyotherstotry.
4–ProgrammingwithScratch
Scratchisavisualprogramminglanguagethathelpsteachtheconceptsofprogrammingto
peoplewhohaveneverworkedwithtraditionalprogramminglanguages.Itisaimed
primarilyatpeoplewhowanttolearntobuildsmallgames.However,thecombinationof
itssimpleinterfaceandrichfeaturesetalsomakeitusefulforpresentations,simulations,
andprototypesofsoftwarethatwillbeimplementedinotherlanguages.
ThecurrentversionofScratchfortheRaspberryPiis1.4.Version2.0ofScratchisavailableonmanyplatforms,
however,itisnotcompatiblewiththePi.
4.1TheUserInterface
TostartScratchonRaspbian:
•Onthedesktop,double-clickScratch;or
•OntheLXDEpanel,clicktheMenubutton,pointtoProgramming,andthenclick
Scratch.
TheScratchwindowisdividedintoseveraldistinctareas:
Figure1.ScratchonRaspbian1CursorTools.Thesebuttonsareforduplicating,deleting,growing,andshrinkingthe
spritesonthestage.Clickthecursortool,andthenclickaspritetoactivatethefunction.
2Menu.
3BlocksPalette.
4ScriptsArea.ThisiswhereyoucombineblockstocontrolthespritethatisselectedintheSpriteList.
5SpriteList.Allofthespritesinyourprojectareshownhere.Clickaspritetoshowthescriptsthatyouhaveaddedfor
aparticularsprite.6Stage.Thisiswhereyourspritesmoveandinteractwitheachother.
ThekeyconceptbehindScratchisthateverythingyouneedtomove,animate,orcontrol
isasprite.Eachspriteisacollectionofimagesandscripts,andisindependentofallofthe
others.YoucombinethecoloredblocksfromtheBlocksPalettetosetthebehaviorofa
specificsprite.
OpeningandSavingProjects
Scratchprojectsaresavedinaspecialfileformatthatusestheextension.sb.Thesefiles
containallofthegraphicsandsoundfilesthatyouimportintoScratch,andallofthe
scriptsthatyoucreate.
Tosaveaprojecttoanewfile:
1.OntheMenubar,clickFile,andthenclickSaveAs…
2.IntheNewFilenamebox,typeanameforyourprojectandthenclickOK.
Ifyouhavepreviouslysavedyourprojectandyouwanttosaveitagain:
•OntheMenubar,clicktheSavethisprojectbutton(itlookslikeafloppydisk);or
•OntheMenubar,clickFile,andthenclickSave.Toclosethecurrentprojectandopen
another:1.OntheMenubar,clickFile,andthenclickOpen…2.Browsetothefilethat
youwanttoopen,clickit,andthenclickOK.
UsingtheStage
AllofthespritesinyourprojectappearontheStage,andthisiswhereallofyouractions
andscriptstakeplace.AspritecannotcompletelyleavetheStage,however,youcanhide
spritesthatarenotneededatspecificpartsofyourproject.
InScratch,theStageisalways480stepswideand360stepstall.Itneverchangessize,it
nevermoves,anditneverresets.Forexample,onceaspritemovesitremainsatthat
positiononthestageuntilanotherscriptmovesit.Thepositionofeachspriteisdescribed
withacoordinate–twonumbers,onethatrepresentsthehorizontalposition(x)andone
thatrepresentstheverticalposition(y).Thetop-leftoftheStageis-240,180,the
bottomrightoftheStageis240,-180,andthismakesthecenteroftheStage0,0.
IntheSpriteList,thereisanimagefortheStage.Ifyouclickthis,youcanaddblocksto
theStageitself.WhentheStageisselected,thetabsatthetopoftheScriptsAreachange.
YoucanchangethebackgroundoftheStagefromtheBackgroundstab.Youcaneitheruse
thePaintEditortodrawanewbackground(ThePaintEditorisdescribedinsection4.9
ThePaintEditoronpage89),orimportgraphicfiles.Importedgraphicsshouldbe480
pixelswideand360pixelstall,orScratchwillpositiontheminthecenteroftheStage
surroundedbybordersofthecurrentbackgroundcolor.
YoucanhavemultiplebackgroundsinaScratchproject,butonlyonecanbevisibleata
time.
YoucannotmovebackgroundsinScratch,soifyouwantareasofthebackgroundtomovethenyouhavetocreate
themassprites.
BuildingandRunningScripts
ThissectiondescribeshowtoworkwithblocksfromtheBlocksPalettetocreatescripts–
sequencesofblocks.Eachsprite(andtheStageitself)cancontainmanyscripts.
ToattachablocktoaspriteortheStageitself,selectitintheSpriteListandthendrag
blocksfromtheBlocksPalettetotheScriptsArea.Forexample:
1.IntheSpriteList,clickStage.
2.IntheBlocksPalette,clickControl.
3.Clicktheblockwhen<greenflag>clickedand,whileholdingthemousebutton,drag
theblockovertotheScriptsArea.Releasethemousebutton.
4.IntheBlocksPalette,clickLooks.
5.Dragtheblockchangecoloreffectby25totheScriptsAreaandunderneaththeother
block.Thewhitelineindicatesthatthisblockwillsnap
togetherwiththeoneaboveit.Releasethemousebutton.
6.IntheScriptsArea,ontheblockchangecoloreffectby25,clickcolor,andthenclick
brightness.7.Ontheblockchangebrightnesseffectby25clickthewhiteboxthat
contains25.Changethisto-25.8.IntheBlocksPalette,clickControl.
9.Dragtheblockwait1secstotheScriptsAreaandsnapittothebottomoftheblock
change
brightnesseffectby-25.
10.Ontheblockwait1secs,clickthewhiteboxthatcontains1.Changethisto0.5.
11.IntheBlocksPalette,clickLooks.
12.Dragtheblockchangecoloreffectby25totheScriptsAreaandsnapittothe
bottomofthewaitblock.
13.Ontheblockchangecoloreffectby25,clickcolor,andthenclickbrightness.
Figure2.Ashortscript
AbovetheStage,therearetwobuttons:thegreenflagbuttonstartsallscriptsinthe
project,andtheredoctagonstopsallofthescripts.
Thefirstblockthatisinthescript,when<greenflag>clicked,statesthatthescriptshould
runwhenthegreenflagbuttonabovetheStageisclicked.Clickthegreenflagbuttonnow
andyoushouldseethatthebackgroundbrieflychangescolor.
ToDoThis
Runascript(fortesting)IntheScriptsArea,double-clickanyoftheblocksinthescript.
Insertablockaboveanexistingblock
IntheBlocksPalette,dragablockovertotheScriptsAreaandoverthetopofanexistingblock.Thewhiteline
indicateswheretheblockwillbeinserted.
Detachablock(andanyblocksthatfollowit)fromascript
IntheScriptsArea,clicktheblockanddragitawayfromtheblockaboveit.Alloftheblocksbelowtheselectedblock
willmovewithit.
Removeablock,aseriesof
connectedblocks,orascriptfromtheproject
IntheScriptsArea,clickthefirstblockintheseriesthatyouwanttoremoveanddragitovertotheBlocksPalette.
ToDoThis
Duplicateablock,aseriesofconnectedblocks,orascriptIntheScriptsArea,right-clickthefirstblockintheseries
thatyouwanttocopy,clickduplicate,andthenclickintheScriptsAreatopositionthenewblocks.
FittingtheBlocksTogetherScratchusesthecolorandshapeofblockstoindicatehow
theycanbeconnectedtoeachother.Blockswithacurvedtop,suchasthewhen<green
flag>clickedblock,arethestartofascriptandcanonlyhaveblocksconnected
underneaththem.
Figure3.Youcanonlysnapinblocksbelowthisone,notabove.
Anotchinthetopofablockindicatesthatitcanbeattachedtoblocksaboveit.Atabon
thebottomindicatesthatyoucansnapotherblocksintopositionbelowit.
Figure4.Ablockthatallowsotherblockstobeconnectedontop,orunderneath.
Aneight-sidedwhiteboxintheblockmeansthatyoucantypenumbersinthere,butalso
thatyoucanaddvariablesandblocksfromtheOperatorssectionoftheBlocksPalette.
Touseanoperatororvariableblockinsteadofanumber:
•Draganeight-sidedblockfromtheBlocksPalette,intotheScriptsArea,andoverthe
whitebox.
Someblockshavesquareboxesthatyoucantypein.Theseacceptnumbers,strings
(sequencesofcharacters),variables,andeight-sidedoperatorblocks.
BlockslikeifintheControlsectionoftheBlocksPalettehavespacesforsix-sidedblocks.
Six-sidedblocksrepresentthevaluesYesorNo,orTrueorFalse.Thesearedescribedin
moredetailinsection4.4Decisionsonpage82.
4.2Sprites
InScratch,youwillspendthemajorityofyourtimemovingandchangingtheappearance
ofspritesinresponsetokeypresses.
AddingandRemovingaSprite
ToaddaspritetothecurrentprojectandmakeitappearontheStage:
1.AbovetheSpriteList,nexttoNewSprite,clicktheChoosenewspritefromfile
button.Thisisthesecondbuttoninthatarea.
2.IntheNewSpritewindow,browsetoaspritethatyouwanttoadd,clickitandthen
clickOK.
3.OntheStage,clickanddragthespritetoanewlocation.
Ifaspriteisthewrongsize,clickontheShrinkspriteorGrowspritebuttoninthe
CursorToolsareaandthenclickonthesprite:
Todeleteasprite:
•IntheSpriteList,right-clickaspriteandthenclickdelete.
CreatingaNewSprite
TherearetwowaysofcreatingnewspritesinScratch:youcanusethebuilt-indrawing
toolstopaintanewsprite,oryoucanimportgraphicfilesfromothertoolslikeAdobe
PhotoshopandKolourPaint.
Ineithercase:
•AbovetheSpritesList,nexttoNewSprite,clickthePaintnewspritebutton.Thisis
thefirstbuttoninthatarea.
Ifyouwanttoimportagraphicfile,clickImportinthePaintEditor.Theeditoris
describedinsection4.9ThePaintEditoronpage89.
UnderstandingCostumes
Inmostprojects,andespeciallyingames,youwillneedtochangetheappearanceofyour
spritesastheprojectisrunning.Thesecanbeframesofananimation,asisthecasewhen
thespriteis“walking”.Orthesecanbealternativeversionsofthespritethatusedifferent
colorsorholddifferentweapons.
InScratch,variationsofaspriteareknownas“costumes”.Ifyoucreateanewsprite,it
willonlyhaveonecostume.Toaddanothercostumetotheselectedsprite:
1.IntheScriptsArea,clickCostumes.
2.Ifyouwanttodrawanewspriteusingthebuilt-inPaintEditor,clickPaint.
3.Ifyouwanttoimportagraphicfiletouseasacostume,clickImport.
ToDoThis
SetthecurrentcostumeofaspritefromtheScriptsArea(notfromascript)
IntheScriptsArea,clickCostumes,andthenclicktheimageofthecostume.
RenameacostumeIntheScriptsArea,clickCostumes.
Clickthetextboxthatcontainsthecurrentname(forexample,
costume1)andthentypeanewname.
Duplicateacostume
IntheScriptsArea,clickCostumes.Nexttothecostumethatyouwanttoduplicate,clickCopy.
ToDoThis
DeleteacostumeIntheScriptsArea,clickCostumes.Nexttothecostumethatyouwanttoremove,clickx.
Editacostumeusingthebuilt-inPaintEditor
IntheScriptsArea,clickCostumes.Nexttothecostumethatyouwanttochange,clickEdit.
ScriptingYourSpritesMotionblockssetthepositionofsprites.OntheStageyoucan
clickanddragspriteswhereyouwantthem,buttomovethemfromscripts(forexample,
inresponsetotheuserpressinganarrowkey)youneedtouseoneofthemotionblocks.
Theseare:
BlockDescription
move?stepsMovesaspriteanumberofstepsinthedirectionitiscurrentlypointing.
turn(clockwise)?degrees
Rotatesaspriteanumberofdegreesinaclockwisedirection.
turn(counter
clockwise)?degreesRotatesaspriteanumberofdegreesinancounter-clockwisedirection.
pointindirection?Rotatesorflipsaspritetofacethespecifieddirection.
pointtowards?Rotatesorflipsaspritetofacethemousepointeroranothersprite.
gotox:?y:?Setsthepositionofasprite.goto?Movesaspritetothelocationofthemousepointeroranothersprite.
glide?secstox:?y:?
Animatesthemovementofaspritetothespecifiedlocation.
changexby?Movesaspritehorizontallybythenumberofstepsspecified.Thisnumbercanbenegative.
setxto?Movesaspritehorizontallytothespecifiedposition.
changeyby?Movesaspriteverticallybythenumberofsteps
specified.Thisnumbercanbenegative.setyto?Movesaspriteverticallytothespecifiedposition.
ifonedge,bounceChangesthedirectionofaspritewhenitreachestheedgeoftheStage.
Eachspritealsohasthreevariablesthatarechangedbythemotionblocks.Thesecanbe
usedindecision-makingandarithmeticblocks.
VariableDescription
xpositionThehorizontalpositionofthespriteontheStage.ypositionTheverticalpositionofthespriteontheStage.
directionThedirectionthatthespriteiscurrentlyfacing.
WhenspritesareaddedtotheStage,Scratchassumesthattheyfacetotheright.Whenyou
changethedirectionthataspritefaces,Scratchrotatesthesprite.TotellScratchthatit
shouldflipaspriteandnotrotateit:
1.IntheSpriteList,clickasprite.
2.AtthetopoftheScriptsArea,nexttothepictureofthesprite,clicktheonlyfaceleftrightbutton.Thisisthesecondbuttonofthethreethatarearrangedvertically.
TheLooksblocksintheBlocksPalettechangetheappearanceofspritesontheStage.
Someoftheseblockschangeasprite’scostume,andsomeofthemapplyeffects(suchas
fades).
switchtocostume?Setsthecostumedisplayedforthissprite.nextcostumeChangestothenextcostume.Ifthecurrent
costumeisthelastone,thefirstcostumewillbeusedinstead.
say?for?secsDisplaysaspeechbubblenexttothesprite.say?Displaysaspeechbubblenexttothesprite.Thisbubble
remainsuntilyouuseasayblockwithnotext.
think?for?secsDisplaysathoughtbubblenexttothesprite.think?Displaysathoughtbubblenexttothesprite.This
bubbleremainsuntilyouuseathinkblockwithnotext.
change?effectby?Seebelow.set?effectto?Seebelow.cleargraphiceffectsSeebelow.changesizeby?Growsor
shrinksaspritebytheamountspecified.setsizeto?%Growsorshrinksaspritebysettingitssize.Thisisapercentage
ofthesizeofthegraphicusedtocreatethesprite,anditcanbegreaterthan100%.showShowsthespriteontheStageif
itiscurrentlyhidden.
hideHidesaspriteifitiscurrentlyshown.gotofrontMovesaspriteinfrontofallothers.goback?layersMovesa
spritebehindothersprites.
Therearesevendifferenteffectsthatyoucanaddtosprites:
EffectDescriptioncolorChangesthecolor(hue)ofasprite.fisheyeDistortsthesprite.EffectDescription
whirlDistortsthespriteintoaswirlarounditscenterpoint.
pixelateMakesthespriteappeartobemadeupoflargerpixels.
mosaicMakesthespriteappeartobemadeupsmallerclonesofitself.
brightnessWhenusedwithpositivenumbers,thisincreasesthebrightness(howclosethecolorsaretowhite).When
usedwithnegativenumbers,thisdecreasesthebrightness(howclosethecolorsaretoblack).
ghostMakesthespritetranslucent(sothatotherspritescanbeseenthroughit)orcompletelytransparent(thespriteis
invisible).
Youcontroltheseeffectsusingthreeblocks:
•Tosetaneffecttoaspecificvalue,usetheset?effectto?block.
•Toincreaseordecreasetheamountofaneffectthatisappliedtoasprite,usethechange
?effectby?block.
•Toremoveallactiveeffectsfromasprite,usethecleargraphicseffectsblock.
Allspriteshavetwovariablesrelatedtotheirappearance:
VariableDescription
costume#Thenumberofthecostumethatiscurrentlydisplayedforthissprite.
sizeThesizeofaspriteontheStage.Thisisapercentageofthesizeofthegraphicusedtocreatethesprite,anditcan
begreaterthan100%.
YoucanchoosewhetherScratchshoulddisplaythesevariablesontheStage.Toshowthe
valueofavariable:
•IntheBlocksPalette,clicktheboxnexttothevariablename.
ClicktheboxagaintoremovethevariablefromtheStage.
4.3ArithmeticandVariables
IntheOperatorssectionofBlocksPalette,thereareeightblocksthatyoucanuseto
performbasicmathoperations,suchasaddingtwonumberstogether.Theseblocksare
eight-sided,greenblocksandtheyfitintoanyotherblockthatacceptsanumber.
BlockDescription
?+?Addstwonumberstogether.?-?Subtractsthesecondnumberfromthefirst.?*?Multipliestwonumbers
together.?/?Dividesthefirstnumberbythesecond.
pickrandom?to?Picksarandomnumberbetweenthefirstnumberandthesecondnumber.
?mod?Performsmodulararithmetic–thefirstnumber“wrapsaround”ifitreachesthevalueofthesecondnumber.
round?Roundsthespecifiednumbertothenearestwholenumber.
?of?Selectfromarangeofadditionalmathfunctions.
Youcanusearithmeticoperatorblocksasinputstootherarithmeticblocks.Forexample,
theexpression1+((14/3)x3.14)canbecreatedwiththreeblocks:
Figure5.Nestedoperatorblocks
CreatingandUsingVariables
Avariableisanamedareaofthecomputer’smemoryinwhichyoucanstorepiecesof
data.
TocreateavariableinScratch:
1.IntheBlocksPalette,clickVariables.
2.ClickMakeaVariable.
3.Typeanameforyourvariable.
4.Ifyouwantallspritestobeabletoaccessthevariable,clickthecirclenexttoForall
sprites.5.Ifyouonlywantthisspritetobeabletoaccessthevariable,clickthecircle
nexttoForthisspriteonly.6.ClickOK.
Whenyoucreateavariable,ScratchaddsablockforitintheVariablessectionofthe
BlocksPalette.Theseorangevariableblockswillfitintoblocksthatacceptanumber.
TherearefourblocksintheVariablessectionoftheBlocksPaletteforworkingwith
variables:
BlockDescription
set?to?Setsthevalueofavariable.change?by?Incrementsordecrementsavariable.showvariableAddsthe
specifiedvariabletotheStage.hidevariableRemovestheselectedvariablefromtheStage.
4.4Decisions
Therearesixblocksthatyouusetocomparenumbersandmakedecisions.Theresultof
theseblocksisa“Boolean”value–eithertrueorfalse..
BlockDescription
?<?Istrueifthefirstnumberissmallerthanthesecond,orfalseifitisnot.
?=?Istrueifthetwonumbersarethesame,orfalseiftheyarenot.
?>?Istrueifthefirstnumberislargerthanthesecond,orfalseifitisnot.
?and?Istrueifthebothoftheattachedblocksaretrue,orfalseifeither(orboth)ofthemisfalse.?or?Istrueifeither
ofthetwoattachedblocksistrue.Ifneitheraretrue,thenitreturnsfalse.not?Istrueiftheattachedblockisfalse,and
falseiftheattachedblockistrue.
TwoblocksintheControlsectionoftheBlocksPaletteareusedwiththeBooleanoperator
blockstomakedecisions.
BlockDescription
if?Runstheblocksinsideit,iftheattachedBooleanoperatoristrue.
if?elseRunstheblocksinthetopsectioniftheattachedBooleanoperatoristrue,andtheblocksinthebottomsection
iftheattachedoperatorisfalse.
Youcansnapanynumberofblocksintothemiddleoftheifandif…elseblocks.This
includesaddingotherifblockstocreatehighly-complicateddecision-making.
ControllingYourScriptswithaKeyboardandMouseUsersplayScratchgamesand
interactwithprojectsusingthemouseandkeyboard.
TherearetwoblocksintheControlssectionoftheBlocksPalettethatyoucanusetostart
ascriptwhenakeyispressed,orwhentheuserclickswiththeleftmousebutton.These
blockshavecurvedtopsandsoyoucannotplacetheminanexistingscript,theymust
alwaysstartanewscript.
BlockDescription
when?keypressedRunstheblockssnappedbelowwhentheuserpressesakeyonthekeyboard.
whenspriteclickedRunstheblockssnappedbelowwhentheuserclicksonasprite.
Ingames,thewhenkeypressedblockisusedmanytimestomoveaspritewhentheplayer
pressesoneofthearrowkeys.
Figure6.Multiplescriptstocontrolasprite
Allspritescanlistenandreacttothesamekeypresses.
ThereisaspecialsetofoperatorsintheSensingsectionoftheBlocksPalettethatyoucan
useformakingdecisionsbasedonkeyboardormouseinputfromtheuser.Unlikethe
controlblocks,theseblocksmustbeusedaspartofanifdecisionorwithaBoolean
operatorblock.
BlockDescription
mousedown?ABooleanvaluethatistrueiftheuseriscurrentlyholdingtheleftmousebuttondown.key?ispressed?
ABooleanvaluethatistrueiftheuseriscurrentlypressingthespecifiedkeyonthekeyboard.
Youcanusethemincombinationwiththecontrolblocks.Forexample,tocreatetwo
differentactionsdependingonwhethertheuserclicksaspritenormallyorholdstheup
arrowkeywhentheyclickasprite.
DetectingaCollisionbetweenSprites
Acollisioniswhentwospritesoverlapeachotheronthescreen.Theblocksthatyouneed
areintheSensingsectionoftheBlocksPalette,andtherearetwowaysyoucandetecta
collisioninScratch:
•Usetouchingtocheckifspritesaretouching;or
•Usethetouchingcolorandcolortouchingcolorblocks.
Checkingiftwocolorstouchisusefulingameswhenyouneedtoknowifaspecificpart
ofaspriteismakingcontactwithaspecificpartofanother.ButbecauseScratchis
programmedtoignoretransparentareasofyoursprites,thetouchingblockisallyouneed
formanygames.
Thetouchingblockdoesnotdetectcollisionswhenspritesarehiddenwiththehideblock.However,itdoesdetect
collisionswhenspritesaremadeinvisibleusingtheghosteffect.
4.5Loops
Loopshavespaceinthemiddleforyoutosnapinotherblocks,andyoucanusethemto
piecesofascriptrepeatedly.TherearethreetypesofloopinScratch:infiniteloops,which
rununtilthescriptisstopped;definiteloops,whichrunasetnumberoftimes;and
indefiniteloops,whichrunrepeatedlyuntilacertainconditionismet.
BlockDescription
wait?secsThisisaspecialkindofloopthatrepeatedlydoesnothinguntilthespecifiednumberofsecondshaselapsed.
foreverRepeatedlyrunstheblocksuntilthescriptisstopped.
repeat?Repeatedlyrunstheblocksasetnumbertimes.
BlockDescription
foreverif?CheckstheBooleanoperationandifitistruethen
Scratchrunstheblocksthatareinthemiddleoftheloop.Thenitcheckstheconditionagain.IftheBooleanoperationis
false,theloopingends.
waituntil?ThisisaspecialloopthatrepeatedlydoesnothinguntiltheBooleanoperationistrue.
repeatuntil?CheckstheBooleanoperationandifitisfalse
thenScratchrunstheblocksthatareinthemiddleoftheloop.Thentheloopcheckstheconditionagain.IftheBoolean
operationistrue,theloopingendsandScratchrunstheblockthatissnappedontothebottomoftherepeatuntilblock.
Theforeverifandrepeatuntilblocksseemverysimilar.However,therearetwoimportant
differences:
1.ForeverifrunsblockswhiletheBooleanoperationistrue–itendswhentheoperation
isfalse.RepeatuntilrunsblockswhiletheBooleanoperationisfalse–itendswhenthe
operationistrue.
2.Youcannotsnapotherblockstothebottomofaforeverifblock.
4.6Strings
Astringisasequenceofcharacters,likeaname,word,orsentence.Manyoftheblocks
thatyoucanusetoworkwithstringsareintroducedearlierinthischapter:
BlockSectionDescription
set?to?VariablesSetsthevalueofthespecifiedvariabletoastring.say?forLooksDisplaysaspeechbubblenextto
thespriteforthe?secsnumberofsecondsspecified.
say?LooksDisplaysaspeechbubblenexttothesprite.BlockSectionDescription
think?Looksfor?secs
Displaysathoughtbubblenexttothespriteforthenumberofsecondsspecified.
think?LooksDisplaysathoughtbubblenexttothesprite.
ask?andSensingwait
Showsthespecifiedstringandatextinputboxtotheuser.WhentheuserpressesEnterorclicksthebutton,their
answerisstoredinthevariableanswer.
ButintheOperatorssectionoftheBlocksPalette,therearethreeoperatorblocksthatonly
workwithstrings:
BlockDescription
join??Joinstwostringstogether.letter?of?Extractsthecharacteratthespecifiedpositionofthestring.
lengthof?Calculatesthenumberofcharactersinthestring.Figure7.Abasicloginpromptusingstrings
4.7Messages
InScratch,allscriptsareassociatedwithanindividualspriteandrunindependentlyofany
otherscripts.MessagesallowthedifferentspritesontheStagetocommunicateand
synchronizewitheachother.Thesemessagesarenevershowntotheuser.IntheControls
sectionoftheBlocksPalette,therearetwoblocksforsendingmessages,andonefor
receivingthem:
BlockDescription
broadcast?Sendsthespecifiedmessagetoallspritesintheproject.
broadcast?andwaitSendsthespecifiedmessagetoallspritesinthe
projectandthenwaits.Whenallofthespritesthatlistenforthatmessagehavefinishedtheirwork,Scratchrunsthe
blocksthataresnappedontothebottomofthebroadcastandwaitblock.
whenIreceive?Startsanewscriptwhenaspritereceivesthespecifiedmessage.
Tosendamessagefromasprite:1.IntheBlocksPalette,dragabroadcastblockoverto
theScriptsAreaandintoposition.
2.Ontheblock,clickthedownarrow,andtheneitherclickthenameofthemessagethat
youwanttosend,orclicknewtocreateanewmessage.
3.Ifyouarecreatinganewmessage:intheMessagenamebox,typeauniquenamefor
themessage,andthenclickOK.
Toreceiveaspecificmessagewhenitoccurs:
1.IntheBlocksPalette,dragawhenIreceiveblockintofreespaceintheScriptsArea.
2.Clickthedownarrow,andthenclickthenameofthemessage.
3.SnapblocksontothebottomofthewhenIreceiveblock.Whenthemessageis
received,Scratchrunstheseblocks.
4.8SoundandMusic
Therearetwowaystoaddsoundeffectsandmusictoyourproject:import.wavandMP3
filesintoScratch,orcreatemusicbyplayingnotes.
Soundfilesareattachedtoindividualsprites,andonlythespritethatthesoundisattached
tocanplayit.Toimportasoundfile:
•IntheScriptsArea,clickSounds,andthenclickImport.
TherearefiveblocksintheSoundsectionoftheBlocksPaletteforworkingwithimported
soundfiles:
BlockDescription
playsound?Startsplayingthespecifiedsound.playsound?untildone
Playsthespecifiedsoundanduntiltheend.
stopallsoundsStopsallsoundsthataspriteisplaying.changevolumeby?Increasesordecreaseshowloudasound
plays.setvolumeto?%Setshowloudthesoundplays,asapercentageofhowloudthatsoundiswhenimported.
Playsoundandplaysounduntildoneappeartodothesamething,butthereisan
importantdifferencebetweenthem.Ifyousnaptwoplaysoundblockstogetherthen
Scratchplaysbothsoundsatthesametime.Butwithaplaysounduntildoneblock,
Scratchwillplaythesoundfileallthewaytotheendbeforerunningtheblocksbelow.
4.9ThePaintEditor
Althoughitcannotcompetewiththefeaturesofdedicatedsoftwarepackagessuchas
AdobePhotoshop,Scratch’sPaintEditorhasallofthetoolsthatyouneedtodrawsprites
fromwithinScratch.
Figure8.ThePaintEditor
1Tools.
2Options.Thisareachangesdependingonwhichtoolyouhaveselected.
3Colorpalettes.Usetheseoptionstochangethecolorthatyouaredrawingwith.
4Setsthecenterpointofthepicture.Youcanusethisforcontrollinghowspritesrotateandwhereonthepicturethe
locationvariablesofthespritereferto.
5Zoom.Clickthe-buttontolookatyourpicturefromfurtheraway,orthe+buttontoviewyourpicturecloseup.
6Drawingarea.
Thetoolsareacontainstoolsforpaintinganddrawingyourspritesandbackgrounds..
ToDoThis
MakethepicturebiggerIntheToolsarea,clicktheGrowbutton.
MakethepicturesmallerIntheToolsarea,clicktheShrinkbutton.
Rotatethepicturecounterclockwise
IntheToolsarea,clicktheRotatecounter-clock-wisebutton.
Rotatethepictureclockwise
IntheToolsarea,clicktheRotateclock-wisebutton.
ToDoThis
Flipthepicturesothatitfacesintheoppositedirection
IntheToolsarea,clicktheFliphorizontallybutton.
Flipthepicturesothatitfacesthesamedirection,butistheotherwayup
IntheToolsarea,clicktheFlipverticallybutton.
ImportagraphicfileSeebelow.ClearthedrawingareaIntheToolsarea,clickClear.Reversethelastchangeyoumade
IntheToolsarea,clickUndo.Remakethelastchangethatyouundid
IntheToolsarea,clickRedo.
Closetheeditorwithoutsavingthechangesyoumadetothepicture
ClickCancel.
Thetenlargerbuttonsinthetoolsareaareselectedbyclickingthem,butonlyactivate
whenyoudosomethinginthedrawingarea.
ToolDescription
PaintbrushDrawfreehandshapesinthedrawingarea.EraserClickandholdtheleftmousebuttoninthedrawingareato
erasepartsofthepictureunderthemousepointer.
FillFillsanareawithacolororgradient.RectangleDrawsrectanglesandsquareswhenyouclickanddragthemouse
pointeraroundinthedrawingarea.
EllipseDrawsellipsesandcircleswhenyouclickanddragthemousepointeraroundinthedrawingarea.LineDrawsa
straightlinebetweentwopoints.TextTypetextontothepicture.
ToolDescription
SelectionClickanddragoutarectangletoselectapartofthepicture.Youcanthenmove,rotateorchangethisselection
withoutaffectingtherest.
StampClickanddragoutarectangletoselectapartofthepictureandcopyitintomemory.Youcanthenpasteitdown
ontothepicturerepeatedly.Tostopstamping,selectanothertool.
EyedropperClickanywhereinthedrawingarea.Theeyedroppersetsthecurrentcolorinthecolorpaletteareatomatch
whateverisunderthemousepointer.
UsingTransparencies
Thebackgroundofthedrawingareaisagreyandwhitecheckerboardpattern.This
indicatesthattheareaistransparent.Spritesandbackgroundsthatareunderneaththe
spriteontheStagewillshowthroughthesetransparentareas.
WhenusingthePaintEditortodraworchangesprites,anythinginthedrawingareathatis
nottransparentispartofthesprite.
ImportingYourGraphics
Ifyouhaveagraphicfilethatyouwanttouseasasprite,costume,orbackgroundthen
youcanimportitintothePaintEditor.
Toimporta.jpgor.pngfile:
1.InthePaintEditor,clickImport.
2.Browsetothefile,clickit,andthenclickOK.
Ifyouareimportinggraphicfilesforuseassprites,youmayneedtoremovethesolidcolorbackgroundinthePaintEditor.Inthecolorpalettesarea,clickthetransparentcolor
(thegreyandwhitecheckerboardpattern)andthenusetheFilltooltoclearthesprite’s
background.
4.10AutomaticStartupofScratchProjects
Scratchhasafull-screenoptionthatitcalls“presentationmode”,whereonlytheStageand
threebuttonsareshownonthescreen.ByeditingafewconfigurationfilesinRaspbian,
youcanopenaprojectinpresentationmodewhenthePistarts.
Therearetwostepsyoushouldtakebeforeyoudothis.First,saveyourprojectinafolder
thatdoesnotcontainspaces.Forexample,/home/pi/MyGame.sb.Next,youwillneedto
disableremotesensorconnectionsforyourproject.OpenthefileinScratch,andthen:
1.IntheBlocksPalette,clickSensing.
2.Right-clickoneofthetwosensorvalueblocksatthebottomoftheBlocksPalette,and
thenclickdisableremotesensorconnections.
3.OntheMenu,clickFileandthenclickSave.Now,usetheraspi-configtooltochange
thebootorder:
1.Onthedesktop,clickLXTerminal.
2.TypethefollowingcommandandthenpressEnter:sudoraspi-config
3.UsetheDownArrowkeytohighlightEnableBoottoDesktop/Scratch,andthen
pressEnter.
4.PresstheDownArrowkeytohighlightScratchStarttheScratchprogramming
environmentuponboot,andthenpressEnter.
5.PresstheRightArrowkeytwicetohighlight<Finish>,andthenpressEnter.
6.PressEnter.
7.WhenScratchappears,pressCtrl+Alt+F1.
8.PressCtrl+C.
9.Whenprompted,pressCtrl+C.
10.TypethefollowingcommandandthenpressEnter:
sudonano/etc/profile.d/boottoscratch.sh11.Onthelinethatendswithxinitdev/stdin,changeit
toscratchpresentationfollowedbythepathtoyour
Scratchproject.Forexample:
scratchpresentation/home/pi/MyGame.sb12.PressCtrl+O.
13.PressEnter.
14.PressCtrl+X.
15.TypethefollowingcommandandthenpressEnter:
sudoshutdown–rnow
4.11SharingYourFinishedProjects
WhenyouarefinishedwithaScratchproject,youcanshareitwiththeworld.However,
the.sbfilesthatScratchusescanonlybeopenedintheScratchenvironment.
Therearetwootherwaysthatyoucandistributeyourprojects:
PuttingYourProjectontheScratchWebsite
TheofficialScratchwebsiteisathttp://scratch.mit.eduandifyouarearegistereduser
thenyoucanuploadyourScratchprojects.Visitorstothesitecanthenplayyourgamesin
anywebbrowserthatsupportsAdobeFlash.
ConvertingYourScratchProjectFilestoExecutablesSeveralScratchusers
(“Scratchers”)havewrittensoftwaretoconvert.sbfilesintostandaloneexecutables.You
canfindanuptodatelistofallofthesetypesofconversiontoolsontheScratchwikiat
http://wiki.scratch.mit.edu/wiki/Porting_Scratch_Projects
5–BuildinganArcadeGameinScratch
Inthistutorial,youcanseehowtobuildaverybasicversionofthearcadegameDouble
Dragon®1.DoubleDragon®isasidescrollingactiongameinwhichtheplayertakes
controlofacharacterandmustwalkfromtheleft-handsideofthelevel,totheright.In
thewayarenumerousenemiesthattheplayermustdefeatbypunchingandkicking.Ifyou
arenotfamiliarwiththisgame,itmightbeusefultowatchafewvideosofitonYouTube.
ThisprojectpushesScratchontheRaspberryPitoitslimits.IfScratchstrugglestorunthegamewhenyouclick
thegreenflag,tryScratchin“presentationmode”.
ComparedtomanyoftheexamplegamesthatyoufindontheScratchwebsite,thegame
youarebuildingmayseemcomplicated.ItisintendedtohelpyoulearnScratch,havinga
workinggameattheendisabonus.
5.1TheTitleScreen
Evensimplegamesusuallystartbyshowingsomekindoftitlescreentotheplayer.When
thegameends,thetitlescreenappearsagainsothattheplayercanhaveanothergo.
Tobegin,startScratchonRaspbiananddeletethecat:1.Onthedesktop,double-click
Scratch.
2.IntheSpriteList,right-clickSprite1,andthenclickdelete.
TheStage’sbackgroundcolorshouldmatchthebackgroundcolorofthelogosand
graphicsthatyouuse.Tochangeit:1.IntheSpriteList,clickStage.
2.IntheScriptsArea,clickBackgrounds,andthenclicktheEditbuttonnextto
background1.1.DoubleDragonisaregisteredtrademarkofBallyGaming,Inc.3.InthePaintEditor,in
theColorPalettesarea,clicktheblacksquareinthegridofcolors.
4.IntheToolsarea,clicktheFilltool,andthenclickinthedrawingarea.
5.ClickOK.
TocreatealineoftextthattellstheplayertopresstheSpacekey:
1.IntheSpriteList,clickPaintnewsprite.
2.IntheToolsarea,clicktheZoomoutbuttonsothatyoucanseetheentiredrawingarea.
3.IntheToolsarea,clicktheTexttool,andthenclickthewhitesquareinthegridof
colorsintheColorPalettesarea.
4.TypePressSpace,andthenclickOK.
5.OntheStage,dragthetextintoposition.
6.IntheScriptsArea,clicktheboxthatcontainsSprite1andchangethenameofthe
spritetoPressSpace.
Youneedalogographicforyourtitlescreen.ClickPaintanewspriteandeitherdrawa
logointhePaintEditor,orimportone.RenamethisspriteTitleLogousingtheboxinthe
ScriptsArea.
TotellthetwospritesonthetitlescreentofadeinwhentheScratchprojectbegins,you
mightnormallyusethewhen<greenflag>clickedblock.However,thetitlescreenneeds
tore-appearattheendofthegameandthegreenflagisnotclickedthen.
Tocreateanewstartpointforthetitlescreen,youcanuseabroadcastblockattachedto
theStage:
1.IntheSpriteList,clickStage.
2.IntheBlocksPalette,clickControl,andthendragawhen<greenflag>clickedblock
totheScriptsArea.
3.FromtheBlocksPalette,dragabroadcastblockovertotheScriptsAreaandsnapit
intopositionunderneaththewhen<greenflag>clickedblock.
4.Onthebroadcastblock,clickthedownarrow,andthenclicknew…
5.IntheMessagenamebox,typeStartGameandthenclickOK.
Youcanusethebrightnesseffecttocreateasimplefade-inanimation.Youcanseethis
scriptinFigure1,inthewhenIreceiveStartGamescripts.
Thewhen<greenflag>clickedblockiscurrentlytheonlyplacewherethegameis
started.Butlater,otherspritescanbroadcast“StartGame”toresettheproject.
Tofinishthetitlescreen,youneedtodetectwhentheuserpressestheSpacekeyandthen
broadcastamessagetotellthefirstleveltostart.Youcouldalsomakethe“PressSpace”
spriteflashandplayasoundeffectwhenthishappens.
Todetectthekeypress:
1.IntheSpriteList,clickPressSpace.
2.IntheBlocksPalette,clickControl,andthendragawaituntilblockovertothe
ScriptsAreaandsnapitintopositionbelowtherepeatblock.
3.IntheBlocksPalette,clickSensing,andthendragakeyspacepressedblockoverto
theScriptsAreaanddropitontothesix-sidedslotonthewaituntilblock.
4.IntheBlocksPalette,clickControl,andthendragabroadcastblockovertothe
ScriptsArea.Snapitintopositionbelowthepreviousblock.
5.Onthebroadcastblock,clickStartGameandthenclicknew…
6.IntheMessagenamebox,typeLevel1andthenclickOK.
Ifyouhaveasoundeffectin.wavor.mp3formatthatyouwanttoplaywhentheuser
pressestheSpacekeyonthetitlescreen:
1.IntheSpriteList,clickPressSpace.
2.Importthesoundfile.
3.IntheScriptsArea,clickScripts.
4.IntheBlocksPalette,clickSoundandthendragaplaysoundblockovertothe
ScriptsAreaandunderneaththewaituntilkeyspacepressedblock.
5.Makesurethecorrectsoundfileisshownintheplaysoundblock.
TohidetheTitleLogowhenPressSpacebroadcasts“Level1”.1.IntheSpriteList,click
TitleLogo.
2.FromtheBlocksPalette,dragawhenIreceiveblockovertotheScriptsArea.Click
thedownarrowandthenclickLevel1.
3.IntheBlocksPalette,clickLooks,andthendragahideblockovertotheScriptsArea
andsnapitintounderneaththepreviousblock.
Figure1.Originalartwork©1987TechnosJapan
Corp.
5.2TheLevelBackgrounds
Scrollingisaneffectwherethebackgroundofagamemovesintheoppositedirectionto
theplayer.Thismakesitlookliketheplayer’scharacterismovingwhentheyareactually
standingstill.
However,Scratchcannotmovetheprojectbackgroundsoyourscrollinghastobecreated
usingsprites.Butithastwofurtherrestrictionsthatmakethiscomplicated:
•SpritescannotmovecompletelyofftheStage;and
•Themaximumsizeofaspriteis480stepsx360steps.Youcannotuseonespriteforthe
entirebackground.
PreparingtheBackgroundSprites
YoucanfindanimageoftheNESversionofDoubleDragon®onTheSpritersResource
(http://www.spriters-resource.com).Tousethisbackground,youneedtomakeittwiceas
large–2030pixelswideand384pixelstall.Thenyouwillhavetotrimoff24pixelsfrom
thetop.
Scratch’sPaintEditorisnotidealforworkingwithlargefiles,soyoushouldusea
differentpainteditor,suchasAdobePhotoshop,MicrosoftPaint,orKolourPaint.
IfyouareusingAdobePhotoshop:whenresizingtheimage,nexttoResampleImageclickBicubicandthenclick
NearestNeighbor.
Next,youneedtodividethebackgroundintofourimagesthatmeasure480pxby360px
andoneimagethatmeasures110pxby360px.Saveeachpiecetoitsownfileinportable
networkgraphics(PNG)format.
Figure2.Thefivebackgroundsprites.Originalartwork©1987Technos
JapanCorp.
IfyouprefertodrawyourownbackgroundthenyoucandothisinScratch’sPaintEditor
insteadofimportingyourgraphicsinthenextsection.Trytomaketheoverallshapeand
designsimilartotheimageabove,asthiswillhelpinlatersectionsofthetutorial.
ImportingtheBackgroundGraphics
Toimporteachbackgroundsprite:
1.IntheSpriteList,clickPaintnewsprite,andthenclickImport.
2.Browsetoyourbackgroundfile,clickit,andthenclickOK.
3.ClickOK.
4.IntheSpriteList,clickyournewspriteandthenintheScriptsArea,renamethe
sprite.Forexample:L1M1forthefirstsprite,L1M2forthesecond,andsoon.
HidingtheBackgroundontheTitleScreen
Thefurthestpositionthataspriteofthissizecanmovetotheleftis-462.Thismeansthat
a480pxwidebackgroundspritecannotmovefarenoughtothelefttohidethelast18
pixels.Thefurthestpositionthataspriteofthissizecanbepositionedtotherightis462.
Thismeansthatthefirst18pixelsoftheimagearealwaysvisible.
Thesetwo18-pixel-wideareasattheedgeoftheStagecausevisibleerrorsinthe
appearanceofthescrollingandarehiddenlater.
Whenthegamestarts,thetitlescreenbroadcaststhemessage“StartGame”.Atthispoint,
thebackgroundspritesshouldnotbevisibleonthescreen.Youneedtoaddascriptto
eachbackgroundspritesothatithideswhenthatmessageisreceived.Makesurethat
whenthebackgroundspritesaremadevisible,thattheyareonthelowestlayer.Dothisby
bringingeachspritetothefront,andthensendingitbacksixlayers.Todoallofthis,add
thefollowingscripttotheL1M1sprite:
Nowcopythisscriptintotheotherfourbackgroundsprites:1.Right-clickthewhenI
receiveStartGameblock,andthenclickduplicate.
2.MovethemousepointertotheSpriteList,andclickL1M2.
Repeatthisprocessfortheremainingbackgroundsprites.
ScrollingtheBackground
Thescrollinginthisprojectworkslikethis:
1.ThereisavariablecalledscrollXthatcontrolsthepositionofthebackground.
2.WhenscrollXiszero,allofthebackgroundspritesareintheirdefaultposition.
3.Eachbackgroundspritecalculatesitspositionslightlydifferently,sothattheyappear
onebyone.
4.IfscrollXischanged,thebackgroundspritesrecalculatetheirposition.Forexample,if
scrollXischangedto10,thenallofthebackgroundspriteswillmove10pixelstotheleft.
5.Spritesthathaveanxpositionofgreaterthan462willstayintheareaontherightside
oftheStage.
6.Spritesthathaveanxpositionoflessthan-462willallbeintheunusableareaonthe
left-handsideoftheStage.
AddthevariablescrollXtotheproject:
1.IntheSpriteList,clickStage.
2.IntheBlocksPalette,clickVariables,andthenclickMakeavariable.
3.IntheVariablenamebox,typescrollXandthenclickOK.
4.IntheBlocksPalette,clicktheboxnexttoscrollX.
Whenthetitlescreenbroadcaststhemessage“Level1”tostartthegame,thefirst
backgroundspriteshouldmakeitselfvisible.AddthefollowingscripttotheL1M1sprite:
SincethefirstbackgroundspritestartsinthecenteroftheStage,itsxpositionis0scrollX.SoifscrollXis10,thenthexpositionis-10.Thisishowincreasingthevalueof
scrollXcausesthebackgroundspritestomovetotheleft.
CopythatscriptintoL1M2.SinceL1M1startsatcoordinate0,0andis480stepswide,
L1M2startsat480,0.Soyouneedtochangethevalueinthesetxtoblockto480scrollX.
CopythatscriptintoL1M3.SinceL1M2startsat480,0andis480stepswide,L1M3starts
at960,0.Sochangethesetxtoblockto960-scrollX.
Copythescriptintothenextbackgroundsprite,L1M4.Thisstartsat1440,0.Sochange
thesetxtoblockto1440-scrollX.
Thelastbackgroundspriteisdifferent.Becauseitislesswidethantheothers,itsstart
pointis1735,0.Andwhenthisspriteisatcoordinate195,0itisfullyon-screen.Asthelast
spriteinthechain,L1M5muststopanymorescrollingfromhappening.Todothis,create
avariablecalledCanScroll:
1.IntheBlocksPalette,clickVariablesandthenclick
Makeavariable.
2.IntheVariablenamebox,typeCanScroll.
3.ClicktheboxnexttoForallsprites.
4.ClickOK.
5.IntheBlocksPalette,clicktheboxnextto
CanScrolltoremoveitfromtheStage.
TomakeL1M5scrollwiththeothersandsetCanScrolltozero,addthisscripttoL1M5:
Beforecontinuing,itisimportantthatthesetwovariablesaresettodefaultvalueswhen
thegamebegins:
1.IntheSpriteList,clickStage.
2.IntheBlocksPalette,clickVariables.
3.Dragaset?to0blockovertotheScriptsAreaandpositionitabovethebroadcast
StartGameblock.4.Ontheset?to0block,clickthedownarrowandthenclick
scrollX.
5.Dragaset?to0blockovertotheScriptsAreaandsnapitbelowthepreviousblock.
6.Ontheset?to0block,clickthedownarrowandthenclickCanScroll.
7.OnthesetCanScrollto0block,clickthewhiteboxandchangethevalueto1.
MaskingtheAwkwardAreas
TohidethetwoareasatthefarleftandfarrightoftheStagewherethescrollingdoesnot
workproperly,createanewspritethatadds20step(orpixel)thickblackbordersaround
theStage.NamethisspriteBorder,andaddthefollowingscript:
AddingtheBackgroundMusic
ArcadegamesfromthetimeperiodwhenDoubleDragon®wasreleasedhavebackground
musicthatplaysinaloop.Youcanuseany.wavor.mp3fileforthis.
ToimportafiletouseasbackgroundmusicinScratch:1.IntheSpriteList,clickStage.
2.IntheScriptsArea,clickSounds,andthenclickImport.
3.Browsetothefile,clickit,andthenclickOK.ToplaythesoundwhenLevel1starts:
1.IntheScriptsArea,clickScripts.
2.IntheBlocksPalette,clickControl.ThendragawhenIreceiveblockovertothe
ScriptsArea.3.OnthewhenIreceiveblock,clickthedownarrowandthenclick
Level1.
4.DragaforeverblockovertotheScriptsAreaandattachitunderneaththeprevious
block.
5.IntheBlocksPalette,clickSound.Thendragaplaysounduntildoneblockoverto
theScriptsAreaandsnapitinthemiddleoftheforeverblock.
6.Ontheplaysounduntildoneblock,clickthedownarrowandthenclickthenameof
thebackgroundmusic.
5.3ThePlayerSprite
Forthemainsprite,youneed10costumes:
•Four“walking”sprites.
•Onecostumeforwhenthecharacterthrowsapunch.
•Twocostumesforwhenthecharacterkicks.
•Onecostumeforwhenthecharacterishit.
•Twocostumesforwhentheplayerisknockedover.
Figure3.Tencostumesforthemainsprite.Originalartwork
©1989TechnosJapanCorp.
YoucanuseScratch’sPaintEditortocreateyourcostumes.However,itisofteneasierto
useanexternaleditor.OnTheSpritersResource,youcandownloadimagesofthemain
spritefromtheNESgame.However,manyoftheenemiesarenotavailable.Instead,use
thespritesfromDoubleDragon2.
Whenpreparingthecostumes,keepthemonasolid-colorbackgroundandmakeeach
graphicfilethesamesize.Saveeachcostumetoanewfileinportablenetworkgraphic
(PNG)format.
CreateanewspriteinScratchbyimportingthefirstcostume.NamethisspriteBilly,and
thenimporttheothercostumes.ThistutorialassumesthatthecostumesarenamedBilly-1,
Billy-2,Billy-3,andsoon.Youmayneedtorenamethefirstcostume.
Whenyouhaveimportedallofthecostumes,youcanremovethesolid-colorbackground
usingtheFilltoolinthePaintEditor,withoutScratchmovingthesprites.
Finally,dragtheBillyspriteintoitsstartingpositionontheStage.AndthenintheScripts
Area,clicktheonlyfaceleft-rightbutton.
HidingtheSpriteontheTitleScreen
Themainspriteshouldnotbevisibleuntilthetitlescreenbroadcaststhemessage
“Level1”.AddthesescriptstoBilly:
ControllingandMovingtheMainSprite
Theplayerwillcontrolaninvisible“ghost”spritewhichtellstheBillyspritetomoveby
broadcastingmessages.Addtheseblocks:
Theifblockandcostumechangescyclethespritethroughthefourframesofanimation
thatshowthecharacterwalking.
Theghostspritebroadcaststwoothermessages:FakeWalkandMoveToGBilly.Theseare
usedlater,soaddthesetwoscriptstotheBillysprite:
Theghostspriteisnotcreateduntilsection5.4CollisionDetectiononpage109.Ifyouwanttotestthemovement
withthekeyboard,addscriptsthatbroadcastandwaitthemovemessageswhenthearrowkeysarepressed.
WhentheplayerpressestheZkeytopunchortheXkeytokick,theBillyspritechanges
costume.Itthenwaits,sotheplayerhastimetoseetheattackandenemieshaveachance
tobehit,beforechangingthecostumeagain.Notethatkickinghasanextracostume(an
extraframeofanimation).
AddthesescriptstoBilly:
Atthispoint,theplayerspritecanmoveacrosstheStage.Butitcanmoveanywhereon
thescreen(includingupintotheairandthroughwalls)andthemovementofthesprite
doesnotcausethebackgroundtoscroll.Theselimitationsareaddressedinsection5.4
CollisionDetectiononpage109.
AddingVariablesforHealth,LivesRemaining,andthePlayer’sScore
SincetheBillyspriterepresentstheplayerinthegame,nowisagoodtimetocreatethree
variablesthatareneededforthegametowork:Health,Lives,andScore.
AddthesethreevariablesandselecttheForallspritesoptionsothatallspritescansee
andmodifythevariables.
HealthshouldneverbedisplayedontheStage.LivesandScoreshouldbedisplayedonthe
Stagewhenthelevelstarts,butnotonthetitlescreen.So:
1.IntheSpriteList,clickStage.
2.IntheBlocksPalette,clickVariables,andthendragahidevariableblockovertothe
ScriptsAreaandsnapitintopositionunderneaththestopallsoundsblock.1
3.Onthehidevariableblock,clickthedownarrowandthenclickLives.
4.FromtheBlocksPalette,dragahidevariableblockovertotheScriptsAreaandsnap
itintopositionunderneaththepreviousblock.
5.Onthehidevariableblock,clickthedownarrowandthenclickScore.
Thenaddthreesetvariabletoblocksbelowthehidevariableblocksthatyouhave
created.UsethefirsttosetCanScrollto1,thesecondtosetHealthto5,andthethirdto
setLivesto3.Then
1.FromtheBlocksPalette,dragashowvariableblockovertotheScriptsAreaand
snapitintopositionbeforetheforeverblockinthewhenIreceiveLevel1script.
1.Ifyoudonothavea“stopallsounds”blockbecauseyoudidnotaddbackgroundmusic,snapittothebottomofthe
“broadcastStartGame”block.
2.Ontheshowvariableblock,clickthedownarrowandthenclickScore.
3.FromtheBlocksPalette,dragashowvariableblockovertotheScriptsAreaand
snapitintopositionunderneaththepreviousblock.
4.Ontheshowvariableblock,clickthedownarrowandthenclickLives.
5.4CollisionDetection
Topreventtheplayerspritefrommovingthroughwallsandintoareasthatitisnot
supposedtomove,youcanusewhatScratcherscalla“wall-sensingsprite”.
This“ghost”spriteisinvisibleandmovesaheadoftheplayersprite.Whentheplayer
pressesanarrowkeyonthekeyboard,theghostspritemoves.Ifitcollideswithawall,or
anareathattheplayerspriteisnotsupposedtogo,thenitmovesbacktoitsprevious
position.Ifitdoesnotcollidewithawall,ittellstheplayerspritetomovetothesame
location.
Tomakethiswork,createfivenewsprites(“masks”)–oneforeachofthefive
backgrounds.Thesenewspritesarealsoinvisible,buttheircostumeshowstheareasthat
theplayerspritecannotmove.Theareasinwhichtheplayerspritecanmoveare
transparent.
Youcancreatethesemasksinanyimageeditor,butyoucanalsodothisusingScratch’s
built-intools.
Tocreatethemaskforthefirstbackgroundsprite,L1M1:1.IntheSpriteList,right-click
L1M1andthenclickduplicate.
2.ClickthenewspriteandthenrenameitML1M1.
3.IntheScriptsArea,removethegotofrontandgoback6layersblocksfromthe
whenIreceiveStartGamescript.
4.IntheScriptsArea,clickCostumes,andthenclickEdit.
5.Usingasingle,solidcolor(forexample,brightgreen),drawshapesovertheareasthat
theplayerspritecannotwalk.
6.UsingtheErasertoolandSelectiontool,deletethepartsoftheimagewheretheplayer
canwalk.Theseareasmustbetransparent.
Repeatthisprocessfortheotherbackgroundsprites–forthesecondmask,copythe
secondthebackground;forthethirdmask,copythethirdbackground,andsoon.Name
themasksML1M2,ML1M3,ML1M4,ML1M5respectively.
Makesurealloftheareasinyourmaskarejoined.Donothavetwoseparatepiecesofgreen–itwillwork,but
causesthecollisiondetectiontorunmuchtooslowlyforthisproject.
Becauseyoucopiedmostoftheblocksfromthebackgroundsprites,thesemaskswill
scrollwiththebackground.Itdoesnotmatterwhatlayertheyappearonasyouwillnot
seethem.Scratchcannotdetectcollisionsbetweenhiddenobjects,andsousetheghost
effecttomakethemasksinvisible.
InthewhenIreceiveLevel1scriptsoneachofthemasks:1.IntheBlocksPalette,click
Looks.
2.DragasetcoloreffecttoblockovertotheScriptsArea,andsnapitintoposition
abovetheshowblock.
3.Onthesetcoloreffecttoblock,clickcolorandthenclickghost.
4.Clickthewhitebox,andchangethevalueto100.Thencreatethewall-sensingsprite:
1.AbovetheStage,clickthegreenflagtostartthegame.
2.PresstheSpacekeyatthetitlescreen.
3.Whenthemainspriteappears,stopallofthescripts.
4.IntheSpriteList,clickPaintnewsprite.
5.ClickImport.
6.Browsetothegraphicfileforthefirstcostumeofthemainsprite,clickit,andthenclick
OK.7.Drawasolidcolorrectangle(anycolor)aroundthefeetofthemainsprite.
8.UsingtheEraserandSelectiontools,deletetherestofthesprite.
9.ClickOK.
10.IntheSpriteList,clickthenewsprite.
11.IntheScriptsArea,renamethespriteGBilly.
12.AddthefollowingscriptstotheScriptsArea:
Scratchwillputthecurrentspritecoordinatesintothegotox:y:block.Youdonotneedto
changethem.TherectangleshouldbepositionedcorrectlyoverthefeetoftheBillysprite.
Ifitisnot,youmayhavetomoveitinthePaintEditor.
Makeanoteofthedifferencebetweentheypositionoftheghostspriteandthatofthe
Billysprite.ThengobacktotheBillyspriteandchangethenumberinthewhenIreceive
MoveToGBillyscriptfrom34tothisvalue.
MovingtheGhostSprite
Tomovethewall-sensingsprite,first:
1.IntheSpriteList,clickGBilly.
2.IntheBlocksPalette,clickControl.
3.DragaforeverblockovertotheScriptsArea,andsnapitintopositionbelowtheshow
block.
Theplayershouldnotbeabletocontroltheirmovementwhentheyareattacking,orwhen
theyhavebeenhit.
1.DraganifblockovertotheScriptsArea,andsnapitintopositioninsidetheforever
block.
2.IntheBlocksPalette,clickOperators.
3.Draga?<?blocktotheScriptsAreaandsnapitintotheifblock.
4.Onthe?<?block,clickthesecondwhiteboxandtypethevalue5.
5.IntheBlocksPalette,clickSensing.
6.Dragaxpositionof?blocktotheScriptsAreaandsnapitintothefirstwhiteboxon
the?<5block.
7.Clickxpositionandthenclickcostume#.
8.Clickthedownarrowinthebox,thenclickBilly.
9.Addtheblocksonthefollowingpageintothemiddleoftheifcostume#ofBilly<5
block:
Whereitsays“SeeAbove”onthediagram,youneedtocreateanoperatorblockthat
reads:touchingML1M1ortouchingML1M2ortouchingML1M3ortouchingML1M4
ortouchingML1M5.
Whenbuildingscriptsthataremadeofthismanyblocks,assembleitinsmallpiecesinunusedspaceinthe
ScriptsArea.Thenslowlycombinethepieces.
IftherightarrowkeyispressedthenthescriptchecksthattheGBillyspriteisinthefar
rightoftheStage.Ifitis,andscrollingisenabled,thenthereisablocktoincrement
scrollX(whichinturncausesthebackgroundspritestomovetotheleft).Ifscrollingthe
backgroundcausesawalltocomeincontactwiththewallsensingspritethenoneofthe
touchingblockswillbetrue.Inresponse,thescriptpushestheghostspriteandtheBilly
spritetotheleft.
IftheplayerisnotatthefarrightoftheStage,thenthechangexby10blockmovesthe
ghostspritetotheright.Itthencheckswhetheritcollideswithawall.Ifitdoes,itmoves
backtoitspreviousposition.Ifnot,ittellstheBillyspritetowalktotheright.
Tomoveleftorup,addthefollowingblocksunderneaththeentireifkeyrightarrow
pressed?block.Duplicatethelongoperatorblock,andallofthetouchingblocks,and
insertthemwherethediagramsays“SeeAbove”.
Whenmovingup,thisscriptreliesonthebackgroundmaskstostoptheplayersprite.But
thescripttomovedownusestheypositiontorestricttheplayer’smovement.Addthese
blocksunderneaththeifkeyuparrowpressed?block:
WhenyoumovetheBillysprite,yourwalkingspritesmaynotlineupwithGBilly.Tofixthis,editthecostumesin
thePaintEditorand“nudge”thecostumestotheleftorright.
5.5Enemies
Whentheplayerreachessetpointsinthelevel,thescrollingstopsandthegame“spawns”
enemiesthattheplayermustdefeat.Onlyhavingtwoenemiesonscreenatonce(likethe
NESgame)isasensiblelimitationforthisproject.
Preparethegraphicsforanenemyspriteinasimilarwayasdescribedinsection5.3The
PlayerSpriteonpage105.Enemiesonlyneedninecostumes,asshowninFigure4below.
Figure4.Ninecostumesforthefirstenemy.Originalartwork©1989TechnosJapanCorp.
Namethesprite“Williams1”inScratchandsetittoonlyfaceleftandright.Dragthe
spritewhereyouwantittoappearontheStage.
Addthefollowingscripttothissprite:
Theenemyneedstwovariables:DefeatedandHits.Defeatedisusedtoensurethatthe
spriteonlymovesandattacksuntiltheplayerdefeatsit.Hitsisthehealthoftheenemy
andisreducedwhentheplayerhitsthesprite.AddthesevariablestotheWilliams1sprite
onlybyselectingtheForthisspriteonlyoption.YoualreadyhavethevariableCanScroll
whichisusedtostoptheplayerscrollingthebackgroundwhenenemiesappearorwhen
theendofthelevelisreached.Butyouneedonethatholdshowmanyenemiesmustbe
defeatedbeforescrollingisre-enabled.CallthisEnemiesRemaining,andmakeitvisibleto
allsprites.
Todetectwhentheplayerreachesapointwhenenemiesappear,createanotherinvisible
sprite.Thisissometimescalleda“spawnpoint”.
1.Startthegameandthenstopitonthefirstscreen.
2.IntheSpriteList,clickPaintnewsprite.
3.Drawasolid-colorrectangleandthenclickOK.
4.Thisspritemustbetallenoughtoblocktheplayer’spath.Dragthespriteintoposition
ontheStage,andeditthecostumeifitisnotlargeenough.
5.IntheScriptsArea,renamethespriteSpawn1.
6.Makeanoteofthexpositionofthesprite.
7.Addthefollowingscriptstothespawnpoint:
ThepositionofthespawnpointiscalculatedusingscrollX,inthesamewayasthe
backgroundspritesandmasksarepositioned.
Assumingthexpositionofthespawnspriteis88andthefirstscreenstartsatcoordinate
0,0thenthepositionofthespawnspritecanbecalculatedas88-scrollX.
WhenthespawnpointtouchestheBillysprite,it:1.SetsCanScrollto0tostopthe
background
scrolling.
2.SetsEnemiesRemainingto1.
3.Broadcaststhemessage“Spawn1”.
4.HidesitselfsothatnofurthercollisionsbetweenitandtheBillyspritearedetected.
NowyouneedtomakeWilliams1respondtothismessage.Addthesetwoscriptstoit:
Tocreateanewspawnpointforthesecondscreen,calculatethepositionofthenewsprite
withthesecondbackgroundspritefullyinview.Thesecondbackgroundspritestartsat
480,0,sothepositionofthesecondspawnpointisthexvalue(fromtheScriptsArea)plus
480andthenminusscrollX.
MakingWilliamsAttack
TomaketheWilliams1spriteattacktheplayer,youneedtoaddaloopthatrunsuntilthe
spriteisdefeated.Thisloop:
1.PointsthespriteinthedirectionoftheBillysprite.
2.Calculatesifitisinstrikingrangeandifso,punches.
3.Walksafewstepsifitisnotinstrikingrange.
Addthefollowingblocksunderneaththegotox:y:block:
Eventually,therewillbetwocopiesofthisspriteonthescreenatthesametime.Toavoid
themmovingidentically,noticehowthescriptpicksitsdirectionbylookingatBillyand
thenchangingthedirectionbyarandomnumberofdegrees.Andthespriteintentionally
movesslowerthantheplayer’scharacter–otherwiseitwouldbeimpossibletoescapeand
thegamewouldbeverydifficult.
UpdatingtheOrderofLayers
Becauseoftheperspectiveusedinthebackgroundgraphics,whenthespritesmoveupthe
screentheyareactuallymovingintothedistance.Whenthespritesmovedownthescreen,
theyarecomingcloser.However,Scratchdoesnotknowthatspriteswithagreatery
positionshouldbebehindothersprites.
Thesolutionistochecktheypositionofsprites,andusethegoback?layersblocktoreorderthespritelayers.Youalsoneedtoallowforspritesdisappearingwhentheyare
defeated,andbearinmindthatthenamesofenemyspritesmaychange.
Onewaytodothisistomakea“list”ofthespritesthatareonthescreen.Listsstore
stringsandnumbers,andgiveeachiteminthelistanumber.Thefirstitemisnumber1.
Thesecondisnumber2,andsoon.Wherethisbecomesuseful,isthatyoucanuseanitem
inalistwithmanyoftheblocksinScratch;inparticular,the?of?blockintheSensing
sectionoftheBlocksPalette.
First,makealistcalledMobs(shortfor“mobiles”)ontheStage(sothatitisaccessibleby
allsprites).
ToaddBillytotheMobslist:
1.IntheSpriteList,clickBilly.
2.IntheBlocksPalette,clickVariables.
3.Draganinsert?at?of?blockovertotheScriptsAreaandsnapitintoposition
betweenthewhenIreceiveLevel1blockandtheshowblock.
4.Ontheinsert?at?of?block,clickthefirstboxandthentypeBilly.
5.Clickthesecondboxandthentype1.
6.ClickthethirdboxandthenclickMobs.DothesamefortheWilliams1sprite:
1.IntheSpriteList,clickWilliams1.
2.IntheBlocksPalette,clickVariables.
3.Draganinsert?at?of?blockovertotheScriptsAreaandsnapitintoposition
betweenthewhenIreceiveSpawn1blockandtheshowblock.
4.Ontheinsert?at?of?block,clickthefirstboxandthentypeWilliams1.
5.Clickthesecondboxandthenclicklast.
6.ClickthethirdboxandthenclickMobs.
ThescriptthatlooksattheMobslistanddeterminestheorderinwhichspritesareplaced
onlayerswillbeontheStage.Forittowork,youneedtwootherlists:ZSpritesand
OZSprites.CreatethesetwolistsinthesamewaythatyoucreatedtheMobslist.
YoualsoneedtoclearMobsatthestartofthegame:
1.IntheSpriteList,clickStage.
2.IntheBlocksPalette,clickControl.
3.DragawhenIreceiveblocktotheScriptsArea,andchangeittobewhenIreceive
StartGame.4.IntheBlocksPalette,clickVariables.
5.Dragadelete?of?blockovertotheScriptsAreaandsnapitintopositionunderneath
thepreviousblock.
6.Clickthedownarrowonthefirstboxandthenclickall.
7.ClickthedownarrowonthesecondboxandthenclickMobs.
Createthescripttoordertheplayerspriteandactiveenemies:1.IntheBlocksPalette,
clickControl,andthendragawhenIreceiveblocktotheScriptsArea.
2.ChangetheselectiontoLevel1.
3.DragaforeverblockovertotheScriptsAreaandsnapitintopositionunderneaththe
previousblock.4.Addthefollowingblockstothemiddleoftheforeverblock:
ZSpritesisusedtostorethespritenamesintheorderthattheyshouldbedisplayedonthe
Stage.
TheifblockcheckstoseewhetherthespritethatissecondintheMobslisthasay
positionthatislessthantheiteminpositiononeoftheZSpriteslist.1Ifitdoes,thenthe
spriteislowerdownontheStageandshouldbedisplayedinthefront,sothescriptinserts
theseconditemfromMobsintothefirstpositionofZSprites.ThispushesBillyinto
secondpositioninZSprites.Ifitdoesnothavealoweryposition,thescriptputstheitem
inZSpritesafterBilly.
ThenextifblockcheckswhetherthespritethatisthirdintheMobslisthasayposition
thatislessthanthefirstiteminZSprites.Ifitdoes,thescriptputsthisitemfirst.Ifitdoes
not,thescriptcheckswhetherithasalowerypositionthantheseconditem–ifitdoes,
thescriptaddstheitemtoZSpritesastheseconditem;otherwisetheitemisaddedtothe
endofthelist.Itdoesnotmatterifthereisonlytwo(orone)itemsinthelist.
1.TheiteminpositiononeisalwaystheBillysprite.
Addthenexthalfofthescriptinsidetheforeverblock,butbelowthepreviousblocks.
Wherethediagramsays“SeeAbove”,createanoperatorblockthatreads:
not(item[1]ofZSprites=item[1]ofOZSpritesanditem[2]ofZSprites=item[2]of
OZSpritesanditem[3]ofZSprites=item[3]ofOZSprites)
ThisreducesthenumberoftimesthatScratchre-ordersthelayers.TheOZSpriteslist
containsacopyoftheZSpriteslistfromthelasttimethescriptwasrun.IfZSpriteshas
changed,thentwothingshappen:thescriptcopiestheitemsfromZSpritesintoOZSprites,
andthenbroadcaststhreemessagestotellthespriteswhichlayerstomoveto.
Itbuildsamessagebycombiningthenameofthespritewiththestrings“GF”,“GL2”,or
“GL3”,dependingonwhichlayerthespriteshouldmoveto.Youneedtoaddthreescripts
toBilly:CopytheseintoWilliams1,andthenchangethewhenIreceiveblocksto
“GFWilliams1”,“GL2Williams1”,and“GL3Williams1”.
Layerre-orderingisnotinstantaneousastheRaspberryPiisnotpowerfulenough.The
approachmayworkveryquicklyinotherprojects,butifitslowsthisgamedowntoo
muchthenremoveit.
HittingWilliams
Enemiescanhaveanyname,soitiseasierforthemtodetectthecollisionsthantohave
theplayerspritedoit.Theyneedtolistentotheplayer’sattackkeys,soaddtheseblocks
toWilliams1:
TherearealsotwochangesthatyouneedtomaketothewhenIreceiveSpawn1script.
Thiswillreducehowfrequentlytheenemyattacks:
1.Createanifblockthatreadsifcostume#<5.Then
duplicateit.
2.DragoneoftheifblocksdirectlyunderneaththerepeatuntilDefeated=1block,so
thatitisinsidetheloopandsurroundstheotherblocksintheloop.
3.Dragtheotherifblockdirectlyunderneaththerepeat4block,sothatitisinsidethe
loopandsurroundsalloftheotherblocksintheloop.
4.Addawait0.1secstothebottom–insidetherepeatuntilDefeated=1blockbut
underneaththeifcostume#<5block.
Todetectwhentheenemyisdefeatedandreactivatescrolling,createtheseblocks
underneaththeswitchcostumetoWilliams1blockinthewhenZkeypressedscript.
ThefinalblockmovesthespritetoaknownlocationofftheStage–thisistoallowthe
scriptthatre-ordersthespritelayerstoremove“dead”spritesfromtheMobslist.You
needtoaddafewblocksforthistohappen.SelecttheStageintheSpriteList,andthen
addthefollowingblocksasthefirstblocksinsidetheforeverloop:
TofinishthescriptsfortheWilliams1sprite,clickitontheStage.Then,duplicatethe
wholescriptthatbeginswithwhenZkeypressedandmakethefollowingchanges:
1.ChangewhenZkeypressedtowhenXkeypressed.2.Changetheswitchtocostume
Williams-6blockstoswitchtocostumeWilliams-7.
3.ChangethechangebyHitsby-1blockstochangebyHitsby-2.
4.Changetheifcostume#=6blockto7.
5.Addawait0.1secsblocktothetopofthescript.
HittingthePlayer
WhentheBillyspriteishit,thevariableHealthmustbedecremented.Whenitreaches
zero,thespriteisknockedback50steps.However,thiscouldcausetheplayertobe
knockedoffthescreen,andtheghostspritewouldbeinthewrongposition.Tofixthis,
thespawnpointthattriggerstheenemiesdeclaresanxandypositionontheStagethatis
safefortheplayer.Whentheylosealife,ascripttellstheghostspritetomovetothissafe
location.TheghostspritethentellstheBillyspritetoupdateitsposition.
Twonewvariablesareneededforthis:RespawnXandRespawnY.Createthemonthe
Stagesothatallspritescanseethevalues.Thespawnpointsmustsetthesevariables:
1.IntheSpriteList,clickSpawn1.
2.UndertheBroadcastSpawn1block,createasetRespawnXtoblockandenterthex
positionwheretheplayerspritewillreappear.
3.CreateasetRespawnYtoblockandentertheypositionwheretheplayerspritewill
reappear.Now,addthefollowingscripttotheBillysprite:AndthisscripttotheGBilly
sprite:
5.6MoreEnemies
ByduplicatingthespawnpointandWilliams1sprites,youcanfilluptherestofthelevel
withenemies:
1.InSpawn1,changesetEnemiesRemainingto1tosetEnemiesRemainingto2.
2.IntheSpriteList,right-clickWilliams1andthenclickduplicate.
3.ClickthenewspriteandrenameittoWilliams2.
4.InthewhenIreceiveSpawn1script,changeinsertWilliams1atlastofMobsto
insertWilliams2atlastofMobs.
5.ChangetheblockwhenIreceiveGFWilliams1toGFWilliams2.
6.ChangetheblockwhenIreceiveGL2Williams1toGL2Williams2.
7.ChangetheblockwhenIreceiveGL3Williams1toGL3Williams2.
8.Ifyouwantthisspritetospawnatadifferentlocation:changethevaluesinthegotox:
y:blockunderwhenIreceiveSpawn1.
9.Ifyouwanttogivethisspriteaslightlydifferentrandommovement,changethevalues
inpickrandom-65to65.
Tocompletethisproject,youneedtoaddatleastonemoreenemy–theendoflevel
“boss”.Theprocessislargelythesame:1.IntheSpriteList,right-clickSpawn1andthen
clickduplicate.
2.Clickthenewsprite,andthenrenameitSpawnE.
3.Changetheblocksetxto88-scrollXtosetxto1700-scrollX.Thismovesthespawn
pointtothefarrightofthefourthbackgroundsprite.
4.ChangetheblocksetEnemiesRemainingto2tosetEnemiesRemainingto1.
5.ChangethebroadcastblocktosendSpawnE.
Followingthepreviousinstructions,makeanothercopyofWilliams1.Namethissprite
Williams3andchangethewhenIreceiveSpawn1blocktowhenIreceiveSpawnE.
InthewhenZkeypressedandwhenXkeypressedblocks,replacethesetCanScrollto1
blockswithbroadcastWinGameblocks.
5.7GameOver
Thegamebroadcaststwomessagesthatarenotyetreceivedbyanysprites:“FailGame”is
sentwhentheplayerlosesalltheirlives,and“WinGame”issentwhentheplayerdefeats
theenemyinthelastpartofthelevel.Youcanusethesetoreturntothetitlescreen.
IfyouareconvertingyourScratchprojecttoan.exe,.app,or.jarfile,thenitwillrunalot
quickerandyoumaybeabletoaddmoreintothegame.Therearealotofareasinthis
projectthatyoucanextend.Forexample:
ToDoThis
Stoptheenemiesfromwalkingthroughwalls
Useawall-sensingspriteforeachenemy.
AddanotherlevelChangethefinalenemysothatitbroadcasts“Level2”.
AddweaponsIncludeanextrasetofcostumesfortheplayerandenemyspritesthatshowsthemholdingaweapon.
Maketheanimationsmoother
Usemorecostumes,reducethenumberofstepsinthemovements,andtheamountofsecondsinwaitblocks.
6–ProgramminginPython
Pythonisawidely-usedprogramminglanguagethatisavailableonmostmodern
operatingsystemsandcomputers.OnthePi,Pythonisagreatwaytowritesoftwareand
games,andtocontroltheGPIOpins.
UnlikeprogramminglanguagessuchasC++orObjective-C,Pythonisaninterpreted
language.Thismeansthatspecialsoftwarereadsyourcodefilesandrunsthem.Youdo
nothavetocompilePythonfilestoexecutablesor.appfilesbeforeyoucanusethem.
Whenprogrammerswritecode,theyusuallydoitinapieceofsoftwarecalledan
integrateddevelopmentenvironment(IDE).AnIDEisatexteditorthatispackagedwith
othertoolstomakewritingcodealittleeasier.OnRaspbian,therearetwoPythonIDEson
thedesktop–IDLEandIDLE3.ThisisbecausetherearetwoversionsofPython,andthey
areincompatiblewitheachother.Inthischapter,youwilllearnPython3usingtheIDLE3
IDE.
6.1YourFirstPythonProgram
“Hello,World!”isashortprogramthatpeopleoftenwriteastheirfirstprograminanew
environmentorlanguage.Itisatest,andonlydisplaysthemessage“Hello,World!”tothe
user.
InPython,youcanwritethisprogramwithonelineofcode,anditisagoodwayof
introducingyoutotheIDEandhowtorunPythonprograms.
Tostart:1.OntheRaspbiandesktop,double-clickIDLE3.2.Typeprint(“Hello,World!”)
andthenpressEnter.
ThefirstthingtonoteisthatthewindowopenedbyIDLE3istitled“PythonShell”.The
PythonShellworksliketheLinuxterminal–itrunscommandsthatyoutypeherewhen
youpresstheEnterkey.
Pythonprograms(or“scripts”)aretextfilesthatcontainallofthecommandsthatyou
wanttorun.Youcanuseanytexteditortocreatethesefiles,butthereisonebuilt-into
IDLE3:
1.InthePythonShell,ontheMenu,clickFileandthenclickNewWindow.
2.Typeprint(“Hello,World”)
3.OntheMenu,clickFileandthenclickSaveAs.Saveyourfilewiththeextension.py.
4.OntheMenu,clickRunandthenclickRunModule.Theresultsofyourprogramare
showninthePythonShell.TorunyourprogramfromaLinuxterminal:
1.OntheRaspbiandesktop,double-click
LXTerminal.
2.Typepython3followedbyaspace,andthenthefullfilename(includingthefilepath)
ofyour.pyfile.
Ifyouwanttorunyourprogrambyclickingitonthedesktopthenyouneedtocreatea
desktopshortcut.Theseareshorttextfilesthatcreateadditionaliconsonyourdesktopand
describewhathappenswhentheuserclicksthem.
TocreateadesktopshortcutforaPythonscript:
1.OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclick
Leafpad.
2.Typethefollowingtextintothedocument.ReplaceMyTestScriptwithwhatyouwant
tocalltheicon,andthefilenameafterpython3withthelocationofyour.pyprogram.
[DesktopEntry]
Type=Application
Name=MyTestScript
Exec=lxterminal—command“python3/home/pi/Desktop/test.py”
Terminal=False
Categories=None
3.OntheLeafpadMenu,clickFile,andthenclickSaveAs.
4.Savethefiletoyourdesktopwiththeextension.desktop.
Ifyoudouble-clicktheicononthedesktop,youshouldseeaterminalwindowopenand
displaythetext“Hello,World!”However,theterminalwindowclosesassoonasthe
programcompletes.
Whileyouaredevelopingyourprograms,itcanbeusefultokeeptheprogramrunning
(andkeeptheterminalwindowopen)untiltheuserpressesakey.InIDLE3,addthe
followingcommandtoyour.pyfile.Putitonanewlineunderneathprint(“Hello,
World!”).
input(“Pressanykeytoclosethiswindow.”)
6.2Python
Inthefollowingsectionsofthischapter,youwilllearnaboutthefeaturesofthePython3
language.
AddingCommentstoPythonPrograms
AsyourPythonscriptsbecomemorecomplicated,youcanputinexplanationsofwhat
partsofyourcodedo.Thisistohelpyouincaseyouneedtoachangeaprogramthatyou
wrotealongtimeago.
Toaddacommenttoa.pyfile:
•Onanewline,typea#symbolandthenanytext.
PerformingBasicArithmetic
Youhaveseenthefunctionprint()thatdisplaysinformationtotheuser.FromaPython.py
file,youneedtousethistoshowtheresultofarithmeticcalculations.ButfromthePython
Shell,youcantypetheexpressionandtheresultisautomaticallyshown.
Forexample:
•InthePythonShell,typethefollowingexpressionandthenpressEnter:
5+5
ToDoThis
AddtwonumberstogetherTypeonenumberfollowedbya+symbolandthenanothernumber.
Subtractthesecondnumberfromthefirst
Typethefirstnumberfollowedbya
-symbolandthenthesecondnumber.
MultiplytwonumberstogetherTypeonenumberfollowedbya*symbolandthenanothernumber.
Dividethefirstnumberbythesecond
Typethefirstnumberfollowedbya/symbolandthenthesecondnumber.
Dividethefirstnumberbythesecond,andreturnawholenumberTypethefirstnumberfollowedby//andthenthe
secondnumber.
UsingVariablesInprogrammingterms,avariableisanareaofthecomputer’smemory
thatyougiveanameto.Youcanstoreinformationinthesevariablesandaccessitlater.
Tocreateavariable:specifyaname,followedbyanequalssign,andthenthevalueit
shouldcontain.Forexample:
result=5+5print(result)
Variablenamesmuststartwithaletter(a–z,orA–Z).Theremainingcharactersinthe
namecanbeletters,numbers,oranunderscore(_).Youcannotusepunctuationmarksor
otherspecialcharactersinthenamesofvariables,andthereareseveralwords(suchas
“print”)thatyoucannotuseasavariablenamebecausetheyarealreadyusedfor
somethingelse.
InPython,variablescanholdanytypeofinformation.Toextendtheexampleabove,you
couldassignastring(asequenceofcharacters)tothevariableresult,evenwhenit
currentlycontainsanumber.
result=“Hello”
Youcanusevariableswhereveryouwouldotherwisetypeavalue.Forexample,inmath
expressionssuchasx+5andx/y.
Pythonisa“weaklytyped”language.Thismeansthatyoudonothavetodeclarewhattypeofdataavariable
holds.Forexample,ifresultcontains“Hello”thenresult+5is“Hello5”.However,5+resultcausesanerrorwhen
theprogramisrunbecausePythontriestouseresultasanumber.
TherearemanytypesofdatainPython,butthesearesomeofthemostcommon:
TypeDescription
BooleanCaneitherbeTrueorFalse.
NumberAnumberorfractionofanysize.However,youcanspecifythetype(andsize)ofnumberwhenyouneedtobe
specific.
StringAsequenceofcharacters(letters).Forexample,“Hello,World!”isastring.
ListAnorderedsequenceofitems.Eachitemcanbeanytypeofdata(includingotherlists).SeeUsingListsand
Dictionariesbelow.
ByteArrayAlistofbytes(small,8-bitnumbers).Thisismainlyusedforwritingbinaryfiles(seesection6.8)andwhen
workingwiththePi’sGPIOpins.
TupleLikealist,exceptthatthecontentsoftuplescannotbechangedwhiletheprogramisrunning.SetAnunordered
listwhereeachitemisunique.TypeDescription
DictionaryAcollectionofkey-valuepairs.SeeUsingListsandDictionariesbelow.
However,mostthingsinPythonareobjects.Youwilllearnmoreabouttheseinsection6.6
ClassesandObjectsonpage141.
UsingListsandDictionaries
Listscollectitemstogetherintoasinglevariable.Theyareordered–eachslotinthelistis
givenanumberstartingatzero.
Tocreatealist,usesquarebrackets.Andtheneachiteminthelistisaccessedusingsquare
bracketsandtheitemnumber:
Beatles=[“John”,“Paul”,“Pete”,“George”]
print(Beatles[0])
Theitemsinalistcanbechanged:
Beatles[2]=“Ringo”
Listsareusefulwhenyoudonotwanttogiveeachitemaseparatevariablename,orwhen
theamountofdatathatyouhavechangeswhentheprogramisrunning.
Youcanfindthelengthofalistusingthefunctionlen().Forexample,len(Beatles)gives
theresult4.
Todeleteanitemfromalist,usedel().Whenanitemisdeleted,alloftheitemsthat
followitmoveuponeposition.So,inthisexample,deletingthefirstitemmakes“Paul”
thenewfirstitem.“Ringo”wouldthenbeseconditem,and“George”third.
Therearealsoseveraluseful“methods”thatyouaccessusingadotafterthevariable
name.Forexample:
Beatles.reverse()
MethodDescription
append(obj)Addsthespecifieditemtotheendofthelist.
count(obj)Countshowmanytimesthespecifieditemappearsinthelist.
index(obj)Searchesthelistforthespecifieditemandreturnsitspositioninthelist.
insert(position,obj)Addsanitemtothelistinthespecifiedposition.Alllistitemsthatfollowaremoveddowna
position.
remove(obj)Removesthespecifieditemfromthelist.Forexample:Beatles.remove(“John”).
reverse()Reversestheorderofitemsinthelist.
Adictionaryisaspecialtypeoflist.Insteadofaccessingtheitembyitspositioninthelist,
youuseaname.Youcreateadictionaryusingcurlybraces.Forexample:
Beatles={“Lead”:“John”,“Bass”:“Paul”,“Drums”:“Pete”,“Guitar:”,“George”}
Eachitemisnowmadeupofapairofvalues–akey(thename),andavalue.Toaccess
theitemsinadictionary,usethekeyinsidesquarebrackets.Forexample:
Beatles[“Drums”]=“Ringo”
Thelen()anddel()functionsworkthesamewayfordictionariesastheydoforlists.And
therearealsoseveraluseful“methods”thatyouaccessusingadotafterthevariablename.
MethodDescription
clear()Removesallitemsfromthedictionary.copy()Returnsacopyofthedictionary.has_key(key)ReturnsTrueifthe
specifiedkeyisinthedictionary,orFalseifitisnot.
keys()Returnsalistofthekeysinthedictionary.update(dic)Addstheitemsfromthespecifieddictionarytothecurrent
dictionary.
values()Returnsalistofthevaluesinthedictionary.
6.3Decisions
InPython,makingadecisioninvolvescalculatingwhetheranexpressionisTrue,or
whetheritisFalse.Dependingontheresultofthatcalculation,youcanrundifferent
blocksofcode.
Thebasicdecision-makingcommandinPythonistheifstatement.
ifvariable==value:doThis()
andThis()
The==operatorcomparesthetwovaluesandreturnsTrueiftheyarethesame,orFalse
iftheyarenot.IftheresultisTruethenPythonrunsthecommandsbelowtheifstatement.
Itisveryimportantthatyoupayattentiontothewhitespacethatyouusearoundthe
commandsunderanifstatement.UsetheTabkeytoindentlinesthatyouwanttorunif
theresultofthecomparisonisTrue.
Youcanextendtheifstatementwithanotherblockofcodethatrunsifthetwovaluesare
notthesame:
ifvariable==value:doThisIfTrue()
else:
doThisIfFalse()
ThereareseveralotheroperatorsthatyoucanuseinPython:
OperatorDescription
!=ReturnsTrueiftwovaluesarenotequal,andFalseiftheyare.
>ReturnsTrueifthefirstnumberisgreaterthanthesecond,andFalseifitisnot.
OperatorDescription
<ReturnsTrueifthefirstnumberislessthanthesecond,andFalseifitisnot.
>=ReturnsTrueifthefirstnumberisgreaterthanorequaltothesecond,andFalseifitisnot.<=ReturnsTrueifthe
firstnumberislessthanorequaltothesecond,andFalseifitisnot.
Youcancombinetwo(ormore)expressionsbysurroundingeachwithparenthesisand
thenusingoneofthelogicaloperatorsbelow.
Forexample:
if(variable1==value)or(variable2==value):doThis()
OperatorDescription
andReturnsTrueifbothexpressionsareTrue,andFalseifeitheroneisFalse.
orReturnsTrueifeitheroftheexpressionsisTrue.ReturnsFalseiftheyarebothFalse.
Youcanusenot()toreversetheresultofanexpression,turningTruetoFalseandFalseto
True.Forexample:
ifnot(variable==value):doThis()
Byusingcorrectspacing,youcanalsoputifstatementsinsidethecodethatrunsifan
earlierifstatementisTrue.However,usingelifisoftenalittleeasiertoread.
TheexamplebelowrunsdoThis1()ifthevalueofvariableis1.Ifitisnot,itchecks
whetherthevalueis2andrunsdoThis2().Ifitisnot2either,itcheckswhetherthevalue
is3andrunsdoThis3().Ifthevalueisnot1,2,or3thenitrunsdoThisInAllOtherCases().
ifvariable==1:doThis1()
elifvariable==2:doThis2()
elifvariable==3:doThis3()
else:
doThisInAllOtherCases()
6.4Loops
LoopsareblocksofcodethatrepeatasequenceofPythoncommandsasetnumbertimes,
orcontinuallyuntilacertainconditionismet.
TherearetwotypesofloopinPython:
LoopDescription
whileChecksaconditioninthesamewayastheifstatement,andthenrunsthecodeunderneathiftheconditionisTrue.
ThenitcheckstheconditionagainandifitisstillTrue,itrunsthecodeunderneathagain,andsoon.Theloopends
whentheconditionisFalse.
forRunstheblockofcodeforeachiteminalistorsequence.Theloopendswhentherearenomoreitems.
Therearetwomainwaystouseawhileloop.Torunsomethingasetnumberoftimes,use
avariabletokeeptrackofhowmanytimestheloopisrun.Forexample:
count=0
while(count<5):print(“Hello”)
count=count+1
Thissendsthemessage“Hello”totheterminalwhilethevariablecountcontainsanumber
thatislessthan5.Ineffect,itprints“Hello”fivetimes.
Youcanalsouseawhilelooptoruncodeuntilsomethinghappens.Theexamplebelow
continuallypromptstheusertotypesometextandechoeswhattheytypebacktothem,
untiltheypresstheEnterkeywithouttypinganything.
text=“?”
whilenot(text==””):
text=input(“Typesomething(ornothingtoquit).>”)
print(text)
Theforloopisfor“iterating”overalistorsequence.Itrunsasmanytimesasthereare
itemsinthelist,andassignseachonetoavariablesothatyoucanaccessit.Forexample,
usingtheBeatleslistthatyousawearlier,youcanprinteachitemusingaforloop.
Beatles=[“John”,“Paul”,“Ringo”,“George”]forbeatleinBeatles:
print(beatle)
Itiseasytowritealoopthatneverends.TostopaprogramthatisrunninginthePythonShellorLinuxterminal,
pressCtrl+C.
TherearetwoPythoncommandsthatyoucanuseinsidewhileandforloops,andthat
affecthowaloopruns.
CommandDescription
breakImmediatelyexitstheloop.continueRestartstheloop,ignoringanyothercommandsthatareunderneaththe
continuecommand.
6.5Functions
FunctionsareoneofthewaysthatyoubreakaPythonprogramintosmallerchunks.This
canhelpyoumanageprojects,anditmakesiteasierforyoutoreusepartsofoneproject
inanother.
Youhavealreadyseenafewexamplesoffunctionsbuilt-intoPython,butyoucanalso
createyourown.Whenwritingafunction,youcanchoosewhetheritshouldaccept
arguments(valuesthatarepassedintothefunction),andwhetheritshouldreturnavalue.
TocreateafunctioninPython:
1.Typethekeyworddeffollowedbythefunction’sname.
2.Typeopeningandclosingparenthesis–().
3.Ifyouwanttoacceptarguments:typethembetweentheparenthesesandseparateeach
onewithacomma.
4.Endthelinewithacolon.
5.(Optional)Addastringonthenextlinethat
describesthefunction.
6.Placeanylinesofcodeyouwanttoincludeinthefunctiononfollowinglines,anduse
theTabkeytoindentthem.
7.Ifyouwanttoreturnavalue,usethecommandreturn.
Forexample:
defmyFunction():
“Afunctionthatprintsamessage.Thislineisignored.”print(“Myfirstfunction”)
defmyFunction2(val1,val2):
“Afunctionthataddstwonumbersandreturnstheresult.”returnval1+val2
Functionnamesfollowthesamerulesasvariablenames.Theymuststartaletter(a–z,or
A–Z),andtheremainingcharactersinthenamecanbeletters,numbers,oranunderscore
(_).
Tocalloneofyourfunctionsfromotherpartsofyourcode,usethefunctionnameand
thenparentheses.Forexample:
myFunction()
z=myFunction2(x,y)
Tospecifytheargumentsinadifferentorder,youcanusekeywordarguments.Asshown
below,keywordargumentsspecifytheparameternamebeforetheargument.
myFunction2(val2=y,val1=x)
Anargumentisavariableorvaluethatyoupassintoafunction.Intheexamplesabove,xandyarearguments.
Parametersarepartofthefunction’sdefinitionandrefertothenamesgiventothedatawhenitispassedtothe
function.Forexample,val1andval2areparameters.
Itisimportanttorealizethatwhenyouchangeanargumentinsideafunction,thevalueof
italsochangesoutsideofthefunction.ThisisbecausePythonactuallypassesareference
totheargument,notacopyofit.
Forexample:
defInc(val):
val=val+1
x=1
print(x)Inc(x)
print(x)
MakingParametersOptional
Sometimesitcanbeusefultocallafunctionwithoutincludingallofthearguments.You
candothisbyspecifyingthedefaultvaluethataparametershouldhaveifanargumentis
notpassedintothefunction.
defPrintAndMultiply(val1,val2=1):
print(val1*val2)
YoucancallthisfunctionwithPrintAndMultiply(5,2)toseethevalue10,orjust
PrintAndMultiply(5).Ifyoudonotpassthesecondargument,thenPythonassignsthe
value1toval2becausethatisthedefaultspecifiedinthefunction’sdefinition.
6.6ClassesandObjects
Pythonisanobject-orientedlanguage.Object-orientedprogramming(OOP)isawayof
writingcodethattreatsdataandconceptsasstandaloneobjects.Theseobjectscancontain
multipleitemsofdata(“fields”),andevenfunctionsthatoperateonthatdata(“methods”).
Asasimpleexample,consideranentryinyourphone’saddressbookorcontactlist.You
canthinkofeachentryasanobject,andinsideeachobjecttherearenumerousfields.
“Firstname”isonefield,“Lastname”isanother,andsoon.
IntroducingClasses
InPython,aclassislikeablueprint.Itdescribesthestructureofobjectsanddefinestheir
methods.Touseanobject,youneedtocreateaninstanceoftheclassthatdescribesit.
YoucreateyourownclassesinPythonbyusingtheclasskeyword.Forexample:
classAddressBookEntry:
firstname=””
lastname=””
telephone=””
Tocreateaninstanceofthatclassandgetausableobject:
Alice=AddressBookEntry()
Toaccesstothefieldsandmethodsthatisinsideanobject,usethedotsyntax.
Alice.firstname
Alice.lastname
Youcanaddmethodstotheclassbyindentingthem.Torefertofieldsinsidetheobject
frommethods,usethekeywordself.
classAddressBookEntry:
firstname=””
lastname=””
telephone=””
defprintName(self):
print(self.firstname+””+self.lastname)
TocalltheprintName()methodfromotherpartsofyourcode,specifythevariablename,
thenadot,andthenthemethodname.Forexample:
Alice.printName()
__init__isaspecialmethodthatPythonrunswhenaninstanceoftheclassiscreated.You
canwriteyourownandusethistoensurethatthecorrectargumentsarepassedintothe
codewhenyoutrytocreateaninstanceoftheclass.Forexample:
classAddressBookEntry:firstname=””lastname=””
telephone=””
def__init__(self,firstname,lastname):self.firstname=firstname
self.lastname=lastname
Mark=AddressBookEntry(firstname=“Mark”,lastname=“White”)
InheritingFieldsandMethods
Inheritanceiswhereobjectsthataresimilarsharepartsoftheirstructure.Usingthe
addressbookexampleagain,youcouldhaveaseparateobjectforbusinesscontacts.Since
thisobjectcontainsthesamebasicinformation(name,phonenumber,andsoon),itcan
inheritthosefieldsfromthestandardentryobject.Butthenyoucanaddotherfieldsthat
arespecifictobusinesscontacts(suchascompanynameandwebsite).
classAddressBookEntry:
firstname=””
lastname=””
telephone=””
def__init__(self,firstname,lastname):
self.firstname=firstname
self.lastname=lastname
defprintName(self):
print(self.firstname+””+self.lastname)
classBusinessContactEntry(AddressBookEntry):
company=””
CreateaninstanceofBusinessContactEntryusingthesyntax:
Bob=BusinessContactEntry(firstname=“Bob”,lastname=“Smith”)
EventhoughtheBusinessContactEntryclassonlydefinesthefieldcompany,thefields
firstname,lastname,andtelephonearealsousable.Itinheritsthesefieldsfrom
AddressBookEntry.
Bob.firstname=“Bob”
Bob.company=“Bob’sWidgets,Inc.”Bob.printName()
Thisrelationshipdoesnotworktheotherway.SinceAddressBookEntrydoesnotinherit
fromBusinessContactEntry,youcannotaccessthecompanyfieldfromaninstanceof
AddressBookEntry.
OverridingInheritedMethods
Intheexampleabove,theBusinessContactEntryclassinheritstheprintName()method
fromAddressBookEntry.However,ifyouincludeanewdefinitionof__init__and
printName()inBusinessContactEntrythenyoucanoverridetheinheritedversions.
classBusinessContactEntry(AddressBookEntry):
company=””
def__init__(self,firstname,lastname,company):
self.firstname=firstname
self.lastname=lastname
self.company=company
defprintName(self):
print(self.firstname+”“+self.lastname+”(”+self.company+“)”)
Wherethisgetsinteresting,isifyouhaveafunctionliketheexamplebelow:
defprintEntry(entry):entry.printName()
Thisfunctionacceptseithertypeofobject,anddoesnotknowthedifference.Itsimply
callsthemethodprintName()andthetwodifferenttypesofobjectrespondslightly
differently.
HidingFieldsandMethods
InPython,youcanstopotherpartsofyourcodeaccessingfieldsandmethodsinanobject
bydefiningthemwithanamethatstartswithtwounderscorecharacters.
6.7ModulesandPackages
Amoduleisacollectionoffunctionsandclassesthatarerelatedtoaspecificpurpose.You
candownloadmodulesthatarewrittenbyotherprogrammersandusetheminyour
projects.RaspbianalreadyhasalargenumberofPythonmodulespreinstalled.Toseealist
ofallthemodulesthatareinstalledonyourPi:
1.Onthedesktop,double-clickIDLE3.
2.InthePythonShell,typethefollowingcommandandthenpressEnter:
help(“modules”)
InstallingaModule
YoucanfindmanyadditionalPythonmodulesthatyoucandownloadandinstallwiththe
PackageManagerinRaspbian.
IfyoudownloadamodulewithoutusingthePackageManager,youwillhavetoinstallit
yourself.Modulesusuallycomewithaninstallationscript(setup.py)thatcopiesthe
module(s)tothecorrectlocationonyoursystem.Torunit:
1.Onthedesktop,double-clickLXTerminal.
2.Moveintothefolderthatcontainsthemodulethatyouwanttoinstall.Usethecd
command.
3.TypethefollowingcommandandthenpressEnter:
python3setup.pyinstall
UsingaModule
Beforeyoucanuseaclassorfunctionfromamodule,youneedtoimportitintoyour
project.
Toimporttheentiremodule,putanimportstatementatthetopofyour.pyscript.For
example,toimportthemathmoduleusethestatement:
importmath
Thenaccessitemsfromamoduleusingthedotsyntax,asyoudowhenworkingwith
objects.Forexample,tocallthefloor()functioninthemathmodule:
math.floor(10.3)
Ifyouonlywanttoimportaspecificitemfromamodule,ratherthaneverythingthatthe
modulecontains,youcanusethefrom…importsyntax.Intheexamplebelow,onlythe
floor()functionisimportedandsothecalltotheceil()functiongeneratesanerror.
frommathimportfloorprint(floor(10.3))print(ceil(10.7))
LearningaboutPackages
Packagesgroupmodulestogetherinnamespaces–organizedandhierarchicaltreesof
modules.Workingwithnamespacesisalittlelikeworkingwiththefilesystem,except
thatyouusedotsinsteadofslashes.
Youusepackagenameswhenimportingmodulesandreadingtheirdocumentation.Soyouwillbecomefamiliar
withhowthisworkswithouthavingtomakeaspecialeffort.
6.8FileI/O
WorkingwithfilesandfoldersfromPythonisimportantonRaspbian,becausemanyof
thesystemprocessesanddevicesaremappedintothefilesystem.
OpeningaFile
ToreadfromorwritetoafileinPython,youneedtoopenitusingthebuilt-infunction
open().Initsbasicform,open()acceptstwoarguments:
open(filename[,mode])
IfthefileisnotinthesamedirectoryasyourPythonscript,youneedtospecifythefull
pathtothefile.
ModeisoptionalandifyoudonotspecifyitthenPythonopensthefileinread-onlymode.
Thismeansthatyoucannotchangethefile,onlyreaddatafromit.Themost-common
valuesthatareusedhereare:
ModeDescription
rOpenthefileforreading.rbOpenthefileforreadinginbinaryformat.
wOpenthefileforwritingonly.Thisoverwritestheexistingfileor,ifitdoesnotexist,createsthefile.wbOpenthefile
forwritingonly,inbinaryformat.
aOpenafilefor“appending”.Anythingyouwriteisaddedtotheend.Thisoverwritestheexistingfileor,ifitdoesnot
exist,createsthefile.
abOpenafileforappendingbinarydata.
Pythonmakesadistinctionbetweenworkingwithatextfileandworkingwithabinary
file.ThekeydifferencebetweenthetwoisthatwithtextfilesPythondealswiththetext
encodingandlinebreakformatsforyou.Inbinarymode,youhaveaccesstoeachbyte
thatmakesupthefile,anditisuptoyoutodecidehowtoprocessthem.
Whenreadingandwritingtoatextfile,youcanonlyusestringobjects.Whenreadingand
writingtoabinaryfile,usebytesandbytearrayobjects.
ReadingfromaTextFile
Toreadfromafile,openitusingthemode“r”,oranyoftheothermodesthatsupport
reading.Thenusethemethodread()toreadanumberofcharactersfromthefile.
Youmustremembertoclosefilesonceyouarefinishedworkingwiththem.Dothiswith
theclose()method.Ifyoudonotcloseafilethenyoumightbeunabletoworkwiththe
fileagain,untilyourestartthePi.
Forexample,toreadthe“messageoftheday”(MOTD)file:
motd=open(“/etc/motd”,“r”)
message=motd.read()
print(message)
motd.close()
Ifyoudonotspecifyhowmanycharacterstoread,read()willfetchtheentirecontentsof
thefile.Toreadonlytencharacters:
motd.read(10)
Ifyouspecifymorecharacterstoreadthenthefilehasleft,Pythonreadsasmany
charactersasitcan.WhenPythonreachestheendofthefile,thestringreturnedbyacall
toread()willhavealengthofzero.
WritingTexttoaFile
Tocreateanewtextfileandwriteatestmessagetoit,openthefileusingmode“w”.Then
usethemethodwrite().Forexample:
test=open(“/home/pi/Desktop/Test.txt”,“w”)
test.write(“HellofromPython!”)
test.close()
Ifyourunthisexampletwice,youwillseethatthetextfileonyourdesktopstillonly
containsonesentence.
AppendingTexttoaFile
Toaddcontenttotheendofafile,useoneofthe“append”modeswhenopeningthefile.
Forexample:
test=open(“/home/pi/Desktop/Test.txt”,“a”)
test.write(“AnotherhellofromPython!”)
test.close()
IfyouopenthefileTest.txtnow,youshouldseethatthestringhasbeenaddedtotheend
ofthefile.
RenamingandDeletingFiles
Torenameafile,importosandthenusetherename()function:
importos
os.rename(“/home/pi/Desktop/Test.txt”,“/home/pi/Desktop/Test2.txt”)
Todeleteafile,usetheremove()function:
importos
os.remove(“/home/pi/Desktop/Test2.txt”)
WorkingwithFolders
Theosmodulealsoincludesmanyfunctionsforcreatingandworkingwithfolders.Here
aresomeoftheonesyouwilluseoften:
FunctionDescription
mkdir(path)Createsanewfolderatthespecifiedpath.makedirs(path)Createsanewfolderatthespecifiedpath,and
anyfoldersaboveitthatdonotexistyet.listdir(path)Returnsa“list”ofthecontentsofthespecifiedfolder.
removedirs(path)Removes(deletes)thespecifiedfolderandeverythinginsideit.
rename(path,path)Changesthenameofafolder.
6.9GraphicalUserInterfaces(GUIs)
AlthoughalloftheexamplesinthischapterhaveassumedthatyouarerunningPython
programsfromthePythonShellortheLinuxterminal,itispossibletobuildfullGUIsin
Python.Todothis,youneedtouseaGUItoolkit(or“framework”)thatsupportsallofthe
differenttypesofcontrolsthatyouneed–windows,textboxes,andbuttons,forexample.
TocreateaPythonprogramwithaGUIthatalsorunsonotheroperatingsystems,you
havetouseaframeworkthatisavailableonallofthemachinesonwhichyouwanttorun
yourprogram.Afulllistofcross-platformGUItoolkitsisavailableathttp://
wiki.python.org/moin/GuiProgramming.Ofthese,theTkInterframeworkisparticularly
popularandisalreadyinstalledonRaspbian.
7–ControllingInputandOutputPins
OneofthedifferencesbetweentheRaspberryPiandthedesktopcomputers,smartphones,
andtabletsthatyoumayhaveused,isthatthePiisdesignedwitha40-pinconnectorthat
youcancontrolfromyourownsoftware.Thismakesitsimilartodevelopmentboardslike
theArduino,butthePihasthepowerandspeedofaregularcomputer.
The40-pinheaderismade-upofmanygeneralpurposeinputandoutput(GPIO)pins.In
thiscontext,“generalpurpose”meansthatyoucanusethemforwhateveryoulike–for
example:turningonlight-emittingdiodes(LEDs);workingwithsensors(devicesthatread
thingsliketemperatureandlightlevels);movingservosandmotors;andtalkingto
electroniccircuitsthatyoubuildyourself.
Inthischapter,youwilllearnsomeofthetechniquesandknowledgethatyouneedto
buildbasicelectroniccircuits,andthenseehowtocontroltheGPIOpinsfromRaspbian.
PoorlydesignedorincorrectlyassembledcircuitscandamagetheRaspberryPi,andmaybehazardoustothe
personusingorbuildingthem.Alwaysseekadvicefromaqualifiedpersonifyouarenotsureaboutwhatyouare
doing.
7.1ElectronicCircuits,VoltageandCurrent
Electricityisaformofenergythatflowsinacircuit(aloop).Itcanbehelpfultothinkof
itstartingfromoneconnectoronabatteryorpowersupply,andthenmovingaroundthe
circuituntilitreachestheotherconnector.Alongtheway,itprovidespowertothe
componentsthatyouplaceinthecircuit.Ifthecircuitisbrokenatanypoint,then
electricitycannotflowandsonothingwillreceivepower.
Aschematicisadrawingthatshowshowdifferentcomponentscanbeconnectedtogether.
Forexample:
Figure1.Threetypesofcircuit–closed(left),open(middle),andshort(right).
1Batteryorpowersource.Thissuppliesthecircuitwithelectricity.
2Light-emittingdiode(LED).Whenpowerflows,itlightsup.
3Resistor.Seebelow.
Inaclosedcircuit,electricitycanflowfromthe+terminal,tothe
-terminal(groundindigitalelectronics).ItpassesthroughtheLED,whichcausesitto
glow.Butinanopencircuit,electricitycannotflowallthewayaroundtogroundsoit
doesnotmoveatall.Inthisexample,theLEDdoesnotlight.Aswitchworksbyopening
andclosingthecircuit.
Ashortcircuitcanbedangerous.Thereisadirectconnectionbetweenthe+andterminalsonthebattery.Withnocomponentsinbetween,thereisnothingtouseorlimit
theamountofelectricitythatflows.
Voltageistheamountofforcethatpusheselectricityaroundacircuitanditismeasuredin
volts(V).Forexample,5Vor9V.Youwilloftensee3.3Vwrittenas“3V3”indiagrams
whereadotmightbedifficulttoread.
Currentistheamountofelectricalchargeinacircuit.Itiscurrentthatmakesthings
happen,likelightinganLED.ItismeasuredinampsandthisisshownwithanA.For
example,1Aor3A.Butelectroniccircuitsusuallyuseverysmallamountsofcurrent,and
somilliamps(mA,orthousandthsofanamp)canbeusedinstead.
Theresistanceofacircuitlimitstheamountofcurrentthatflowsandprotects
components.Itismeasuredinohms,andwrittenwiththesymbolΩ.Resistorshavecolorcodedstripesthatindicatetheamountofresistancethattheyputinacircuit.
7.2SolderlessBreadboards
Breadboards(or“solderlessbreadboards”)areeasywaysofconnectingcomponents
temporarily.
Thevariousrowsofholesarejoinedtogetherinsidetheboard.Onastandardbreadboard,
therearefourlongrows.Theholesineachrowarejoinedtogetherinsidetheboard,but
noneoftheserowsarejoinedtoeachother.
Inthemiddleoftheboard,theholesaredividedintocolumns.Column15ishighlighted
onthediagrambelow.
151015202530A
B
C
D
E
F
GHI
J
151015202530
Figure2.Layoutofatypicalbreadboard
A15–E15arejoined,andF15–J15arealsojoined.Butthetwogroupsarenotconnected
togetherortoanyothercolumns.
ConnectingtheRaspberryPitoaBreadboard
Inelectronics,amaleconnectorisapin,plug,orwirethatslotsintoafemaleconnector.
Femaleconnectorsareusuallysocketsorjacks.Unlikethedesignersofotherdevelopment
boards,theRaspberryPiFoundationusemalepinsfortheGPIOheadersonthePi.To
connectthePitoasolderlessbreadboard,youcaneitheruse:
•A40-pinfemale-to-femaleribboncable;or
•Individualfemale-to-malejumperwires.
Ifyouuseafemale-to-femaleribboncable,youneedtouseregularmale-to-malejumper
wiresoraRaspberryPiB+GPIObreakoutboardtoconnectthesocketonthecableto
holesonthebreadboard.
7.3TheGPIOHeader
The40-pinGPIOheaderislocatedinthetop-leftofthePi.Thepinsarenumberedfrom
lefttoright,butodd-numberedpinsareonthelowerrowandeven-numberedpinsareon
thetop-row.
Figure3.LocationoftheGPIOheader(left),andthepowerandgroundconnections(right)
YoucanconfiguremostoftheGPIOpinsasinputsoroutputsandcontrolthem.Butsome
haveadditionaluses:
Pin#NameDescription3GPIO2Input/output.OrI2CwireSDA(I2C1_SDA).5GPIO3Input/output.OrI2Cwire
SCL(I2C1_SCL).7GPIO4Input/output.Orprovidesamasterclockoutput(GPCLK0)toexternalcircuits.
8GPIO14Input/output.OrUARTtransmitpin(UART_TXD).
10GPIO15Input/output.OrUARTreceivepin(UART_RXD).
11GPIO17Input/output.
12GPIO18Input/output.
13GPIO27Input/output.
15GPIO22Input/output.
16GPIO23Input/output.
18GPIO24Input/output.
19GPIO10Input/output.OrSPImaster-outputwire(SPI_MOSI).
21GPIO9Input/output.OrSPImaster-inputwire(SPI_MISO).
22GPIO25Input/output.
23GPIO11Input/output.OrSPIclockwire(SPI_SCLK).
24GPIO8Input/output.OrSPIdeviceselect0(SPI_CE0).
26GPIO7Input/output.OrSPIdeviceselect1(SPI_CE1).
27ID_SDReserved.
28ID_SCReserved.
29GPIO5Input/output.
31GPIO6Input/output.
32GPIO12Input/output.
33GPIO13Input/output.
35GPIO19Input/output.
36GPIO16Input/output.
37GPIO26Input/output.
38GPIO20Input/output.40GPIO21Input/output.
TheGPIOpinsareratedfor3.3V.Theyarenot5Vtolerantandsoapplyingmorethan
3.3VtoaninputpincanbreakthePi.
7.4BasicOutput
BlinkinganLEDistheelectronicsequivalentofthe“Hello,World!”program.Inthis
example,youwill:
1.MakeacircuitusinganLEDand270Ωresistor.
2.LearnhowtosetaGPIOpintoanoutput.
3.TurntheLEDonandofffromaterminalwindow,andfromaPythonscript.
LEDsmustbeplacedinacircuitinthecorrectdirectionaselectricityonlyflowsoneway
throughthem.OnelegofanLEDislongerthantheother–thisiscalledthe“anode”and
itistheonethatreceivespower.Theotherlegiscalledthe“cathode”,andthistheoutput
leg.InFigure4youcanalsoseethatontheanodeside,thepieceofmetalinsidetheLED
issmaller.
Figure4.Light-emittingdiodes(LEDs)
Itdoesnotmatterinwhichdirectionyouplacetheresistor.
UnplugthePi,andthenbuildthecircuitinFigure5.Ifyoudonothavea270Ωresistor,
thenyoucanusearesistorofaslightlygreatervalue.Trytoavoidusingsmallervalue
resistors–ifthereisnotenoughresistanceinthecircuitthentheLEDwilldrawtoomuch
currentandbreak.
Eachinput/outputpinontheGPIOheadercanonlysupply16mAofcurrent,andthePicanonlysupply50mA
ofcurrenttoallofthepinsintotal.
Figure5.LightinganLED
Checkthat:
1.The+legoftheLEDisonthesamerowasthe3.3Vwire,andthe-legoftheLEDis
notonthesamerow.
2.Thetopwireisconnectedtopin1(3.3V).
3.Thebottomwireisconnectedtopin6(ground).
ConnectthePitoitspowersourceandtheLEDwillturnon.Ifitdoesnot,unplugthe
powerimmediately,andthencheckthat:
1.YouhaveplacedtheLEDinthecorrectdirection.Theanodereceivespower,the
cathodeallowsthepowertoflowoutandintothenextcomponent.
2.YouhaveplacedtheLED,resistors,andwiresinthecorrectholesonthebreadboard.
3.Youhaveanappropriatevalueresistor.Iftheresistanceistoogreat,youwon’tbeable
toseethattheLEDison.
Sofar,youareusingthePiasabattery.Butnowthatyouknowyourcircuitworks,you
canplacetheLEDunderthePi’scontrol:
1.ShutdownthePiandunplugitfromthepower.2.Disconnectthered3.3Vwirefrom
headerpin1,andthenconnectittopin3(GPIO2).
3.PlugthepowerbackintotheRaspberryPi,andallowRaspbiantoload.
WhenthePiboots,GPIO2isoftenbroughthigh.Ahighsignalis3.3V,alowsignalis
connectedtoground(0V).
ControllingGPIO2fromaTerminalWindow
YoucancontroltheGPIOpinsfromaterminalwindowinRaspbian.Butonlythe
superusercandothis.Formoreinformationaboutusersandsuperusers,see
UnderstandingLinuxUsersandSuperusersonpage36.
Ifyouwanttocontrolthepinsfromtheterminal,youfirstneedtoexportthepin.This
createsaspecialfolderinthefilesystemthatyoucanusetochangethepinfromaninput
toanoutput,sendthepinhigh,orsendthepinlow.
1.OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickRoot
Terminal.
2.TypethefollowingcommandandthenpressEnter:echo2>/sys/class/gpio/export
3.TypethefollowingcommandandthenpressEnter:ls/sys/class/gpio/gpio2
Thefilesthatyouseeinthegpio2directorycontrolthestateofGPIO2.Whenexporting
GPIOpins,thenumberyouuseistheGPIOnumbernotthepinnumber.
TosetGPIO2asanoutputandturniton:
1.IntheRootTerminal,typethefollowingcommandandthenpressEnter:
echoout>/sys/class/gpio/gpio2/direction
2.TypethefollowingcommandandthenpressEnter:echo1>/sys/class/gpio/gpio2/value
ToturnGPIO2off:
•IntheRootTerminal,typethefollowingcommandandthenpressEnter:
echo0>/sys/class/gpio/gpio2/value
Whenyouaredone,itisagoodpracticetounexportthepinsothatitisnolongerunder
thecontrolofthefilesystementries:
•IntheRootTerminal,typethefollowingcommandandthenpressEnter:
echo2>/sys/class/gpio/unexport
Asafinalnote,outputting0actuallyconnectstheGPIOpintogroundinsidethePi.So
anythingconnectedtothatpinisalsobroughttoground.
ControllingGPIO2fromPython3
FromPython,youcancontroltheGPIOpinsusingtheRPi.GPIOmodule.Thisexample
setsGPIO2asanoutput,andthenblinkstheLEDbyrepeatedlyturningitonandoff
again.Todothis,youalsoneedtoimportthetimemodule,whichcontainsafunctionfor
causingadelay.
1.Onthedesktop,double-clickIDLE3.
2.InthePythonShell,ontheMenu,clickFile,andthenclickNewWindow.
3.OntheMenu,clickFile,andthenclickSaveAs.4.Savethefiletoyourdesktop,with
theextension.py.
5.Atthetopofthefile,typethefollowingstatements:importRPi.GPIO
importtime
6.Onanewline,typethefollowingstatement:RPi.GPIO.setmode(RPi.GPIO.BCM)
setMode()isafunctionintheRPi.GPIOmodulethatsetshowyouaregoingtoreferto
pins.Therearetwooptionsforthis:
•BOARDstatesthatwhenyoupassthevalue2intofunctionsintheRPi.GPIOmodule,
youarereferringtopin2.
•BCMstatesthatwhenyoupassthevalue2intofunctionsintheRPi.GPIOmodule,you
arereferringtoGPIO2.
NowyouneedtoconfigureGPIO2asanoutput:
•Onanewline,typethefollowingstatement:
RPi.GPIO.setup(2,RPi.GPIO.OUT)
Thefunctionsetup()acceptstwoarguments:thefirstisthepinorGPIOnumber
(dependingonwhetheryouuseBOARDorBCMinthecalltosetMode());andthesecond
canbeRPi.GPIO.INorRPi.GPIO.OUT.Tomakeapinanoutput,useRPi.GPIO.OUT.
Nowaddthefollowingcodetothescriptandsavethefile:
whileTrue:
RPi.GPIO.output(2,True)
time.sleep(1)
RPi.GPIO.output(2,False)
time.sleep(1)
Thefunctionoutput()setstheoutputpinhighwhenthesecondargumentisTrue.Itsets
theoutputpinlowwhenthesecondargumentisFalse.Ifyouprefer,youcanuse
RPi.GPIO.HIGHandRPi.GPIO.LOWinsteadofTrueandFalse.
Thecalltosleep()causesPythontowaitonesecondbeforemovingontothenext
instruction.IfyouwanttoblinktheLEDslower,increasethevaluethatyoupassinto
sleep().Forexample,sleep(2).IfyouwanttoblinktheLEDfaster,decreasethevaluethat
youpassintosleep().Forexample,sleep(0.5).
YoucannotrunthisscriptfromIDLE3,becausecontrollingtheGPIOpinsrequires
superuseraccess.Torunyourscript:
1.Onthedesktop,double-clickLXTerminal.
2.Browsetoyourscript.Forexample,ifyousavedthefileastest.pyonthedesktop:
cdDesktop
3.TypethefollowingcommandandthenpressEnter.
Changetest.pytothenameofyourscript.
sudopython3test.py
TheLEDwillnowblinkonandoff.Becausethewhileloopinthisscriptneverreceives
False,thescriptrunsforever.Tostopthescript,pressCtrl+C.
7.5BasicInput
WiththeGPIOpins,inputinvolvesfindingoutwhetherthevoltagethatiscomingintoa
pinfromyourexternalcircuitishigh,orwhetheritislow.Inthissection,youwillsee
howtodetectwhenaswitchisclosed.Anyswitchwillworkforthis,buttwo-terminal
on/offswitchesandfour-terminaltactilepushbuttonsaretheonesthatpeopleusemost
often.
Withfour-terminalpushbuttons,itcanbedifficulttoseewhichwayroundinthecircuit
youshouldplacethem.Thetop-leftandtop-rightterminalsarealwaysjoined.Thetop-left
andbottomleftterminalsareonlyjoinedwhentheswitchispressed.Soifyourcircuit
alwaysdetectsthattheswitchispressed,rotatethebutton90°inaclockwisedirection.
Donotwireaswitchonitsownbetweenthe3.3Vpower-outputpinandaGPIOinput.
Whentheswitchispressed,3.3Vflowsintotheinputpinandbringstheinputhigh.But
therearetwopotentialproblemswiththis:
1.Whentheswitchisnotpressedtheinputpincanbefloating.Whenapinfloats,itis
neitherhighnorlow,andcanchangebetweenthetwoseeminglyatrandom.
2.Whentheswitchispressed,thereisverylittleresistanceinthecircuitandsothiscan
damagethePi.Itis,effectively,ashortcircuit.
IntroducingPull-UpandPull-DownResistors
Inthediagrambelow,whentheswitchisopen,electricityflowsthroughtheresistorand
intotheGPIOpin.Sowhentheswitchisopen,theGPIOpinishigh.Whentheswitchis
closed,alloftheelectricityisdrawntoground,andthiscreatesalowontheGPIOpin.So
thepinisalwaysinoneorstateortheother,itisneverfloating.
Pullingthelineupinthiswayiscalledusingapull-upresistor.
Figure6.Aswitchandapull-upresistor
Apull-downresistorworksintheoppositeway:whentheswitchisopen,theGPIOpinis
tiedtogroundandislow.Butwhentheswitchisclosed,electricityflowsintotheGPIO
pinanditishigh.
TheRaspberryPihaspull-upandpull-downresistorsbuilt-intoalloftheGPIOpins.And
youcanchoosewhichonesyouwanttousefromyoursoftwareprograms.
BuildingtheCircuit
OnthePi,thecircuitabovehasaproblem.IftheGPIOpin(themiddlelineonthe
diagram)isaccidentlysettoahighoutput(eitherbytheuserorbythePiwhenitis
starting-up)thenpressingtheswitchcausesashortcircuitandcandamagethePi.
BuildthecircuitinFigure7.ItreliesonthePi’sinternalpull-upresistorbutalsoaddsa
330ΩresistortoprotectthePiiftheGPIOpinischangedtoanoutput.
IftheGPIOisahighoutputthentheelectricityflowsthroughthe330Ωresistorandthis
isenoughtoprotectthePi.Theresistormustbeahigh-enoughvaluetoprotectthePibut
lowenoughsothatelectricitypreferstoflowtogroundwhenyoupresstheswitch,rather
thanintotheGPIOpin.
Figure7.Basicinput–schematic(left),andbreadboard(right)
WiththeGPIOpinconfiguredasaninputandthePi’sinternalpull-upresistorenabled,if
theswitchisopenthenthepull-upbringstheGPIOpinhigh.Iftheswitchispressed,the
connectiontogrounddrainstheelectricityfromthepinandthiscausesittogolow.
ReadingaGPIOPinfromaTerminalWindow
ToreadthestateofGPIO2fromtheterminalorshell,youneedtoexportthepintothefile
system.
1.OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickRoot
Terminal.2.TypethefollowingcommandandthenpressEnter:
echo2>/sys/class/gpio/export
Toconfigurethepinasaninputandenabletheinternalpull-upresistor:
1.IntheRootTerminal,typethefollowingcommandandthenpressEnter:
echoin>/sys/class/gpio/gpio2/direction2.TypethefollowingcommandandthenpressEnter:
echo0>/sys/class/gpio/gpio2/active_low
Toreadthepin,youcanusethecatcommand,whichisusedtoreadfilesanddisplay
themintheterminal:
1.IntheRootTerminal,typethefollowingcommandandthenpressEnter:
cat/sys/class/gpio/gpio2/value
2.TypethefollowingcommandbutdoNOTpressthe
Enterkey:
cat/sys/class/gpio/gpio2/value
3.Presstheswitch(holditifyouareusingapush
button),andthenpressEnter.
Whenyouaredone,unexportthepinsothatitisnolongerunderthecontrolofthefile
systementries:
•IntheRootTerminal,typethefollowingcommandandthenpressEnter:
echo2>/sys/class/gpio/unexport
ReadingaGPIOPinfromPython3
Asforoutputpins,youcanusetheRPi.GPIOmoduletoreadfromaninputpin,andthe
setMode()methodtostatehowyouwanttorefertopinnumbers.
1.CreateanewPythonscriptandsaveitwiththeextension.py.
2.Atthetopofthescript,typethefollowing
statements:
importRPi.GPIO
RPi.GPIO.setmode(RPi.GPIO.BCM)
NowyouneedtoconfigureGPIO2asaninputandenabletheinternalpull-upresistors:
•Addthefollowingstatementononeline:
RPi.GPIO.setup(2,RPi.GPIO.IN,pull_up_down=RPi.GPIO.PUD_UP)Thepull_up_downparametercanbe
oneofthreevalues:
ValueDescription
RPi.GPIO.PUD_UPActivatestheinternalpull-upresistor.RPi.GPIO.PUD_DOWNActivatestheinternalpull-down
resistor.RPi.GPIO.PUD_OFFDisablesthepull-upandpull-downresistors.
Addtheremainderofthecodetothescript:
whileTrue:
ifRPi.GPIO.input(2)==RPi.GPIO.LOW:print(“Switchpressed.”)break
RPi.GPIO.cleanup()
ThisscriptloopsuntiltheswitchispressedandGPIO2goeslow.Atthatpoint,itprintsa
messagetotheuser,breaksfromthewhileloopandthenreleasesitscontroloverthe
GPIOpin.
7.6Communicationbetween3.3Vand5VDevices
EventhoughthePihasa5Vpowersupply,itisa3.3Vdeviceand3.3Visthemaximum
voltagethatyoucansafelyconnecttoitsinputpins.However,mostotherpopular
developmentboards,sensors,andcomponentsare5Vdevices.
Toconnect5VoutputstoaninputonthePi,youwillneedtoconvertthevoltagelevelsso
thathighsignalsareonly3.3V.
ThehighsignalfromthePiisusuallyenoughtoensurethatthe5Vdevicedetectsthelineashigh.Thissectionis
primarilyconcernedwithprotectingthePi’sinputpins.
Ifyouneedtoconvertmorethanatwoorthreesignals,thenabi-directionallogiclevel
converterchipisausefulpurchase.Butifyouonlyneedtoconvertoneortwosignals
thenthereseveralmethodsyoucanuse.Twoareshownhere.
1.UsingaVoltageDivider
Intheexamplebelow,thetworesistorsformapotentialdivider.Thisdividesthevoltage
andallowsenoughofittopasstogroundsothattheGPIOpinonlyreceivesaround3.3V.
Theexactresistorvaluesarenottooimportant–butthefirstresistormustbeslightlyover
halfthevalueofthesecondresistororthedividerdoesnotworkcorrectly.
Figure8.Usingresistorsfor5Vto3.3Vinterfacing
2.UsingaDiodeandPull-UpResistor
Diodesarepassivecomponentsthatonlyallowelectricitytoflowinonedirection.On
schematics,theyresembleanarrowandthisindicatesthedirectioninwhichelectricitycan
flow.Onanactualdiode,thereisathicklinethatcorrespondstotheverticallineonthe
schematicsymbol.
InFigure9,whentheoutputonthe5Vdeviceislowthenitisactuallyconnectedto
ground.Thismeansthattheelectricityfromthe3.3Vsupplypassesthroughthediodeand
intothe5Vdevice,pullinglowtheGPIOpinonthePi.Whenthe5Vdeviceoutputsa
highsignal,thediodeblocksthevoltage.Butbecausethediodeisblocking,the3.3V
cannotflowtothe5VdeviceandsoitflowsintotheGPIOpinonthePi–creatingahigh
signal.
Figure9.Usingadiodefor5Vto3.3Vinterfacing
7.7SerialPeripheralInterface(SPI)
Serialperipheralinterface(SPI)isaserialdataprotocolthatisusedbymicrocontrollers
andsmallelectronicdevicestoexchangeinformation.Theterm“serial”meansthateach
bitofabinarynumber(forexample,thenumber255ismadeupofeightbitsinbinary–
11111111)issentoneatatime,onthesamewire.
SPIdividesdevicesintotwocategories:masters,andslaves.Themasteristhedevicethat
startsthecommunication.Theslavereceivesinstructionsfromthemasteranddoeswhatit
istold.Amastercantalktomanyslavedevices,butusuallyonlyoneatatime.
TouseSPI,youneedfourpins:
PinNameDescription
MOSIMasteroutput,slaveinput.Themasterusesthislinetosendinformationtotheslave.MISOMasterinput,slave
output.Themasterusesthislinetoreadinformationfromtheslave.SCKSerialclock.Eachbitisreadonthe“edge”of
theclocksignal(seebelow).
SSSlaveselect.Useoneoftheseforeachslavedeviceinthecircuit.Themasterusesthiswiretoindicatewhichslave
deviceshouldlistenandrespondtoinstructions.
Whenthemastersendsinformationtoaslave,itusually:1.PullstheSSlinelowforthe
selectedslave.2.BringstheMOSIlinehighifthebititissendingis1;orbringsMOSI
lowifthebitis0.
3.PulsestheSCKline.Forexample,iftheclocklineislowwhenSPIisnotbeingused,
thenpulsingthelineinvolvesbrieflybringingtheclocklinehighandthenbringingitlow
again.
4.Repeatsthisprocessuntilallofthebitsaresent.
5.BringstheSSlinehigh.
Whenthemasterreadsinformationfromaslave,itusually:
1.PullstheSSlinelowfortheselectedslave.
2.PulsestheSCKline.
3.ReadswhethertheMISOlineishigh,orlow.
4.Repeatsthisprocessuntilithasallofthe
informationthatitisexpecting.
5.BringstheSSlinehightoendcommunicationwiththeslave.
Withsomedevices,themastersendsacommandtotheslavedevicetotellittosenddata.
Inthesecases,themastermovesbetweenthesendingandreadingphaseswithout
changingtheSSline.
ThereissomevarietyinhowdifferentSPIdevicesexpectthesetwoprocessestowork.
Somerequirethattheclocklineishighwhenitisnotin-use,andothersrequireittobe
low.SomeSPIslavedevicesexpecttheirSSlinetobehighwhenthemasterwantsto
communicatewithit,andothersexpecttheSSlinetobelow.
EnablingSPIontheRaspberryPi
YoucanuseanyoftheGPIOinput/outputpinsforSPIsinceitonlyinvolvesbringingpins
highandlow,andreadinginputinthesamewayasdescribedearlierinthischapter.This
approachisoftencalled“bit-banging”.However,fiveoftheRaspberryPi’sGPIOpins
havealternativeusesforcommunicatingoverSPI.Byusingthesepinsyoucanuse
prebuiltlibrariesandtoolsinsteadofwritingasmuchcode.
TheSPIpinsontheGPIOheaderare:MOSI–pin19;MISO–pin21;SCK–pin23.The
headerhastwoslaveselectpins–pin24andpin26.
Bydefault,theSPIfunctionsofthesepinsaredisabledinRaspbian.Toenablethem:
1.OntheRaspbiandesktop,double-clickLXTerminal.
2.TypethefollowingcommandandthenpressEnter:
sudoraspi-config
3.PresstheDownArrowkeyseventimestoselectAdvancedOptions,andthenpress
Enter.4.PresstheDownArrowkeyfourtimestoselectSPI,andthenpressEnter.
5.PressEnter.
6.PressEnter.
7.PresstheRightArrowkeytwicetoselect<Finish>.ThenpressEnter.
8.TypethefollowingcommandandthenpressEnter:sudonano/etc/modules
9.Onanewlineattheendofthefile,addthefollowingtext:
spi-dev
10.PressCtrl+O,andthenpressEnter.
11.PressCtrl+X.
12.TypethefollowingcommandandthenpressEnter:sudoshutdown–rnow
WhenthePirestarts,theSPImodulesloadautomatically.
UsingSPIfromPython3
TouseSPIfromPython,youneedtoinstallthepython3-devlibraries,andamodulefor
PythonthatmakestheSPIdevicesaccessible.
1.OntheRaspbiandesktop,double-click
LXTerminal.
2.TypethefollowingcommandandthenpressEnter:
sudoapt-getinstallpython3-dev
3.Whentheinstallationiscomplete,typethe
followingcommandandthenpressEnter:
gitclonegit://github.com/rpodgornypy-spidev4.TypethefollowingcommandandthenpressEnter:
cdpy-spidev
5.TypethefollowingcommandandthenpressEnter:
sudopython3setup.pyinstall
WhenconnectingthePitoSPIdevices,theGPIOpinMOSI(masteroutput,slaveinput)
connectstotheSI(slaveinput)pinontheexternaldevice.Similarly,theGPIOpinMISO
(masterinput,slaveoutput)connectstotheSO(slaveoutput)pin.
TouseSPIinPython:
1.Onthedesktop,double-clickIDLE3.
2.InthePythonShell,ontheMenu,clickFileandthenclickNewWindow.
3.Typethefollowingatthestartofthescript:
importspidev
importtime
Figure10.Connectinga23K640SPImemorychiptothePi
TocreateaninstanceoftheSpiDevclassandopenaconnection,addthestatements:
spi=spidev.SpiDev()spi.open(0,0)
Thefirstparametertoopen()isthedevicenumber.OnlyoneSPImasterdeviceis
availableontheGPIOheaderandsothisisalwayszero.Thesecondparameteristheslave
selectpinthatyouwanttouse.0tellsthemoduletousepin24,and1tellsittousepin26.
TowriteabytetotheSPIdevice,youcanusethexfer()method.Forexample:
spi.xfer([2,0,0,8])
Thexfer()methodacceptsoneargument,andthatisanarrayofbytes.Whenyoucallthis
method,theslaveselectpinisbroughtlowandthenitsendsthevaluesinthebytearrayto
theSPIdevice.Theclocksignalisgeneratedforyou.
Youalsousethexfer()methodtoreadfromanSPIdevice.Theslavedeviceexpectsthe
mastertogeneratetheclockpulsesthatitneedstotransmitdata.Soyoumayneedto
includeextrabytesinthecalltoxfer().Forexample,ifanSPIdeviceexpectsthemasterto
sendthesequence3,0,0beforeitsendsbackabytethenyouwouldpassanextra0into
xfer():
spi.xfer([3,0,0,0])
YoucanuseseveralpropertiesoftheSpiDevclasstochangehowtheSPImethodswork.
ThisisusefulwhenyouareusingSPIdevicesthatdonotfollowtheusualprocess.
PropertyDescription
cshighWhenTrue,ahighsignalisusedtotelltheslavedevicethatitshouldlistenandrespond.WhenFalse,alow
signalisused.Falseisthedefault.
max_speed_hzNotallSPIdevicescanrunasfastasthePi.DecreasethevalueofthispropertytoslowtheSPI
transmissionsdown.
modeSetstheclockpolarityandphase.Canbe0–2.
7.8I2CCommunication
I2C(pronouncedeye-too-see)isanotherserialcommunicationsprotocol,butitusesfewer
wires.ThemasterdevicecontrolsI2Ccommunications,andyouconnectallslavedevices
tothesamewires.Eachslavedevicehasauniquenumber(calledan“address”)anditonly
respondstomessagesthatitreceiveswhichspecifythisaddress.Thismeansthatyou
cannotusetwoslavedevicesthathavethesameaddress.
ThetwoI2ClinesarecalledSDAandSCL.Youneedtouseapull-upresistoronthese
lines.Thevalueoftheresistorsisnotveryimportant,butaround10KΩisgenerally
suitable.
AnyGPIOpinscanbeusedforI2C,ifyouwanttowriteallofthecode.Butitisamore
complicatedprotocoltoimplementfromscratch.TouseprebuiltI2Clibrariesand
modules,thetwoI2Cwiresarepin3andpin5oftheGPIOheader.
Figure11.I2CcommunicationbetweenthePiandmultipledevices
EnablingI2C
OnRaspbian,I2Cisdisabled.Toenableit,youmustfirstremoveI2Cfromthemodule
“blacklist”.ThisisafilethatstopsRaspbianloadingcertainmodules.ToremoveI2Cfrom
thelist:
1.Onthedesktop,double-clickLXTerminal.
2.TypethefollowingcommandandthenpressEnter:
sudonano/etc/modprobe.d/raspi-blacklist.conf3.Ifyouseelinesinthisfilethatreadblacklistspi
bcm2708orblacklisti2c-bm2708thenadda#
symbolatthestartofthelines.Thismakestheline
intoacommentsothatRaspbianignoresit.
4.PressCtrl+O,andthenpressEnter.
5.PressCtrl+X.
Toaddthei2c-devmoduletothelistofmodulesthatRaspbianloadswhenthePiis
started:
1.InLXTerminal,typethefollowingcommandandthenpressEnter:
sudonano/etc/modules
2.Onanewline,add:
i2c-dev
3.PressCtrl+O,andthenpressEnter.
4.PressCtrl+X.
Nowyouneedtoinstallthei2c-toolspackageandbuildthepysmbusmodule:
1.InLXTerminal,runthefollowingcommandsonebyone:
sudoapt-getinstalli2c-tools
sudoshutdown-rnow
2.InLXTerminal,typethefollowingcommandandthenpressEnter:
sudoapt-getinstallpython3-dev
3.Runthefollowingcommands:
sudoapt-getinstalllibi2c-dev
cd/home/pi/Desktop
4.TypethefollowingcommandandthenpressEnter:wgethttp://ftp.de.debian.org/debian/pool/
main/i/i2c-tools/i2c-tools_3.1.0.orig.tar.bz25.Runthefollowingcommands:
tarxfi2c-tools_3.1.0.orig.tar.bz2
cdi2c-tools-3.1.0/py-smbus
6.TypethefollowingcommandandthenpressEnter:
wgethttps://www.dropbox.com/s/
am9wb0g3wpixq3k/smbusmodule.c?dl=1–Osmbusmodule.c
7.Runthefollowingcommands:
python3setup.pybuild
sudopython3setup.pyinstall
UsingI2CfromPython3
AtthetopofyourPythonscript,youneedtoimportthemodulesmbusandcreatean
instanceoftheSMBusclass.
Intheexamplebelow,thecodesendsthevalue88totheI2Cdevicewiththeaddress23:
importsmbus
bus=smbus.SMBus(0)
bus.write_byte(23,88)
ToreadfromanI2Cdevice,usetheread_byte()methodandpassthedevice’saddressas
anargument.Forexample:v=bus.read_byte(23)
7.9SerialUARTs
Auniversalasynchronousreceiver/transmitter(UART)isachipthattranslatestheparallel
datausedbyamicroprocessorormicrocontrollertoserialdataforusewith
communicationsports.
Serialportsareasynchronous,whichmeansthatyoucansenddataatthesametimeas
receivingit,andbothdevicescaninitiateconnectionsandsenddatawhentheywantto.
OnthePi,theGPIOheaderhastwoUARTpinsformakingconnectionstootherdevices
usingatraditionalserialport.Thesearepin8(UART_TXD)andpin10(UART_RXD).
TheTXDpinofthePiisconnectedtotheRXDpinoftheotherdevice,andtheRXDpin
ofthePiisconnectedtotheTXDpinoftheotherdevice.Andtomakeelectricityflow,
youalsoneedtoconnectawirebetweenthegroundofeachdevice.
ThePi’sserialportuses3.3Vlogiclevels.YouneedlogiclevelconverterstoconnectthePitothe5Vportsused
bymostUSBserialportadapters.
InRaspbian,thePi’sserialportis/dev/ttyAMA0.Thisdeviceisusuallyconfiguredfor
consoleinputandoutput,andsoifyouwanttocontroltheportfromyourownprograms
thenyouneedtochangetwoconfigurationfiles:
1.OntheRaspbiandesktop,double-click
LXTerminal.
2.TypethefollowingcommandandthenpressEnter:sudonano/etc/inittab
3.OnthelinethatreadsTO:23:respawn:/sbin/getty
–LttyAMA0115200vt100,adda#symbolatthestartoftheline.Thismakesthelineinto
acommentsothatRaspbianignoresit.
4.PressCtrl+O,andthenpressEnter.
5.PressCtrl+X.
6.TypethefollowingcommandandthenpressEnter:sudonano/boot/cmdline.txt
7.Removeallreferencesto/dev/ttyAMA0sothatthelinereads:
dwc_otg.lpm_enable=0console=tty1root=/dev/mmcblk0p2rootfstype=ext4elevator=deadlinerootwait
8.PressCtrl+O,andthenpressEnter.
9.PressCtrl+X.
10.TypethefollowingcommandandthenpressEnter:sudoshutdown–rnow
MakingSerialCommunicationsfromPython3
TosendandreceivedatafromtheserialportinPython,youcanusethepySerialmodule:
1.Atthetopofyourscript,includethefollowingline:importserial
2.CreateaninstanceoftheSerialclass,usingtheline:
ser=serial.Serial(“/dev/ttyAMA0”,19200,timeout=0)
3.Usethewrite()methodtosenddata.Forexample:ser.write(“Hello”)
ThefirstparameterofthecalltoSerial()isthenameoftheserialportdevice.
/dev/ttyAMA0istheserialportthatisavailableonthePi’sGPIOheaders.Thesecond
parameteristheconnectionspeed(alsoknownas“baudrate”).Theotherdeviceneedsto
openitsserialportatthesamespeed.
Theremainingsettingsthatyouneedtouseontheotherdeviceare:parity:none;databits:
8;stopbits:1;handshaking(hardwareflowcontrol):off.
Toreadfromtheserialport,youcaneithercalltheread()methodwithnoargumentsto
readasinglebyte,orpassthenumberofbytesthatyouwanttoreadintothemethod.The
timeoutparameterthatyouspecifiedearlierdefineshowlongthePiwillwaittoreceive
data.Iftimeoutiszerothenread()willwaituntilitreceivesallofthebytesthatyou
request.
Towaituntiltheothermachinesendsaspecificnumberofbytesbeforeyouattemptto
readfromtheport,youcanusethemethodinWaiting().Thisreturnsthenumberofbytes
thatyourscripthasnotyetread.
Whenyouarefinishedwiththeserialconnection,youshouldclosetheserialportby
callingtheclose()methodoftheSerialclass.
8–BuildinganIPCamera
IPcamerasareatypeofcamerathatyoudonotneedtoconnecttoacomputerinorderto
viewthevideosandimagesthattheyrecord.Instead,theyconnecttoyourlocalnetwork
routerandmaketheoutputavailableoverInternetprotocols(IP).Thisallowsthevideos
andimagestobeviewedacrosstheInternet.
BecausetheRaspberryPiissmall,andhasgoodInternetconnectivity,itiswell-suitedfor
buildingthistypeofcamera.Inthischapter,youwillseehowtoconnectaPicamera
moduletotheModelB+andconfigureRaspbian.
Youneed:
1.ARaspberryPi(anymodel)runningRaspbian.
2.AnEthernetorWi-FiconnectionsetuponthePi.
3.ARaspberryPiCameraModule.
4.Administratoraccesstoyournetworkrouter(tomakethevideoaccessibleoverthe
Internet).
8.1ThePiCameraModule
TheRaspberryPicameramoduleisasmall,high-definitionvideocamerathatconnectsto
theRaspberryPiusingthecameraserialinterface(CSI)connector.
Ithasafixed-focus,5-megapixelsensor,capableoftakingstillimagesinresolutionsupto
2592pixelswideand1944pixelstall,andvideoinresolutionsuptohigh-definition1080p
at30framespersecond.
ConnectingtheCamera
Thecameramoduleusesalong,flexiblecable,andthisisusefulwhenyouneedtofitthe
cameraandthePiintoacase.However,thistypeofcablecanbedamagedeasily.Donot
bendortwistthecableexcessively,anddonotuseitasaweight-bearingsupport.
ToconnecttothecameramoduletothePi:
1.EnsurethePiisunplugged.
2.OpentheCSIconnectoronthePibygraspingthetopoftheCSIconnectorandpulling
itupwards.
3.TaketheflexiblecableandgentlypushitdownintotheCSIconnector.Itwillonlypush
inbyafewmillimeters.ThebluestripeonthePiendofthecableshouldfacetheEthernet
port.
4.HoldtheflexiblecableinpositionandthenpressdownonthetopoftheCSIconnector
tocloseit.5.ReconnectthePitoitspowersupply.
Figure1.ConnectingthecameramoduletotheModelB+
EnablingtheCamera
Bydefault,thecameraisdisabledinRaspbian.Toenableit:1.OntheRaspbiandesktop,
double-click
LXTerminal.
2.TypethefollowingcommandandthenpressEnter:sudoraspi-config
3.PresstheDownArrowkeyfourtimestohighlightEnableCamera,andthenpress
Enter.
4.PresstheRightArrowkeytohighlight<Enable>,andthenpressEnter.
5.PresstheRightArrowkeytwicetohighlight<Finish>,andthenpressEnter.
6.PressEnter.
DisablingtheLED
ThePi’scameramodulehasaredlight-emittingdiode(LED)ontheboard.Todisableit:
1.OntheRaspbiandesktop,double-click
LXTerminal.
2.TypethefollowingcommandandthenpressEnter:sudonano/boot/config.txt
3.UsetheDownArrowkeytomovetotheendofthefile,andthenaddthefollowingtext
onanewline:
disable_camera_led=1
4.PressCtrl+OandthenpressEnter.
5.PressCtrl+X.
6.TorestartthePi,typethefollowingcommandandthenpressEnter:
sudoshutdown–rnow
8.2Motion
Motionisacommand-linetoolthatisdesignedforworkingwithcamerasfromLinux.It
takesstillimages,recordsvideos,detectsmovement,andstreamslivevideofeedsacross
theInternet.
Motion-mmalisaversionofMotionthatisdesignedtoworkwiththePicameramodule.
ToinstallMotion-mmal,youmustfirstinstallseveralfilesandpiecesofsoftwarethatit
workswith.
1.OntheRaspbiandesktop,double-click
LXTerminal.
2.Typethefollowingcommandononeline,andthenpressEnter:
sudoapt-getinstall–ylibjpeg62libjpeg62-devlibavformat53libavformat-devlibavcodec53libavcodec-devlibavutil51
libavutil-devlibc6-devzlib1g-devlibmysqlclient-devlibpq5libpq-dev
3.Changetoyourdesktopfolder.Forexample:cd/home/pi/Desktop
4.TypethefollowingcommandandthenpressEnter:
wgethttps://www.dropbox.com/s/
xdfcxm5hu71s97d/motion-mmal.tar.gz
5.TypethefollowingcommandandthenpressEnter:tarzxvfmotion-mmal.tar.gz
6.TypethefollowingcommandandthenpressEnter:sudomvmotion/usr/bin/motion
7.TypethefollowingcommandandthenpressEnter:sudomvmotion-mmalcam.conf
/etc/motion.conf
8.TypethefollowingcommandandthenpressEnter:sudochownroot:root/usr/bin/motion
Steps6–8abovemoveMotionintoasystemfolderandchangeitsowner.
ConfiguringtheSoftware
BeforestartingMotion,youshouldcheckitsconfigurationsettings.Whenyoustart
Motionwithnocommand-linearguments,itreadsitsconfigurationsettingsfromthefile
/etc/motion.conf.Toopenthisfile:
1.OntheRaspbiandesktop,double-click
LXTerminal.
2.TypethefollowingcommandandthenpressEnter:nano/etc/motion.conf
Therearemanysettingsthatyoucanchange,butthekeyonesare:
SettingDescriptionwidthThewidthofstillimagesandvideoframesinpixels.
SettingDescription
heightTheheightofstillimagesandvideoframesinpixels.
framerateThemaximumnumberofframestocapturepersecond.
rotateYoucanusethissettingtorotatetheimage.Acceptablevaluesare0,90,180,and270.target_dirThefolderwhere
Motionsavesimagesandvideos.
stream_portTheportnumberyouwanttousewhenaccessingthelivestreamfromotherdevices.
stream_maxrateThemaximumnumberofframestosendpersecondtodevicesviewingthelivestream.output_pictures
SetthistooffifyoudonotwanttosavepictureswhenMotiondetectsmovement.
ffmpeg_output_movies
SetthistooffifyoudonotwanttorecordvideofileswhenMotiondetectsmovement.
ffmpeg_video_codecIfyouhavedifficultyviewingthevideofilesthatMotionrecords,changethistouseadifferent
videocodec.Forexample,msmpeg4.
max_mpeg_timeThemaximumlengthofvideothatMotionsavestoeachfilebeforestartinganewone.
webcontrol_portTheportnumberforaccessingthecontrolpanelfromawebbrowser.
webcontrol_localhostWhenthisison,onlywebbrowsersrunningonthePicanaccessthecontrolpanel.
Whentakingimagesorrecordingvideo,thelargertheimagesize(widthandheight)and
thenumberofimagestaken(framerate)greatlyaffecthowmuchspacethefileswilluse
ontheSDcard.Ifyouarestreamingthevideofeedtootherdevices,thewidth,height,and
stream_maxratesettingsaffecthowfasteachimageorframeissenttoconnecteddevices.
Thedefaultimagesizeof1024x576isalittlelargeforthePitostreamtoconnectedweb
browsers.Thesizesuggestedinmotion.confof352x288worksmuchbetterandathigher
framerates.
Ifyouonlywanttoaccessthelivevideofeed,itisrecommendedthatyouset
ffmpeg_output_moviesandoutput_picturestooff.Otherwiseyoumayrunoutofspaceon
theSDcardveryquickly.
TochangetheconfigurationofMotion:1.OntheRaspbiandesktop,double-click
LXTerminal.
2.TypethefollowingcommandandthenpressEnter:nano/etc/motion.conf
3.Changeanysettings.
4.PressCtrl+O,andthenpressEnter.
5.PressCtrl+X.
Password-ProtectingyourCameraStream
Ifyouwanttostopothersfromaccessingyourvideostream,youcanconfigureMotionto
requireausernameandpassword.
Todothis:
1.OntheRaspbiandesktop,double-click
LXTerminal.
2.TypethefollowingcommandandthenpressEnter:nano/etc/motion.conf
3.Changethesettingstream_auth_methodto1.
4.Onthelinethatstartswith;stream_authentication,removethesemi-colonandchange
usernameandpassword.
5.PressCtrl+O,andthenpressEnter.
6.PressCtrl+X.
StartingMotion
Withthedefaultsettings,youstartMotionfromthecommandline.Oncethesoftwareis
configuredhowyouwantit,andyouhavetestedit,youcansetMotiontostart
automaticallywhenthePistartsandloadsRaspbian.
TostartMotionmanually:
1.OntheRaspbiandesktop,double-click
LXTerminal.
2.TypethefollowingcommandandthenpressEnter:motion
WhenyouwanttostopMotion,pressCtrl+C.
ToconfigureMotiontostartautomatically:
1.OntheRaspbiandesktop,double-click
LXTerminal.
2.TypethefollowingcommandandthenpressEnter:nano/etc/motion.conf
3.Changethesettingdaemontoon.
4.PressCtrl+O,andthenpressEnter.
5.PressCtrl+X.
6.TypethefollowingcommandandthenpressEnter:sudonano/etc/rc.local
7.Beforethelinethatreadsexit0,addthefollowingtextonitsownline:
motion
8.PressCtrl+O,andthenpressEnter.
9.PressCtrl+X.
10.TorestartthePi,typethefollowingcommandandthenpressEnter:
sudoshutdown–rnow
ViewingtheLiveStreamfromDevicesonyourNetworkToviewthevideofroma
deviceonyourlocalnetwork,ensureMotionisrunningandthenopenawebbrowseron
thedevice.
YouneedtoknowtheIPaddressoftheRaspberryPi.Formoreinformation,seeFinding
theIPAddressonpage40.
Typehttp://followedbytheIPaddressofyourPi,thenacolonandtheportnumber
(stream_portinmotion.conf)intotheaddressbarofthewebbrowser.ThenpresstheEnter
key.
InternetExploreronWindowsisnotabletoopenthestreamthisway,butotherbrowserscan.Youcanalsouse
VLC
(http://www.videolan.org)toopenthestreamusingitsaddress.
ViewingtheLiveStreamovertheInternet
Toaccessthelivestreamfromdevicesoutsideyourlocalnetwork,configureyourrouter
toallowincomingrequestsontheportstream_port(inmotion.conf).Todothis,youwill
usethePi’sIPaddressandsoitishelpfulifthePiisusingastaticIP,seeUsingaStaticIP
Addressonpage41.
YouneedtocreatearulethatallowsincomingtrafficonaTCPportofyourchoosing(for
example,8081),andstatesthatthistrafficshouldbeforwardedtothePionport8081(or
thevalueofstream_portinmotion.conf).
ToaccessthestreamovertheInternet,youneedtoknowtheexternalIPaddressofyour
router.Openawebbrowseronadeviceconnectedtoyournetworkandvisithttp://
www.whatsmyip.org.Thenyoucanopenthelivestreamusinganaddressthatbegins
http://,followedbytheexternalIPaddressofyourrouter,acolon,andthentheincoming
portnumberthatyousetinyourrouter’sportforwarding.
WhenyourrouterrestartsorreconnectstotheInternet,yourIPaddressmaychange.Usingadynamicdomain
namesystem(DDNS)serviceprovider,youcanmapyourIPaddresstoanInternetdomainnameandusethis
domainnametoaccessyourlivestream.
9–BuildingaSmarterDoorbell
Adoorbellisapush-buttonswitchthatclosesasmallelectricalcircuitwhenavisitor
pressesthebutton.Withthecircuitclosed,electricityflowsintocomponentsthatmakethe
chimeorbuzzingsound.
WithaRaspberryPi,youcanmakeamuchsmarterdoorbell–onewhichiscapableof
doingalotmorethanplayingasound.AnythingthatthePicando,youcandoinresponse
tosomeoneringingthedoorbell.
Inthischapter,youwillseehowtomakeaprototypeRaspberryPi-powereddoorbell.
Youneed:1.ARaspberryPirunningRaspbian.
2.Asetofspeakers.Formoreinformationaboutsuitablespeakers,seesection9.2.
3.AdoorchimesoundeffectasanMP3.
4.Adoorbell(“bellpush”)ormomentarypushswitch.
5.Somewire.
6.One330Ωresistor.
7.Asolderlessbreadboard,perfboard,orstripboardforattachingwiresandcomponents.
Thedoorbellonthefrontofyourhouseisusuallywiredintothe“mains”electricalsupply.DonotconnectthePi
doorbelltothemainssupply,andconsultaqualifiedelectricianbeforeattemptingtoremoveyourcurrent
doorbell.
9.1TheButtonCircuit
Thepush-buttoncircuitusedinthisprojectisthesameasyoucanseedescribedinsection
7.5BasicInputonpage160.Youcanuseapushbuttonforthisproject,orastandard
doorbellswitch.Doorbellsusuallyhavetwoscrewterminalsinside,whichmakeelectrical
connectionsbytightlyholdingwiresontometalcontacts.Toconnectawiretoaterminal:
1.Loosenthescrewbyturningitcounterclockwise.
2.Strip25mm–35mmofinsulationfromthewire.
3.Wraptheexposedpartaroundthescrew.
4.Tightenthescrewbyturningitinaclockwisedirection.
Repeattheprocessfortheotherterminal.
Thedirectionthatyouconnectthewirestoyourcircuitdoesnotmatter.
1.ConnectonewirefromthebelltoGPIO2(pin3).2.Connecttheotherwirefromthe
doorbelltoonelegofthe330Ωresistor.
3.ConnecttheotherlegoftheresistortoagroundontheGPIOheader.
9.2Speakers
TherearetwotypesofspeakerthatworkwellforthistypeofRaspberryPiproject:stereo,
desktopPCspeakers;andspeakersthathaveanHDMIinputandbuilt-inamplifier.
SpeakersthathaveanHDMIinputextracttheaudioinformationfromtheHDMIsignal.If
youareusingtheHDMIoutputthenyoudonothavetochangeyourconfigurationtouse
thesespeakers.
StereoPCspeakerscomeintwovarieties:passive,andactive.Activespeakershavetheir
ownpowersupplyandcanplayActivespeakershavetheirownpowersupplyandcan
playpole3.5mmstereoplugthatyoucanconnectintothePi’s3.5mmoutputjack.
Bydefault,ifyouconnectanHDMIcabletothePithenanyaudiosignalswillalsouse
that.Youcanforcetheaudiooutthroughthe3.5mmoutputjackwiththeamixer
command:
1.OntheRaspbiandesktop,double-click
LXTerminal.
2.TypethefollowingcommandandthenpressEnter:sudoamixercsetnumid=31
9.3ABasicDoorbell
Tomakeadoorbell,youcanuseaPythonscripttodetectwhenthebuttonispressedand
thenplayasound.
Tobegin:1.Onthedesktop,double-clickLXTerminal.
2.Tomakeanewfolderforyourdoorbellproject,typethefollowingcommandandthen
pressEnter:
mkdirDoorbell
3.Onthedesktop,double-clickIDLE3.
4.InthePythonShell,ontheMenu,clickFileandthenclickNewWindow.
5.OntheMenu,clickFileandthenclickSaveAs.
6.Savethefiletoyourfolder,asdoorbell.py.
7.AddthePythoncodebelow,andthensaveyourscriptagain:
importRPi.GPIO
RPi.GPIO.setmode(RPi.GPIO.BCM)
RPi.GPIO.setup(2,RPi.GPIO.IN,pull_up_down=RPi.GPIO.PUD_UP)
defRing():
pass
whileTrue:
ifRPi.GPIO.input(2)==RPi.GPIO.LOW:
Ring()
ThiscodedetectsabuttonpressinthesamewayasdescribedinChapter7–Controlling
InputandOutputPinsonpage150.ItthencallsthefunctionRing(),whichdoesnothing
yet.ToplayasoundfilefromPython,youcanusempg321.Thisisacommandlinetool
forplayingMP3filesonRaspbian,butyoucanstartitfromaPythonscript.Toinstall
mpg321:
•InLXTerminal,typethefollowingcommandandthenpressEnter:
sudoapt-getinstallmpg321
Copythesoundeffect.mp3intoyourDoorbellfolder.Addthefollowingimportdirective
tothetopofthescript:
importos
ThenintheRing()function,removethepassstatementandaddthefollowingcode;
replacethefilenameoftheMP3fileifnecessary.
os.system(“mpg321ring.mp3”)
Thesystem()functionintheosmodulerunscommandlinetoolsfromPythonscripts.To
runthescript:
•InLXTerminal,typethefollowingcommandandthenpressEnter:
sudopython3Doorbell/doorbell.py
Presstheswitchtoheartheaudiofileplay.Ifyouholdthebuttondown,thescript
repeatedlyplaysthesound.
Tostopthescriptfromloopingthesound,youcanmakesurethatthebuttonisreleased
beforethescriptchecksforanotherpress:
•Addthefollowingstatementstoyourscriptfile,intheRing()function,afterthecallto
os.system():
whileRPi.GPIO.input(2)==RPi.GPIO.LOW:
pass
Thewhileloopcontinuallyrunsthepassinstruction(whichdoesnothing)untilthebutton
isreleasedandGPIO2goeshigh.
StartingtheDoorbellScriptAutomatically
IfyouwantyourdoorbellscripttorunwhentheRaspberryPistartsup,youcanusea
featurebuilt-intoLinuxcalledcron.Cronisawayofstartingprogramsinthe
background.
First,createashellscriptthatstartsyourPythonprogram:1.InLXTerminal,typethe
followingcommandandthenpressEnter:
nanoDoorbell/doorbell.sh
2.Addthefollowingtexttothefile:
#!/bin/sh
cd/home/pi/Doorbell
sudoamixercsetnumid=31
sudopython3doorbell.py
3.PressCtrl+O,andthenpressEnter.
4.PressCtrl+X.
5.TypethefollowingcommandandthenpressEnter:sudocrontab-e
6.Attheendofthefile,addthefollowingtextonanewline:
@rebootsh/home/pi/Doorbell/doorbell.sh
7.PressCtrl+O,andthenpressEnter.
8.PressCtrl+X.
9.TypethefollowingcommandandthenpressEnter:sudoshutdown–rnow
Step6tellscrontorunthecommand“sh/home/pi/Doorbell/doorbell.sh”whenRaspbian
starts.TostopthescriptfromstartingwhenthePistartsup,repeatstep5andremovethe
line.
9.4AnEnhancedDoorbell
Inthissection,youwillseeashortexampleofhowyoucanextendthePidoorbellscript
sothatPythontakesapicturefromthePicameramodulewhenavisitorpressesthe
doorbell.ThePythonpicameramodulecontainsthefunctionsforaccessingthecamera.
Timecontainsfunctionsforworkingwiththedateandtime.Addthefollowingimport
statementstothetopofyourdoorbell.pyscript:
importpicameraimporttime
ThencreateaninstanceofthePiCameraclass:
•UnderneaththetwoRPi.GPIOfunctions,addthefollowingstatement:
camera=picamera.PiCamera()
Totakeapicturefromthecameramodule,usethemethodcapture().Thismethodaccepts
oneargument–thefilenamewheretheimageistobesaved.Intheexamplebelow,the
currentdateandtimeiscombinedwiththestring“Ring.jpg”tocreateauniquefilename
eachtimethedoorbellispressed.
Addacalltocapture()abovetheos.system()call.Forexample:
camera.capture(“Ring%s.jpg”%time.strftime(“%Y%m%d-%H%M%S”))
Thestringpassedintostrftime()determinestheformatofthedateandtimestring.Formoreinformationabout
thetimemodule,seehttp://docs.python.org/3/library/time.html
ThefullPythonscriptshouldlooklikethis:
importRPi.GPIO
importos
importpicamera
importtime
RPi.GPIO.setmode(RPi.GPIO.BCM)
RPi.GPIO.setup(2,RPi.GPIO.IN,pull_up_down=RPi.GPIO.PUD_UP)camera=picamera.PiCamera()
defRing():
camera.capture(“Ring%s.jpg”%time.strftime(“%Y%m%d-%H%M%S”))os.system(“mpg321ring.mp3”)
whileRPi.GPIO.input(2)==RPi.GPIO.LOW:
pass
whileTrue:
ifRPi.GPIO.input(2)==RPi.GPIO.LOW:Ring()
10–MakingFreePhoneCallswith
GoogleVoice
GoogleVoiceisaformofvoiceoverInternetprotocols(VOIP)thatisnowavailablein
GoogleHangouts.YoucanuseittomakefreephonecallstonumbersintheUSand
Canada1,anditgivesyoualandlinenumberthatotherscanusetocallyou–eitherfrom
theirGoogleaccount,orfromaregularphone.
YoucanuseGoogleVoicefromtheGoogleMailwebsite,ortheGoogleHangoutsapps
forsmartphones.However,ifyousetupyourRaspberryPiasaprivatebranchexchange
(PBX)thenyoucanallowanySIP-compatiblephoneorsoftphonetomakeandreceive
callsusingyourGoogleVoiceaccount.
Inthischapter,youwilllearnhowtoinstalltheRasPBXdistributionandconfigureittolet
SIPphonesuseyourGoogleVoiceaccount.
Youneed:1.ARaspberryPi,andeitheranEthernetconnectionoraUSBWi-Fidongle.
2.AsparemicroSDcard.
3.ASIPphone,SIPappforyoursmartphone,oraSIPsoftphoneforyourdesktopPC.
10.1SIPandSoftphones
Sessioninitiationprotocol(SIP)isaVOIPstandardthatdefineshowphonesand
softphones(softwarethatrunsonyourcomputerandpretendstobeaphone)communicate
withtheserversthatroutephonecallsovertheInternet.Unlikeregularphones,SIP
phonesconnecttoalocalareanetworkusingEthernetinsteadofconnectingtoaphone
line.APBXserveroftenconnectstoaphonelineandtocomputernetworks,anditroutes
landlinecallstotheSIPdevices.
1.Youcanmakeinternationalcalls,butthesearenotfreeandrequireyoutoaddcredittoyouraccount.
IfyoudonothaveaSIPphone,therearemanysoftphonesavailableforWindows,Linux,
andMacOSXdesktopPCs,andtherearealsoSIPappsthatrunonsmartphones.Itis
beyondthescopeofthisguidetoreviewallofthesoftphonesthatareavailable.However,
asastartingpoint,youmaywanttodownloadLinphone(http://www.linphone.org)or
Zoiper(http://www.zoiper.com).
TherearealsohostedSIPserviceprovidersthatgiveyoualandlinenumberwhichis
associatedwiththeirSIPserversandPBXs.YoucanconnectyourSIPphoneorsoftphone
totheseserversandreceivefreeincomingcalls.However,outgoingcallsusuallyincur
charges.UsingGoogleVoicemeansthatyoudonothavetopayforoutgoingcallsto
numbersintheUSorCanada.
TheregistrationprocessforGoogleVoicerequiresthatyougivethemaphonenumber
whereyoucanbereached.IfyoudonothaveonethenyoucangetafreenumberandSIP
servicethatyoucanusefortheregistration.
Todothis:
1.Openawebbrowserandvisithttp://sip.pregi.net
2.ClickCreateAccount.
3.Completetheregistrationform(youdonotneedtoenteravalueforthephonenumber
field),andthenclickRegister.
4.Checkyouremailandconfirmtheregistration.
5.Inyourwebbrowser,visithttp://www.ipkall.com
6.Click*Sign-Up*.
7.IntheSIPURIusernamebox,enteryoursip.pregi.netusername.
[email protected],entersip.pregi.net.9.Completetherestoftheform
andthenclickSubmit.
WhenyouregisterwithIPKall,theygiveyouaWashingtonstatephonenumberand
associatethisnumberwithyourSIPaccountatsip.pregi.net.Totestthenumber:
1.InstallaSIPsoftphoneonyourdesktopPC.
2.Inthesoftphone,createanaccountusingthefollowingdetails:
Domain:sip.pregi.net
Username:<yoursip.pregi.netusername>
Password:<yoursip.pregi.netpassword>
Transport:UDP
Port:5060
3.Fromalandlineorcellphone(ifyouareusingaSIPapp,useadifferentphoneforthis
step),callthenumberthatIPKallgivesyou.
IfyourSIPphonedoesnotring,checkallofyoursettingsandtryagain.
10.2GoogleVoice
ToregisterforGoogleVoice,youmust:belocatedintheUSorCanada1;haveanexisting
phonenumber(onlyfortheregistrationprocess);andhaveaGoogleaccount.
Duringtheprocess,youcreateanewGoogleVoicelandlinenumber.Thiscanbeinany
areacode(youarenotrestrictedtotheareacodethatyoulivein)wheretheyhave
numbersavailable.
IfyoudonothaveaGoogleaccount,createoneathttp://accounts.google.com/SignUp
andthencreateaGoogleVoiceaccountathttp://www.google.com/voice
WhenyouhavefinishedtheGoogleVoiceregistrationprocessandhaveyournewphone
number:
1.OnceyouregisterandobtainyourGoogleVoicenumber,youcanusetheservicefrominternationallocationstocall
numbersintheUSorCanada.
1.OntheGoogleVoicewebpage,clicktheSettingsbutton.
2.OnthePhonestab,underForwardcallsto,deselectthecheckboxnexttoyourphone
number.3.OntheCallstab,nexttoCallScreening,clickOff.
10.3RasPBX
RasPBXisaLinuxdistributionfortheRaspberryPithatpackagestogetherallofthe
telephony,server,anddatabasesoftwarethatmostusersneed.Someofthesetoolsare
quitecomplicatedtoinstall,sousingaprebuiltRasPBXdiskimagesavesyoualotoftime
andeffort.
FreePBXisoneofthekeypiecesofsoftwarethatthisdistributioncontains.Itistheserver
softwarethatyouusetosetupextensions(equivalenttouseraccounts),passwords,and
configureaccesstoyourGoogleVoiceaccount.
ToinstallRasPBX:1.DownloadthelatestRasPBXdiskimagefromhttp:/
/www.raspberry-asterisk.org/downloads/
2.Extractthe.imgfilefromtheziparchive.
3.WritethediskimagetoanewmicroSDcard.Formoreinformation,seesection2.3
InstallationofRaspbianusingaDiskImageonpage20.
4.SafelyejectthemicroSDfromyourPC.
5.UnplugthePi,andinsertthemicroSDcard.
6.ReconnectthePi.
IfyouareusinganEthernetcabletoconnectthePitoyournetwork,andyoudonothave
adisplay,makeanSSHconnection.Formoreinformation,seeConnectingtothePiwith
SSHonpage43.
LoginintothePiwiththeusernameroot,andthepasswordraspberry.
IfyouareusinganEthernetcable,configurethePiwithastaticIPaddress.Formore
information,seeUsingaStaticIPAddressonpage41.
TouseaUSBWi-Fiadapter,youmustfirstinstallthewpasupplicanttoolandthen
configureit.Todothis:1.Intheterminal,typethefollowingcommandandthenpress
Enter:
apt-getinstallwireless-toolswpasupplicant2.TypethefollowingcommandandthenpressEnter:
nano/etc/network/interfaces
3.Addthefollowingtexttotheendofthefile1:
autowlan0
allow-hotplugwlan0
ifacewlan0inetstatic
wpa-ssid<YOURNETWORKSSID>
wpa-psk“<YOURNETWORKPASSWORD>”
address<ANIPADDRESSTOUSE>
netmask<YOURNETWORKNETMASK>
gateway<YOURNETWORKGATEWAY>
4.PressCtrl+O,andthenpressEnter.
5.PressCtrl+X.
6.TypethefollowingcommandandthenpressEnter:shutdown–rnow
RasPBXisprimarilyaserverdistribution.However,youcanstillaccessthegraphicaldesktopenvironmentusing
thestartxcommand.Ifyouwanttoinstallasoftphone(suchassflphone)onthesamePithatrunsRasPBXthen
youcanalsodothat.
AccessingtheAdminPanel
FreePBXincludesaweb-basedadministrationpanelthatyoucanusetocompletethis
tutorial.Toaccessit:
1.Onadeviceconnectedtoyourlocalnetwork,open
1.Ifyouarenotsureaboutthevaluestoenterintothisconfiguration,lookatthenetworkconnectionpropertiesofother
devicesonyournetwork.
awebbrowser.
2.Visithttp://raspbxorhttp://followedbythestaticIPaddressofyourPi.
3.ClickFreePBXAdministration.
4.Inthefirstbox,typeadmin.
5.Inthesecondbox,typeadmin.
6.ClickContinue.
CreatingtheSIPExtensions
Beforeyoustartroutingthecalls,youneedtocreateextensions(thePBXequivalentofa
useraccount)foreachSIPdevicethatyouwanttouse.
TocreateaSIPextension:
1.IntheFreePBXAdministrationpanel,ontheMenu,pointtoApplicationsandthen
click
Extensions.
2.IntheDevicelist,clickGenericSIPDevice.
3.ClickSubmit.
4.IntheUserExtensionbox,typeanumber.Forexample,2001.
5.IntheDisplayNamebox,typethenameofthepersonwhousesthisextension.
6.Inthesecretbox,typeapasswordforthis
extension.
7.ClickSubmit.
8.Atthetopofthepage,clickApplyConfig.
ToregisteraSIPdeviceonyourlocalnetworktothisextension:1.Inthesettingsofyour
SIPphoneorsoftphone,createanewaccount.
2.Intheusernamebox,entertheextensionnumber.Forexample,2001.
3.Inthepasswordbox,enterthesecretthatyousetintheFreePBXconfiguration.
4.Inthedomainbox,entertheIPaddressofyourPi.5.Checkthatthephoneconnectsto
theserverusingUDPport5060.
Itcanbeusefultocreateasecondextension,forexample2002,sothatyoucantestthe
server.IftheSIPdeviceonextension2001dials2002thentheseconddeviceshouldring.
Ifitdoesnot,checkthatbothSIPdevicesareshowing“registered”.Thisindicatesthat
theyarecommunicatingwiththeRaspberryPiok.ToseewhatishappeningonthePi:
1.MakeanSSHconnectionorlogintotheterminalonthePi.
2.TypethefollowingcommandandthenpressEnter:asterisk-rvvvv
WhentheAsteriskCLItoolisrunning,youseealloftheactionsthatoccur–including
whenSIPdevicesconnecttothePi,andwhentheydisconnect.Thiscanbehelpfulin
debugging.SomeSIPsoftphonesdropoffthenetworkwithoutwarning,soifyoucannot
dialadevicetryusingdifferentsoftphonesoftware.
WhenyouarefinishedwiththeCLItool:
•TypethefollowingcommandandthenpressEnter:exit
SettingupGoogleVoiceandOutgoingCalls
RasPBXcontainsaFreePBXpluginforcommunicatingwithGoogleVoice.Thispluginis
called“Motif”anditworksoverextensiblemessageandpresenceprotocol(XMPP).
ToaddaGoogleVoiceaccounttothesystem:
1.IntheFreePBXAdministrationpanel,ontheMenu,pointtoConnectivityandthen
clickGoogleVoice(Motif).
2.IntheGoogleVoiceUsernamebox,typeyourGoogleMailemailaddress.
3.IntheGoogleVoicePasswordbox,typeyourGoogleMailpassword.
4.IntheGoogleVoicePhoneNumberbox,typethephonenumberthatyouobtained
fromGoogleVoice.
5.ClicktheboxnexttoAddTrunk.
6.ClicktheboxnexttoAddOutboundRoutes.
7.ClicktheboxnexttoSendUnansweredtoGoogleVoicemail.
8.ClickSubmit.
9.Atthetopofthepage,clickApplyConfig.
10.Ontheright-handsideofthescreen,underAddGoogleVoiceAccount,clickyour
GoogleVoiceaccount.
11.CheckthattheStatussaysConnected.Ifitdoesnot,checkyourGoogleVoiceaccount
details.
Motifcreatestheoutboundrouteforyou,andallSIPextensionscannowusethis
outboundroutetomakecalls.Thedefaultcannowusethisoutboundroutetomakecalls.
Thedefaultdigitphonenumberora1followedbythe10-digitnumber.
RoutingtheIncomingCalls
ToreceivetheincomingcallsfromyourGoogleVoicenumber,youneedtodirectthem
somewhere.FreePBXhasalotoffeaturesthatworkwithincomingcalls,butthisguide
onlycoversdirectingcallstoaspecificextension.Toroutecallstoanextension:
1.IntheFreePBXAdministrationpanel,ontheMenu,pointtoConnectivityandthen
click
InboundRoutes.
2.IntheDescriptionbox,typeanameforthisrule.Forexample,GoogleVoice.
3.IfyouwanttocreatearulethatonlyappliestoincomingcallsfromonespecificGoogle
Voiceaccount:intheDIDNumberbox,typethephonenumberthatGoogleVoicegave
you.
4.Inthe==chooseone==list,clickExtensionsandthenclicktheextensionthatyou
wanttoconnecttheincomingcallsto.
5.ClickSubmit.
6.Atthetopofthepage,clickApplyConfig.
IfyouaddmultipleGoogleVoiceaccountstoyoursystemandwanttodirectthemto
differentextensions,createdifferentrulesforeachGoogleVoiceaccountandspecifythe
phonenumberintheDIDNumberboxforeachrule.
10.4SIPPhonesacrosstheInternet
IfyouwantSIPdevicesorsoftphonestobeabletoaccessyourPBXfromoutsideyour
localnetwork,youneedtoconfigureyournetworkroutertoallowincomingtrafficonthe
followingportsandroutethemthroughtothesameportnumbersonthePi:
StartPortEndPortTypeDescription
50605061UDPThetwoportsusedforSIPsignalingandcontrol.
1000120000UDPPortsformedia(voiceandvideo)transmission.
YourSIPdevicesneedtoconnecttotheexternalIPaddressofyourrouter,nottothe
internalIPaddressofthePiasyouhaveusedsofar.
WhenyourrouterrestartsorreconnectstotheInternet,yourIPaddressmaychange.Usingadynamicdomain
namesystem(DDNS)serviceprovider,youcanmapyourIPaddresstoanInternetdomainnameandusethis
domainnametoaccessyourPBX.
11–Accessories
OneofthegreatthingsabouttheRaspberryPiisthenumberofperipherals,expansion
boards,connectors,andcomponentsthatyoucanusewithit.Hereisaselectionofa
usefulaccessoriesthatyoucanusewiththeprojectsandinformationinthisguide.
USBtoTTLCable
ThishandycableconnectstoaPCusingtheUSBconnector,andtothePiusingindividual
femalesocketsthatfitdirectlyontotheserialportpinsofthePi’sGPIOheader.Thebuiltincircuitryhandlesvoltagelevelconversions.
http://www.vilros.com/usb-to-ttl-cable.html
40-pinGPIORibbonCable
AfemaletofemalecableforconnectingexternalcircuitstotheRaspberryPi.Itcanalso
beusedtoconnectmaletomalejumpercablestothePiwhenprototypingyourcircuitson
abreadboard.http://www.vilros.com/40-pin-gpio-ribboncable.html
JumperWires
Jumperwires(alsocalled“jumpwires”)havereinforcedendsthatmakeiteasytoconnect
componentsonabreadboard,ormakeconnectionswithdevicesthathavefemalesockets.
http://www.vilros.com/jumper-wires.html
Breadboard
Astandard,400-holebreadboardisinvaluableforprototypingandtestingyourcircuits.
TheiruseisexplainedinChapter7–ControllingInputandOutputPinsonpage150.
http://www.vilros.com/breadboard.html
Light-EmittingDiodes(LEDs)
LEDsarecomponentsthatyouwilluselotsof.Inadditiontomakingthemflashorusing
themasstatusindicators,theycanbeveryhelpfulforcheckingwhichpartsofacircuitare
working.http://www.vilros.com/red-led.html
Resistors
Almostallelectroniccircuitscontainatleastoneresistor.Unlikeothercomponentsthat
youmaybuyspecificallyfortheprojectthatyouareworkingon,youwillusesomany
resistorsthatitisworthkeepingastockofdifferentvalues.
10KΩ:http://www.vilros.com/10k-resistors.html330Ω:http://www.vilros.com/330resistors.html
Buttons
Thesehigh-quality,push-buttonswitchesareidealformakinginputcircuitsusingthePi’s
GPIOheader.Whentheconveniently-largebuttonispressedandheld,electricityflows
betweentwooftheswitch’sterminals.Exactlythetypeusedinsection7.5BasicInputon
page160.
http://www.vilros.com/big-12mm-buttons.html
10KTrimpot
Alsoknownas“potentiometer”or“variableresistor”,thesetrimpotsareusedwhenyou
needtochangetheamountofresistanceinacircuitwithoutdisassemblingit.Forexample,
toreducethebrightnessofanLED.These”pots”haveresistancethatchangesasyouturn
theknob,from0Ωthrough10KΩ,andslotneatlyintoplaceonabreadboard.
http://www.vilros.com/10k-trimpot.html
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