vilros raspberry pi user guide by vilros
DESCRIPTION
Vilros Raspberry Pi User Guide by VilrosWhat can I do with the Raspberry Pi? This book is the perfect introductory guide to getting started as well as step-by-step instructions for creating your very own projects.Chapter 1. Getting Started Chapter 2. Introducing Raspian Chapter 3. Building a Media center with XBMC Chapter 4. Programing with Scratch Chapter 5. Building an arcade for scratch Chapter 6. Programming in Python Chapter 7. Controlling Input and Output Pins Chapter 8. Building an IP camera Chapter 9. Building a Smarter Doorbell Chapter 10. Making Free Phone calls With Google VoiceTRANSCRIPT
-
RaspberryPIUsersGuide
Copyright2014Vilros.Allrightsreserved.www.vilros.com1-855-207-9254ISBN:978-0-692-31936-9
Nopartofthispublicationmaybereproduced,distributed,ortransmittedinanyformorbyanymeans,includingphotocopying,recording,orotherelectronicormechanicalmethods,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembodiedincriticalreviewsandcertainothernon-commercialusespermittedbycopyrightlaw.
Trademarkednames,logos,andimagesmayappearinthisbook.Ratherthanuseatrademarksymbolwitheveryoccurrenceofatrademarkedname,logo,orimage,thenames,logos,andimagesareusedonlyinaneditorialfashionandtothebenefitofthetrademarkowner,withnointentionofinfringementofthetrademark.
TheinformationinthispublicationisprovidedonanASISbasis.Vilrosmakesnowarranties,expressorimplied,regardinguseoftheinformationaloneorincombinationwithyourproducts.Neithertheauthornorthepublishercanacceptanylegalresponsibilityforanyerrorsoromissionsthatmaybemade.
-
ConventionsUsedinthisBook
Thefollowingtabledescribesthetextconventionsusedinthisbook.ConventionMeaning
ItalicTextthatappearsinitalicsreferstofilenames,variableandfunctionnames,orothercode.Withinthecontextofgivinginstruction,italictextshouldbetypedexactlyasshown.
BoldWithinthecontextofgivinginstruction,itemsinboldtextareuserinterfaceelements,suchaskeystrokes,menuitems,orbuttonlabels.
MonospacefontAmonospacefontisusedforshellcommandsandPythoncodethatshouldbetypedinonthekeyboard.
-
Contents1GettingStarted51.1Introduction51.2TechnicalSpecifications71.3BasicSetup81.4SDCards14
2IntroducingRaspbian162.1RaspbianandLinux162.2InstallationofRaspbianwithNOOBS162.3InstallationofRaspbianusingaDiskImage202.4Raspi-config222.5RaspbiansDesktopEnvironment262.6CommonTasks372.7NetworkConnectionsandRemoteAccess402.8OtherOperatingSystems45
3BuildingaMediaCenterwithXBMC473.1XBMC473.2Installation483.3FirstSteps513.4MediaFilesandtheLibrary533.5NetworkDevicesandOtherComputers593.6Add-ons653.7RemoteControls66
4ProgrammingwithScratch694.1TheUserInterface694.2Sprites754.3ArithmeticandVariables814.4Decisions824.5Loops854.6Strings864.7Messages874.8SoundandMusic894.9ThePaintEditor894.10AutomaticStartupofScratchProjects934.11SharingYourFinishedProjects94
5BuildinganArcadeGameinScratch955.1TheTitleScreen955.2TheLevelBackgrounds995.3ThePlayerSprite1055.4CollisionDetection1095.5Enemies1155.6MoreEnemies1275.7GameOver128
6ProgramminginPython1296.1YourFirstPythonProgram1296.2Python1316.3Decisions1366.4Loops1386.5Functions1396.6ClassesandObjects1416.7ModulesandPackages1446.8FileI/O1466.9GraphicalUserInterfaces(GUIs)149
7ControllingInputandOutputPins1507.1ElectronicCircuits,VoltageandCurrent1507.2SolderlessBreadboards1527.3TheGPIOHeader1537.4BasicOutput1557.5BasicInput1607.6Communicationbetween3.3Vand5VDevices1647.7SerialPeripheralInterface(SPI)1667.8I2CCommunication1717.9SerialUARTs173
8BuildinganIPCamera1768.1ThePiCameraModule1768.2Motion178
9BuildingaSmarterDoorbell1849.1TheButtonCircuit1849.2Speakers1859.3ABasicDoorbell1869.4AnEnhancedDoorbell188
10MakingFreePhoneCallswithGoogleVoice19010.1SIPandSoftphones19010.2GoogleVoice19210.3RasPBX19310.4SIPPhonesacrosstheInternet198
11Accessories199
-
1GettingStarted
-
1.1Introduction
TheRaspberryPiisasmallcomputer,averysmallcomputer.
Itconsistsofmostlythesamepartsasastandarddesktopcomputerorlaptop.Acentralprocessingunit(CPU)actsasabrain,randomaccessmemory(RAM)andlong-termstoragedevicesareusedtoholddata,avideodisplayshowsyouwhatishappening,andyouinteractwithallofthisusingmice,keyboards,joysticks,andotheruniversalserialbus(USB)devices.ThePimaybelesspowerfulthanyourWindowsPCorMacintosh,butitisstillimpressivethatitfitsallofthisonaboardonlyslightlylargerthanacreditcard.
TheoriginalgoaloftheUK-basedRaspberryPiFoundationwastocreateadevicethatwouldaddresstheirperceptionoffallingstandardsintheteachingofcomputerscience.Ascomputershaveevolved,theyhavebecomemoredifficulttowritesoftwareforatalow-levelwithcloseinteractionbetweenhardwareandsoftware.Andastheyhavebecomemoreintegratedinourdailylives,theconsequencesofbreakingyourcomputerbyexperimentinghavebecomemoresevereandexpensive.
So,unlikeconventionalsystems,thePiisamachinethatisdesignedtobeplayedwithandusedforexperiments.Itsdiminutiveformfactorandrelativelylowcostmeanthatyoucandowhatyouwantwithit,andthisattractsfarmorediversegroupsofusersthanjuststudentsandteachers.
Itissuitableforawiderangeofapplications,including:
UsingthePiforGeneralComputingYoucaninstallavarietyofoperatingsystemsonthePi,andmanyofthesehavefulldesktopenvironments.Withsupportforexternalhardwaredevices,Internetconnections,anddownloadingandinstallingsoftware,youcanusetheRaspberryPiasaregularcomputer.Itcandojustabouteverythingyourmainsystemcandoonlyalittleslower.
PlayingGamesTherangeofgamesavailableontheRaspberryPisoperatingsystemsisextensive.Butyoucanalsoinstallemulators,whicharepiecesofsoftwarethatallowprogramsfromothermachinestoberunonthePi.ThisgivesyouaccesstotitlesonclassicmachinessuchastheAtari2600,NintendoEntertainmentSystem,SegaGenesis,SharpX1,MSX,Panasonic3DO,andmanymore.AllRaspberryPimodelssupportHDMIvideooutputandUSBgamecontrollers,makingthePiapopularchoiceforfansofretrocomputingandretrovideogames.
PlayingMovieFilesandMusiconYourTVPutthePiinacase,connectittoatelevisionusinganHDMIcable,andinstallXBMC.ThenyouhaveacapablemediacenterthatcanloadmoviefilesfromtheSDcard,USBharddrives,oracrossyourlocalnetwork.
ProvidingNetworkServicesAsasmall,standalonedevicethatconnectstotheInternetandlocalnetworks,theRaspberryPimakesanexcellentserver.Youcanuseittoservefilesandwebpages,answerdomainnamesystem(DNS)requests,sharehardwaredevices(forexample,printers)acrossanetwork,andalmostanythingelseyoumightneedaserverfor.
-
SettingupDevelopmentEnvironmentsThesimplenatureofthePi,anditssupportformanydifferentprogramminglanguages,makeitanidealsystemtousewhenlearninghowtoprogram.ThePicontainsanARMprocessor,andthesearepopularlyusedincellphones,tablets,gamesconsoles,andinthecomputer-controlledequipmentusedinmanufacturing.Theabilitytoprogramoneisaskillthatisinhighdemand.
BuildingControllerBoardsandInteractionwithElectronicsItssmallsize,lowcost,andeaseofprogrammingmaketheRaspberryPiveryusefulinembeddedapplications.Inthesetypesofproject,thePiisusedalongwithotherelectronicscircuitstocreateeverythingfrom3Dprinters,tohomeautomationsystemsandrobots.
-
1.2TechnicalSpecifications
TheModelB+isarevisedversionoftheModelBthatwilleventuallyreplacetheearliermodel.Ithasmoregeneralpurposeinput/output(GPIO)pinsthanearliermodels,andtwiceasmanyUSBsockets.ModelB+CPUBroadcommicroprocessorrunningat700MHz(ARMv6architecture)GPUBroadcomVideoCoreIV,250MHz
OpenGLES2.0MPEG-2andVC-1,1080ph.264/MPEG-4AVCdecoder
Memory512MBVideoOutputVideoOutputpole3.5mmjack,LCDpanelsthroughDSI.AudioOutput4-pole3.5mmjack,HDMI,I2SUSBPorts4(2dualsockets)Input/Output17xGPIO,UART,I2C,SPINetworking10/100Mb/sEthernet,USBdevicesStoragemicroSDcardslotPower5Vthroughmicro-USBsocketorGPIOheader
ThediagrambelowshowstheavailableconnectorsontheRaspberryPiModelB+.Figure1.TheRaspberryPianditsconnectors1Generalpurposeinput/output(GPIO)headerthesepinscanbecontrolledfromsoftware.
2Universalserialbus(USB)socketforattachingperipheraldevicessuchasmice,keyboards,ormemorysticks.ThisisadualsocketandtwoUSBdevicescanbeconnectedatthesametime.
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.AnSDcardwithanoperatingsystemorbootableprograminstalledWithoutthese,thePiwilldonothing,notevenoutputavideosignal.Fortheinitialconfiguration,youmayalsoneedtoconnect:
1.Adisplay(usingHDMIorcompositevideo)2.AUSBkeyboard3.AnEthernetcableorUSBWi-Fidongle
Thedisplay,andanyUSBdevicesyoumayconnect,canberemovedwhentheyarenotinuse.Forexample,aPiactingasafile/printservermayonlyacceptinputfromcomputersonthenetworkanddoesnotalwaysneedakeyboardorscreen.
FittingaHeatSinkWhenthecomponentsinacomputersystemworkhard,theygenerateheat.Andaboveacertainlevel,thisheatcanreducethelifespanofthecomponentsorevenbreakthemaltogether.Aheatsinkisacarefullydesignedblockofmetalthattakestheheatawayfromtheelectroniccomponentandthenpassesitintotheairsurroundingthedevice.
TherearethreechipsonaRaspberryPithatcangetveryhotifthedeviceisworkinghard:thecentralprocessingunit(1),thechipthatcontrolstheEthernetandUSBports(2),andthepowerregulator(3).
Toinstallaheatsink:1.UnplugthePiandleaveittocoolbeforeattemptingtohandlethedevice.2.Onthebottomoftheheatsink,peelawaytheplasticbackingthatcoverstheadhesive.
3.Presstheheatsinkdownfirmlyanddirectlyontothechip.Holdthepressureforafewsecondstoallowtheadhesivetowork.
IfyoubuyheatsinksforyourPi,onlyusethethermaladhesivethattheyarrivewith;neveruseanyothertypeofadhesiveorstickyplastictoinstallaheatsinkonaRaspberryPi.TheadhesivemustbeaspecialcompoundsothatiteffectivelytransfersheatfromthechiponthePitothemetaloftheheatsink.
Figure2.Thethreeheat-outpointsonaPi(left);andinstallingaheatsinkontheCPU(right)
ConnectingPowerTheRaspberryPirequiresapowersupplyof5Vthatcanprovideatleast700mAofcurrent.BeforeconnectingthePiandturningiton,youshouldchecktheratingofthepowersupplycarefully.
Manycellphonechargerswillwork,butsomesupplylesscurrentthanthePineeds.Usinginadequatepowersupplies,orevenpoweringthePifromtheUSBportofanothercomputer,isnotrecommendedasthelackofcurrentmaymakethePiunstable.YoushouldcertainlyavoiddoingthisifyouneedtoconnectanyotherdevicestothePi.
PowercanbefedintothePithroughthemicro-USBsocketor,ifyouhaveasuitable
-
connector,throughthegeneralpurposeinputoutputpins.However,youshouldbeawarethatprovidingpowerthroughtheGPIOheaderpinsbypassestheon-boardprotectioncircuitrythatisdesignedtopreventdamagetothedevice.Forthisreason,itshouldonlybeattemptedbypeoplewhoareexperiencedinbuildingelectroniccircuits.
ItisworthnotingthattheRaspberryPidoesnothaveanon/offswitch.Someoperatingsystemscanpowerdownthedeviceorputitintostandbymodebutwhenyouwanttoturnitoff,youwilloftenhavetoremovethepowersupplyorswitchitoffatthewallsocket.Therearetwoholesontheprintedcircuitboard(PCB)oftheModelB+.TheseholesarelabelledRUNandyoucansolderaswitchacrossthesetwoconnectionstocreatearesetbutton.
ConnectingaDisplayHDMIoffersahigh-qualityvideoandaudiosignal,andisthepreferredwayofconnectingallmodelsofRaspberryPitoamoderntelevision.Toconnectahigh-definitiontelevision:
PlugoneendofanHDMIcableintotheRaspberryPisHDMIsocket,andtheotherendintoanHDMIinputonyourTV.
IfyourdisplaydoesnotsupportHDMI,youcanconnectthecompositevideoandaudiooutputstotheauxiliaryA/Vinputofmosttelevisions.Theseconnectionsarecoloredyellow,red,andmosttelevisions.Theseconnectionsarecoloredyellow,red,andpolejackononeend,andthreeRCAplugsontheother(oneyellow,onered,andonewhite).Tousethesecables:
1.Plugthe4-pole3.5mmjackplugintothe3.5mmjacksocketontheRaspberryPiModelB+.2.ConnecttheyellowcompositevideoplugtotheyellowvideoinputsocketonyourTV.3.ConnecttheredRCAplugtotheredaudiosocketonyourTV.4.ConnectthewhiteRCAplugtothewhiteaudiosocketonyourTV.
IfyourTVdoesnothavetheyellow,red,andwhiteauxiliaryinputs,youcanplugthecompositeoutputsintoaSCARTadapterandconnectthattoyourTVinstead.
Whenusingthecompositevideo,youalwayshavetheoptionofconnectingthevideotoatelevisionandtheaudiooutput(theredandwhiteconnectors)tootherdevices,suchasheadphones,poweredspeakers,oramplifiers.
TouseacomputermonitorasthePisdisplay,youwillneedanHDMItoVGA,orHDMItoDVIadaptor.However,whenconnectingtoamonitorusinganHDMItoVGA/DVIadapter,youwillinitiallybeunabletoconnectspeakerstotheaudioconnector.WhentheHDMIcableisconnected,thecompositevideoandaudiooutputportsareturnedoff.ThiscanbechangedonceyouhaveanoperatingsystemrunningonthePi.Althoughnotcoveredinthisbook,allRaspberryPimodelssupportDSIforconnectingLCDpanels.Figure3.ConnectingadisplaytotheModelB+
ConnectingUSBDevicesWithmostoperatingsystemsthatyourunonthePi,humaninterfacedevices(HIDs)thatconnectusingUSB(suchasmice,keyboards,andgamecontrollers),andstoragedevices(suchasUSBmemorysticksandharddrives)willworkwithoutanyproblemsorinstallationprocesses.Youmayneedtoinstalldriverspiecesofsoftwarewrittentopassmessagesbetweentheoperatingsystemandthehardwaredevicetousemore
-
complicatedperipheralslikesoundcards.
ToconnectaUSBdevice,insertitsUSBconnectorintoanavailablesocketontheRaspberryPi.YoucanusuallydothissafelywhetherornotthePiisturnedonandrunning.
TheRaspberryPicanonlysupplyalimitedamountofpowertoUSBdevices.Itisrecommendedthatyoudonotconnectanydevicesthatdrawover100mA.Tousemorepower-hungrydevices,youcanuseapoweredUSBhubadevicethatallowsmultipleUSBperipheralstobeconnectedtoasingleport,andthathasitsownpowersupply.ThisalsoallowsyouattachmoredevicestothePi.Figure4.ConnectingthePitoa4-portUSBhub
ConnectingtoaNetworkTomakeawirednetworkconnectionbetweenthePiandanetworkrouter:
1.PlugoneendofaCAT5orCAT6EthernetcablewithRJ45connectorsintotheEthernetsocketontheRaspberryPi.
2.Plugtheotherendofthecableintoyournetworkrouter.TheactualnetworkconnectionismadebythesoftwareoroperatingsystemrunningonthePi.
Intheory,Wi-Fiisafastertechnologythanthe10/100Mb/sEthernetcircuitthatisbuilt-intoModelB+.Inpractice,however,thisisnotalwaysthecase.AsthePicannotprocessdataasquicklyasabrandnewdesktopcomputer,thedifferenceinspeedbetweenEthernetandWi-Fiislessnoticeableandyoushouldusewhicheverismostconvenientforyou.NotallWi-FiandEthernetadaptorsarecompatiblewiththeRaspberryPi.Beforebuying,checkthattheadaptorisknowntobeworkingbylookingatthelistathttp://elinux.org/RPi_USB_Wi-Fi_Adapters
-
1.4SDCards
Inthenextchapter,youwilllearnaboutRaspberryPioperatingsystems(inparticularly,RaspbianLinux)andhowtoinstallthemontoanSDcard.Thiswillcompletetheset-upofthePi.
Unlikeconventionaldesktopcomputersystems,thePidoesnothaveaharddrivefromwhichtoloadanoperatingsystem.Instead,itusesthecardsockettoloadfilesfromamemorycard.
WhenthePiisfirstturnedon:1.ThemainARMprocessorandSDRAM(memory)aredisabled.
2.Thegraphicsprocessingunit(GPU)loadsthefirststagebootloaderthatisbuilt-intothePi,andthiscontainsallofthecodenecessarytoworkwithmemorycards.
3.Thefirst-stagebootloaderenablesSDRAM,detectsthepresenceofamemorycard,andloadsthesecond-stagebootloaderfromit.
4.Thesecond-stagebootloaderloadstheoperatingsystemorbootableprogramfromthecard.
InsertingandRemovingSDCardsItislikelythatyouwillneedamemorycardwithatleast4GBcapacityifyouareintendingtorunanoperatingsystemonthePi.4GBSDHCmicroSDcardsarewidelyavailableandgenerallyverycost-effective.
ToinsertanSDcard:1.EnsurethePiisunplugged.2.LocatetheSDcardsocketontheundersideofthePisboard.3.Whenlookingfromabove,theSDcardscontactsshouldbefacingup.4.Gently,butfirmly,pushtheSDcardintothesocketuntilitclicksintoplace.Figure5.InsertingSDcardsintotheRaspberryPiToremovetheSDcard:FirstpushthemicroSDfurtherintothedeviceuntilitclicks.Thenpullthecardout.
WheninsertingandremovingSDcardsinothercomputers,itisnotalwaysnecessarytoturnoffthedevice.However,asthememorycardcontainsitsoperatingsystem,thePimayaccessitatanytime.RemovingthecardwhilethePiisaccessingitcancorruptdataand,inextremecases,maystopthecardworkingatall.
-
2IntroducingRaspbian
-
2.1RaspbianandLinux
Anoperatingsystem(OS)isauniquetypeofapplicationthatyourunonyourcomputer.Itisanenvironmentinwhichmanyotherapplicationscanrunatthesametime,withaconsistentuserinterfaceandsharingthesameresources.MicrosoftWindowsandApplesMacOSXareprobablythetwomostwell-knownoperatingsystems,butthereareothers.
Linuxisoneofasmallgroupofoperatingsystemsthatarefree.ItusuallydoesntcostanythingtouseandpeoplecanmodifytheOS,repackageitwithothersoftware,distributetheirversion,andgenerallydowhattheywantwithit.Becauseofthis,youcanfindLinuxrunningonmosttypesofcomputerfromlargeserversusedbycorporationssuchasGoogle,tosmalldevicesliketheRaspberryPi.AbundleoftheLinuxcorewithotherapplications(suchasdesktopenvironments,filemanagers,andwebbrowsers)iscalledadistribution(ordistro).
RaspbianisaLinuxdistributionthatisbasedonDebian,anotherpopularversionofLinux.ItisdesignedfortheRaspberryPiandistheOSrecommendedbytheRaspberryPiFoundation.AlthoughdifferentLinuxdistributionscanusuallyallrunthesameapplications,thisbookisfocusedonusingRaspbiananditmaybehelpfulforyoutorunthisOSwhileyouarelearning.OnceyouarefamiliarwithRaspbian,youwillfindthatyouareabletouseothervarietiesofLinuxwithoutmuchhelp.
-
2.2InstallationofRaspbianwithNOOBS
NewoutofBoxSoftware(NOOBS)isatoolthatyoucanrunonyourRaspberryPianditwillhelpyouinstallanOS.ItstaysontheSDcard,evenaftertheOSinstalled,andcanalsobeusedtoeditthePismainconfigurationfileorreplacetheinstalledOSifproblemsoccur.TheSDcardsuppliedwithyourPialreadycontainsNOOBS.
InstallingNOOBStoanSDCardTherearetwoversionsofNOOBSavailable:NOOBSandNOOBSLite.NOOBSLiteisquickertodownload,butdoesnotcomewiththeinstallationfilesforRaspbian.Instead,yourPiconnectstotheInternettodownloadtherelevantfileswhenyoustarttheinstallationprocess.ItdoesnotsupportUSBWi-Fiadapters,andthismeansthatyouwillneedanEthernetcablepluggedintoyourRaspberryPitouseNOOBSLite.
ThefullversionofthelatestversionofNOOBSonlycomeswiththefilesneededtoinstallRaspbian.ToinstalladifferentOS,youneedanInternetconnection.
ThespacethatNOOBSoccupiesontheSDcardisnotavailableforusebytheOSthatyouareinstalling.Evena4GBSDcardwillsometimesnotbelargeenoughtoholdNOOBSandanOS,andstillhaveadequatespaceforyourfilesandprograms.
IfyoucannotuseNOOBS,youcaninstallanOSdiskimagetoyourSDcard.Thisisdescribedinsection2.3InstallationofRaspbianusingaDiskImageonpage20.
TheprocessforinstallingNOOBStoanSDcardisthesamewhetheryouareusingthefullNOOBSpackage,orNOOBSLite.OnWindows(8/7/Vista/XP):1.InserttheSDcardintoasuitablecardsocketorUSBcardreader.2.PresstheWindowslogokey+R.TypeexplorerandpressEnter.
3.IntheWindowsFileExplorerwindow,right-clickthecarddevice(usuallylabelledSDHCorRemovableDisk)andthenclickFormat.
4.IntheFilesystemlist,clickFAT32.5.IntheAllocationunitsizelist,clickDefaultallocationsize.
6.ClickStart.7.DownloadoneoftheNOOBSpackagesfromhttp://www.raspberrypi.org/downloads/
8.Findthe.zipfileyoudownloadedandright-clickit.PointtoOpenwithandthenclickWindowsExplorer.
9.PressCtrl+A,toselectallofthefilesinthe.ziparchive.10.PressCtrl+C,tocopytheselectedfilesintomemory.11.IntheWindowsFileExplorerwindow,right-clickthecarddevice.12.ClickPastetocopythefilestotheSDcard.13.IntheWindowsFileExplorerwindow,right-clickthecarddevice.
14.ClickEject.OnMacOSX:
1.InserttheSDcardintoasuitablecardsocketorUSBcardreader.
2.Onthedock,clickFinder.
-
3.Onthesidebar,clickApplications.4.ClickUtilities,andthendouble-clickDiskUtility.
5.Intheleftpanel,clicktheSDcard(usuallylabelledNONAMEifthecardwasnotformattedwithavolumename).
6.OntheErasetab,fromtheVolumeFormatlist,clickMS-DOSFileSystem.7.ClickErase.8.DownloadoneoftheNOOBSpackagesfromhttp://www.raspberrypi.org/downloads/9.InFinder,locatethe.zipfileyoudownloaded.
10.Double-clicktheNOOBSzipfileanditwillunziptoanewfolder.Forexample,afoldernamedNOOBS_lite_v1_3_9.1
11.Double-clickthefoldertoopenit.12.PressCmd+Atoselectallofthefiles.13.PressCmd+Ctocopythefilesintomemory.
14.Intheleftpanel,clicktheSDcard(usuallylabelledNONAMEifthecardwasnotformattedwithavolumename).
15.PressCmd+VtocopythefilestotheSDcard.16.Intheleftpanel,clicktheEjecticonnexttothenameoftheSDcard.
InstallingRaspbianToinstallRaspbian,youwillneedtoconnectakeyboard,mouse,anddisplaytoyourPi.
First,ensurethePiiscompletelyoffandunplugged,andtheninserttheSDcardintothePiscardsocket.ReconnectthepowertoyourPi.ThePiwillstartandwillloadtheNOOBStool.Wheneverythingisready,youshouldseeawindowsimilartoFigure1.
-
Figure1.NOOBSonaRaspberryPiThewindowshowsalistoftheoperatingsystemsthatyoucaninstall.1.IfyouhavearchivingsoftwareinstalledonyourMac,theNOOBSfilemightopenwiththisinstead..ToinstallRaspbian:1.Inthelist,clicktheboxnexttoRaspbian.2.Onthetoolbar,clickInstall.
Whentheinstallationiscomplete,theRaspberryPirestartsandloadstheraspi-configtool.Thishelpsyoutochangecertainimportantsettings.Formoreinformation,seesection2.4Raspiconfigonpage22.IfyouputtheSDcardbackintoaWindowsPCthenthecardwillappeartohaveshrunkincapacity.Ifyouwanttowipethecard,youcanusethecommand-linetooldiskparttodestroythepartitionsandcreateanewprimarypartitionusingalloftheavailablespace.
-
2.3InstallationofRaspbianusingaDiskImage
Adiskimageisaspecialtypeoffileformakingacopyofstoragedevices,suchasfloppydisks,CDs,harddrives,andmemorycards.Itnotonlycontainsallofthefilesfromthedevice,italsostoresalloftheinformationnecessarytorecreatethesamefilestructureandphysicallayoutonanotherdevice.
ManyoperatingsystemsthathavealreadybeenmadetoworkontheRaspberryPiareavailablefordownloadasdiskimages.TowritetheimagetoanSDcard,youcanuseaWindowsPC,MacorLinuxcomputer.1
DownloadtheRaspbiandiskimagefromhttp://www.raspberrypi.org/downloads/itisa.ziparchivethatyouneedtounzipbeforeitcanbeused.
TounzipthefileonWindows(8/7/Vista/XP):
1.Findthe.zipfileyoudownloadedandright-clickit.PointtoOpenwithandthenclickWindowsExplorer.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.
UsersofWindowswillneedtodownloadandinstallWin32DiskImagerfromhttp://sourceforge.net/projects/win32diskimager/beforecontinuing.UsersofMacOSXshouldinstallApplePi-Bakerfromhttp://www.tweaking4all.com/hardware/raspberry-pi/macosx-apple-pi-baker/
TowritetheRaspbiandiskimagetoanSDcardonWindows(8/7/Vista/XP):1.InserttheSDcardintoasuitablecardsocketorUSBcardreader.
2.IfyouarerunningWindowsXP:ontheStartmenu,underagroupnamedImageWriter,clickWin32DiskImager.
3.IfyouarerunningalaterversionofWindows:ontheStartmenu,underagroupnamedImageWriter,right-clickWin32DiskImager.ThenclickRunasadministrator.YoumaybeaskedtoconfirmthisbyawindowtitledUserAccessControl.ClickYes.
4.InWin32DiskImager,underImageFile,clickthefoldericon.Intheleft-handsideoftheWindowtitledSelectadiskimage,clickDesktop,andthendouble-clickthe.imgfilethatyouunzipped.
5.UnderDevice,ensurethatthedrivelettershownmatchestheonethatisdisplayedinWindowsExplorernexttoyourSDcard.
-
6.ClickWrite.7.Whentheprocessiscomplete,clickExit.
8.PresstheWindowslogokey+R.TypeexplorerandpressEnter.
9.IntheWindowsFileExplorerwindow,right-clickthecarddevice(usuallylabelledSDHCorRemovableDisk)andthenclickEject.
OnMacOSX:1.InserttheSDcardintoasuitablecardsocketorUSBcardreader.
2.Onthedock,clickFinder.3.Onthesidebar,clickApplications.4.Intherightpanel,double-clickApplePi-Baker.
5.IfmultipleSDcardsarelistedunderPi-Crust:PossibleSD-Cards,clicktheoneyouwanttowriteto.
6.UnderPi-Ingredients:IMGRecipe,clickIMGtoSD-Card.7.Locatethe.imgfilethatyouunzipped,thenclickOpen.8.EntertheadministratorpasswordforyourMac.
9.Whentheprocessiscomplete,clicktheClosebutton.TheninFinder,clicktheEjectbuttonnexttotheSDcard.
EnsurethePiiscompletelyoff,andtheninserttheSDcardintothePismemorycardsocket.ReconnectthepowertoyourPi.
-
2.4Raspi-config
WhenRaspbianstartsforthefirsttime,itrunsatoolcalledraspiconfig.YoucanusethistochangeseveralconfigurationoptionsthataffecthowRaspbianoperates.Raspi-configisacommandlineapplicationandiscontrolledusingthekeyboard:UsetheUpandDownArrowkeystohighlightmenu
items.PressEntertoactivatethehighlighteditem.
PresstheTabkeytomovethehighlightdowntothetwooptionsatthebottomofthewindowandandthenusetheLeftandRightArrowkeystochoosebetweenthosetwooptions.
Tomovebacktothemainmenu,presstheTabkeyagain.Whenyouhavefinishededitingthesettings,highlighttheoptionandpressEnter.WhenRaspbiansgraphicaldesktopisrunning,youcanaccesstheraspi-configtoolatanytimebydouble-clickingLXTerminalonyourdesktop.ThenenterthefollowingcommandandpressEnter:sudoraspi-config
ExploringtheSettingsinRaspi-configThetablebelowsummarizestheoptionsavailablefromthemainmenuinraspi-config:MenuOptionDescriptionExpandFilesystemMakethefullcapacityoftheSDcardavailabletotheoperatingsystemifisnotalreadyavailable.ChangeUserPasswordChangethepasswordforthedefaultuser(pi).
EnableBoottoDesktop/ScratchRaspbiancanautomaticallyloaddifferentapplicationswhenitstarts.Thissettingchangesthat.
InternationalisationOptionsConfigurelanguage,keyboardandculturesettings(suchasdateformatandtimezone).
EnableCameraIfyouhaveaRaspberryPiCameramodule,youneedtoenableitusingthismenuoption.AddtoRastrack
Rastrack(rastrack.co.uk)showsthelocationofRaspberryPidevicesaroundtheworld.UsethisoptiontoaddyourPitothemap.
OverclockOverclockingyourPimakesitrunfasterthanthe
manufacturerdesigneditto.However,thiscanalsocausethesystemtooverheatorbecomelessstable.
AdvancedOptionsSeebelow.Aboutraspi-configDisplayinformationabouttheraspi-configtool.
SelectingAdvancedOptionsfromthemenutakesyoutoanothermenu:MenuOptionDescriptionOverscanThedisplayinmanyoldertelevisionsisslightly
largerthanthevisiblearea.IfyourPisdisplayrunsofftheedgeofthescreen,youcanenableblackborders(overscan)toensurethatyoucanseeallofthepicture.
HostnameChangethenamegiventothePiwhenitis
connectedtoalocalnetwork.Thiscanbeusefulwhensearchingforthedevice,orwhenyouhaveseveralRaspberryPidevices.
MemorySplitThePismemoryissharedbetweentheCPUandGPU.YoucanchangehowmuchmemoryisallocatedtotheGPUusingthissetting.SSHEnableordisableSSHaccess.SPIWhenconnectingcertainSPIdevices,itcanbe
-
usefultoloadtheSPIkernelmodulewhenthePistarts.Usethissettingtochangewhetherthemoduleisloadedautomatically.
Audio
Usedtosendtheaudiosignaltotheaudiooutputconnector,evenwhenusinganHDMIcableforvideo.
UpdateConnectstotheInternetandupdatestheraspiconfigtooltothelatestversion.
Forsomeusers,thedefaultsettingsareok.However,therearethreesettingsinparticularthatmanyusersmightwanttochangeatthisstage:
ChangingtheDefaultPasswordWhenRaspbianisinstalled,itcreatesanewusercalledpi.Thedefaultpasswordforthisuserisraspberry.
Tochangethis:1.PresstheDownArrowkeytohighlightChangeUserPassword,andthenpressEnter.
2.PressEnteragaintoselect.3.TypeanewpasswordandpressEnter.
4.Toconfirmthepassword,typeitagainandpressEnter.5.PressEntertoselect.
IfyouconnectyourPitotheInternetandareunsurewhetheryournetworkrouterallowsincomingconnectionsthenitisagoodideatochangethispasswordsothatotherpeoplecannotlogintoyourdevice.
ExpandingtheFileSystemIfyouinstalledRaspbiantotheSDcardusingadiskimage,itispossiblethattheOScannotusethefullcapacityofyourSDcard.
Tofixthis:1.UsetheUpandDownArrowkeystohighlightExpandFilesystemandthenpressEnter.2.Whentheprocessiscomplete,pressEntertoselect.
3.PresstheTabkeyandthentheRightArrowkeytohighlight.PressEnter,andwhenyouarepromptedtorebootthePi,select.
ChangingtheDefaultBootSequenceThedefaultsettingisforRaspbiantofinishloadingandplaceyouatthecommandline.
Fromtheraspi-configtool,youcaninstructRaspbiantoloadthegraphicalenvironmenteverytimetheRaspberryPistartsup.Todothis:
1.UsetheUpandDownArrowkeystohighlightEnableBoottoDesktop/Scratch,andthenpressEnter.
2.PresstheDownArrowkeytohighlightDesktopLoginasuserpiatthegraphicaldesktop,andthenpressEnter.
-
2.5RaspbiansDesktopEnvironment
Ifyouhavenotchangedthesettinginraspi-config,theRaspberryPiwillbootintoRaspbianscommandline.Tostartthedesktopenvironment:
1.Typepiastheusername,thenpressEnter.2.Typeyourpassword,thenpressEnter.13.TypethefollowingcommandandpressEnter:startxAfterashortperiodofloading,youwillseeascreensimilartoFigure2.1.Ifyouhavenotchangedthedefaultpassword,itisraspberry.
Figure2.Raspbiansdesktopenvironment
RaspbiansdesktopisacustomizedversionofLXDE,whichstandsforlightweightX11desktopenvironment.ItissimilartoMicrosoftWindowsandmanyofthewaysthatyouuseitarethesame.
Thescreenisdividedintotwodistinctareas:thedesktop,andtheLXDEpanel.
-
Figure3.ElementsoftheRaspbiandesktopenvironment1Desktoparea.Hereyoucanfindfilesandlinks(shortcuts)toapplications.Double-clicktheiconstoopenthefileorapplicationthatitlinksto.
2LXDEpanel.Containsthemainmenu,shortcutstocommonly-usedapplications,thedesktoppager,andthesystemtray.3Menu.TheLXDEmainmenuprovidesaccesstomanyofthesystemsettings,tools,andanyapplicationsthatyouhaveinstalled.4DesktopPager.Formoreinformation,seeSwitchingtheDesktoponpage29.
5Taskbar.Openapplicationsareshownasaniconanddescriptioninthisarea.Ifyouminimizeanapplicationwindow,youcanclicktheiconintheLXDEpaneltorestorethewindowtofullview.
6SystemTray.Thisisusuallyusedbysystemprocessesandapplicationsthatruninthebackground,sothattheuserhassomewayofinteractingwiththem.Bydefault,thesystemtraycontainstheCPUmonitor(whichshowshowbusyistheCPUis),thecurrenttime,andtheapplicationlaunchbar(anotherplaceyoucanstoreiconstoopencommonly-usedapplications).Youcanusuallydouble-clicktheiconsinthisareatoopentheirwindow,orrightclicktheicontoaccesstheapplicationsmenu.
OpeningandClosingApplicationsOnthedesktop,andinthemenuthatyouaccessfromtheLXDEpanel,youcanseethatmanyapplicationsarealreadyinstalledonyoursystem.
ThereareseveralwaysofrunningapplicationsinRaspbian,butthethreemostcommonare:clickingiconsonthedesktop,usingthemenu,andopeninganapplicationfromthecommandline.
Forexample,toopenthewebbrowserMidori:Onthedesktop,double-clickMidori.OntheLXDEpanel,clicktheMenubutton.PointtoInternet,andthenclickMidori.
Fromacommand-lineterminalrunninginthedesktopenvironment,typemidoriand
-
thenpressEnter.Ifyourunapplicationsfromthecommandline,youwillreturntothepromptwhentheyarefinished.Withapplicationsthatopenawindowinthegraphicalenvironment,youcanclosetheminthreeways:
PressAlt+F4onthekeyboard.ClicktheClosebuttoninthetop-rightofthewindow.Itlookslikeanx.Clicktheiconinthetop-leftofthewindow,andthenclickClose.
SwitchingtheDesktopOnmostLinuxdesktopenvironments,youcanhavetwo(ormore)workspaces.Aworkspaceiscollectionofthewindowsandfilesthatarecurrentlyopen.Switchingtoanotherworkspacehidesallofthewindowsthatarecurrentlyvisible,anddisplaysallofthewindowsfromtheotherworkspace.InRaspbian,workspacesarealsocalleddesktops.
YoucanswitchbetweentheseusingthetwodesktopbuttonsthatmakeuptheDesktopPager.Forexample:1.Onthedesktop,double-clickMidori.2.Dragthewindowtothetop-rightcornerofthedisplay.3.Onthedesktop,double-clickLXTerminal.
4.OntheLXDEpanel,pointtothelightgraysquare.Afterafewmoments,thetextDesktop2willappear.Clickthebutton.
5.Onthedesktop,double-clickPiStore.
6.ClicktheDesktop1button(totheleftoftheDesktop2button)toswitchbacktothefirstdesktop.
7.ClicktheDesktop2buttontoswitchtotheseconddesktopagain.Tomoveawindowtoanotherdesktop:clicktheiconinthetopleftofawindow,pointtoSendtodesktop,andthenclickthenameofthedesktop.
Toincreasethenumberofdesktopsthatyoucanuse:
1.OntheLXDEpanel,right-clicktheDesktopPager.2.ClickDesktopPagerSettings.
3.OntheDesktopstab,typeanumberintotheNumberofdesktopsbox,orusetheupanddownarrowbuttonstoincreaseanddecreasethenumberofdesktops.
4.ClickClose.
UsingtheFileManagerYoucanusetheFileManagertocopy,rename,delete,andchangethepropertiesoffilesthatarestoredontheSDcardoranyUSBstoragedevicesthatyouhaveattached.
Toopenthefilemanager:OntheLXDEpanel,clicktheFileManagerbuttonthesecondbuttonfromtheleft;orOntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickFileManager.1
-
23
456
Figure4.TheFileManager
1Applicationmenu.2Toolbarnavigationbuttonsandaddressbar.3Tabbar.4Leftpanelforselectingplaces,devices,andfiletrees.5Rightpanelforselectingfilesandfolders.6Statusbar.
Likeawebbrowser,theFileManagerwindowcanopenmultiplefoldersatthesametimebyusingtabs.Toopenanewtab:Onthetoolbar,clickthefirstbuttonfromtheleft.
Thiswillcreateanewtabinthesamefolder,andwillshowthetabbar.Youcanusethetabbartoswitchbetweenthetabsthatarecurrentlyopen.
IfyouhaveusedtheWindowsExplorerinMicrosoftWindowsortheFinderinMacOSX,youalreadyknowhowtocompletemanyofthemostcommontasks.However,thetablebelowisabriefsummaryofhowtousetheRaspbianFileManager.ToDoThis
SwitchbetweenthePlacesviewandthefulldirectorytreeIntheleftpanel,clickPlacesandthenclickDirectoryTree.
Changethewayiconsfilesandfoldersaredisplayedintherightpanel
-
Ontheapplicationmenu,clickView,andthenclickononeofthefourviewoptionsIconView,ThumbnailView,CompactVieworDetailedListView.
OpenafolderIntheleftpanel,clickthenameofafolder.Intherightpanel,doubleclickfoldersicon.OpenafolderusingafilepathIntheaddressbar,typethefullfilepathandthenpressEnter.ToDoThis
OpenthecurrentusershomedirectoryOntheapplicationmenu,clickGo,andthenclickHomeFolder;oronthetoolbar,clicktheHomebutton.
OpenthedesktopfolderOntheapplicationmenu,clickGo,andthenclickDesktop.
OpenthecurrentfolderinthecommandlineOntheapplicationmenu,clickTools,andthenclickOpenCurrentFolderinTerminal.
SelectafileorfolderIntherightpanel,clickanicon.SelectmultiplefilesorfoldersIntherightpanel,holdCtrlandclicktheiconsofthefilesandfoldersthatyouwanttoselect.DeleteafileorfolderRight-clickaniconandthenclickDelete.RenameafileorfolderRight-clickaniconandthenclickRename.
ViewthepropertiesofafileorfolderRight-clickaniconandthenclickProperties.
OpenafileinitsdefaultapplicationDouble-clickafilesicon.
MoveafileorfoldertoanewlocationRight-clickaniconandthenclickCut.Browsetothefolderthatyouwanttomovetheitemto,right-clickintherightpanel,andthenclickPaste.
CopyafileRight-clickaniconandthenclick
Copy.Browsetothefolderwhereyouwantacopytobecreated,right-clickintherightpanel,andthenclickPaste.
Createanewfolder
Right-clickintherightpanel,pointtoCreateNew,andthenclickFolder.
IfyouareusedtoMicrosoftWindows,theLinuxfilesystemmightseemalittlestrangeatfirst.Itcontainsalargenumberoffolders,andmanyofthesehavespecificpurposes.Thekeyonesare:FolderDescription
homeContainsafolderforeachuseraccountonthesystem.Forexample,/home/piisthehomefolderforthedefaultuseronRaspbianinstallations.Thisiswhereyoushouldstoreallofyourpersonalfiles.
etcContainsmostoftheconfigurationfilesfortheoperatingsystem.
devLinuxcreatesfilesystementriesinthisfolderforhardwaredevicesthatareattachedtothesystem.Mediadevices(forexample,DVDdrives)areplacedin/mntor/mediainstead.
mediaWhenstoragedevicessuchasCDs,memorycards,andUSBflashdrives,areinserted,thesystemcreatesamountpointfortheminthisfolder.Mountpointsprovideaccesstothefilesystemonthedevice.
rootThisisthehomefolderforthesystemadministratoraccount.tmpTemporaryfilesusedbythesystem.ThecontentsofthisfolderaredeletedwhenthePistarts.bootContainsfilesneededtostartRaspbian.
varStoresvariableandtemporaryfilesthatarecreatedbytheuserorapplicationsrunningastheuser.
binContainsapplicationsthatareusedbyalluseraccounts,thesystem,andthesystemadministrator.
usrContainsapplicationsanddocumentationforalluserapplications.sbinContainsapplicationsthatareonlyavailabletothesystemandthesystemadministrator.FolderDescription
libContainslibrariescollectionsofcodeandinformationthatmustbesharedamongallapplications.
mntSimilarto/media,thisfoldercontainsmountpointsfornon-removablemedia.
-
Ingeneral,trytokeepallofyourdatainthe/home/pifolder.Wheninstallingnewsoftwareandhardwaredevices,theywillusethespecialfoldersiftheyneedto.
AccessingtheCommandLineWhilemosttaskscanbecompletedusingthedesktopenvironment,therearestillsomethingsthatyouwillhavetodofromthecommandline.
Toaccessthecommandlinefromthegraphicalenvironment:Onthedesktop,double-clickLXTerminal.OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickLXTerminal.
Inthecommandline,filesandfoldershavefilenamesandfilepaths.Thefilepathincludesthenamesofthefoldersandsubfoldersthatthefileisstoredin.Forexample,afileocr_pi.pnginthepiusershomefolderhasthefullfilepath:/home/pi/ocr_pi.png
Filepathsthatbeginwithaforwardslashstartfromthetop-levelfolder.Sotheexampleabovetellsthesystem:startatthetoplevelandmoveintothehomefolder,thenmoveintothepisubfolder,andthenfindthefileocr_pi.png.
Ifyouarealreadyinthehomefolder,youcanrefertothesamefileas:pi/ocr_pi.png
Andifyouareinasubfolderof/home/pi,youcanrefertothefileusingtwodotsthatsymbolizemovingtotheparentdirectory:../ocr_pi.png
Toruncommands:typethecommandusingthekeyboardandthenpressEnter.Therearealargenumberofcommandsavailable(toomanytolisthere),butthesearesomeofthemostcommon:ToDoThisListthecontentsofthecurrentfolderTypelsandthenpressEnter.ListthecontentsofaspecificfolderTypelsfollowedbyaspaceandthenthenameofthefolder.ThenpressEnter.MoveintoasubfolderTypecdfollowedbyaspaceandthenthenameofthefolder,andthenpressEnter.MovetoaparentfolderTypecd..andthenpressEnter.CreateasubfolderTypemkdirfollowedbyaspaceandthenthenameofthefolder,andthenpressEnter.DeleteafolderTypermdirfollowedbyaspaceandthenthenameofthefolder,andthenpressEnter.DeleteafileTypermfollowedbyaspaceandthenthenameofthefile,andthenpressEnter.CopyafileorfolderTypecpfollowedbyaspaceand
thenthename(orfullfilepath)ofthefiletobecopied.Typeanotherspaceandthenthename(orfullfilepath)tocallthecopy.PressEnter.
RenameormoveafileorfolderTypemvfollowedbyaspaceand
thenthename(orfullfilepath)ofthefiletobecopied.Typeanotherspaceandthenthename(orfullfilepath)tocallthecopy.PressEnter.
ClearthecommandlinewindowTypeclearandthenpressEnter.
Toclosethecommandline,dooneofthefollowing:PressAlt+F4onthekeyboard.ClicktheClosebuttoninthetop-rightofthewindow.
Clicktheiconinthetop-leftofthewindow,andthenclickClose.Ontheapplicationmenu,clickFileandthenclickQuit.TypethefollowingcommandandthenpressEnter:exit
-
IntheAccessoriesgroupoftheLXDEpanelmenu,thereisanotherterminal.ThisoneiscalledRootTerminal.Whenyouopenthecommandlineusingthisapplication,youareautomaticallygrantedsystemadministratorprivileges.Ifyouonlywanttorunasinglecommand,youcandothisfromtheRaspbianmenu.OntheLXDEpanel,clicktheMenubuttonandthenclickRun.TypeyourcommandandthenpressEnter.
UnderstandingLinuxUsersandSuperusersIfyouhaveusedmorerecentversionsofMicrosoftWindowsthenyoumaybeusedtorunningcertainapplicationsasanadministrator.ThisconceptisalsoinLinux.
Superusers(oftencalledroot)havefullaccesstothesystem.Anyapplicationsyourunasasuperuserwillalsohavefullaccesstothesystem.Toprotectthesystemfromaccidentalormaliciousdamage,yourarelylogintoRaspbianasasuperuser.
NormalusershavelessaccesstothecorefilesneededbytheOS,andthismeansthatanyapplicationsthattheyrunalsohavelessaccesstothesystem.InRaspbian,piistheuserthatlogsintothedesktopenvironment,anditisanormaluser.
Whenyoudoneedtochangepartofthesystem,oraccomplishataskthatonlysuperusercando,youcan:OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickRootTerminal;or
Fromthenormalcommandline,typesudofollowedbyaspacebeforethecommandthatrequiressuperuseraccessprivileges.
-
2.6CommonTasks
Inthissection,youcanfindinstructionsforsomeofmostcommontasksthatpeopleperformafterinstallingRaspbian.Theseinstructionscontinueintothenextsection,2.7NetworkConnectionsandRemoteAccessonpage40.
RestartingandShuttingDowntheRaspberryPiTorestartthePi:1.OntheLXDEpanel,clicktheMenubuttonandthenclickRun.2.TypethefollowingcommandandthenpressEnter:sudoshutdownrnowToshutdownthePifromthedesktop:1.Onthedesktop,double-clickShutdown.2.ClickYes.ToshutdownthePifromthecommandline:TypethefollowingcommandandthenpressEnter:sudoshutdownhnow
ConfiguringtheTVServiceIfyouconnectyourPitoatelevisionusinganHDMIcable,Raspbianautomaticallyselectsascreensizethatitdecideswillbethebestforyoursetup.However,thisisnotalwaysthehighestresolution.
TheconfigurationsettingthatcontrolshowRaspbianselectsthescreensizeisinthefile/boot/config.txtandyoucanadjustthissettingwithatexteditor:1.OntheLXDEpanel,clicktheMenubutton,point
toAccessories,andthenclickRootTerminal.2.TypethefollowingcommandandthenpressEnter:tvservicededid3.TypethefollowingcommandandthenpressEnter:edidparseredid
4.Findthevideomodethatyouwanttouse,andmakenoteofthemodenumberandwhetheritsaysDMTmodeorCEAmode.
5.TypethefollowingcommandandpressEnter:nano/boot/config.txt
6.PresstheDownArrowkeyuntilyoufindthelinesthatbeginwith#hdmi_group=#hdmi_mode=
7.Removethe#fromthestartofbothofthoselines.8.IfthevideomodeisDMT,changethehdmi_groupto2:hdmi_group=29.IfthevideomodeisCEA,changethehdmi_groupto1:hdmi_group=110.Typethemodenumberafterhdmi_mode=,forexample:hdmi_mode=1611.PressCtrl+X.12.PressY,andthenpressEnter.13.RestarttheRaspberryPi.
-
InstallingaGraphicalPackageManagerWheninstallingnewapplications,thereareafewstepsthatneedtobetaken:1.Findoutwhethertheapplicationiscompatiblewith
theOS.2.Installanyotherpiecesofsoftwarethatthisnewapplicationrequires.3.DownloadtheapplicationfromtheInternet.4.Installtheapplicationtothecorrectfolders.
InLinux,thepackagemanagerhandlesallofthisforyou.Youcanalsouseittouninstallapplicationsthatyoudonotwantanymore.Packagemanagersconnecttorepositoriesonlinelibrariesofsoftware.AndsinceLinuxisopen-source,mostofthesoftwareintheserepositoriesisalsoopen-source(andfree).
Thepackagemanagerthatisbuilt-intoRaspbianisaccessedfromthecommandline.However,youcanalsoinstallonethatrunsinthegraphicaldesktopenvironment.
OnesuchtoolisSynaptic.Toinstallit,usethecommand-linepackagemanager:1.OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickRootTerminal.
2.TypethefollowingcommandandthenpressEnter:apt-getinstallsynaptic
3.Whentheprocessiscomplete,typethefollowingcommandandthenpressEnter:exitToruntheSynapticpackagemanager:
OntheLXDEpanel,clicktheMenubutton,pointtoPreferences,andthenclickSynapticPackageManager.
-
2.7NetworkConnectionsandRemoteAccess
SettingupWi-FiBeforebuyingaUSBWi-FiadapterforusewiththeRaspberryPi,checkthattheadaptorisknowntobeworkingbylookingatthelistathttp://elinux.org/RPi_USB_Wi-Fi_Adapters
ToinstallaUSBWi-FiadapteronyourPiandconnecttoyournetwork:1.InserttheUSBdeviceintoanavailableUSBsocketonthePi,oronaUSBhub.2.Onthedesktop,double-clickWiFiConfig.
3.IntheAdapterlist,clickwlan0.Ifyouhavenoadaptersinthelist,yourUSBdeviceisnotcompatiblewiththeRaspberryPi.
4.ClickScantoopentheScanresultswindow.5.ClickScan.6.Double-clickthenameofyourWi-Finetwork.
7.CheckthattheAuthenticationandEncryptionsettingsmatchhowyourothercomputersconnecttoyourrouter.
8.TypeyournetworkpasswordintothePSKbox.9.ClickAdd,andthenclickClose.
FindingtheIPAddressToconnecttothePifromanothercomputeronyournetwork,youwillneedtoknowitsIPaddress.Tofindthis:
1.Onthedesktop,double-clickLXTerminal.2.TypethefollowingcommandandthenpressEnter:ifconfig
Theaddressyouneediscalledinetaddrandconsistsoffournumbersseparatedbydots.IfyouareconnectedtoyournetworkusinganEthernetcable,youcanfindtheaddressinthesectionlabelledeth0.Ifyouareconnectedtoyournetworkusingawirelessadaptor,youcanfindtheaddressinthesectionlabelledwlan0.
UsingaStaticIPAddressWhenthePirestarts,orreconnectstothenetwork,yournetworkrouterwillgivethePianIPaddress.However,thiscanchangeeverytime.
YoucanconfigurethePisothatitalwaysusesthesameIPaddress.Youneedafewpiecesofinformationandyouwillneedtoeditaconfigurationfileinatexteditor.
Todothis:
1.Onthedesktop,double-clickLXTerminal.2.TypethefollowingcommandandthenpressEnter:ifconfig
3.IfyouareusinganEthernetcable,inthesectionlabelledeth0,makeanoteofthevaluesinetaddr,BcastandMask.
4.IfyouareusingWi-Fi,inthesectionlabelledwlan0,makeanoteofthevaluesinetaddr,BcastandMask.
-
5.TypethefollowingcommandthenpressEnter:netstat-nr
6.MakeanoteofthevaluesinGatewayandDestination.Ifyoucanseetwoentriesinthetable,ignorethevalues0.0.0.0andusethevaluefromtheotherline.
7.TypethefollowingcommandandthenpressEnter:sudonano/etc/network/interfaces8.IfyouareusingWi-Fi,skiptostep12.
9.IfyouareusinganEthernetcable:changethelinethatreadsifaceeth0inetdhcptoifaceeth0inetstatic
10.Addthefollowinglines,startingonanewlineafterthewordstatic.Replacethevaluesinangledbracketswiththevaluesfromtheprevioussteps:addressnetmasknetworkbroadcastgateway
11.Skiptostep14.12.IfyouareusingWi-Fi:changethelinethatreadsifacewlan0inetdhcptoifacewlan0inetstatic13.Addthefollowinglines,startingonanewlineafterthewordstatic.addressnetmaskgateway
14.PressCtrl+X.15.PressY,andthenpressEnter.16.RestarttheRaspberryPi.
TransferringFilestoandfromtheRaspberryPiYoucanusesecurecopy(SCP)totransferfilesfromyourcomputertoaPi,ortocopyfilesfromthePitoanothercomputer.Raspbianalreadysupportsthis,andsoyouonlyneedtoinstallaclientonyourmaincomputer.
OnWindows,WinSCPisverypopularapplicationfortransferringfiles.Youcandownloaditforfreeathttp://winscp.net
OnMacOSX,youcanuseanapplicationcalledCyberduck.Thisisafreedownloadfromhttp://cyberduck.io/oryoucandownloaditfromtheMacAppStore.
ThedetailsyouneedtomakeaconnectiontothePiarelargelythesameregardlessofwhichSCPclientyouuse:
Server/Hostname:theIPaddressofyourPiUsername:piPassword:thisisraspberryifyouhavenotyetchangedit.Protocol:SCP
TodownloadfilesfromthePi,dragtheiconsfromtheSCPclientswindowtoaWindowsExplorerorFinderwindow.TouploadfilestothePi,dragfilesfromaWindowsExplorerorFinderwindowanddropthemontotheSCPclientswindow.
-
ConnectingtothePiwithSSHSecureshell(SSH)isawayoftalkingtoyourPioveranencryptedtransmission.ItistypicallyusedwhenyouwanttoaccesstheRaspberryPiscommandlinefromanothercomputer.AslongasyourPihasanetworkconnection,youcanconnecttoitremotelyandtypecommands.
OnWindows,youwillneedanapplicationthatunderstandstheSSHprotocol.Therearemanyoftheseavailable,butPuTTYisoneofthemorepopularones.Downloaditfromhttp://www.chiark.greenend.org.uk/~sgtatham/putty/
YoudonotneedanadditionalSSHclienttoconnecttothePionMacOSX.ToconnecttoyourPioverSSHonWindows(8/7/Vista/XP):1.Locatethefileputty.exethatyoudownloaded,andthendouble-clickit.2.IntheHostName(orIPaddress)box,typetheIPaddressofyourPi.
3.ClickOpen.4.Attheloginprompt,typepi.
5.Atthepasswordprompt,typeyourpasswordandpressEnter.Thisisraspberryifyouhavenotchangedit.
ToconnecttoyourPioverSSHonMacOSX:
1.Onthedock,clickFinder.2.Onthesidebar,clickApplications.3.ClickUtilities,andthendouble-clickTerminal.
4.Typethefollowingcommand,replacingwiththeIPaddressofyourRaspberryPi:[email protected],typeyourpasswordandpressEnter.Thedefaultpasswordisraspberryifyouhavenotchangedit.
ConnectingtothePiwithRemoteDesktopMicrosoftWindowscomeswithanapplicationcalledRemoteDesktop.YoucanusethistoconnecttoyourRaspberryPiandusethedesktopenvironmentfromaWindowscomputer.MacOSXusersneedtodownloadMicrosoftRemoteDesktopfromtheMacAppStore.
YoualsoneedtoinstallasmallsoftwareapplicationonthePibeforeyoucanconnectusingRemoteDesktop.Toinstallthesoftwarefromthecommandline:1.OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickRootTerminal.2.TypethefollowingcommandandthenpressEnter:apt-getinstallxrdpTostartaRemoteDesktopconnectionfromWindows(8/7/Vista/XP):1.PresstheWindowslogokey+R.ThentypemstscandpressEnter.2.IntheComputerbox,typetheIPaddressofyourRaspberryPi,andthenpressEnter.3.IntheLogintoxrdpwindow,intheusernamebox,typepi.4.Inthepasswordbox,typeyourpassword.15.ClickOK.
-
BrowsingtheWebIfyouareusingthelatestversionofRaspbian,thewebbrowseriscalledEpiphanyanditisinstalledwhenyouinstalltheOS.Inotherversions,thewebbrowserisMidori.
Toopenawebbrowser:
OntheLXDEpanel,clicktheMenubutton,pointtoInternet,andthenclickMidoriorEpiphanyWebBrowser.
-
2.8OtherOperatingSystems
RaspbianLinuxisnottheonlyOSthatyoucanrunonaRaspberryPi.ManyvarietiesofLinuxhavebeenrepackagedsothatyoucanusethem,andthereareseveralnon-Linuxoperatingsystemsthatalsowork.
ArchLinuxArchLinuxisanextremelylightweightversionofLinuxthatisidealforserversordeviceswithunusualpurposeswheremanyofthepackagesthatarenormallyinstalledtocreateausabledesktopenvironmentarenotneeded.
YoucandownloadadiskimageofArchLinuxfromhttp://www.raspberrypi.org/downloads/,oritcanbeinstalledusingNOOBS.
RISCOSRISCOSisavailableathttp://www.raspberrypi.org/downloads/oryoucaninstallitusingNOOBS.Ithasbeeninusesince1987,andwasdesignedforArchimedeslineofcomputersmadebyAcornComputersLtd.ThesemachinesusedthefirstARMprocessors.1.Ifyouhavenotchangedthedefaultpassword,itisraspberry.
RetroPieRetroPieisacustomizedversionofRaspbianthatrepackagestheOSwithavarietyofemulatorsforclassiccomputersandvideogamesconsoles.Findoutmoreathttp://blog.petrockblock.com/retropie/
Plan9Plan9isdevelopedbyBellLabs,andhasitsoriginsinanOSthatwasreleasedinthe1980s.Itisverylightonsystemresources,andquitedifferentfromtheoperatingsystemsthatpeopleareusedtotoday.YoucandownloadadiskimageofPlan9fromhttp://plan9.bell-labs.com/wiki/plan9/download/
AEROSAROSisdesignedtobeasuccessortotheoperatingsystemAmigaOS,whichisitselfbasedontheoperatingsystemusedbytheCommodoreAmigarangeof16-bitcomputers.TheRaspberryPiversioniscalledAEROS.Thecurrentversionisonlyavailabletoregisteredusers,butolderversionsareavailableathttp://www.aeros-os.org/styled-11/index.html
AndroidAndroidisanoperatingsystemfortabletsandsmartphones,butitisnotyetfullyusableontheRaspberryPi.Thewebpageforthisprojectishttp://androidpi.wikia.com/wiki/Android_Pi_Wiki
NoOperatingSystemIfyouareanexperiencedsoftwaredeveloperandyoudonotneedtorunanyotherapplications,thenyoumightbeabletorunyourcodewithoutinstallinganoperatingsystem.Thisiscalledbare-metalprogrammingandtherearevarioustutorialsandsamplesavailableonthewebtohelpyou.
-
3BuildingaMediaCenterwithXBMC
-
3.1XBMC
XBMCisamediaplayerthatisdevelopedbytheXBMCFoundation.Asamulti-platform,highly-customizable,andopensourcesoftwarepackage,itisextremelypopularandisusedonawidevarietyofdevices.
XBMCcanplayaudioandvideofilesinmanyformats,including:3GP,AAC,APE,AVI,CDDA,FLV,MIDI,MKV,MP3,MP4,M4A,MPEG,OGG,WAV,WMA,WMV,andmanymore.1ItcanevenplayDVDsfromISOdiscimages.
ManypeoplehaveaRaspberryPispecificallyforthepurposeofrunningXBMC.ThePiscompactsize,lowcost,supportforUSBdevicesandnetworking,andbuilt-inHDMIoutputmakeitanexcellentchoiceforamediaplayerthatsitsnexttotheTVanddoesnottakeupalotofspace.ThecurrentversionofXBMCfortheRaspberryPiis13.2Gotham.WhentheXBMCFoundationreleaseversion14ofthesoftware,theywillrenameXBMCtoKodi.
Inthischapter,youcanseehowtoinstallXBMConyourPi.Youwillalsolearnthebasicsofhowtoworkwiththeuserinterface,andhowtoaddmediafilestothesystem.
Tocompletethistutorial,youneed:ARaspberryPi(anymodel)connectedtoyourlocalnetworkandwithaccesstotheInternet.Akeyboardandmouse.AUSBstoragedevice,suchasamemorystickorharddrive.1.ForthecompletelistofcontainerformatsandcodecsthatXBMCsupports,seehttp://wiki.xbmc.org/index.php?title=Features_and_supported_formats
-
3.2Installation
IfyouhaveablankSDcardthatyouwillbeusingforyourmediacenterthenyoucaninstalltheoperatingsystemandXBMCtogether.RaspBMCandOpenELECaretwoLinuxdistributionsthatalreadycontainXBMC,andyoucaninstallthesefromNOOBS.FormoreinformationaboutinstallingoperatingsystemsusingNOOBS,seesection2.2InstallationofRaspbianwithNOOBSonpage16.
TostartNOOBSwhenanexistingOSisalreadyontheSDcard:turnoffthePi,andthenholdtheShiftkeyasyouturnthePibackonanduntilyouseetheNOOBSwindow.NOOBScaneitherremoveyourexistingOS,oraddRaspBMCorOpenELECasanadditionaloption.ToremoveanOS,unchecktheboxnexttoitbeforeyouclickInstall.IfyouleaveyourexistingOSontheSDcard,youwillbeaskedtochoosewhichoneyouwanttoloadwhentheRaspberryPistartsup.
IfyoucannotuseNOOBS,youcanalsodownloaddiskimagesofthedistributionsfromhttp://www.raspberrypi.org/downloads/andthenrefertosection2.3InstallationofRaspbianusingaDiskImageonpage20formoreinformationabouthowtowritethefiletoanSDcard.
IfRaspbianisalreadyinstalledonyourcardandyouwanttoaddXBMCtoit,installingXBMCusuallyonlytakesafewminutes.Tobegin,youneedtoaddMichaelGorvensrepositorytothelistofapplicationsourcesinLinux:
1.OntheLXDEpanel,clicktheMenubutton,pointtoAccessories,andthenclickRootTerminal.
2.TypethefollowingcommandandthenpressEnter:nano/etc/apt/sources.list.d/mene.list3.Typethefollowingtextasthefirstlineinthefile:debhttp://archive.mene.za.net/raspbianwheezycontrib4.PressCtrl+O,andthenpressEnter.5.PressCtrl+X.6.Typethefollowingcommandononeline,andthenpressEnter:apt-keyadvkeyserverkeyserver.ubuntu.com-recv-key5243CDED7.TypethefollowingcommandandthenpressEnter:apt-getupdateToinstallXBMCfromthecommandline:TypethefollowingcommandandthenpressEnter:apt-getinstallxbmc
XBMCdoesnotworkcorrectlyif64MBorlessmemoryisallocatedtotheGPU.AsthisisthedefaultsettingforRaspbianinstallations,youneedtochangeitinraspi-config:
IntheRootTerminal,typethefollowingcommandandthenpressEnter:raspi-configor,ontheLXDEpanel,clicktheMenubutton,andclickRun.TypethefollowingcommandandthenpressEnter:sudoraspi-config
WhentheRaspberryPiSoftwareConfigurationToolappears:
1.PresstheDownArrowkeyrepeatedlyuntilAdvancedOptionsishighlighted,and
-
thenpressEnter.2.PresstheDownArrowkeytwicetoselectA3MemorySplit.PressEnter.3.Changethevalueto128andthenpressEnter.4.PresstheRightArrowkeytwicetoselect.ThenpressEnter.5.PressEntertoselectandrebootthePi.
RunningXBMCXBMCisastandaloneapplicationanddoesnotrunthedesktopenvironment.Torunit,youmustdropbacktothecommandline:pressCtrl+Alt+F1.Toreturntothedesktopenvironment,pressAlt+F7.
TostartXBMC:TypethefollowingcommandandthenpressEnter:xbmc-standalone
However,startingXBMCthiswayreducestheamountofmemoryandsystemresourcesavailabletoit.IfyouwanttouseyourRaspberryPiasadedicatedmediaplayerandautomaticallyrunXBMCwhenitstartsup:
1.OnacommandlineorLXTerminal,enterthefollowingcommandandpressEnter:sudonano/etc/default/xbmc2.ChangeENABLED=0toENABLED=13.ChangeUSER=xbmctoUSER=pi4.PressCtrl+X,thenpressY,andthenpressEnter.5.TypethefollowingcommandandthenpressEnter:sudoraspi-config6.PresstheDownArrowkeytwicetohighlightEnableboottoDesktop/ScratchandthenpressEnter.7.HighlightConsoleTextconsole,requiringlogin(default)andthenpressEnter.8.PresstheRightArrowkeytwicetohighlight,andthenpressEnter.9.PressEntertoselect.
-
3.3FirstSteps
OnceXBMCisfinishedloaded,youshouldseeascreensimilartoFigure1below.
Figure1.TheXBMChomescreen
1Recentvideos.WhentheMoviesorTVShowsmenuoptionishighlighted,XBMCwillshowthefilesthathavemostrecentlybeenaddedtoyourlibrary.Youcanclickoneoftheseitemstostartplaying.
2Mainmenu.
3Favorites.Clickthisbuttonforquickaccesstoitemsthatyouhaveplacedinyourfavoriteslist.Toaddanitemtoyourfavorites,rightclickittoopenitscontextmenu.
4Exit.TocloseXBMCandreturntotheLinuxcommandline,clicktheExitbutton,andthenclickExit.
AllofXBMCsfeaturescanbeaccessedusingitsmouse-drivenmenusystem,yougenerallyonlyneedtousethekeyboardfortypinginconfigurationsettings.
Tocontrolthehomescreenmenu:Movethemousepointertothefarleftandfarrightsidesofthemenutoscrollit.Pointtoamenuitemtobringupanyoptionsthatareavailableinthatcategory.
Clickamenuitem(oroptionunderneath)toopenit.Mostmenuitemsopenadifferentscreenwhenyouclickthem.Tocontrolthesescreens:
Clickwiththeleftmousebuttontoactivatemenuitemsandbuttons.
Right-clickanareaofthescreenthatdoesnotcontainamenuitemorbuttontomovetothepreviousscreen.
Right-clickamediafileorfoldertobringupacontextmenuwhichhasadditionaloptionsthataffecttheselecteditem.
Toopenthesidebar,movethemousepointerovertothetabontheleftsideofthescreen.Toclosethesidebar,movethemousepointerawaytotheright.
ClicktheBackbuttontoreturntothepreviousscreen.ClicktheHomebuttontoreturntothehomescreen.
-
Figure2.TheMoviesbrowserandthesidebar
XBMCdividesmediafilesintocategoriesdependingonwhethertheyareamoviefile,anepisodeofaTVshow,amusicfile,apictureorphoto,oraprogram.Thedifferenttypesoffileareaccessedusingdifferentmenuitemsonthehomescreenmenu.
ChangingtheXBMCSkinTheRaspberryPiversionofXBMCusesaninterfacetheme(orskin)calledConfluence.Ifyouwanttochangethis,youcandownloadnewskinsdirectlyfromtheXBMCsystemsettings.
Todownloadandenableanewskin:1.OntheXBMCHomescreen,clickSystem.
2.ClickAppearance,andthenclickthefirstitemintherightpanel.ThisitemhasthewordSkinononeside,andConfluenceontheorder.
3.ClickGetMore4.Pointtoeachskintoloadapreviewanddescription.5.Todownloadaskin,clickit,andthenclickInstall.6.Whenaskedifyouwanttoswitchtothisskin,clickYes.TochangetheskinbacktoConfluence:1.OntheXBMCHomescreen,clickSystem.2.ClickAppearance,andthenclickthefirstitemintherightpanel.3.ClicktheConfluenceskin.
ThebasiccontrolsforusingXBMCdonotchangewithdifferentskins.However,thelayout,colors,andthewaymediafilesaredisplayedandpreviewedcanchange.
-
3.4MediaFilesandtheLibrary
UsingXBMC,youcanviewfilesfromUSBdevices(suchasmemorysticksandharddrives)oroveryourlocalnetwork.
Inadditiontobrowsingforfileseachtimeyouwanttoplaysomething,youcanadddevicesandnetworkfolderstoyourXBMClibrary.Thelibraryisalistofallofthefilesthatyouhaveavailable,andusuallycontainsextrainformationsuchaspreviewimagesanddescriptions.
Notethatevenifyouaddafiletoyourlibrary,itisstillstoredontheoriginaldeviceandwillnotbeavailableifthatdeviceisunpluggedorturnedoff.
PlayingMediaFilesfromUSBDevicesKeepingyourmediafilesonUSBstoragedevicesmeansthatyouarenottakingupspaceontheSDcardusedtorunXBMC.AndyoucanremoveUSBdevicesatanytimemakingthisaconvenientwayoftransferringfilesfromyourPCtobeplayedonyourmediabox.
Toplayafilewithoutaddingittoyourlibrary:
1.InserttheUSBdeviceintoafreeUSBslotonthePiorUSBhub.YoucandothiswhenthePiisonandrunningXBMC.
2.OntheXBMCHomescreen,pointtoVideosandthenclickFiles.3.ClicktheUSBdevicethatcontainsthefileyouwanttoplay.4.Browsetothefileandthenclickit.
AddingFilestoyourLibraryYourXBMClibraryismadeupofalistofsources,andinformationaboutthemediafilesthatyouhaveonyoursystem.AsourceisXBMCstermforafilepaththatitremembersbetweensessions,andthatitassociateswithaparticulartypeofcontent(forexample,amovie).WhenXBMCupdatesyourlibrary,itopenseachsourcefolderandexaminesallofthecompatiblemediafilesinside.
Duringthisprocess,XBMCrunsspecialprogramscalledscrapers.Theseadd-onsfindtheinformationaboutthefilesinyourlibraryandforthistowork,thefilenamesofmoviesandTVshowsthatyouwanttoaddmustfollowasetpattern.Ifthescrapercannotidentifythefilefromthefilename,XBMCwillnotaddthefiletoyourlibrary.
Theinstructionsbelowareanexampletogetyoustarted;formoredetailedinformation,seehttp://wiki.xbmc.org/index.php?title=Naming_video_files
IfyourUSBdevicecontainsmoviefilesandTVshows,createtwosubfoldersonthedeviceanduseoneformovies,andtheotherfortheTVshowepisodes.
Whennamingmoviefiles,usethepattern:Title(Year).extForexample:HouseOnHauntedHill(1999).mp4ToaddthemoviesfolderontheUSBdeviceasasource,andloadthefilesintoyourlibrary:
1.InserttheUSBdeviceintoafreeUSBslotonthePiorUSBhub.YoucandothiswhenthePiisonandrunningXBMC.
-
2.OntheXBMCHomescreen,pointtoVideosandthenclickFiles.
3.ClickAddVideosandthenclickBrowse.4.ClickRootfilesystem.
5.Clickmedia,andthenclickthenameoftheUSBdevice.
6.Clickthemoviesfolder,andthenclickOK.7.ClickOK.
8.FromtheThisdirectorycontainslist,select(Movies).
9.UnderChooseaScraper,clickTheMovieDatabase(oranotherscraperifyouhavealreadyinstalledone).
10.ClickOK.11.Ifyouareaskedwhetheryouwanttorefreshinfoforallitems,clickYes.IfTheMovieDatabasescrapercannotfindyourmovieinitslistings,XBMCwillnotaddthefiletoyourlibrary.Thereareotherscrapersavailableandyoucaninstalltheminsection3.6Add-onsonpage65.
ToaddTVshowstoyourlibrary,itisadvisabletocreateadirectorystructureinsidetheTVshowfolderontheUSBdevice.
CreateafolderforeachTVseries.Forexample,createafoldercalledTheAddamsFamily.Thencreatesubfoldersinsidethatforeachseason.Forexample,TheAddamsFamily/Season1andTheAddamsFamily/Season2.
Placethevideofilesforeachseasoninthecorrectsubfolder,andnameeachfilewiththepattern:AnythingIncludingSpaces_sXXeYY.ext.ReplaceXXwiththeseasonnumber,andYYwiththeepisodenumber.Forexample:TheAddamsFamily_s01e01.mp4
ToaddtheTVshowsfolderontheUSBdeviceasasource,andloadthefilesintoyourlibrary:
1.InserttheUSBdeviceintoafreeUSBslotonthePiorUSBhub.YoucandothiswhenthePiisonandrunningXBMC.
2.OntheXBMCHomescreen,pointtoVideosandthenclickFiles.
3.ClickAddVideosandthenclickBrowse.4.ClickRootfilesystem.
5.Clickmedia,andthenclickthenameoftheUSBdevice.
6.ClicktheTVshowsfolder,andthenclickOK.7.ClickOK.
8.FromtheThisdirectorycontainslist,select(TVShows).
9.UnderChooseaScraper,clickTheTVDB(oranotherscraperifyouhavealreadyinstalledone).10.ClickOK.
11.Ifyouareaskedwhetheryouwanttorefreshinfoforallitems,clickYes.Ifthescrapercannotfindyourfileinitslistings,XBMCwillnotaddthefiletoyourlibrary.ThereareotherscrapersavailableandyoucaninstalltheseusingtheAdd-onsmenu.
-
Playingandaddingmusicfilestoyourlibraryworksinthesameway.OntheHomescreen,pointtoMusicandthenclickFiles.
RemovingUSBDevicesMakesurethatyouproperlyejectUSBdevicesfromthesystem.ThisprocessstopsXBMCfromreadingorwritingtothedevicewhileyouunplugit,andensuresthatallofthechangesthatneedtobemadetothefilesystemarecompleted.
TosafelyremoveaUSBdevice:1.OntheXBMCHomescreen,pointtoVideosandthenclickFiles.2.Right-clickthedevice,andthenclickRemovesafely.3.RemovetheUSBdevicefromtheUSBsocket.
IftheUSBdevicecontainsthefilesforitemsinyourlibrary,thoseitemswillbeunavailableuntilyouplugthedevicebackintoyourPi.
PlayingVideosfromYourLibraryOnceyouhaveaddedsomevideostoyourlibrary,youcanaccessthemfromtheXBMChomescreen.Toplayamovie,either:
OntheXBMCHomescreen,pointtoMovies,andthenclickthepreviewofthefilethatyouwanttoplay;orOntheXBMCHomescreen,clickMoviestoloadthemoviebrowser.
Ifyouusethemoviebrowser,clickthenameofamovietostartplaying,orright-clickthemovieandthenclickMovieinformationtobringupawindowcontainingalltheinformationthatthescrapercouldfindoutaboutthatfile.
Figure3.ThemovieinformationdisplayToplayaTVshow,either:
OntheXBMCHomescreen,pointtoTVShows,andthenclickthepreviewofthefilethatyouwanttoplay;or
-
OntheXBMCHomescreen,clickTVShowstoloadtheshowbrowser.
IfyouusetheTVshowbrowser,clickthenameofaseriestoloadtheepisodesorright-clickitandthenclickTVshowinformationtoviewthedetailsofthatseries.Clickanepisodetostartplaying,orright-clicktheepisodeandthenclickEpisodeinformationtobringupawindowcontainingalltheinformationthatthescrapercouldfindoutaboutthatparticularepisode.
-
3.5NetworkDevicesandOtherComputers
ConnectingtoSMBSharesServermessageblock(SMB)isanetworkingprotocolforsharingprinters,files,andfoldersbetweendevicesonalocalnetwork.Itisawell-establishedsystem,andsupportforitisbuilt-inonmostpopularoperatingsystems.UsingSMB,XBMCcanaccessfoldersonyourWindows,MacOSX,orLinuxPCsasiftheywerelocaldevices.
SMBsharesmustbeaddedtoXBMCassources,andsoitisusuallyusefultohaveyourmovies,TVshows,music,andpicturesseparatedintodifferentfolders.
TocreateanewsharedfolderonWindows(8/7/Vista/XP):1.PresstheWindowslogokey+R.TypeexplorerandthenpressEnter.
2.BrowsetoalocationonyourPCthateitheralluserscanaccess(suchasanextraharddrivepartition)orthatbelongstotheuserthatiscurrentlyloggedin.
3.Right-clickintherightpanel,pointtoNew,andthenclickFolder.4.Typeaname(forexample,Videos)andthenpressEnter.5.Right-clickthefolder,andthenclickProperties.6.OntheSharingtab,underNetworkFileandFolderSharing,clickShare.
7.IntheFileSharingwindow,clickShare.8.ClickClose.
9.InWindowsExplorer,double-clickthefolder.Right-clickintherightpanel,pointtoNewandthenclickFolder.Typeaname(forexample,Movies)andthenpressEnter.
10.Right-clickintherightpanel,pointtoNewandthenclickFolder.Typeaname(forexample,TVShows)andthenpressEnter.
11.Copyormoveyourmoviefilesintothemoviesfolder,andTVshowepisodesintotheTVshowsfolder.
TocreateanewsharedfolderonMacOSX(10.5orlater)usingGuestSharing:
1.Onthedock,clickFinder.2.Browsetoyourhomefolder.
3.OntheFilemenu,clickNewFolder.Typeaname(forexample,Videos)andpressEnter.4.Clickthisfolder.5.OntheFilemenu,clickNewFolder.Typeaname(forexample,Movies)andpressEnter.6.OntheFilemenu,clickNewFolder.Typeaname(forexample,TVShows)andpressEnter.
7.Copyormoveyourmoviefilesintothemoviesfolder,andTVshowepisodesintotheTVshowsfolder.
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,addtheSMBshareasanXBMCvideosource:
1.OntheXBMCHomescreen,clickVideos.2.ClickAddVideosandthenclickBrowse.3.ClickAddnetworklocation14.IntheProtocollist,clickWindowsnetwork(SMB).5.NexttoServer,clickBrowse.
6.Clickthenameofyourworkgroup,andthenclickthenameoftheWindowsPCorMac.
7.IntheUsernamebox,typeyourWindowsusername(orthenameofauseraccountthathasaccesstothesharedfolder.)DonotenterausernameifyouareusingGuestSharingonMacOSX10.5orlater.
8.InthePasswordbox,typethepasswordforthatuser.9.ClickOK.10.Clickthenewnetworklocation.Thisissmb://,followedbythenameofyourPCorMac.
11.Browsetoyourmoviesfolderandthenclickit.12.ClickOK.13.ClickOK.
14.FromtheThisdirectorycontainslist,select(Movies).
15.UnderChooseaScraper,clickTheMovieDatabase(oranotherscraperifyouhavealreadyinstalledone).
16.ClickOK.17.Ifyouareaskedwhetheryouwanttorefreshinfoforallitems,clickYes.
ToaddtheTVshowsfolder,repeatthisprocessbutselect(TVShows)fromtheThisdirectorycontainslistandTheTVDBscraperfromtheChooseaScraperlist.1.TheAddnetworklocationoptionallowsformorecontrolovertheusernameandpasswordthantheWindowsnetwork(SMB)option.
XBMCsscraperswillattempttoaddthefilesfromyoursourcestoyourlibrary.ThismeansthatthefilesinyoursharedfoldermustfollowthenamingconventionsdescribedinAddingFilestoyourLibraryonpage54.
Ifthescrapercannotfindinformationaboutthefile,XBMCdoesnotaddthefiletoyourlibrary.However,youcanstillusetheVideosfilebrowsertoaccessanyfilesthatwerenotadded.
ThemostcommoncauseofproblemswhencreatingSMBsharesandaddingthemto
-
XBMCisuserpermissions.Ifyoucannotconnecttoyourshare,orcannotseethefilesinsideit,thenchecktheuseraccountpermissionsonyourPCorMac.Ifnecessary,youcandeleteasourceandstartover.
Todeleteasource:1.OntheXBMCHomescreen,pointtoVideos,andthenclickFiles.2.Right-clickasource,andthenclickRemovesource.
ConnectingtoUPnPDevicesUniversalplugandplay(UPnP)isacollectionofnetworkingprotocolsthatallowsdevicesonalocalnetworktofindeachother,tofindoutwhattypeofservicesandfilesotherdevicesoffer,andtosharethosefiles.
YoucansetupyourPCorMacsothatXBMContheRaspberryPicanplaythemediafilesfromit.OnMacOSXandLinuxmachines,youwillneedtoinstallandconfigureaUPnPmediaserver,suchasMediaTomb(http://www.mediatomb.cc).MicrosoftWindowshasabuilt-inUPnPserver,butthisisusuallydisabledwhentheoperatingsystemisinstalled.
ToenabletheUPnPserveronWindows(8/7/Vista):
1.PresstheWindowslogokey+R.Typecontrol.exe/nameMicrosoft.NetworkAndSharingCenterandthenpressEnter.
2.OnWindows8/7:clickChangeadvancedsharingsettings.OnWindowsVista:clickthearrowtotherightofNetworkDiscovery.
3.ClicktheboxnexttoTurnonnetworkdiscovery,andthenclickSavechanges(orApplyonVista).ToenabletheUPnPserveronWindowsXP:1.PresstheWindowslogokey+R.Typeappwiz.cplandthenpressEnter.
2.ClickAdd/RemoveWindowsComponents.3.ClickNetworkingServices,thenclickDetails.
4.Ifitisnotselected,clicktheboxnexttoInternetGatewayDeviceDiscoveryandControlClient.5.Ifitisnotselected,clicktheboxnexttoUPnPUserInterface.
6.ClickOK.7.ClickNext.
8.PresstheWindowslogokey+R.Typeservices.mscandthenpressEnter.9.Double-clickSSDPDiscoveryService.10.OntheGeneraltab,intheStartuptypelist,clickAutomatic.11.ClickOK.12.RestartyourPC.
UPnPdevicesandtheirfoldersshouldbeaddedtoXBMCassources.AlthoughfilesstoredonthesetypesofdevicescannotbeaddedtotheXBMClibrary,theycanstillbeaccessedusingthevideosandmusicfilebrowsers.
Toaddavideosource:
1.OntheXBMCHomescreen,clickVideos.2.ClickAddVideosandthenclickBrowse.
3.ClickUPnPDevices,andthenclickthenameofyourdevice.
-
4.Browseintoafolder,ifyouwanttoadditanditssubfoldersonly.5.ClickOK.6.ClickOK.Toaddamusicsource:
1.OntheXBMCHomescreen,clickMusic.2.ClickAddMusicandthenclickBrowse.
3.ClickUPnPDevices,andthenclickthenameofyourdevice.4.Browseintoafolder,ifyouwanttoadditanditssubfoldersonly.5.ClickOK.6.ClickOK.
IfyourUPnPdeviceappearsintheUPnPDeviceslistbutyoucannotopenittobrowseitscontent,thereareafewthingstocheck:
IfyouarerunningafirewallonaWindowsPCwithUPnPenabled,youmayneedtocreateanexceptionfortheWindowsMediaPlayerNetworkSharingServiceorUPnPFramework.
OnWindows,placeyourvideoandmusicfilesintheVideosandMusicfoldersoftheuserthatiscurrentlylogged-in.CheckthattheWindowsuserEveryoneisabletoreadfromthosefolders.
Checkthatyournetworkrouterallowsdevicesonyournetworktotalktoeachother.Updateyouroperatingsystemtothelatestversion.UpdateXBMCtothelatestversion.
-
3.6Add-ons
Add-onsextendthefunctionalityofXBMCinuniqueways,andtherearemanyadd-onsavailable.Thesevaryfrommakingsmallchangestotheinterface,tolettingyouwatchliveTVandstreamvideosovertheInternet.
Todownloadandinstallanadd-on:1.OntheXBMCHomescreen,pointtoSystem,andthenclickSettings.2.ClickAdd-ons.3.ClickGetAdd-ons,andthenclickXBMC.orgAddons.
4.Clickthetypeofadd-onthatyouwanttoinstall.Forexample,VideoAdd-onsaddnewwaysofwatchingvideos.
5.Inthelistofavailableadd-ons,clickonetobringupadescription.6.ClickInstalltodownloadandinstalltheadd-on.
InstallingMovieInformationAdd-onsMovieinformationadd-onsareatypeofextensionforfindinginformationaboutthevideofilesinyourlibrary.Bydefault,thescraperthatfindsinformationaboutyourmoviefilesusesTheMovieDatabasewebsite.Toinstalladifferentmoviescraper,andconfigureavideosourcetouseit:
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-onsProgramadd-onsarepowerfulextensionsthatincludeprogramsforaccessingthewebandsocialmediasites,clientsforfilesharingandfilehostingservices,backuputilities,andeventorrentclients.
Toopenthelistofprogramadd-ons:1.OntheXBMCHomescreen,pointtoSystem,andthenclickSettings.2.ClickAdd-ons.3.ClickGetAdd-ons,andthenclickXBMC.orgAddons.4.ClickProgramAdd-ons.
-
3.7RemoteControls
XBMChasabuilt-inwebserverthatyoucanusetocontrolit.ThisturnsanydevicewithawebbrowserintoaremotecontrolforXBMC.Therearealsoseveralremotecontrolappsavailableforsmartphonesandtablets.TheseappsusuallytalktoXBMCusingthewebserver.
Toenablethewebserver:
1.OntheXBMCHomescreen,clickSystem.2.ClickServices.3.ClickWebserver.
4.EnsureAllowcontrolofXBMCoverHTTPisselected.5.InthePortbox,typeaportnumber.Thisnumbermustbeover1024.6.IntheUsernamebox,typexbmc.7.InthePasswordbox,typeapasswordthatyouwanttouse.8.PresstheBackorHomebuttonstoleavethesystemsettings.
ToconnecttoXBMC,youneedtoknowitsIPaddressonyourlocalnetwork.TheIPaddressisshownintheSummaryandNetworktabsoftheSysteminfoscreen.Tofindthis:
OntheXBMCHomescreen,pointtoSystem,andthenclickSysteminfo.
Testtheremotecontrolfeaturebyopeningawebbrowseronadeviceonyourlocalnetwork.Intheaddressbar,typehttp://followedbytheIPaddressoftheRaspberryPi,thenacolon,andthentheportnumberthatissetintheXBMCsettings.
Forexample,toaccesstheremotecontrolwebinterfaceoverport8080onaPiwiththeIPaddress192.168.0.9,typehttp://192.168.0.9:8080
Loginwiththeusernamexbmc,andthepasswordthatyousetintheXBMCsettings.
IfyoucannotconnecttoXBMC,firstcheckthattheRaspberryPihasanactivenetworkconnectionandthenverifythattheconnectionsettingsyouareusingmatchthosethatyouenteredintheXBMCsettings.Ifyoustillcannotconnect,tryadifferentportnumber.
-
Figure4.TheXBMCwebinterface
Touseasmartphoneortabletapp,youwillneedthesamedetailsthatyouusedtoaccesstheremotecontrolwithawebbrowser.AppsareavailableforiOS,Android,andWindowsPhone.However,theOfficialXBMCRemoteappisonlyavailableforiOSandAndroiddevices.
Atthetimeofwriting,thecurrentversionoftheOfficialXBMCRemotehasafewproblems.Butdevelopersupdateappsextremelyfrequently,andtheissuesmaybefixedbythetimeyoureadthis.Ifyoucannotgettheofficialappworking,searchyourdevicesappstoreandyouwillfindmanyotherstotry.
-
4ProgrammingwithScratchScratchisavisualprogramminglanguagethathelpsteachtheconceptsofprogrammingtopeoplewhohaveneverworkedwithtraditionalprogramminglanguages.Itisaimedprimarilyatpeoplewhowanttolearntobuildsmallgames.However,thecombinationofitssimpleinterfaceandrichfeaturesetalsomakeitusefulforpresentations,simulations,andprototypesofsoftwarethatwillbeimplementedinotherlanguages.ThecurrentversionofScratchfortheRaspberryPiis1.4.Version2.0ofScratchisavailableonmanyplatforms,however,itisnotcompatiblewiththePi.
-
4.1TheUserInterface
TostartScratchonRaspbian:Onthedesktop,double-clickScratch;orOntheLXDEpanel,clicktheMenubutton,pointtoProgramming,andthenclickScratch.TheScratchwindowisdividedintoseveraldistinctareas:
Figure1.ScratchonRaspbian1CursorTools.Thesebuttonsareforduplicating,deleting,growing,andshrinkingthespritesonthestage.Clickthecursortool,andthenclickaspritetoactivatethefunction.
2Menu.3BlocksPalette.
4ScriptsArea.ThisiswhereyoucombineblockstocontrolthespritethatisselectedintheSpriteList.5SpriteList.Allofthespritesinyourprojectareshownhere.Clickaspritetoshowthescriptsthatyouhaveaddedforaparticularsprite.6Stage.Thisiswhereyourspritesmoveandinteractwitheachother.
ThekeyconceptbehindScratchisthateverythingyouneedtomove,animate,orcontrolisasprite.Eachspriteisacollectionofimagesandscripts,andisindependentofalloftheothers.YoucombinethecoloredblocksfromtheBlocksPalettetosetthebehaviorofaspecificsprite.
OpeningandSavingProjectsScratchprojectsaresavedinaspecialfileformatthatusestheextension.sb.ThesefilescontainallofthegraphicsandsoundfilesthatyouimportintoScratch,andallofthescriptsthatyoucreate.
Tosaveaprojecttoanewfile:1.OntheMenubar,clickFile,andthenclickSaveAs2.IntheNewFilenamebox,typeanameforyourprojectandthenclickOK.
-
Ifyouhavepreviouslysavedyourprojectandyouwanttosaveitagain:OntheMenubar,clicktheSavethisprojectbutton(itlookslikeafloppydisk);orOntheMenubar,clickFile,andthenclickSave.Toclosethecurrentprojectandopenanother:1.OntheMenubar,clickFile,andthenclickOpen2.Browsetothefilethatyouwanttoopen,clickit,andthenclickOK.
UsingtheStageAllofthespritesinyourprojectappearontheStage,andthisiswhereallofyouractionsandscriptstakeplace.AspritecannotcompletelyleavetheStage,however,youcanhidespritesthatarenotneededatspecificpartsofyourproject.
InScratch,theStageisalways480stepswideand360stepstall.Itneverchangessize,itnevermoves,anditneverresets.Forexample,onceaspritemovesitremainsatthatpositiononthestageuntilanotherscriptmovesit.Thepositionofeachspriteisdescribedwithacoordinatetwonumbers,onethatrepresentsthehorizontalposition(x)andonethatrepresentstheverticalposition(y).Thetop-leftoftheStageis-240,180,thebottomrightoftheStageis240,-180,andthismakesthecenteroftheStage0,0.
IntheSpriteList,thereisanimagefortheStage.Ifyouclickthis,youcanaddblockstotheStageitself.WhentheStageisselected,thetabsatthetopoftheScriptsAreachange.
YoucanchangethebackgroundoftheStagefromtheBackgroundstab.YoucaneitherusethePaintEditortodrawanewbackground(ThePaintEditorisdescribedinsection4.9ThePaintEditoronpage89),orimportgraphicfiles.Importedgraphicsshouldbe480pixelswideand360pixelstall,orScratchwillpositiontheminthecenteroftheStagesurroundedbybordersofthecurrentbackgroundcolor.
YoucanhavemultiplebackgroundsinaScratchproject,butonlyonecanbevisibleatatime.YoucannotmovebackgroundsinScratch,soifyouwantareasofthebackgroundtomovethenyouhavetocreatethemassprites.
BuildingandRunningScriptsThissectiondescribeshowtoworkwithblocksfromtheBlocksPalettetocreatescriptssequencesofblocks.Eachsprite(andtheStageitself)cancontainmanyscripts.
ToattachablocktoaspriteortheStageitself,selectitintheSpriteListandthendragblocksfromtheBlocksPalettetotheScriptsArea.Forexample:
1.IntheSpriteList,clickStage.2.IntheBlocksPalette,clickControl.
3.Clicktheblockwhenclickedand,whileholdingthemousebutton,dragtheblockovertotheScriptsArea.Releasethemousebutton.
4.IntheBlocksPalette,clickLooks.
5.Dragtheblockchangecoloreffectby25totheScriptsAreaandunderneaththeotherblock.Thewhitelineindicatesthatthisblockwillsnaptogetherwiththeoneaboveit.Releasethemousebutton.
6.IntheScriptsArea,ontheblockchangecoloreffectby25,clickcolor,andthenclickbrightness.7.Ontheblockchangebrightnesseffectby25clickthewhiteboxthat
-
contains25.Changethisto-25.8.IntheBlocksPalette,clickControl.
9.Dragtheblockwait1secstotheScriptsAreaandsnapittothebottomoftheblockchangebrightnesseffectby-25.
10.Ontheblockwait1secs,clickthewhiteboxthatcontains1.Changethisto0.5.11.IntheBlocksPalette,clickLooks.
12.Dragtheblockchangecoloreffectby25totheScriptsAreaandsnapittothebottomofthewaitblock.
13.Ontheblockchangecoloreffectby25,clickcolor,andthenclickbrightness.Figure2.Ashortscript
AbovetheStage,therearetwobuttons:thegreenflagbuttonstartsallscriptsintheproject,andtheredoctagonstopsallofthescripts.
Thefirstblockthatisinthescript,whenclicked,statesthatthescriptshouldrunwhenthegreenflagbuttonabovetheStageisclicked.Clickthegreenflagbuttonnowandyoushouldseethatthebackgroundbrieflychangescolor.ToDoThisRunascript(fortesting)IntheScriptsArea,double-clickanyoftheblocksinthescript.
InsertablockaboveanexistingblockIntheBlocksPalette,dragablockovertotheScriptsAreaandoverthetopofanexistingblock.Thewhitelineindicateswheretheblockwillbeinserted.
Detachablock(andanyblocksthatfollowit)fromascriptIntheScriptsArea,clicktheblockanddragitawayfromtheblockaboveit.Alloftheblocksbelowtheselectedblockwillmovewithit.
Removeablock,aseriesofconnectedblocks,orascriptfromtheproject
IntheScriptsArea,clickthefirstblockintheseriesthatyouwanttoremoveanddragitovertotheBlocksPalette.
ToDoThis
Duplicateablock,aseriesofconnectedblocks,orascriptIntheScriptsArea,right-clickthefirstblockintheseriesthatyouwanttocopy,clickduplicate,andthenclickintheScriptsAreatopositionthenewblocks.
FittingtheBlocksTogetherScratchusesthecolorandshapeofblockstoindicatehowtheycanbeconnectedtoeachother.Blockswithacurvedtop,suchasthewhenclickedblock,arethestartofascriptandcanonlyhaveblocksconnectedunderneaththem.Figure3.Youcanonlysnapinblocksbelowthisone,notabove.
Anotchinthetopofablockindicatesthatitcanbeattachedtoblocksaboveit.Atabonthebottomindicatesthatyoucansnapotherblocksintopositionbelowit.Figure4.Ablockthatallowsotherblockstobeconnectedontop,orunderneath.
Aneight-sidedwhiteboxintheblockmeansthatyoucantypenumbersinthere,butalsothatyoucanaddvariablesandblocksfromtheOperatorssectionoftheBlocksPalette.
Touseanoperatororvariableblockinsteadofanumber:Draganeight-sidedblockfromtheBlocksPalette,intotheScriptsArea,andoverthewhitebox.
-
Someblockshavesquareboxesthatyoucantypein.Theseacceptnumbers,strings(sequencesofcharacters),variables,andeight-sidedoperatorblocks.
BlockslikeifintheControlsectionoftheBlocksPalettehavespacesforsix-sidedblocks.Six-sidedblocksrepresentthevaluesYesorNo,orTrueorFalse.Thesearedescribedinmoredetailinsection4.4Decisionsonpage82.
-
4.2Sprites
InScratch,youwillspendthemajorityofyourtimemovingandchangingtheappearanceofspritesinresponsetokeypresses.
AddingandRemovingaSpriteToaddaspritetothecurrentprojectandmakeitappearontheStage:
1.AbovetheSpriteList,nexttoNewSprite,clicktheChoosenewspritefromfilebutton.Thisisthesecondbuttoninthatarea.
2.IntheNewSpritewindow,browsetoaspritethatyouwanttoadd,clickitandthenclickOK.3.OntheStage,clickanddragthespritetoanewlocation.
Ifaspriteisthewrongsize,clickontheShrinkspriteorGrowspritebuttonintheCursorToolsareaandthenclickonthesprite:
Todeleteasprite:IntheSpriteList,right-clickaspriteandthenclickdelete.
CreatingaNewSpriteTherearetwowaysofcreatingnewspritesinScratch:youcanusethebuilt-indrawingtoolstopaintanewsprite,oryoucanimportgraphicfilesfromothertoolslikeAdobePhotoshopandKolourPaint.
Ineithercase:AbovetheSpritesList,nexttoNewSprite,clickthePaintnewspritebutton.Thisisthefirstbuttoninthatarea.
Ifyouwanttoimportagraphicfile,clickImportinthePaintEditor.Theeditorisdescribedinsection4.9ThePaintEditoronpage89.
UnderstandingCostumesInmostprojects,andespeciallyingames,youwillneedtochangetheappearanceofyourspritesastheprojectisrunning.Thesecanbeframesofananimation,asisthecasewhenthespriteiswalking.Orthesecanbealternativeversionsofthespritethatusedifferentcolorsorholddifferentweapons.
InScratch,variationsofaspriteareknownascostumes.Ifyoucreateanewsprite,itwillonlyhaveonecostume.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.
ToDoThisDeleteacostumeIntheScriptsArea,clickCostumes.Nexttothecostumethatyouwanttoremove,clickx.Editacostumeusingthebuilt-inPaintEditor
IntheScriptsArea,clickCostumes.Nexttothecostumethatyouwanttochange,clickEdit.
ScriptingYourSpritesMotionblockssetthepositionofsprites.OntheStageyoucanclickanddragspriteswhereyouwantthem,buttomovethemfromscripts(forexample,inresponsetotheuserpressinganarrowkey)youneedtouseoneofthemotionblocks.Theseare:BlockDescriptionmove?stepsMovesaspriteanumberofstepsinthedirectionitiscurrentlypointing.
turn(clockwise)?degreesRotatesaspriteanumberofdegreesinaclockwisedirection.
turn(counterclockwise)?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.Thesecanbeusedindecision-makingandarithmeticblocks.VariableDescriptionxpositionThehorizontalpositionofthespriteontheStage.ypositionTheverticalpositionofthespriteontheStage.directionThedirectionthatthespriteiscurrentlyfacing.
WhenspritesareaddedtotheStage,Scratchassumesthattheyfacetotheright.Whenyouchangethedirectionthataspritefaces,Scratchrotatesthesprite.TotellScratchthatitshouldflipaspriteandnotrotateit:
1.IntheSpriteList,clickasprite.
2.AtthetopoftheScriptsArea,nexttothepictureofthesprite,clicktheonlyfaceleft-rightbutton.Thisisthesecondbuttonofthethreethatarearrangedvertically.
TheLooksblocksintheBlocksPalettechangetheappearanceofspritesontheStage.Someoftheseblockschangeaspritescostume,andsomeofthemapplyeffects(suchasfades).switchtocostume?Setsthecostumedisplayedforthissprite.nextcostumeChangestothenextcostume.Ifthecurrentcostumeisthelastone,thefirstcostumewillbeusedinstead.say?for?secsDisplaysaspeechbubblenexttothesprite.say?Displaysaspeechbubblenexttothesprite.Thisbubbleremainsuntilyouuseasayblockwithnotext.think?for?secsDisplaysathoughtbubblenexttothesprite.think?Displaysathoughtbubblenexttothesprite.Thisbubbleremainsuntilyouuseathinkblockwithnotext.
-
change?effectby?Seebelow.set?effectto?Seebelow.cleargraphiceffectsSeebelow.changesizeby?Growsorshrinksaspritebytheamountspecified.setsizeto?%Growsorshrinksaspritebysettingitssize.Thisisapercentageofthesizeofthegraphicusedtocreatethesprite,anditcanbegreaterthan100%.showShowsthespriteontheStageifitiscurrentlyhidden.hideHidesaspriteifitiscurrentlyshown.gotofrontMovesaspriteinfrontofallothers.goback?layersMovesaspritebehindothersprites.Therearesevendifferenteffectsthatyoucanaddtosprites:EffectDescriptioncolorChangesthecolor(hue)ofasprite.fisheyeDistortsthesprite.EffectDescriptionwhirlDistortsthespriteintoaswirlarounditscenterpoint.pixelateMakesthespriteappeartobemadeupoflargerpixels.mosaicMakesthespriteappeartobemadeupsmallerclonesofitself.
brightnessWhenusedwithpositivenumbers,thisincreasesthebrightness(howclosethecolorsaretowhite).Whenusedwithnegativenumbers,thisdecreasesthebrightness(howclosethecolorsaretoblack).
ghostMakesthespritetranslucent(sothatotherspritescanbeseenthroughit)orcompletelytransparent(thespriteisinvisible).
Youcontroltheseeffectsusingthreeblocks:Tosetaneffecttoaspecificvalue,usetheset?effectto?block.
Toincreaseordecreasetheamountofaneffectthatisappliedtoasprite,usethechange?effectby?block.
Toremoveallactiveeffectsfromasprite,usethecleargraphicseffectsblock.Allspriteshavetwovariablesrelatedtotheirappearance:VariableDescriptioncostume#Thenumberofthecostumethatiscurrentlydisplayedforthissprite.sizeThesizeofaspriteontheStage.Thisisapercentageofthesizeofthegraphicusedtocreatethesprite,anditcanbegreaterthan100%.YoucanchoosewhetherScratchshoulddisplaythesevariablesontheStage.Toshowthevalueofavariable:IntheBlocksPalette,clicktheboxnexttothevariablename.ClicktheboxagaintoremovethevariablefromtheStage.
-
4.3ArithmeticandVariables
IntheOperatorssectionofBlocksPalette,thereareeightblocksthatyoucanusetoperformbasicmathoperations,suchasaddingtwonumberstogether.Theseblocksareeight-sided,greenblocksandtheyfitintoanyotherblockthatacceptsanumber.BlockDescription
?+?Addstwonumberstogether.?-?Subtractsthesecondnumberfromthefirst.?*?Multipliestwonumberstogether.?/?Dividesthefirstnumberbythesecond.
pickrandom?to?Picksarandomnumberbetweenthefirstnumberandthesecondnumber.
?mod?Performsmodulararithmeticthefirstnumberwrapsaroundifitreachesthevalueofthesecondnumber.
round?Roundsthespecifiednumbertothenearestwholenumber.?of?Selectfromarangeofadditionalmathfunctions.
Youcanusearithmeticoperatorblocksasinputstootherarithmeticblocks.Forexample,theexpression1+((14/3)x3.14)canbecreatedwiththreeblocks:Figure5.Nestedoperatorblocks
CreatingandUsingVariablesAvariableisanamedareaofthecomputersmemoryinwhichyoucanstorepiecesofdata.
TocreateavariableinScratch:
1.IntheBlocksPalette,clickVariables.2.ClickMakeaVariable.3.Typeanameforyourvariable.
4.Ifyouwantallspritestobeabletoaccessthevariable,clickthecirclenexttoForallsprites.5.Ifyouonlywantthisspritetobeabletoaccessthevariable,clickthecirclenexttoForthisspriteonly.6.ClickOK.
Whenyoucreateavariable,ScratchaddsablockforitintheVariablessectionoftheBlocksPalette.Theseorangevariableblockswillfitintoblocksthatacceptanumber.
TherearefourblocksintheVariablessectionoftheBlocksPaletteforworkingwithvariables:BlockDescription
set?to?Setsthevalueofavariable.change?by?Incrementsordecrementsavariable.showvariableAddsthespecifiedvariabletotheStage.hidevariableRemovestheselectedvariablefromtheStage.
-
4.4Decisions
Therearesixblocksthatyouusetocomparenumbersandmakedecisions.TheresultoftheseblocksisaBooleanvalueeithertrueorfalse..BlockDescription??Istrueifthefirstnumberislargerthanthesecond,orfalseifitisnot.?and?Istrueifthebothoftheattachedblocksaretrue,orfalseifeither(orboth)ofthemisfalse.?or?Istrueifeitherofthetwoattachedblocksistrue.Ifneitheraretrue,thenitreturnsfalse.not?Istrueiftheattachedblockisfalse,andfalseiftheattachedblockistrue.TwoblocksintheControlsectionoftheBlocksPaletteareusedwiththeBooleanoperatorblockstomakedecisions.BlockDescriptionif?Runstheblocksinsideit,iftheattachedBooleanoperatoristrue.
if?