Download BeagleBone Black Cookbook
Transcript
BeagleBoneBlackCookbook TableofContents BeagleBoneBlackCookbook Credits AbouttheAuthor AbouttheReviewers www.PacktPub.com Supportfiles,eBooks,discountoffers,andmore WhySubscribe? FreeAccessforPacktaccountholders Preface Whatthisbookcovers Whatyouneedforthisbook Whothisbookisfor Sections Gettingready Howtodoit… Howitworks… There’smore… Seealso Conventions Readerfeedback Customersupport Downloadingtheexamplecode Downloadingthecolorimagesofthisbook Errata Piracy Questions 1.SettingUpfortheFirstTime Introduction Firstbootup Gettingready Howtodoit… Gettingready Howtodoit… Powerrequirements–basicguidelines Display ConnectinganHDMILCD Howtodoit… Connectinganon-HDMILCDorcape Howtodoit… There’smore… EssentialGNU/Linuxcommands–thecommandshell Gettingready Howtodoit… Howitworks… EssentialGNU/Linuxcommands–typicalcommands Gettingready Systemnavigationalcommand–changeyourdirectory–cd Howtodoit… There’smore… Systemnavigationalcommand–showyourcurrentdirectory–pwd Howtodoit… Systemnavigationalcommand–findafile–find Howtodoit… Deviceandsysteminsight–showswhat’sinsideadirectory–ls Howtodoit… Deviceandsysteminsight–findoutwhatUSBdevicesareconnected–lsusb Howtodoit… Deviceandsysteminsight–getinformationaboutconnecteddevices– cat/proc/bus/input/devices Howtodoit… There’smore… Deviceandsysteminsight–getyourversionofLinux Howtodoit… Deviceandsysteminsight–findoutrunningprocesses–ps Howtodoit… Deviceandsysteminsight–findouttheresourcesusedbyrunningprocesses–top andhtop Howtodoit… Deviceandsysteminsight–quittingprocesses–kill Howtodoit… Deviceandsysteminsight–messagereports–dmesg Howtodoit… Deviceandsysteminsight–showsdiskspace–df-h Howtodoit… Deviceandsysteminsight–explorenetwork–Ifconfig Howtodoit… Modifycontent/datacommands–makeanewdirectory–mkdir Howtodoit… Modifycontent/datacommands–removeafileordirectory–rm Howtodoit… Modifycontent/datacommands–downloadfiles–wget Howtodoit… There’smore… Modifycontent/datacommands–openatarfile–tar[options] Howtodoit… There’smore… Modifycontent/datacommands–cleanupfiles–autoclean Howtodoit… Modifycontent/datacommands–purgeapackage–apt-getpurge,apt-getremove —purge Howtodoit… Modifycontent/datacommands–shutdownthesystem–[options] Howtodoit… Seealso Editatextfilefromthecommandshell Howitworks… Howtodoit… Seealso Connectivity Connectivity–Ethernet Gettingready Howtodoit… Connectivity–Wi-Fi Gettingready Howtodoit… There’smore… Seealso Packagemanagement–Installingpackagesusingapt-get Gettingready Howtodoit… Seealso SSH/Remoteaccess UsingSSHtocontrolyourBBB Howtodoit… UsingVNCtocontrolyourBBB Gettingready… Howtodoit… There’smore… Systemimages OSimageflashing–internaldriveboot Gettingready Howtodoit… There’smore… Expandyourpartition Backingupacodeimagetoafile OSimageflashing–theSDcardboot Gettingready Howtodoit… UpdatingyourcurrentOSkernel Seealso 2.BasicProgrammingRecipes Introduction IntroductiontoBoneScript ToggleLED Howtodoit… Seealso UsingtheCloud9IDE Howtodoit… Seealso Node.jsbasicrecipes AddinganewmoduletoNode.js Gettingready Howtodoit… There’smore… Seealso UsingNode.jswithJohnny-Five Howtodoit… There’smore… Pythonbasicrecipes Gettingready Addinglibraries Howtodoit… RunningaPythonscripttocontroltheLEDs Howtodoit… There’smore… 3.PhysicalComputingRecipesUsingJavaScript,theBoneScriptLibrary,andPython Introduction Theessentialsofelectronics Headerpinsandpinmuxing Theprocessofpinmuxing There’smore… ControllingexternalLEDs Gettingready Howtodoit… WritinganalternativescriptwithPython There’smore… Usingbuttons–buttonpressfunction Pull-up,pull-down,andfloating Gettingready Howtodoit… There’smore… Usinganalogsensors Temperaturesensors Gettingready Howtodoit… There’smore… Seealso Variableresistancesensor–photocell Gettingready Howtodoit… Usingmotors DCmotors Gettingready Howtodoit… Howitworks… Servomotors Acrashcourseinpulsewidthmodulation Gettingready Howtodoit… There’smore… 4.ExploringGNU/LinuxRecipesUsingBash,Autotools,Debugger,andsystemd Introduction Thebasicshellscript Howtodoit… EpochTimeshellscript Howtodoit… There’smore… Compileandinstall Seealso CompileandinstallGitfromsource Howtodoit… Debugging Seealso DebugasimpleC-codeapplicationfromthecommandlineusingGDB Howtodoit… Seealso DebuganapplicationremotelyfromEclipseandGDBserver Howtodoit… There’smore… systemdservices There’smore… Seealso Basiccommandsforsystemdservices Howtodoit… There’smore… Optimizeboottime Howtodoit… Createasystemdservicetorunatboottime Howtodoit… 5.BasicProgrammingRecipeswiththeLinuxKernel Introduction Kernelbuildingbasics Seealso Kernelapplicationbinaryinterface Gettingready Howtodoit… Howitworks… Installingthelatestkernelimage Gettingready Howtodoit… Installingandbuildingacustomkernel Gettingready Howtodoit… Interactionswiththekernel–sysfsentriesandcontrollingtheGPIOs Gettingready Howtodoit… There’smore… DeviceTreeanditsroots There’smore… DeviceTree/basicbuild Gettingready Howtodoit… DeviceTree/advanced–addingDToverlaytorunacustomcape Gettingready Howtodoit… There’smore… Seealso Universalcapeoverlay Gettingready Howtodoit… There’smore… RunningascripttocheckDTusageonGPIOpins Gettingready Howtodoit… 6.RunFaster,RunRealTime Introduction Installingatesttool Gettingready Howtodoit… Seealso ModifyingthekernelusingRT-PREEMPT Gettingready Howtodoit… There’smore… ModifyingthekernelusingXenomai Gettingready Howtodoit… There’smore… Seealso Programmablereal-timeunits–anintroduction Gettingready Howtodoit… AsimplePRUtestwithanassembler Gettingready Howtodoit… Seealso RunninganultrasonicrangesensorwiththePRUs Gettingready Howtodoit… UsingPythonwiththePRUs Gettingready Howtodoit… Seealso 7.AppliedRecipes–Sound,Picture,andVideo Introduction Wiringupaminiampandspeakers Gettingready Howtodoit… Creatingahigh-qualityaudioplatformwithVolumio Gettingready Howtodoit… There’smore… Seealso Usingvideosanddisplaysinprojects Gettingready Howtodoit… There’smore… TestingaminiLCDcape Gettingready Howtodoit… MakingavideochatclientprototypeusingLinphone Gettingready Howtodoit… PartI–compilingandinstallingaLinphonebinaryfromtherepository PartII–compilingandinstallingLinphonefromsource Gettingready Howtodoit… 8.TheInternetofThings Introduction Location-basedrecipes–hookingupGPS Gettingready Howtodoit… There’smore… Location-basedrecipes–BluetoothLEandBeacons Gettingready Howtodoit… There’smore… UsingsensorsanddatawithThingSpeak Gettingready Howtodoit… Seealso Makingthingssmarter–buildingawirelessdigitalpictureframe Gettingready Howtodoit… Seealso 9.TheBlackinOuterSpace Introduction GrabbingtheInternationalSpaceStationflyoverdataandvisualizingit Gettingready Howtodoit… There’smore… TrackingusingRTL-SDR Seealso AirplanetrackingwithRTL-SDR Gettingready Howtodoit… There’smore… SatellitetrackingusingGPredictandRTL-SDR Gettingready Howtodoit… There’smore… SatellitetrackingusingtheSatNogsNetworkclient/groundstationandRTL-SDR Gettingready Howtodoit… Addingotherinterfaces–ISStrackingandtexttospeech Gettingready Howtodoit… There’smore… Index BeagleBoneBlackCookbook BeagleBoneBlackCookbook Copyright©2015PacktPublishing Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem, ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthe publisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews. Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyofthe informationpresented.However,theinformationcontainedinthisbookissoldwithout warranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,andits dealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecaused directlyorindirectlybythisbook. PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthe companiesandproductsmentionedinthisbookbytheappropriateuseofcapitals. However,PacktPublishingcannotguaranteetheaccuracyofthisinformation. Firstpublished:November2015 Productionreference:1121115 PublishedbyPacktPublishingLtd. LiveryPlace 35LiveryStreet BirminghamB32PB,UK. ISBN978-1-78398-292-9 www.packtpub.com Credits Author CharlesA.Hamilton Reviewers NathanBurles AnujDeshpande DeepakKarki AgrimaSeth CommissioningEditor EdwardGordon AcquisitionEditor RichardBrookes-Bland ContentDevelopmentEditor RohitKumarSingh TechnicalEditor VijinBoricha CopyEditor ShrutiIyer ProjectCoordinator MaryAlex Proofreader SafisEditing Indexer MonicaAjmeraMehta ProductionCoordinator ConidonMiranda CoverWork ConidonMiranda AbouttheAuthor CharlesA.HamiltonistheownerofHudsonWerks,aNewYorkCity-basedDIY hardwareanddevelopmentshopfornewproducts.Passionateaboutemerging technologies,opensourcehardware,andthemakermovement,hisbackgroundasa “technologycreative”,entrepreneur,andmakerprovidesreaderswithaunique perspective. BesidesBeagleBoneBlack,Charlesworksfrequentlywithotherhardwareplatforms, includingtheRaspberryPi,Arduino,andUDOOdevelopmentboards,opensourceboard architectureandPCBdesign,micromechatronics,andsensors.Heisalsoanadvocateand keenuserofemerginglow-costmanufacturinganddesigntoolssuchas3-Dprintersand lasercutters.Amongothersubjects,Charleskeenlyfollowsadvancesanddesign challengesinthearenasofIoT,spacetechnologies,andnext-generationhealthand wellnessdevices.Hewritesandblogsathttp://www.hudsonwerks.com. HeisaformercreativedirectoratAT&TandproductdeveloperataNewYorkCity-based newproductdevelopmentagency.Charles’developmentexpertisespansdevicesinthe consumerelectronics,digitalmedia,display,voicerecognition,andtelecommunication markets.Heisalsoaproudpapatohis4-year-oldson,Hudson. IwouldfirstliketoacknowledgethesupportofJasonKridner,theTexasInstruments embeddedapplicationsEvangelistandfounderofBeagleboard.org,withoutwhomthis bookwouldneverhaveachievedliftoff.Additionally,immeasurablethanksneedtogoto JohnReavesofLearningWorldsandMasuoKitanoofSeikoEpsonCorporation,who ignitedtheprototyping-and-build-something-crazysparkinme.JonathanHirschmanof PCB:NGgaveitafurtherpushbyshowingusthewaytocookupPCBsfromscratch, literally.Finally,morethanthanksarenecessarytothetwopeoplethatshowedthegreatest forbearanceinseeingthisprojecttoitsconclusion:mywife,Mary,andlittleboy,Hudson. Withouttheirencouragement,patience,andlove,thisbookwouldneverhavehappened. Forthis,Iamhumbledandgrateful. AbouttheReviewers NathanBurlesisapostdoctoralresearcherwithaPhDincomputerscience.Heis currentlyworkingforUniversityofYorkonsubjectsasdiverseasartificialneural networks,automatedprogramming/softwareimprovement,andoptimizationforpower consumption. Inhisfreetime,Nathanenjoystinkeringwithembeddedsystemsandelectronicsranging fromfullsystems,suchasRaspberryPiandBeagleBoneBlack,tosimple microcontrollers,suchasArduino,addingcircuitrytocommunicateusing433MHzRF andinfrared. Heblogsabouthisprojectsandtopicssuchaswebsitedevelopment,Android,anddancing athttp://www.nburles.co.uk. AnujDeshpandeisafanofBeagleBoneBlackandallthingsembedded.Hedabblesin embeddedLinuxandlovestoprototypeideasandbuildinteractiveinstallations. SomeoftheprojectsthatAnujhasbeenapartofareUserspaceArduinoandTah.He completedhisbachelor’sdegreeincomputersciencefromPICT,Pune. AnujcurrentlyrunshisowndevelopmentandconsultingfirmcalledMakervilleSolutions (http://makerville.io). DeepakKarkiisasoftwaredeveloperandopensourceEvangelistbasedinBangalore, India.Heenjoysworkingwithlike-mindedhackersandisoftenaparticipantin hackathonsinandaroundthecity.Duringtheday,Deepakworksonchallenging hyperconvergenceproblemswithNutanix,andinthenight,hekeepsbusypushingcode ontoGitHub. HewasaGoogleSummerofCode(GSoC)studentforbeagleboard.orgin2014and, consequently,amentorforthesameorganizationduringGSoC2015.Deepak’smainareas ofinterestincludeSaaSapplicationdevelopment,embeddedsystems,parallelcomputing, networks,andsecurity. Lately,hehasbeenheavilyinvolvedinIoTprojectsandisworkingwithWorldWideWeb Consortium(W3C)tohelpstandardizeInternetofThingsbycontributingtotheirWoT platform. Apartfromwritingcode,Deepaklovesteachingandworkingout.Youcancatchhimat github.com/deepakkarkioron#beaglefreenodeIRCasnick:karki_. AgrimaSethiscurrentlyasenioryearstudentpursuingabachelor’sdegreeof engineeringininformationtechnologyatUniversityofPune,India.Herresearchinterests includemachinelearningandinformationretrievalsystems.Sheiscurrentlyaninternwith theSIG(GeneralizedInformationSystems)researchteamunderProfessorJosianeMothe atIRIT,France.Here,Agrimaisworkingonperformingeffectivedataindexingandquery reformulationonTRECdatasetstostudyandcreatebetterinformationretrievalsystems. ShehasbeentherecipientofSirRatanTataMemorialScholarshipandothermerit scholarships. Apartfrommachinelearning,Agrimahasalsoworkedoncomputergraphicsand computervisionatIndianInstituteofSpaceScienceandTechnology,India.Herworkis publishedatarXiv(http://arxiv.org/abs/1409.5024).Agrimahasworkedonaprojectfor ThermaxIndiaonmakingaminisolartrackerusingMSP430.Shehasbeeninvolvedin thecreationofamachinelearninggroupatherinstitutewhereshetrainedundergraduate studentsonvariousmachinelearningtechniquesandcomputergraphics.Agrimaisa voraciousreaderandatrainedIndianClassicaldancerwhoenjoysparticipatinginpublic speakingevents. Acompletelistofherworkisavailableathttp://agrimaseth.github.io,andthelatest happeningscanbereadathttps://agrimaseth.wordpress.com. IwouldliketothankmyparentsandmyHoD,DrSangeetaJadhav,forconstantly encouragingmetopursuemydreamsandworktowardsachievingexcellence. www.PacktPub.com Supportfiles,eBooks,discountoffers,and more Forsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com. DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFand ePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandas aprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwith usat<[email protected]>formoredetails. Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signup forarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooks andeBooks. https://www2.packtpub.com/books/subscription/packtlib DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigital booklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks. WhySubscribe? FullysearchableacrosseverybookpublishedbyPackt Copyandpaste,print,andbookmarkcontent Ondemandandaccessibleviaawebbrowser FreeAccessforPacktaccountholders IfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccess PacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsfor immediateaccess. Preface It’smakermadnessoutthere!SBCs,MCUs,FPGAs,PCBs,GPIOs,BeagleBoneBlack andWhites,RaspberryandBananaPis,Odroids,Udoos,Arduinos,MCUduinos, TinyDuinos… Whatdoesthisimpossiblestewofacronymsandtechnoarcanamean?Howdowemake senseofitall,especiallyifallyouwanttodoismake,invent,anddesigngreatwhizzy thingsthatgobeepandbumpandflashbrightlyorjustgrabhotdatafromtemperature sensors?Mostimportantly,whattodoifyouarenotaspecialist,anengineer,orahardcoresoftwareprogrammer? ThisisabookpreciselyforthoseofyouwhowanttoknowaboutBeagleBoneBlackbut areafraidtoask,overwhelmedbyitscomplexity,orunderwhelmedbythedearthof understandable,timelyinformationaboutthistinybutpowerfulmicrocomputer. WhyBeagleBoneBlack? Althoughmanyofthecompetingsmallboardcomputers(orSBCs)havetheirstrengths, thevirtuesofBeagleBoneBlackaresignificant: Physicalcomputingoptions:Withitshugearrayofpins,youcanwireupfarmore —beitsensors,motors,displays,orotherhardware—thanalmostanyotherboardon themarket,evenRPi. Out-of-the-boxsimplicity:AstheBBBcomespreloadedwithaLinuxOS(Debian), allyouneedtogetgoingquicklyisaminiUSBcabletopoweruptheboard.Thereis nofutzingaroundwithinstallingsoftwareoraddingperipheralstooperateit. Internaldrive:Whileothersmallboardcomputersofthisilkcanonlyrunfroman SDormicroSDboot,BeagleBoneBlackcomeswithaninternalsolid-statedrive, referredtoaseMMC,toruntheOS. Opensourcedesign:Ifyouwanttoknockitoffforacustomproject,youcandoit; allboarddesignsandschematicsarefreelyavailable. Real-timeapplications:Unlikeotherboards,suchasRaspberryPi,BeagleBone Blackhasasetofseparateprocessorsthatcanensurethatyourcoderunsrock-solid andaccordingtoyourexpectations,whichisanextremelyuniquefeaturefora computeratsuchalowpricepoint. Asyoubegintastingthevariousrecipesthroughoutthisbook,perhapsakeydifference worthkeepinginmindisthatthedesignersofBeagleBoneBlackregardtheboardasa prototypingplatformtobuildembeddedapplicationsandproducts.Anembedded computingdeviceistypicallypartofalargerelectronicssystem.Thisisquiteunlikethe designstrategyofotherboards,suchasRaspberryPi,whichisadevicespecifically createdasafull-blowndesktopsystemandtargetedatthegradeschoolmarket. Whatthisbookcovers Thisbookexploresarangeofrecipesforthenoviceuser,gainingincomplexityasthe materialprogresses.Inanutshell,thesearethechaptersandtheirtopics: Chapter1,SettingUpfortheFirstTime,startsbybootingupyourboardoutofthebox, gettingitconnectedonline,teachinghowtocontrolitremotely,andthendivingintothe essentialLinuxcommand-linecommands. Chapter2,BasicProgrammingRecipes,movesbrisklyalongtoscenariosusingseveral flavorsofprogrammingingredientsonBeagleBoneBlack,includingBoneScript(aneasy JavaScriptvariantforBeagleBone),Node.js,Python,andJohnnyFive. Chapter3,PhysicalComputingRecipesUsingJavaScript,theBoneScriptLibrary,and Python,tellsitlikeitisaswewilltaketherecipesdiscussedinChapter2,Basic ProgrammingRecipesandapplythemtotheuseofbuttons,sensors,LEDs,andmotors. Chapter4,ExploringGNU/LinuxRecipesUsingBash,Autotools,Debugger,andsystemd, looksatsomefoundationalLinuxtoolsthatyouwillneedtobendtheboardtoyourwill, toolsthatcomeinhandyforawidevarietyofusecases. Chapter5,BasicProgrammingRecipeswiththeLinuxKernel,helpsyoustartputtingyour armsaroundthesystemkernelbyinstallingthelatestversionandthenbuildingacustom kernel.WewillalsowillcookupsomemischiefwithoneofthehallmarksofallARM devices,DeviceTree,whichmakesiteasiertoaddperipheralsanddaughterboardstoyour system.Wewillfinishusingtheuniversalcapeoverlay,atoolsetthatmakesmanipulating GPIOpinsandDeviceTreeinfinitelysimpler. Chapter6,RunFaster,RunRealTime,enablesyoutogetmoreadvancedinyourskills; youwilllearnhowtomodifytheLinuxkernel(yikes!)andthendiveintotherealmof real-timecomputing,lookingatrecipestousetheRT-PREEMPTpatch,Xenomai,andthe uniquesubsystemfeaturesofBeagleBoneBlack—theprogrammablereal-timeunits (PRUs). Chapter7,AppliedRecipes–Sound,Picture,andVideo,looksatsomewaystousesound, display,andvideoinyourprojects.Wewillbeginbywiringupaminisoundamplifierand speakersandthentakethislessontocreatingahigh-qualityaudioplatformusingtheopen sourcemusicplatform,Volumio.Then,wewillcookupavarietyofrecipestoutilize videoanddifferenttypesofdisplaysinprojects,includinganOLEDandaminiLCD. Thischapterendsbybuildingavideochatclientfromsource. Chapter8,TheInternetofThings,plungesintoasamplingofthingsfortheInternetof Things;thingssuchaslookingatwaystousesensorswithmiddlewaresystems,settingup location-baseddevicestointeractwithBeagleBoneBlack,andmixarecipeformakinga smarterobject,specificallyacloud-drivendigitalpictureframe. Chapter9,TheBlackinOuterSpace,concludesthebookbyheadingintomoredistant regions:outerspace(ornearspace,tobemoreexact),delvingintorecipestotrack satellitesandcraft,suchastheInternationalSpaceStation.Wewilldiscusshowtousethe verylow-costbutpowerfulandexcitingSoftwareDefineRadiochipRTL-SDR. Whatyouneedforthisbook DescribingeverypermutationandcombinationtosetupBeagleBoneBlackisbeyondthe scopeofthisbook.Althougheveryrecipestartsbydescribingyourhardware requirements,wewillsuggestabaselinesetupherethatcanbeassumedfornearlyall chapters. Therewillbeanumberofrecipesscatteredthroughoutthebookthatrequireadditional hardware,suchassensors,jumperwires,resistors,breadboards,andsoon.Neverfear! Thevastmajorityofthesepartsisverylowcostandtypicallyalreadyapartofyour physicalcomputingandelectronickits.Thereareafewexamples,however,whereyou mightneedtospendalittlemoremoneyondaughterboards(calledcapes)andsomeother peripherals,suchaspoweredUSBhubs. Thehardwarerequirementsareasfollows: BeagleBoneBlackRevisionC:TypicallyreferredtoasRevC,theversionofthe boardwewilluseisthemostcurrentoneavailableonthemarketatthetimeof writing.Earlierversionsshouldworkwiththevastmajorityoftherecipesinthis book;however,wecannotguaranteetheirreliabilityinallcases. MicroSDcard(minimum8GB):Eventhoughtheboardhasaninternalsolid-state drive(eMMC)toruntheOS,weoftenneedtotestrecipesanddifferentflavorsofthe kernel.So,beingabletoquicklyswapouttheoperatingsystemonaMicroSDcardis anenormoustimesaver.Infact,youwillseeusmorecommonlybootingfromthe MicroSDthantheinternaldrive. Powersupply:Youhavemorethanoneoptiontopowerup,thoughtherecipewill recommendspecificallywhichofthesetouse: 5Vpower:Thisisa5V2A(2000mA)switchingpowersupply. Amini-BUSBcable:Agreatmanyoftherecipesallowyoutopowertheboard withnothingmorethantheUSBcablethatshouldhavecomewithyourboard whenyoupurchasedit.ThestandardUSBconnectorgoesintotheUSBporton yourdesktopclient,whichbecomesthepowersourceforBeagleBoneBlack. Display:Therearebasicallythreeoptionstogetadisplaygoingonyourboard: AnHDMIscreen:Thisout-of-theboxapproachassumesthatyouwillconnect yourboardtoanHDMImonitor.Compatiblehardwareislistedat http://elinux.org/Beagleboard:BeagleBoneBlack_HDMI.Ifyoudousethis option,youwillneedamicroHDMItostandardHDMIcable. AminiLCDor“cape”:WewilllearnhowtoconnectasmallLCDtothe board’sheaderpins.Asthisissomewhatofacustomsolution,wedonotassume thatyouwilltypicallyusethismethodexceptinrelevantusecases. Aremotesession:Aswewillseeinanearlychapter,muchofyourworkon BeagleBoneBlackcanbedoneviaremotesessionsusingSecureShell(SSH)on aclientdesktopmachine,suchasaMacorWindowsbox.Notethatthiswillbe ourfavoredapproachandrecommendationbecauseitobviatestheneedfora keyboard,monitor,andmouse. AUSBhub:Wefrequentlyrecommendapoweredhub,otherwise,theboard’spower drawwillcausesomeperipherals,suchasBluetoothdongles,tounderperformornot performatall.NotethatthismustbeapoweredUSBhub. Aclientmachine:InteractingandcontrollingBeagleBoneBlackisoftengreatly simplifiedbyconnectingittoaclientdesktopmachinerunningWindows,MacOS, orevenLinux.WearebiasedtowardtheMacOS,somostoftherecipesassumethat youareusingaMacintoshbox.However,ifyouarenotonMac,therecipesare essentiallythesameandtheprincipalstepsandcodearenotaffected. Aboardenclosure:Thisisnotactuallyarequirementbutahighlyrecommended “nice-to-have”tool.Besidesprotectingtheboardfromdamage,enclosingitinsome kindofsmallboxmakesitmuchmoremanageable,especiallywhenyouhave multiplewiressnakingallovertheplace.Youcanfindavarietyofenclosuresat http://bit.ly/1KTNPbFandonoursiteathttp://bit.ly/1WrBqrv. Thesoftwarerequirementsareasfollows: DebianLinux:Ifyoupurchasedyourboarddirectlyfromawell-established distributor,itshouldhavecomepreloadedwithDebian7Wheezy(kernel3.8.x-bone kernel),whichwillbeourprincipalassumptionfortheOS.Wewillalsobe referencingDebian8Jessie(kernel3.14.x). Youwilllearntoloadotherversionsofthesoftwareasweproceedthroughthebook. NotethatpriorversionsoftheboardwereshippedwithAngstromLinux.However, thisbookwillnotrunrecipesusingthisdistribution. Homebrew:IfyouareusingaMacbox,addingHomebrewtoMacgivesyouLinuxsavvytoolsonyourdesktop.ItincludesabasketofLinuxutilitiessothatyoudon’t alwayshavetofireuptheboardtorunatest.Fora“how-to”oninstalling Homebrew,refertothedevelopers’websiteathttp://brew.sh/. Drivers:IfonMac,installthelatestversionsofdeveloperJoshuaWise’sHoRNDIS driversforUSBtetheringtoBeagleBoneBlack,whichyoucanfindat http://joshuawise.com/horndis#available_versions.Wewillprovidemoredetailson thisstepinChapter1,SettingUpfortheFirstTime. Whothisbookisfor Thisisabookprimarilyforthoseofyouwhoarenewtomicrocontrollers,smallboard computing,andphysicalcomputing.Althoughwewillgetintosomerelativelyadvanced examples,thevastmajorityofourbook’srecipesarefortheaspiringmaker,casual programmer,andbuddingengineerortinkererwhohaswonderedhowtogetstartedona full-blownmicrocomputingLinuxsystem. YoumightfindsomethingsinherethatyoucouldhavefoundinsomeformontheWeb. Aswearedealingwithopensourcetoolsandtechnology,thisisinevitable.However, whatwefoundwhentryingtolearnaboutusingBeagleBoneBlackforthefirsttimewas thatalthoughwecouldfindsomeanswers,itisalwaysastruggletogettoananswer quickly. Asweproceed,ourintentionistodoourbesttogiveyouclearandsimpleintroductionsto concepts.So,forexample,ifyoualreadyknowyourwayaroundthingssuchasi2c,sysfs, andGPIOpinsandknowhowtowritecustomfunctionsinPython,youmayfindthis bookabittooslow. Giventhespeedofchangesinthesmallboardcomputingsector,manyonlinetutorialsare quicklyagingoutorjusttooadvancedforabeginner.Thus,webelievethatthereisa dearthonthemarketofgood,“easy-to-succeed”introductorybooksandmaterialon BeagleBoneBlack. Furthermore,unlikeRaspberryPi,whichissurroundedbywarmandfuzzysupport forums,theBeagleBonecommunityforumiscomparativelysparse.Worse,itisoften intimidatingandunwelcomingtoanewuser.Ourintentionistobelight-hearted,fun,and invitingforafirst-timeuser. Sections Inthisbook,youwillfindseveralheadingsthatappearfrequently(Gettingready,Howto doit,Howitworks,There’smore,andSeealso). Togiveclearinstructionsonhowtocompletearecipe,weusethesesectionsasfollows: Gettingready Thissectiontellsyouwhattoexpectintherecipe,anddescribeshowtosetupany softwareoranypreliminarysettingsrequiredfortherecipe. Howtodoit… Thissectioncontainsthestepsrequiredtofollowtherecipe. Howitworks… Thissectionusuallyconsistsofadetailedexplanationofwhathappenedintheprevious section. There’smore… Thissectionconsistsofadditionalinformationabouttherecipeinordertomakethereader moreknowledgeableabouttherecipe. Seealso Thissectionprovideshelpfullinkstootherusefulinformationfortherecipe. Conventions Inthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkinds ofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheir meaning. Codewordsintext,databasetablenames,foldernames,filenames,fileextensions, pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Thereis noreasontorecapitulateallthematerialcoveredintheSTART.htmpresentation.” Ablockofcodeissetasfollows: functionupdateDuty(){ //computeandadjustduty_cyclebasedon //desiredpositioninrange0..1 varduty_cycle=(position*0.115)+duty_min; b.analogWrite(SERVO,duty_cycle,60,scheduleNextUpdate); console.log("DutyCycle:"+ parseFloat(duty_cycle*100).toFixed(1)+"%"); } Anycommand-lineinputoroutputiswrittenasfollows: $sudoapt-getupdate $sudoapt-getupgrade $sudoapt-getinstallgdb Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen, forexample,inmenusordialogboxes,appearinthetextlikethis:“FromyourBBB’s desktop,openupLXTerminal.” Note Warningsorimportantnotesappearinaboxlikethis. Tip Tipsandtricksappearlikethis. Afewwordsaboutnomenclature BBB:Onethingthatgetstiresometorepeatisthedarnednameoftheboard—BeagleBone Black.Toomanysyllables!So,insteadofspellingitouteverytime,wewilloftenjust refertotheboardastheBBBortheBlack. Note ThereareotherversionsoftheBeagleBoneoutinthewild,includingBeagleBoneXM, BeagleBoard(white),andthenewsuper-charged(andmuchpricier)BeagleBoard-X15. Desktop:EventhoughyourBeagleBoneBlackhasadesktopifyou’rerunningitonan externalmonitororviaanx11(xwindows)session,we’llusethetermdesktoptoreferto theclientPCorMacorLinuxboxthatyou’rerunningaspartofthedevelopment environmentfortheBBB. SayhellotoMajorTom Ubiquitousandnearlyinevitableintheworldofcomputerprogrammingisthetypical beginner’sexamplecode“HelloWorld”.Althoughwecertainlyusesimpleusecasesto getyoustarted,wedon’tusetheHelloWorldrubric.Instead,becausewe’respacegeeks, weuse“MajorTom”asatouchstone,evokingtheastronautfromDavidBowie’siconic ZiggyStardust.Tothatend,weroundoutthebookwithanassortmentofrecipesusing yourBBBfortrackingspacestuff,satellitesandtheInternationalSpaceStation, specifically.Geeks,indeed. Readerfeedback Feedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthis book—whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsus developtitlesthatyouwillreallygetthemostoutof. Tosendusgeneralfeedback,simplye-mail<[email protected]>,andmentionthe book’stitleinthesubjectofyourmessage. Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingor contributingtoabook,seeourauthorguideatwww.packtpub.com/authors. Customersupport NowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelp youtogetthemostfromyourpurchase. Downloadingtheexamplecode Youcandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.com forallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbook elsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilesemaileddirectlytoyou. Inmanycases,youwillalsobedownloadingcodefromtheauthor’sgithubsiteat https://github.com/HudsonWerks. Downloadingthecolorimagesofthisbook WealsoprovideyouwithaPDFfilethathascolorimagesofthescreenshots/diagrams usedinthisbook.Thecolorimageswillhelpyoubetterunderstandthechangesinthe output.Youcandownloadthisfilefrom https://www.packtpub.com/sites/default/files/downloads/2929OS_GraphicBundle.pdf. Wherenoted,youmayalsodownloadsomeoftheimagesanddiagramsfromtheauthor’s websiteathttp://www.hudsonwerks.com/beaglebone-black-recipe-book/images/ Errata Althoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdo happen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthe code—wewouldbegratefulifyoucouldreportthistous.Bydoingso,youcansaveother readersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufind anyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata, selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthe detailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedand theerratawillbeuploadedtoourwebsiteoraddedtoanylistofexistingerrataunderthe Erratasectionofthattitle. Toviewthepreviouslysubmittederrata,goto https://www.packtpub.com/books/content/supportandenterthenameofthebookinthe searchfield.TherequiredinformationwillappearundertheErratasection. Piracy PiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.At Packt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucome acrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswith thelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy. Pleasecontactusat<[email protected]>withalinktothesuspectedpirated material. Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluable content. Questions Ifyouhaveaproblemwithanyaspectofthisbook,youcancontactusat <[email protected]>,andwewilldoourbesttoaddresstheproblem. Chapter1.SettingUpfortheFirstTime Inthischapter,wewillfocusonthefollowingtopics: Firstbootup Powerrequirements–basicguidelines Display EssentialGNU/Linuxcommands–thecommandshell EssentialGNU/Linuxcommands–typicalcommands Editatextfilefromthecommandshell Connectivity Packagemanagement–Installingpackagesusingapt-get SSH/Remoteaccess Systemimages Introduction GettingofftoarunningstartwithyourBeagleBoneBlackrequiresdivingintoanumber offundamentalrecipesfirst.Afterall,youhavetolearntochopanddicebeforemakinga propersoup. Asyouprobablyalreadyknow,creatingtherightdevelopmentenvironmentsavestime, reduceserrors,andcreatesagoodworkflow.Tothisend,afterwegetourdisplay hardwarehookedup,it’scriticaltolearnabitabouttheLinuxcommandsthatpowerour projects.Then,wewillmoveontogettingyourboardbothconnectedonlineand controlledremotelyoveranetwork.Next,wewilllearnthebasicsofinstallingand managingapplications(packages).Finally,wewillexplorehowtogetanOSontoyour board,whetherit’swiththeinternalsolid-statedrive(eMMC)orviaanSDcard. Firstbootup BeagleBoneBlack(BBB)designershaveworkedhardtosimplifytheuser’sfirstout-ofthe-boxexperience.Althoughthingsgetmorechallenginglater,whichisnatural,itis prettyclosetoPlugandPlayattheoutset. Youdonotevenneedtoloadanysoftwareastheplatformarrivespreloadedwithacustom distributionofLinuxDebianontheinternalsolid-statedrive(eMMC). Gettingready Here’swhatyouneed: DesktopclientPC:Asnotedintheintroduction,wewillprincipallybeusingaMac boxasourclientmachine.However,thefollowingstepsapplyequallytoaWindows orLinuxmachine. USBcable:AminiUSB-BtoUSBcableisrequired,whichistypicallysuppliedwith yourboard. BeagleBoneBlackRev.C:Toreiterateapointfromthisbook’sintroduction,our recipesuseRev.C,whichisthecurrentlyshippingversionoftheboard.Ifyouhave anearlierboard,youmayrunintooccasionalconflictswiththerecipes. Howtodoit… Performthefollowingsteps: 1. Topowerup,plugtheUSBcableintotheBBBandyourclientbox. 2. WaitforthethreeblueLEDstolightup;eachofthemfunctionsasausefulindicator oftheboard’shealth: Power:Oncepowerissuppliedtotheboard,theLEDnexttothe5Vbarreljack willremainonwithoutflashing USR0:Nexttothetinyresetbutton(S1),thislightmaintainsacontinuous,solid “heartbeat”blinkwhenpowered USR2:TwodownfromtheEthernetjack,thisLEDflutterssubtlyduringCPU access Note Unlessotherwisenoted,allimagesarecopyrightCharlesA.Hamilton. 3. Withinafewmomentsonyourclientmachine,theBEAGLE_BONEdriveshouldappear asavisiblevolumeonyourdesktop.BrowsethefolderandopenuptheSTART.htm file. 4. Onceopened,youwillfindaclearsetofquickstartsteps,includinghowtoinstall drivers(ifneeded). 5. Browseyourboard—BeagleBoneBlack’sbootsystemincludesahandywebserver thatallowsimmediateconnectivity.ClickingonthelinkwilltakeyoutothelocalIP addressoftheboardat192.168.7.2.Oncethere,youwillfindaveryhelpful presentationontheboard. ThereisnoreasontorecapitulateallthematerialcoveredintheSTART.htm presentation.Instead,reviewitasagoodjumpingoffpointfortheupcomingrecipes inthischapter. Gettingready Powerdown:Beforeproceeding,removeallcablesandpower(USB,Ethernet,DCcord, HDMI,andsoon). Howtodoit… Performthefollowingsteps: 1. ConnecttheUSBcable:WithaUSB2.0AtoMini-Bcable,connecttheBBBtoa USBportonyourdesktopPC. 2. Lookforstatuslights:AfterpluggingintheUSBcable,youwillseetheboard’s firstLEDlightup,followedsubsequentlybythethreeotherLEDs.Ifallgoeswell, theBEAGLE_BONEdevicewillappearonyourdesktop. 3. Installdrivers:Iwon’tbelaborthisstep.Itsufficestosaythatyourdesktop— whetherit’saWindows,Mac,orLinuxmachine—requirescertaindriversto recognizeandruntheBBBviaUSBproperly.IfyourdesktopOSdoesn’tcomewith thedriversalreadyinstalled(assomedo),installthemviathelink, http://beagleboard.org/Getting-Started. 4. Onceyourdriversareinstalled,browsetotheBASIC_START.htmfileonthe BEAGLE_BONEdeviceandopenit. Iftheplanetsarealignedandthedriversareinstalledproperly,youwillseethefollowing atthetopofthebrowserwindow: Yourboardisconnected!BeagleBoneBlackrev0A5CS/Nxxxxxxxxxxxxrunning BoneScript1.2.3at192.168.7.2. Atthispoint,you’rereadytofly;atleastatlowaltitude.Withaco-pilot…onanemulator. Powerrequirements–basicguidelines GivingyourBBBtheproperamountofloveandpoweriscrucialtohavingahappyboard. FollowingthesebasicguidelineswillensurethatyourBBBoperatesreliablyand predictably. Theboard’susermanualrecommendsthatyousupplycurrenttoatleast1.2A(or6W). However,ifyouconnectupanythingovertheUSB,atleast2A(or10W)isrecommended. Herearesomeadditionalrulesofthumb: YoucanpowertheBBBviatheUSBtether.However,ifyouattachadditionalUSB devices,suchaswebcams,Wi-FiorBluetoothdongles,keyboardsandmice,andthen powerthemthroughtheUSBtether,itmayleadtounreliableconnectionsandpower fluctuations.WeweresuccessfulinpoweringsomeUSBdonglesdirectlyviathe BBB’sUSBport,whereassomedevices,suchasUSBwebcams,werenotreliably powered. IfyouconnectUSBdevices,itisbesttopowerthemfromapoweredUSBhuband thensupplypowertotheBBBviaa5VDCpowersupplyofatleast1A. 5VDCpower—mostusersoftheboardwillinvariablyrecommendthatyoualways poweryourboardusinga5VDCsupply. Youcanalsousea5VwallchargerpoweradapterwithaUSBportonitaslongasit candeliver1A. Tip Downloadingtheexamplecode Youcandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.com forallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbook elsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilesemaileddirectlytoyou. Inmanycases,youwillalsobedownloadingcodefromtheauthor’sgithubsiteat https://github.com/HudsonWerks. Display TheBBB’sonboardmicroHDMIportprovidesarelativelyeasywaytoattachadisplay device.WiththenewDebiandistribution,compatibility,andeaseofinstallation,the processisgreatlysimplified.Wewilltakealookattwotypesofdevicesyoumaybe using:anHDMImonitorandasmallform-factorLCD(withoutHDMI). Note Usingadisplayisnotarequirementtooperatetheboardandismerelyoptional.Youwill learnhowtocontroltheBBBwithoutadisplaylaterinthischapter. ConnectinganHDMILCD RunningyourboardwithanHDMImonitoristhedefaultmethodtouseyourBBB. Howtodoit… 1. CheckthecompatibilitylistforyourHDMILCDmonitorat http://elinux.org/Beagleboard:BeagleBone_Black_Accessories#Monitors_and_Resolutions GiventhelargeuniverseofLCDsoutthere,thisisnotadefinitivelist.However,it doeslendguidanceondisplaysthatwillworkwiththeBBB.Youwillalsobe pleasantlysurprisedthatmostconsumer-gradeHDTVsworkprettywelloutofthe boxwithyourboard. 2. Checkyourresolutionathttp://elinux.org/Beagleboard:BeagleBoneBlack_HDMI. 3. PluginoneendofyourHDMIcabletoyourmonitorandtheotherend,whichisthe microHDMIend,intoyourpowered-downBBB. 4. Fulfillthepowerrequirements;powerupyourboardwitha5Vadapter. Note SinceHDMIdisplayscandrawalotofpower,don’ttrytorunoffyourdesktop’s USBslot.Otherwise,youwillgetflakyresultsatbestand,morelikely,nopictureat all. 5. Youshouldgetastraightforwardbootupintothedefaultdesktop“beagle”screen. Connectinganon-HDMILCDorcape There’snoobligationtouseonlyanHDMIdisplayonBeagleBoneBlack.Forexample, withtherightHDMItoVGAconvertercable,youcanactuallyattachastandardVGA monitortotheBBB.Compatibleconverterscanbefoundat http://elinux.org/Beagleboard:BeagleBone_Black_Accessories#HDMI_Adapters. YoumayalsodevelopanembeddedprototypedevicethatonlyneedsasmallLCDandno HDMI.Here’sonerecipeforascenariousinga3.5-inchscreenfromCircuitco (http://elinux.org/CircuitCo:BeagleBone_LCD3)thatI’veusedinmyownprojects.The displayisinthecategoryofadd-onstotheBBBcalledcapes,whichareakintothe shieldsonanArduinoboard.Capesaretypicallyrobustdaughterboardsand, unfortunately,tendtobemuchmoreexpensivethanArduinoadd-ons. CircuitCoLCD3cape Howtodoit… Performthefollowingsteps: 1. Powerdownyourboard. 2. ExaminetheheaderpinsatthebottomoftheLCD3andnotethepinlayout:oneshort rowandonelongerrow.Also,notethePower(PWR)buttonatoneend. ThepinlineupatthebottomofthePCB(printedcircuitboard) 3. PositionthelongrowofpinsontheLCDontopoftheP9pinslotsontheBBBand theshortpinrowontheP8row.Don’tpushthepinsinyet.ThePWRbuttonshould restbetweentheEthernetportandthe5Vbarreljack,asinthefollowingimage: 4. Next,slowlypushthepinsintotheBBBheaders.Allpinsshouldgoinmoreorless simultaneously.It’salittletrickyasyoualsohavetosquishthePWRbuttoninplace atthesametimesothatitlodgessnuglybetweenthe5VbarrelandtheEthernetjack, asinthefollowingimage: 5. AllpinsonbothsidesoftheLCDshouldbefirmlypushedintoplaceontheboard, andthePWRbuttonshouldbesecurelysqueezedinplace. 6. Powerupyourboard.Mostdistributions—includingtheDebianfirmware,ofcourse —havecompatibledriversforthedisplay,soyoushouldbootrightintoyourdesktop withinafewmoments. There’smore… Formoreinformationonthefollowingtopics,refertotherespectivewebsites: HDMITroubleshooting:http://elinux.org/Beagleboard:BeagleBoneBlack_HDMI OtherLCDcapeoptions:http://elinux.org/Beagleboard:BeagleBone_Capesuxdriver EssentialGNU/Linuxcommands–the commandshell FancyGUIsarenice,butonBeagleBoneBlack,youwillbemainlyworkingwiththe commandshellanditsaccompanyingcommand-linetoolstoprovideaccesstothe operatingsystem.First,let’stakealookatsometerminology:commandshell,commandlineshell,commandline,orsimplyshellwillallbeusedsomewhatinterchangeablyas theyallbasicallyrefertothesamething—ameanstoprovideaccesstotheoperating systemwiththecommandlineandwithoutaGUI.BashisthedefaultshellonLinux. Terminalisyetanothertypicalwaytorefertotheshell.Thetermisderivedfromits precedingtechnologieswhereanyinteractionwithacomputerrequiredusingatext-based terminalinterface. Oftenintimidatingtonewusers,commandshellisthestartingpointforanyserious embeddedsystemproject.TheDebiandistributionforBeagleBoneBlackcomespreloaded withtwocommand-linetoolstouseacommandshell:LXTerminalandRootTerminal. Althoughthereareotherswithmorerobustandcolorfulinterfacesthatyoucaninstall, suchasxtermandeterm,forsimplicity’ssake,wewilluseLXTerminal.Inthenext section,youwilllearnaboutthecommandsyntaxrequiredwithinthetool.Finally,wewill create,edit,andsaveatextfilefromthecommandline. Gettingready EnsurethatyourBeagleBoneBlackissetupandrunninginthemannerdescribedinthe Introductionsection.(Notethathere,wewillshowthetwodifferentmethodsofrunning theboard:poweredviaUSBandpoweredvia5V). Howtodoit… 1. BeginbyopeningupLXTerminal,whichyouwillfindintheAccessories applicationonthelowerleft-handsideofthescreen: 2. Youwillnowseeacommandpromptthatlookssimilartothisonyourscreen: 3. Justforfun,let’stypeinthefollowingatthecommandprompt: debian@beaglebone:~$echoCanyouhearmeMajorTom? Thiswillshowthefollowingoutput: Congratulations!You’vejustsentyourfirstcommandtoBeagleBoneBlack(anditwasn’t HelloWorld).Butwe’regettingaheadofourselves.Commandsareforthenextsection. Howitworks… Let’stakeaquicklookatthevariouspartsofwhatLXTerminalshowsus.Firstly,we knowthatLinuxlikestokeepthecurrentusernameatthefrontandcenter,inthiscase debian.Thisway,youalwayshaveaquickreferencepointtoknowwhetheryouarearoot user,whichgivesyoutotalcontroloverthesystem,orjustanotheruserwithlimited privileges. Thencomestheaddressofthedeviceyou’reworkingon:beaglebone.Youcanactually customizethename,butwewillsavethatfortheappendix.Lastly,considerthe$sign, whichdenotesthatyou’reloggedinasaregularuser.Ifyouwerearootuser,thesymbol wouldbethe#sign.Youwilllearnmoreaboutusersandrootusersinalatersection. EssentialGNU/Linuxcommands–typical commands Thecommandlineisyourfriend. Foradvancedusers,thisisanobviousstatement;forthebeginner,notsofriendly.Where doyoustartwiththatdarnblinkingcursor? HowmanyLinuxcommandsarethere?Awholebunch.Thousands.Tensofthousands dependingondependenciesandpackages.Butdon’tworry,youdon’thavetolearnthem all. SayingorwritingsomethingoriginalaboutLinuxcommandsisabitdifficult:farsmarter, folksthanIhavewrittenabout,compiled,andbattle-testedthemultiplecombinationsof commandsavailabletotheLinuxuser.AndthisbookisnotintendedtobeaboutLinux commands.Soinstead,IwillgiveyouahandfulofbasiccommandsthatIfindmyself consistentlyusingontheBBBandalsoprovideyouwithsomeofmyfavoritereference materialsandcheatsheetsthatwillgiveyouamorecomprehensivelistofimportant commands. Gettingready Ofcourse,weassumethatifyouintendtousesomecommandlineinterface(CLI) commands,youhavetohaveyourcommandshellwindowopenandgainrootaccess: sudo Usingsudoaspartofyourcommandsyntaxisarequirementthatoftenbedevilsnew Linuxusers.ItisimportanttounderstandthatmanyLinuxcommandsdemandwhatare knownas“superuser”privileges,whichgrantyoutotalcontrolovertheboardandits software.Havingfulladminrightswithinacommandpreventsanycasualuserfrom comingalonganddestroyingyourhardwork,bydesignoraccident. The“opensesame”ofDebianLinux,themagicsudocommand(pronounced“soo-doo”), means“SuperUserdox-command”whendissected.Ifyoudon’tappendyourcommand atthebeginningwithsudo,yourmkdircommand,forexample,willreturna“bad command”error. sudo-iandroot Addingthe-ioption(thesudo-icommand)providesevenmorecontroloverthe environment:therootuseraccess.Whenrunningcommandsasarootuser,thereare ampleopportunitiestocompletelymangleyoursystem,soexerciseextremecautioninits use. However,notallcommandsrequiresuperuserprivileges.Forinstance,whenyou’rereally justpokingaroundthesystemandnotmodifyingfiles,directories,orthesystemitself, sudoisn’tnecessary. Youshouldkeepinmindseveralthingswhenworkingwiththecommandline: Lowercase:Usinglowercasesyntaxistheshell’srequiredexpectation,withthe exceptionofsomeoptionsandargumentsthatareuppercase. Argumentsandoptions:Mostcommandshavemultipleoptionsorargumentsthat canbeusedtofine-tuneyourcommand.Wewillonlybeabletotouchonafew instancesofhowandwhentheseoptionsareused. Help: Help(nohyphens):Typinghelpbeforeacommandoutputsinformationabout thiscommand.Anexampleofthisis$helpcd. Help(hyphens):Manyexecutablecommandshavemorehelpandinformation abouttheiroptionsorarguments.Anexampleofthisis$mkdir--help. Manpages:Shortfor“manualpages”,addingmantothebeginningofmany Linuxcommandsopensupamanualforthesecommands.Itcanoftenyieldtoo muchinformation,butitcanbehelpfulifyou’relookingforadeeper understandingofacommand.Anexampleofthisis$manchmod. Tabcommand:Thislistsrecentcommands.Inordertousethis,youneedtodothe following: Typealetter(orastringofletters)andthenpresstheTabbutton.Allcommands thatbeginwiththisletterorstringwillbeshown.Thiswillpreventavast majorityoftypingmistakes. PressTabtwicequickly,anditwillshowallthecommandsthatarecurrentlyin yourpath. Conventions Earlyinthebook,wewillfrequentlyusetheentirelinefromthecommandline,including theusername,address,symbolsconnotingusertype,directory,andsoon.So,for example,youwillseealinethatlookssimilartothefollowing: debian@beagle_bone:~$mkdir However,aswebecomemorefamiliarwiththeshell,wewillmostlyshortenthe commandinstructiontoonlyincludethecommanditself: ~$mkdir Alternatively,youwillseeaslightvariationontheprecedingcommandwhenwerefertoa rootuser.Notethe#signinplaceofthe$signinthefollowingcommand: ~#mkdir Now,let’smoveontothecommands.Asuper-dupersubsetofcommands,anyway.We’ve organizedthemintoSystemnavigationalcommands,Deviceandsysteminsight,and Modifycontent/datacommands. Systemnavigationalcommand–changeyour directory–cd Tomovefromonedirectorytoanother,therearenumerousvariationsonhowtodoit. Howtodoit… Performthefollowingsteps: 1. TochangefromyourcurrentdefaultdirectorytotheDesktopdirectory,typeinthese commands: debian@beaglebone:~$cdDesktop debian@beaglebone:~/Desktop$ 2. Togobackonedirectorylevel,usethefollowingcommandlines: debian@beaglebone:~/Desktop$cd.. debian@beaglebone:~$ 3. GototheHomedirectoryusingthefollowingcommand: debian@beaglebone:~/Desktop$cd~ debian@beaglebone:~$ 4. Gobacktothepreviousdirectoryyouwereinbytypinginthefollowingcommands: debian@beaglebone:~$cd/home/debian/Desktop debian@beaglebone:~/Desktop$ There’smore… Inadditiontotheprecedingcommands,youshouldbefamiliarwiththefourspecial directorysymbols: Thecurrentdirectory(.) Theparentdirectory(..) Therootdirectory(/) Thehomedirectory(~) Systemnavigationalcommand–showyourcurrent directory–pwd Thisstandsforprintworkingdirectory,ameanstoshowtheuserwhereinthesystemthey arecurrentlyworkingortheabsolutepathrelativetothecurrentdirectory. Howtodoit… Usethefollowingcommandtoshowyourcurrentdirectory: debian@beaglebone:~$pwd /home/Debian Systemnavigationalcommand–findafile–find Lookingforafile?Onewaytosearchforitiswiththefindfunction.Justbesuretoadd the-nameoptionsothattheoutputshowsthedirectorylocation.Addsudoaswellsothat youdonotgetdirectoryaccesserrors. Howtodoit… Usethefollowingcommandtofindafile: $sudofind/-name<filename> Deviceandsysteminsight–showswhat’sinsidea directory–ls Thelscommandliststhecontentsofyourcurrentdirectory. Howtodoit… Usethefollowingcommandtoseethelistofcontentsinthecurrentdirectory: debian@beaglebone:~$ls Desktop Atthemoment,theonlythingyouwillseeistheDesktopdirectory.Aswecontinue addingcontentinsubsequentchapters,therewillbemorethatwouldbeseenuponusing ls. Addingthe-lahoptionattheendofthecommandgivesmoredetailedinformationonthe files,asfollows: debian@beaglebone:~$ls-lah total112K drwxr-xr-x19debiandebian4.0KMay423:37. drwxr-xr-x3rootroot4.0KMay500:05.. -rw-------1debiandebian55May423:37.Xauthority -rw-------1debiandebian2.4KMay501:41.bash_history -rw-r--r--1debiandebian220Jan12015.bash_logout -rw-r--r--1debiandebian3.4KJan12015.bashrc drwxr-xr-x6debiandebian4.0KMar82015.cache drwxr-xr-x9debiandebian4.0KMar423:51.config drwx------3debiandebian4.0KMar423:37.dbus -rw-r--r--1debiandebian35Mar423:37.dmrc drwxr-xr-x2debiandebian4.0KMar82015.fontconfig drwxr-xr-x24debiandebian4.0KMar82015.gimp-2.8 drwx------3debiandebian4.0KMar82015.local Theoptionsinthecommandnowrevealavarietyofthingsaboutthefile:theirpermission status(column1),ownerandgroup(columns3and4),filesizes(column5),and modificationdate(column6).Theloptionoutputsinthelistform,addingtheaforcesthe commandtoshowanyhiddenfiles,andthehoptionturnsitallintoahumanreadable format. Deviceandsysteminsight–findoutwhatUSB devicesareconnected–lsusb ThiscapturesandlistsallUSBdevicescurrentlyconnectedtotheBBBwhileshowing basicinformationaboutthedevice. Howtodoit… UsethefollowingcommandtofindoutabouttheUSBdevicesconnected: debian@beaglebone:~$lsusb Bus001Device002:ID0d8c:013cC-MediaElectronics,Inc.CM108Audio Controller Bus001Device001:ID1d6b:0002LinuxFoundation2.0roothub Bus002Device001:ID1d6b:0002LinuxFoundation2.0roothub Note NotethatthefirstdevicehereshowsaconnectedUSBaudiodongle. Deviceandsysteminsight–getinformationabout connecteddevices–cat/proc/bus/input/devices Wherelusbleavesoff,thiscommandlistsmoredetailedinformationaboutanydevice connectedtotheBBB.NotethedifferenceinoutputforthesameUSBaudiodevice(Cmedia)showninourprecedingrecipeusinglsusb. Howtodoit… Usethefollowingcommandtogetinformationaboutconnecteddevices: debian@beaglebone:~$cat/proc/bus/input/devices I:Bus=0000Vendor=0000Product=0000Version=0000 N:Name="tps65217_pwr_but" P:Phys= S:Sysfs=/devices/ocp.3/44e0b000.i2c/i2c-0/0-0024/input/input0 U:Uniq= H:Handlers=kbdevent0 B:PROP=0 B:EV=3 B:KEY=100000000 I:Bus=0003Vendor=0d8cProduct=013cVersion=0100 N:Name="C-MediaElectronicsInc.USBPnPSoundDevice" P:Phys=usb-musb-hdrc.1.auto-1/input3 S:Sysfs=/devices/ocp.3/47400000.usb/musb-hdrc.1.auto/usb1/1-1/11:1.3/input/input1 U:Uniq= H:Handlers=kbdevent1 B:PROP=0 B:EV=13 B:KEY=780e0000000 B:MSC=10 There’smore… Thestemofthiscommandiscat,whichisoneofthemostpopularcommandstoquickly readfileswithoutwritingormodifyingthem: $catfile4 Youcantryitwithanyfiletoseehowthescreenoutputlooks. Deviceandsysteminsight–getyourversionof Linux YoucanfindoutwhichversionanddistributionofLinuxyouarerunningthroughseveral methods. Howtodoit… TofindoutyourversionofLinux,usethefollowingcommand: debian@beaglebone:~$lsb_release-a Thescreenoutputwilllooksimilartothis: NoLSBmodulesareavailable. DistributorID:Debian Description:DebianGNU/Linux7.6(wheezy) Release:7.6 Codename:wheezy Theprecedingcommandisagoodcomplementtothemoretypicalwaywedeterminethe actualkernelversion,whichisasfollows: $uname-r 3.8.13-boneXX Deviceandsysteminsight–findoutrunning processes–ps InLinux,applicationsarereferredtoasprocesses,andeachisgivenauniqueIDnumber orPID.Theps(thatis,processstatus)commandprovidesinformationaboutthecurrently runningtasksorprocesses.TheoutputincludesthePIDs. Howtodoit… Thiscommandtakesasnapshotofyourboard.Youcanrunthecommandunadulterated andwithnooptions,asfollows: $ps Buttheoutputisathingruel: debian@beaglebone:~$ps PIDTTYTIMECMD 1623pts/000:00:00bash 2035pts/000:00:00ps So,itisoftenbettertomodifytheoutputinordertogetmoreinsightintotherunning processesanddisplaythisinformationinamoreorderlyfashion,asinthefollowing command: $psaux Thefollowingistheoutput: Theauxseriesofoptionscomplementthebasiccommandbydoingthefollowing: Theaoptionshowstheprocessesforallusers.Historically,psrequiresdifferent syntaxdependingonourflavorofLinuxorUnix.Thisoptionsimplifiesthemethod requiredtoaddoptions. Usingtheuoptiontellsthecommandtodisplaytheuserorowneroftheprocessin theoutput.Thereasonyouwanttodothisisthatthereareprocessestypically runningattherootlevelandotherprocessesrunningatanon-root-userlevel. However,wefrequentlywanttoseeallprocessesrunningregardlessofuser,sothis optionisimportant. Thexoptionensuresthatprocessesthatarenotcurrentlyrunninginaterminal window—whichformthemajorityofrunningprocesses—arealsointheoutputthat wewanttosee. Deviceandsysteminsight–findouttheresources usedbyrunningprocesses–topandhtop Thiscommandtakesitabitfurtherthanthepscommandasitdynamicallyupdatesnot onlytheprocessesrunningbutalsotheCPUresourcesusedbytheprocesses.Thestatusis continuousandinrealtime. Howtodoit… Usethiscommandline: $top Theoutputisasfollows: ThetopcommandisadequateandonethatyouwillhearmostLinuxuserscallupon,but thereisnowamuchlovelier,easierwaytoreadapackage—htop.Let’sinstallitand compareittotopwiththefollowingcommand: $sudoapt-getinstallhtop Now,theoutputwillbeasfollows: Asyoucansee,ithasanoutputthatismuchcleanerandeasiertoread. Deviceandsysteminsight–quittingprocesses–kill Thetypicalwaytoforcequit—orkill—anapplicationistousethekillcommandand combineitwiththeprocessID(PID),whichyoucanderivefromanyofthepreceding recipestocaptureprocessinformation.Let’stakealookatthebasicmethod. Howtodoit… Usethefollowingcommandtokillprocesses: $kill<process_id> Here’sarealexample,whichwouldforcequitthetopprocessshowninourpriorrecipe: $kill4569 Whenyouknowthenameofaprocess,youcanusethepkillcommand,whichoperates ontheprocessnameinstead,asfollows: $pkill-9gdb Naturally,thereisyetanotherwaytoskinthecatwhilekillingaprocess.Forexample, youmaydiscoverthatthereareseveralprocessesassociatedwithoneapplication,and killingthemonebyonegetsabitslippery.Instead,usekillallandkissthemgoodbye: $killallchromium Deviceandsysteminsight–messagereports– dmesg Asyoualreadyknow,everytimeyoubootupyourdevice,atonofmessagesquickly scrollspastonthescreen.Unlessyouwearablueleotardwitharedcapeandpossess exceptionallyfasteyes,youlikelywillnotcatchallthesepearlsofASCIIwisdom.Yet, thesemessagescanbeextremelyusefulattimes,particularlywhenyouneedto troubleshootasystemproblem. Howtodoit… Thedmesgcommandisusedasfollows: $dmesg Typically,theoutputlookssimilartothis: [0.000000]BootingLinuxonphysicalCPU0x0 [0.000000]Initializingcgroupsubsyscpu [0.000000]Linuxversion3.8.13-bone47(root@imx6q-wandboard-2gb-0) (gccversion4.6.3(Debian4.6.3-14))#1SMPFriApr1101:36:09UTC2014 [0.000000]CPU:ARMv7Processor[413fc082]revision2(ARMv7), cr=50c5387d [0.000000]CPU:PIPT/VIPTnonaliasingdatacache,VIPTaliasing instructioncache [0.000000]Machine:GenericAM33XX(FlattenedDeviceTree),model:TI AM335xBeagleBone [0.000000]Memorypolicy:ECCdisabled,Datacachewriteback [0.000000]Onnode0totalpages:130816 [0.000000]free_area_init_node:node0,pgdatc0824280,node_mem_map c089f000 Thelistgoesonandonasyourmachineisfullofactivity!So,limitingdmesgtooutput smallerchunksofinformationwithacommandoptionisprimarilythecoursefollowed.In thiscase,wewanttoshowthelastteneventsonthesystem,sowewillusethefollowing: $dmesg|tail Alternatively,wecanusethelessoption,whichallowsustoadvanceforwardinthelist moremethodically,asfollows: $dmesg|less Deviceandsysteminsight–showsdiskspace–dfh Thiscommandoutputsinformationonyourboard’savailablediskspaceanddisplaysitin humanreadableformat. Howtodoit… Usethefollowingcommandtofindoutthediskspace: debian@beaglebone:~$df-h FilesystemSizeUsedAvailUse%Mountedon rootfs7.2G1.6G5.4G22%/ udev10M010M0%/dev tmpfs100M824K99M1%/run /dev/mmcblk0p27.2G1.6G5.4G22%/ tmpfs249M0249M0%/dev/shm tmpfs249M0249M0%/sys/fs/cgroup tmpfs100M0100M0%/run/user tmpfs5.0M05.0M0%/run/lock /dev/mmcblk0p196M71M25M75%/boot/uboot /dev/mmcblk1p21.7G1.7G0100%/media/rootfs /dev/mmcblk1p196M11M86M11%/media/boot Deviceandsysteminsight–explorenetwork– Ifconfig Thislistsallthenetworkdeviceswithnetworkinformation.Youwillcommonlyfind yourselfusingthiscommandontheBBBwhenyouneedtotroubleshootaproblemorset upnetworkconnections. Howtodoit… Usethefollowingcommandtoexplorenetworkconfiguration: $ifconfig Theoutputisasfollows: Modifycontent/datacommands–makeanew directory–mkdir Thiscommandhelpsyoucreateadirectory(folder)whereyouwanttoworkorplacefiles. Howtodoit… Usethefollowingcommandtomakeanewdirectory: debian@beaglebone:~$mkdirtest Nowisagoodtimetocheckyourworkwiththelscommand,asfollows: debian@beaglebone:~$ls Desktoptest Modifycontent/datacommands–removeafileor directory–rm Asthenameimplies,thiscommandremovesafileordirectorythatyoudesignate. Howtodoit… Removingafileisverysimple.Youjustneedtotypeoutthefollowing: $rmfile1 Addingthe-ioptionisgoodpractice,especiallyforbeginners,asitpromptsyouto confirmthefile’sremovalasfollows: $rm-irfile1 rm:removeregularfile`file1'? Toremovedirectories,thereareprincipallytwocommandsyoucanuse.Firstly,whenyou haveanemptydirectory,thecommandissimilartothefollowing: $rmdirdir1 However,rmdirworksonlyifthedirectoryisempty.Ifyouwanttoremoveadirectory withallitscontents,youcanusermwiththe-roption.Thisoptiontellsrmtoremovea directoryrecursively,asinthefollowingcommand: $rmdir-rdir1 Tip RedAlert! Obviously,rm-rcanwreakhavoconyoursystemanddeletefilesanddirectoriesthatyou mayactuallyneed.Tobecautious,thefirstfewtimesyouusethiscommand,youmight wanttoincludethe-ioption.Thisway,eachtimeyoudeleteadirectoryanditscontents, youwillgetapromptbeforeeachfileisdeleted. Modifycontent/datacommands–downloadfiles– wget Runningthiscommandgivesyoucontrolovergrabbinganddownloadingfilesfromweb serversviaHTTP,HTTPS,andFTP.Unliketheexperienceofdownloadingafileinaweb browser,wgetisnoninteractive.Thismeansthatyoudon’thavetobeloggedonforthe commandtocompleteitstask,whichispotentiallyagreattime-saverwithlargefile downloads. Howtodoit… Inordertodownloadfiles,youcanuseacommandsuchasthefollowing: $wgethttp:// ThiswilldownloadtheMajorTompageatwww.hudsonwerks.comintoyourcurrent directoryandcreateafilenamedindex.html.Next,performthefollowingsteps: 1. Checkyourworkusingthefollowingcommand: $ls Desktoptestindex.html 2. Now,performanotherwget;thistime,downloadviaftp.Here,wewillgrabwget sourcecodefromtheGNUsiteasfollows: wgetftp://ftp.gnu.org/pub/gnu/wget/wget-1.15.tar.xz 3. Checkyourworkagain,usingthefollowingcommandthistime: $ls Desktoptestindex.htmlwget-1.15.tar.xz There’smore… Wheredoweputthenewtarballs,packages,andsoon?Itisgoodpracticetocreatea directorycalled/home/username/Packages/.Thisiswhereyoucanputtarballs,their extractedfiles,compiledcode,backupsofreplacedfiles,andinstallationscripts.Forthis, youcanusethefollowingcommand: $mkdir/home/username/Packages/ $wget-P/home/debian/packages<download-url> Modifycontent/datacommands–openatarfile– tar[options] Workingwithfilesinthe.tar(tarball)format,atypeofarchivedfile,iscommonin Linux.Thevariousoptionsthatcomewiththetarcommandwillconsiderablyeaseyour managementofthefilesthatarenotarchived. Howtodoit… Usethefollowingcommandtoopenatarfile: $tar-zxvffile_name.tar.gz Beforeactuallyrunningthecommand,let’sunderstandabitabouttheoptions: -z:Thisisusedtouncompresstheresultingarchivewiththegzipcommand -x:Thisisusedtoextracttodiskfromthearchive -v:Thisproducesaverboseoutput,whichmeansthatitshowsprogressandfile nameswhileextractingfiles -fdocument.tar.gz:Thisreadsthearchivefromthefilecalleddocument.tar.gz Otherfiletypesinclude.xz,whichistheactualfiletypewedownloadedpreviouslyusing wget—wget-1.15.tar.xz.So,herearetheessentialrecipesteps: 1. Bydefault,filesareextractedintoyourcurrentdirectory.However,youcan simultaneouslyextractyourfilesandputtheminadifferentdirectorywiththe-C option.Usingthefollowingcommand,wewillextractfilesandputtheminthe/test directory: $wget-1.15.tar.xz-Ctest 2. Checkyourworkbynavigatingtothenewdirectorycreatedandrunningthe followingcommand: $cd/test/wget-1.15 Youshouldseealltheunarchivedwgetsourcefileswiththeiraccompanying directories. Theflipsideofunarchivingisarchiving.Here’showyoucancreateatarfile: $tar-cvffile.tarinputfile1inputfile2 Replaceinputfile1andinputfile2withthefilesand/ordirectoriesthatyouwantto combine.Youcanuseanynameintheplaceoffile.tar;youshouldkeepthe.tar extension,though. There’smore… Youmayoccasionallyrunintoerrorswhileopeningtarballs(orothergzipfiles).Ifso, onetroubleshootingtipistoensurethatthefileisactuallyazippedarchivewiththe followingcommand: $filefilename Thiswillshowthefiletypeandsize;ifit’snotanarchive,youcan’trunthetarcommand onit. Modifycontent/datacommands–cleanupfiles– autoclean Thiscommandremovespartialpackagesfromthesystem. Howtodoit… Usethefollowingcommandtocleanupfiles: $sudoapt-getautoclean Modifycontent/datacommands–purgea package–apt-getpurge,apt-getremove—purge Thesecommandscompletelygetridofpackagesanddependencies. Howtodoit… Usethefollowingcommandtogetridofpackagesanddependencies: $sudoapt-getpurgepackagename Alternatively,youcanusethefollowingcommand: $sudoapt-getremove--purgepackagename Modifycontent/datacommands–shutdownthe system–[options] Itisabadideatopulltheplugonyourboardtoturnitoff.Doingsocanoftenleadtoa corruptedSDcardormangledfiles.Instead,here’showyoupowerdownyourboard gracefully. Howtodoit… IfyouwanttoshutdowntheBBBandrebootit,thefollowingcommandwillbeuseful: sudoshutdown-rnow However,ifyousimplywanttoshutdownthesystemandpowerdowncompletely,then eitherofthefollowingtwooptionswilldothetrick: sudoshutdown-hnow Youcanalternativelyusethefollowingcommand: sudopoweroff Seealso LinuxinANutshell:Theonlineversionofthisbookdeliversanabbreviatedlistof 687commands(http://www.linuxdevcenter.com/cmd/) Workingwithcommands:Youcanworkwithcommandsat http://linuxcommand.org/lc3_lts0060.php Youwillfindsomeofthebestone-pagecheatsheetreferencesforLinuxcommands.Print themoutandposttheminanhonoredplace! ThetablefromMakeuseof:http://www.makeuseof.com/pages/linux-commandsreference-pdf Freeelectrons’commandmemento:Thisiswelldesignedandcomprehensiveand canbefoundathttp://free-electrons.com/doc/training/linuxkernel/command_memento.pdf AnexcellentcheatsheetthatcomesindifferentlanguagesandprintablePDFscanbe foundathttp://fosswire.com/post/2007/08/unixlinux-command-cheat-sheet/ Youcanreadupmoreoncleaninguppackagesat http://www.stchman.com/cleanup.html Editatextfilefromthecommandshell ThereisnothingprettyaboutthetexteditingtoolsinLinux.Afterall,itisacommand shellenvironment;howprettycanitbe?Butifyouareaminimalistatheart,youwillfeel rightathome. TwoeditorsmostlydominateDeveloperland:nanoandvim.Thelatteristhemost powerfulandfullyfeatured.However,thevimcommandisnotagoodstartingpointfor neophytesasitismorecomplex.Instead,ourtexteditingtoolofchoicefortherestofthis bookwillbenano.Inthissection,youwilllearnyourwayaroundtheeditorandthen createandeditatextfile. Howitworks… Whenyou’reusingnano,takenoteofalltheoptionsatthebottomofthescreen:Exit,Get Help,ReadFile,andsoon.Youaccessthesefunctionswiththekeyboardshortcuts shownnexttoeachoption.Bewarethattheseshortcutsactuallymaychangetheirfunction ormodewhenyounavigatetoanotherscreenorchooseanoption.So,rememberwhatthe bottommenusaysbeforeassumingthattheshortcutyoujustusedremainsinthesame mode. Inthemain(default)window,here’saquickrundownonthemostcommonlyused functionsandtheirshortcuts: Ctrl+X:Closesthefile. Ctrl+V:Takesyoutothenextpage. Ctrl+Y:Takesyoubacktothepreviouspage. Ctrl+K:Cutstext(deletesthelineoftextwhereyourcursoris). Ctrl+U:Uncutstext(undoesthelinedeletionfromthelastlinethatyoucut. Repeatingthiscommandwillkeepaddingthesamelineoftextthatyoucut). Ctrl+G:Helpmenu. Ctrl+C:Showsthecurrentposition(givesyouline,column,andcharacter coordinates). Ctrl+R:Insertsafileintothefileyouhaveopen.Nowthat’satimesaver,huh? IrecommendusingCtrl+Gperiodicallywhenyou’rejustbeginningasareminderforthe additionalfunctionsavailable,manyofwhicharepowerfulanduseful.Overall,youwill findthatevenasimpleLinux-basedtexteditorsuchasnanocomesloadedwithfeatures thatmostWintel/Macdesktopversionsdon’ttypicallyinclude. Howtodoit… Thisfunctioncanbeperformedthroughthefollowingsteps: 1. Let’sbeginbyopeningnanoandsimultaneouslycreatingafilenamedmajor_tom: ~$nanomajor_tom Pow!Awindowopens.That’sthenanointerfaceinallitsglory.Allright,notsosexy. Butveryfunctional,asyoucanseeinthefollowingimage: 2. Onthefirstline,whichiswhereyourcursorshouldbebydefault,type(orpaste)the following: IlovemyBeagleboneBlacksomuchIwanttosenditintoorbitwith MajorTom. Quicklylookingaroundthewindow,youwillnoticethefollowing: Atthetopofthewindow,youwillseetheversionofnanothatyou’reusingandthe filename,major_tom. Atthebottomofthewindowisanassortmentofoptions. Ifyou’veplayedaroundwithanyoftheoptionsinthemenu,ensurethatyou’reback inthemainscreenwherewebeganwithourtypedlineaboutMajorTom. 3. Next,savethefilebypressingCtrl+x;whenprompted,typeyforyes: Error!Whatabummerthatwecouldn’tsaveourwork.Thisisbecausewedidn’tfirst executenanowiththerightuserprivileges.So,tryagainbyclosingthefileby pressingCtrl+x;whenprompted,typenforno. Welostourwork,butitwasonlyonelineoftext.Wewouldnowhavepoppedbackinto thecommandline,andwewillhaveanothergo;thistime,weneedafewmoresteps: 1. Let’smakeacustomdirectory;runthiscommand: mkdirbbb_recipe_book 2. Gointothisnewdirectoryandmakeasubdirectory;then,makeasubdirectoryofthis one.Thismaysoundoverlycomplicated,butwe’rejusttryingtosetupsomefiles anddirectoriesbyorganizingprinciplesearly.Usethefollowingcommandsforthis: cdbbb_recipe_book mkdirprojects cdprojects 3. Checkyourworktoensurethatyou’vesetupthedirectorystructureproperly.Use thefollowingcommand: pwd 4. Now,let’stypesudonanomajor_tom.txt.Thistime,weappendedthefilename withatextfiletype.Ifyoudon’tdothis,nano—andLinux—won’tknowwithwhich applicationtypetoassociatethefile. 5. Inthenanowindowagain,typeIlovemyBeagleboneBlacksomuchIwantto senditintoorbitwithMajorTom.,asshowninthisimage: 6. Then,pressCtrl+x;whenpromptedtypeyforyes. 7. Nowyouwillseethatthebottommenuhasanewprompt,whichreadsasfollows: Filenametowrite:major_tom.txt 8. Hitreturn(Enter)onyourkeyboard.Thefileissavedtothenewdirectorywe’re workingin(/home/debian/bbb_recipe_book)andclosedsimultaneously. You’venowmadeaveryexciting.txtfilethatyoucangobackandreadwheneveryou want.Okay,thatwasn’tterriblychallenging.Butdon’tworry;wewillbeaddingmore complexityasweproceedinupcomingchapters. Seealso ForthosewhofindnanoabitSpartaninfunctionalityandpreferamorepowerfuleditor, vimisapopularchoice.Althoughchallengingtolearnatfirst,youmayfindittobea morerewardingandflexiblechoiceasatool.Learnhowtouseitat http://www.openvim.com/tutorial.html. Connectivity WewillshowyouthetwoprincipalrecipestogetyourBeagleBoneBlackconnected: Ethernet Wi-Fi BewarethatthereisathirdwaytogettheBBBonline,whichisbytetheringyourboardto yourdesktopmachineandpiggybackingonitsnetworkconnection.Thisisahighlyuseful butoccasionallytrickyoption. Connectivity–Ethernet Ifyouhavedirectaccesstoyournetwork’srouter,usingtheEthernetconnectionispretty muchPlugandPlayontheBBB. Gettingready Here’swhatyouneedforthisrecipe: 5VDCpowersupply AnEthernetcable ABBBconnectedtoanHDMImonitor.Foreaseofuseandfirsttimeconnectivity, wesuggestthatyouhaveyourboardconnectedtoamonitorforthisrecipe.Afteryou gainconfidenceandlearnmoreaboutconnectivitymethods,youwillbeableto dispensewithusinganexternalmonitor. Howtodoit… PerformthefollowingstepsforEthernetconnectivity: 1. WithyourBBBpowereddown,pluginoneendofanEthernetcabletotheBBBand theotherendtoyourrouter. 2. Powerupyourboardviathe5Vpowersupply. 3. Theconnectionshouldoccurseamlessly,assumingyourEthernetcableissound,your internetconnectionisreliable,andtheBBBhasnodefects. 4. Atyourscreen’sloginprompts,enteryourloginnameandpassword.Youwillbe takentothedesktop. 5. Next,wewillcheckourconnectionviaaterminalsession.Inthelowerleft-hand cornerofyourscreen,clickonthebird-likeiconandthennavigatetoAccessories| LXTerminal. 6. Intheopenterminalwindow,typethefollowing: $pingwww.google.com Youshouldbegettingpingresponsesbackthatlooksimilartothefollowingoutput: Connectivity–Wi-Fi Sinceitsoriginalreleaseinthespringof2013,Wi-FiontheBBBhasbeenabitofan AchillesHeelfortheplatform.ComparedtothetypicalexperiencewithRaspberryPi,you couldpulloutyourhairgettingWi-FitoworkontheBBB.Ifyouwerehappyusing Angstromonlyforyourprojects,youwereinluckasthisdistributionwas(mostly)solid, giventhatseveralUSBminidonglesonthemarketworkedwell. However,onDebianandUbuntu,unlessyoudidnotmindusinglargerdongleswith protrudingantennae,connectionswereflaky.Alternatively,youcouldinvestachunkof timewritingcustomdrivers.Somuchforout-of-the-boxportability. Fastforwardtothe(mostly)goodnews.WiththethreedifferentWi-Fidonglesthatwe testedonthecurrentshippingversionofDebian7WheezyfortheBBB(using3.8.13bone71)andonDebian8Jessie,welargelygotpositiveresults.Thebadnews?Withthe exceptionofusingDebianJessie,notalldongleswererecognizedbytheBBBwithout someconfiguration.However,itisfairlyeasytosetupthehardware,andyoualsomay getluckywiththedongleyouhaveinyourkitandgetimmediateconnectivity. Note IfyouareusingDebian8Jessie,skipimmediatelytoMethodFour:DebianJessie. Gettingready ThefollowingaretheprerequisitesforWi-Ficonnectivity: DCpowertotheBBB—theboardshouldbepoweredfroma5VDC1Aminimum supplyandnotviaUSB. AconnectedHDMImonitor. WiredorwirelesskeyboardandmouseconnectedtotheUSBhub. ApoweredUSBhub—theWi-FidongledrawsmorepowerthantheBBBcandeliver ifyouonlypowertheboardviatheUSBportonyourclientbox.Instead,youneeda poweredhubtodothejob.Ifyoudon’tuseapoweredhub,youmaybeabletoget awaywithdecentstability,butyouarejustaslikelytogetpoorresults. Wi-Fidongle—refertotablestotestcompatibleversions. Wewilldividethisrecipeintothreedifferentsetupmethodsassomedonglesarehappy withonemethodwhileotherspreferthesecondone.Wewillalsoincludethesetupfor Debian8.0(Jessie)asthisdistributionhasgreatlyimprovedandsimplifiedtheprocess. Someofthesetupinstructionsarederivedfromhttp://elinux.org/BBBWiFiConfigs. ThemicroUSBdonglemodels Theuniverseoflow-costWi-Fidonglesavailableonthemarketisfairlylarge,the followingtablebeingaverysmallsubset.Theminidonglesweusedintheserecipeshave beenhistoricallyproblematicwiththeBBBbutarenowmorereliablewiththecurrent Debiandistribution.Yourbestresults,however,maybewithastandard-sized(nonmicro) donglethatalsocomesaccompaniedbyanantenna. ThefollowingtableshowsthetestedandworkingmodelsofmicroUSBdonglesforour recipes.NotethatthefirstthreemodelsuseMethodTwoforsetupandthelasttwouse MethodThree.AlldonglesarepricedaroundUSD$10.00-12.00: MethodTwo Product Name Supplier Manufacturer Chipset Ourlink Adafruit Realtek RTL8188CUS poweredUSB Thisisthesameproductas#2 802.11b Adafruit Realtek Trendnet B&H TEW648UBM Realtek Power NOTES requirements RTL8188CUS none Theboardmayfreezeupwithoutusinga poweredUSB.Mayalsoneedtorebootand RTL8188CUS poweredUSB run.Usethereset(S1)buttontogeta connection. MethodThree Logic ThisissoldbyAdafruitasthesame productas#1;however,thereseemstobe somedifferencesinceapoweredUSBis notrequired. UWN100 Supply Ralink/MediaTek MT7601 poweredUSB UWN200 Logic Supply Ralink/MediaTek MT7601 poweredUSB Thisusesantennae. Note UWN200isnottestedbytheauthorbutcitedbytheBBBGoogleforumpostersasa compatibledonglewithpossiblysuperiorperformancegiventheantennaaddition. Howtodoit… Methodone:Graphicaldesktopapplication Inlieuofthecommandline,thecurrentdistributionofDebian7(3.8.13-bone71,Wheezy) includesahandygraphicaltool—WicdNetworkManager—tosetupWi-Fi.Thisrecipeis quitesimple: 1. PowerupyourBBBvia5VDC. 2. Logintoadesktopsession. 3. Inthelowerleft-handcornerofyourscreen,clickonthebird-likeiconandthen navigatetoInternet|WicdNetworkManager. 4. Inthenewlyopenedwindowoftheapplication,clickontheSwitchOnWi-Fi button.Thedonglewillnowbeginscanningforaccessiblenetworks. 5. Chooseyourlocalnetwork.Enteryourpasswordinthepopupwindowaccordingto thetypeofencryptionyournetworkuses.Then,clickonOK.Afterafewmoments, yourdonglewillbeconnected. 6. Checktheconnectionwiththepingcommand: $pingwww.google.com Ifalliswell,youwillbegettingsolidpingbackmessages. Althoughtheprecedingstepsarestraightforward,youmightfindthatyourdonglewillnot workwiththisrecipeorthatyouareusingadifferentversionofthekernelandeasy connectivityeludesyou.Ifso,hereareotherrecipestogetconnected. MethodTwo:commandlineoption1 ConsultthetableatthebeginningofthissectionforthetestedmodelsthatuseMethod Two.NotethattheyallusethesameRTL8188CUSchipset.Thismeansthatyouwill likelybeabletouseotherdongleswiththefollowingstepsaslongastheyusethe aforementionedchipset.Nowtothesteps: 1. FromyourBBB’sdesktop,openupLXTerminal. 2. Inthecommandpromptwindow,openthefileinthedirectoryspecifiedinthe followingpath: $sudonano/etc/network/interfaces Amongothersettings,youshouldseethefollowinglinesinthefile’sopenwindow: ##WiFiExample #autowlan0 #ifacewlan0inetdhcp #wpa-ssid"mynetworkname" #wpa-psk"mypassphrase" 3. Withtheexceptionofthefirstexplanatoryline,uncomment(whichmeansremove) the#signatthebeginningofeachline.Toclarify,itshouldlooksimilartothis: ##WiFiExample autowlan0 ifacewlan0inetdhcp wpa-ssid"mynetworkname" wpa-psk"mypassphrase" 4. ChangemynetworknametoyourWi-Finetwork’sname,andmypassphrasetoyour Wi-Fipassword. Note Ifyournetworknameusesspacesorotheroddcharacters,somedonglesmaynot recognizethenameandestablishaconnection. 5. ClosethefilebypressingCtrl+x;whenprompted,typeyforyesandthenpressthe return(Enter)key. 6. PowerdowntheBBBintheterminalwindowwiththefollowingcommand: $sudopoweroff 7. PoweruptheboardagainandlogintoyourBBBdesktop. 8. YouwillnowgetasolidWi-Ficonnection.Testitviathecommandshellwiththis command: $pingwww.google.com Ifallwentwell,youshouldseeasteadyscreenoutputfromtheping. MethodThree:commandlineoption2 Consultthetableforthetestedmodelsthatusethefollowingsteps.Themaindifference betweenthesestepsandthepreviousrecipeisthatthedriversinthesedonglesrequirea differentinterface—awirelesssupplicant—withtheBBBtofunctionproperly.Before startingthesteps,besuretoremoveanyWi-Fidonglesyoumayhaveinsertedintothe USBhub: 1. Weneedtocreatea.conffileforwpa_supplicant,atoolthatcomespreloadedon thecurrentDebiandistribution.Thefollowingcommandlinewillbeusefulforthis: $sudonano/etc/wpa_supplicant/wpa_supplicant.conf 2. Pasteintheopenfilethefollowinginformation: ctrl_interface=DIR=/var/run/wpa_supplicantGROUP=netdev update_config=1 network={ ssid="my-ssid" scan_ssid=1 psk="my-psk" proto=RSN key_mgmt=WPA-PSK pairwise=CCMP auth_alg=OPEN } 3. Twothingsneedtobemodified(justasinMethodTwo):my-ssid,whichyouwill replacewithyournetwork’sname,andmy-psk,whichwillbeyournetwork’s password. 4. WenowneedtofigureouttheWi-Fidongle’sinterfacename.Todothis,wewillfirst examinewhichinterfacesarepresentusingthefollowingcommand: $ifconfig-a Thiscommandoutputsthecurrentlyactiveinterfaces,whichmayincludeeth0,lo, andusb0. 5. Rebootyourboard. 6. Pluginyourdongleandrunthesamecommandagain: $ifconfig-a Theoutputshouldnowshowthenewdevice’sinterfacename,whichcouldbera0, wlan0,orsoon. 7. Openthefileinthedirectoryspecifiedinthefollowingpath: $sudonano/etc/network/interfaces 8. Atthetopofthefile,pastethefollowingcode,replacinginterfacenamewiththe namethatappearedinStep6: allow-hotplugra0 ifaceinterfacenameinetmanual wpa-roam/etc/wpa_supplicant/wpa_supplicant.conf ifacedefaultinetdhcp 9. ClosethefilebypressingCtrl+x;whenprompted,typeyforyes,thenpressthe return(Enter)key. 10. Assumingyourdongleisstillpluggedin,runacommandthatbringsuptheinterface: $ifupinterfacename 11. PowerdowntheBBBbyrunningthis: $sudopoweroff 12. MakesureyourWi-FidongleispluggedintoapoweredUSBhubwiththehub’s USBcableinsertedintotheBBB’sUSBport. 13. Restarttheboard;thistime,plugintotheDCpowersupply. 14. YouwillnowgetasolidWi-Ficonnection.Testitviathecommandshellusingthe followingcommand: $pingwww.google.com Ifallwentwell,youshouldseeasteadyscreenoutputfromtheping. Note Sometimesyoumayneedtopoweroff,unplugthe5Vinput,andthenpluginagain asthedongleisn’talwaysrecognizedthroughtheS1(Reset)ortheS3(Power) buttons. MethodFour:DebianJessie UsingJessieistheeasiestandfastestroutetoareliableWi-Ficonnection.Hereishowto dothis: 1. PluganEthernetcableconnectedtoyourrouterintotheBBB’sEthernetport. 2. BootupandlogintoyourBBBconnectedtoamonitor. 3. Openaterminalwindowandloginasrootwiththefollowingcommand: $sudo-i # 4. Installthepackagenetworkmanager.Beforeinstallinganewpackage,alwaysbegin byupdatingyourrepositoriesasfollows: #apt-getupdate #apt-getinstallnetwork-manager 5. Now,openupthenewpackagewiththiscommand: #nmtui Arudimentaryinterfaceshouldopenupintheterminalwindow,similartothe followingimage: 6. SelectActivateaconnection. 7. Inthenextwindow,selectyournetwork,andyouwillbepromptedforthepassword. 8. Quitthenetworkmanagerscreenafterputtinginyourpassword.Then,checkto verifythatyourdonglenowhasanIPaddressinthewlanXinterfacewiththis command: #ifconfig-a 9. Now,powerdown,removetheEthernetcable,andrebootusingthiscommand: #reboot 10. Runthemagicalpingcommandtocheckhowwedid: $pingwww.google.com Voila!YourBBBshouldnowbeconnectedwirelessly. There’smore… SomeusersreportthattheboardcaninterferewithaWi-Fidongle’sUSBsignal.So,if youdonotgetareliableconnection,positionyourpoweredUSBdevicecontainingthe Wi-FidongleafewfeetawayfromtheBBB. Seealso Takealookatalistofothercompatibledongleshereat http://elinux.org/Beagleboard:BeagleBoneBlack#WIFI_Adapters. Packagemanagement–Installing packagesusingapt-get IfyouareanewcomeronLinux,youwillfindthatmanagingsoftwareonyourBBBisa verydifferentexperiencefromtheoneonyourWindowsorMacbox.Linuxdistributions haveaverydifferentsensibilitywhenitcomestoinstallingandsupervisingyoursoftware. Insomeways,itisakintowhatyoursmartphoneuniverseislike:yougotoacentralized place(GooglePlay,AppStore,andsoon)anddownloadavettedapplication. Ofcourse,therearehugedifferencesinLando’Linux.Firstly,everythingisfree. Secondly,everythingis(mostly)opensource.Thirdly,piecesofyourpackage— dependencies,libraries,andsoon—thatevolveandimprovearetreatedasseparate entitiesthatonlyneedtobeconjoinedwhenyouarereadytoactuallyinstallapieceof software. Thismeansthatyou’realwaysgettingthefreshest,moststablebuild.WhereasinClosed SourceLand,executablesarebuilttobeself-contained.Anynewmoduleorbetterlibrary thatisbuiltafterthebinarywascompiled….well,toobad.Youwillhavetowaitforthe nextrelease,wheneverthatmightbe.Andthenyouhavetopayfortheupgrade. SoftwareapplicationsforLinuxarereferredtoaspackages.Henceforth,wewillmainly usethetermpackageinlieuofapplication.Inthissection,wewilllearnthebasicsof packagemanagementthroughthefollowingtopics: Updatingpackages Upgradingpackages Installingpackages Note Theserecipesassumethatyouhaveinternetconnectivityworkingviaanyofthemethods explainedintheearlierConnectivitysection. Forourrecipesthroughoutthisbook,wewillprincipallyusetheapt-getcommandfor packagemanagement.Althoughthereareothermethods,apt-getistheeasiestandmost commonwaytohandlepackagesforabeginner. Gettingready Usethefollowingstepstoinstallpackages: 1. Updatingpackages:BeforeactuallyinstallingnewsoftwareinLinux,it’sbest practicetoensurethatyouhavedownloadedthemostcurrentversionsofyourlocal packagelistsalongwithinformationabouttheirdependencies.Youexecuteoneof themostcommoncommandsintheLinuxrepertoire: $sudoapt-getupdate Asaresultofthiscommand,wegetaresynchronizedpackageindexfilethatis targetednotonlyatyourspecificLinuxdistributions,butyourhardwareenvironment aswell.FortheBBB,thismeansthatyourpackagemanagerknowstoonlygrab packagesthatareDebian-savvyandcompatiblewiththeArmboardarchitecture. 2. Upgradingpackages:Next,youwanttograbandupgradetonewversionsofthe packagesalreadyinstalledonyourBBB,whichtheapt-getupdatewillpresumably havechronicled,throughthefollowingcommand: $sudoapt-getupgrade 3. Finally,yougettoinstallyournewwhizzytoolorapp!Usethiscommand: $sudoapt-getinstallpkg_name Howtodoit… Let’sdoarealpackage,though,onethatwewillbeusinginalaterchapter.Forour recipesfocusedondebugginginChapter3,PhysicalComputingRecipesUsing JavaScript,theBoneScriptLibrary,andPython,wewilluseatoolcalledgdb,alsoknown asGNUDebugger,whichisastandardtoolintheLinuxarsenalthus: $sudoapt-getupdate $sudoapt-getupgrade $sudoapt-getinstallgdb Onceyou’veinstalledtheprettypackageonyourBBB,it’suseful—andofteninteresting —totakeapeekinside.So,anotherapt-getvariantgivesyousomeinterestinginsight: $sudoapt-cacheshowpackage-name Inourcase,thiswouldbeasfollows: $sudoapt-cacheshowgdb Package:gdb Version:7.4.1+dfsg-0.1 Installed-Size:5192 Maintainer:HectorOron<[email protected]> Architecture:armhf Depends:libc6(>=2.13-28),libexpat1(>=2.0.1),libgcc1(>=1:4.4.0), libncurses5(>=5.5-5~),libpython2.7(>=2.7),libreadline6(>=6.0), libtinfo5,zlib1g(>=1:1.2.0),gdbserver Suggests:gdb-doc Description-en:TheGNUDebugger GDBisasource-leveldebugger,capableofbreakingprogramsat anyspecificline,displayingvariablevalues,anddetermining whereerrorsoccurred.Currently,gdbsupportsC,C++,D, Objective-C,Fortran,Java,OpenCLC,Pascal,assembly,Modula-2, andAda.Amust-haveforanyseriousprogrammer. Homepage:http://www.gnu.org/s/gdb/ Description-md5:8132571fab028a898d029eecd88e571e Seealso Tolistallinstalledpackages,enter: dpkg--list Alternatively,youcanusethiscommand: dpkg--list|less Youcanalsorunthefollowingcommand: dpkg--list|grep-i'http' Notethegrepoptionaspartofthecommandstring.Oneofthemostpopularcommands onLinux,grepisapowerfulsearchmechanismtofindaparticularfile,adirectory,a patternorchunkofcode. SSH/Remoteaccess LocalcontrolofyourBBBshouldalwaysbesupplementedwiththeabilitytocontrolit remotely.Thereareavarietyofreasonsyoumaywanttodothis.Forexample,youmay wanttooperatethedevicefromonelocationwhileyouareinanotherlocation. Theprimaryandmosttypicalreasonforremoteaccess,however,istoruntheboard headlessly.Thismeansrunningitwithoutadisplay,keyboard,ormouse.Headlesscontrol is,infact,thewayIoperatetheboardabout99percentofthetime.Irarelyevenusean externalmonitorwiththeBBBsinceitrequiresfewerpiecesofhardwareandreduces headache. Therearetwobasicrecipetypesforremoteusage: 1. CommandlineviaSSH 2. GUI-centricviaVNC UsingSSHtocontrolyourBBB UsingSSH(secureshell)onadesktopPCorotherclientwillgiveyoucontroloveryour BBBacrossanetwork.Hereistherecipe. Howtodoit… OnyourBBB: 1. OpenLXTerminal. 2. Now,enterthefollowingcommand: ~$sudoifconfig 3. Intheonscreentext,gettheIPaddressofyourBBB.Underetho0,lookforinet addr:xxx.xxx.xxx.xxx. OnyourPC/Mac/Linuxbox: 1. Openyourpreferredterminalapp.OntheMac,it’sjustcalledTerminal. 2. Atthecommandprompt,typethefollowing: ~$ssh-keygen-R<your_ip_address> 3. Youshouldthengetthefollowing: /Users/username/.ssh/known_hostsupdated. Originalcontentsretainedas/Users/username/.ssh/known_hosts.old username@hrh:~$ 4. Next,typethefollowing: username@devicename:~$sshdebian@<your_ip_address> 5. Now,youwillseethefollowingonscreen: Theauthenticityofhost'<your_ip_address>(<your_ip_address>)'can't beestablished. RSAkeyfingerprintis97:b4:04:f5:24:f3:75:f9:90:3c:cc:ff:78:36:f3:d9. Areyousureyouwanttocontinueconnecting(yes/no)? 6. Typeyes(noquotes,alllowercase). 7. Youwillthenseethefollowingwithanewprompt: Warning:Permanentlyadded'<your_ip_address>'(RSA)tothelistof knownhosts. debian@<your_ip_address>'spassword: 8. TypethepasswordofyourBBBlogin(thedefaultistemppwd). 9. Ifyoutypedinyourpasswordcorrectly,youwillendupbackhere: debian@beaglebone:~$ Congratulations!You’venowgainedcontroloveryourBBBusingthecommandlinefrom anotherbox. UsingVNCtocontrolyourBBB So,areyoustillnotentirelycomfortablewiththecommandlineandwantaccesstosome oftheGUI-basedtools?Or,doyouneedtotestandcontrolusinganactualGUI?Or, perhaps,isyourappnotrunningproperlyfromonlythecommandline?Then,it’stimefor VNC. VirtualNetworkComputing(VNC)allowsremoteaccesstoadevicethat’srunningan Xsessionorwindows/GUI-basedsystemfromaremotedeviceorclientmachine.With thecurrentDebiandistribution,runningVNCiseasierthaneverastheBBBarrives preloadedwiththerelevantpackage,theTightVNCserver.Onyourclientbox,youneed toinstallaremoteviewer. Gettingready… Foryourclientbox,downloadandinstalloneofthefollowingremoteviewerapplications: TheWindows,Mac,andLinuxboxes:http://www.tightvnc.com/ VNCViewer:http://www.realvnc.com/download/viewer/ Onceagain,we’recookinguparecipefromaMacperspective,soVNCVieweritwillbe. Howtodoit… Asnoted,theBBBnowcomeswiththeremoteserverinstalled,sotheonlynew installationrequiredistheoneforyourclientbox.Forthis,performthefollowingsteps: 1. Installtheclientapponyourdesktopbox. 2. Fromtheterminalwindow,runtheVNCserverontheBBBthroughthefollowing command: $vncserver 3. Next,youwillneedyourBBB’sportaddress.Youwillfinditinthestatusmessage nowrunningintheCLIwindow: New'X'desktopisbeaglebone:1 Note Yourportnumbermaydiffer. 4. Onyourdesktopbox: OpenupVNCviewer(orwhicheverclientappyou’reusing) TypeintheIPaddressofyourBBBandtheportnumberattheendoftheVNC serverfield:123.456.78.9:1.Thedefaultmybe“beaglebone:1. 5. YouwillthenhaveawindowpopupUnencryptedConnection. 6. ClickContinue. 7. SelectConnect. YouwillnowbeloggedintoyourBBB,beabletoseethedesktop,andhavefullcontrol overthedeviceusingthemouseonyourclientbox. There’smore… Security:UsingthedefaultorbasicsettingsinVNCisnotsecure.Unlessyou’re familiarwithdoingso,thesessionsarenotencrypted.Onequick,thoughimperfect, measureistochangefromthedefaultserverport5900toaspare,randomlychosen port. GettingtheIPaddressonaheadlessBBB:Fromanothercomputeronthenetwork, usethefollowingstepstolistanetwork’sbasketofIPaddresses: ifconfig|grepinet NotethatthiswillshowtheIPaddressrangeandonlynamespecifichost devicesbutnototheraddresses. Thismethodmayonlybefeasibleinasmallernetwork,wherethenumberof addressesismorelimitedandyoudonothavetolookforaneedleinahaystack. YouwilllikelyneedtoinstalltheNMapsecurityscanner(http://nmap.org/). Checkwhetherit’sinstalledfirst. Then,typeinsudonmap-sn-PE192.168.1.0/24(withtheIPaddressofthe hostmachineandthen/xxxfromtheendrangeshowninStep1). Browsetothelocalrouteradminaddress:Findtheconfigurationoptionsthatshow allcomputers/devicesonthenetworkwiththeirIPaddresses. SetastaticIPaddress:Thistakesseveralsteps,butoneofthebesttutorialsisDerek Molloy’sathttp://derekmolloy.ie/set-ip-address-to-be-static-on-the-beagleboneblack/. Systemimages Inthissection,wewillgiveyoutherecipestodownload,install,andupdatetheDebian distributionfirmwareandsoftwarekernelthatcomespreloadedonyourboard.Finally,we willwalkyouthroughchangingoverfromthecurrentlyshippingDebian7.0(Wheezy)to thenewerDebian8.0(Jessie). Therearetwobasicmethodstoinstallandupdateyourboard’ssoftware:installtheOS ontotheeMMCsolid-stateinternaldriveoracompatibleSDcard(refertothe compatibilitylistinfurtherchapters).Ineithercase,theprocessiscommonlycalled flashingtheimage,whichishowwewillrefertoit. Note OneofthesignaturefeaturesoftheBBBisitsabilitytousemanydifferentflavorsof Linuxtoruntheboard.Inthefurtherchapters,youwillfindreferencesandmaterialto installvariousversionsofLinux,includingUbuntu,ArchLinux,andAndroid. OSimageflashing–internaldriveboot AlthoughyourboardcomespreloadedwithashippingversionofDebian7,youcertainly wanttounderstandhowtoreplaceitorupdateitwhennecessary.Here,wewilldiscuss therecipetoflashtheOStoyourinternalsolid-statedrivealongwithhowtoupdateto Debian8. Asofthewritingofthisbook,Debian8(Jessie)isstillconsideredatestingoption, whereasDebian7(Wheezy)istheofficialshippingfirmwareOSfortheBBB. Additionally,youwillnotice“LXQt”aspartoftheURLdownloadlink.LXQtisa lightweightQtvariantofLXDE,theLightweightDesktopEnvironment.Qtisatoolsetto buildcrossplatformapplicationsthatyoucanuseonMacOSX,Windows,andLinux.It usestheC++programminglanguageandhasaniceGUIbuilder,soitisapopularchoice formanyopensource-centricdevelopers. Gettingready Youwillneedthefollowing: BeagleBoneBlackpowereddown. A5VDCpowersupply.Youcanalsousea5V“wallwart”poweradapterwitha USBportonitaslongasitcandeliver1A. AmicroSDcard(4GBorgreater). AnSDcardreader.YouwillinsertthemicroSDcardintothecardreaderandthecard readerintoanSDportonyourdesktopmachine. AboardconnectedtoeitheranHDMImonitororanLCDcape(asexplainedearlier inthischapter). Note Ifyouhaditconnected,ensurethatyouremovetheEthernetcablebeforeproceedingwith thisrecipeasanEthernetconnectionrequiresmorecurrentandwilllikelycausethe softwareflashingtofail. Howtodoit… ThefollowingstepsareusedtoflashtheOStoyourinternaldrive: 1. Usingthewgetcommand,getthesoftwareandputitonyourdesktopcomputer. ThelatestversionoftheshippingOS,Debian7(Wheezy),isavailableat http://beagleboard.org/latest-images.So,youneedtogettheexactURLandappendit accordinglyinthefollowingcommand: $wgethttps://rcn-ee.com/rootfs/bb.org/release/YEAR-MONTH-DAY/lxde4gb/BBB-eMMC-flasher-debian-7.8-lxde-4gb-armhf-YEAR-MONTH-DAY4gb.img.xz TheprecedinglinkreferencesaRev.Cboard,thecurrentlyshippingversion.Ifyou haveanotherversionoftheBBB,youcanfindsoftwareforpriorreleasesat http://elinux.org/Beagleboard:BeagleBoneBlack_Debian#Debian_Build_Instructions. Note Debiantestingversion YoucanalsoalternativelyinstallDebian8(Jessie)usingthesamestepsasthe following,substitutingtheURLandappendingthemonth,day,andyearaccordingly: https://rcn-ee.com/rootfs/bb.org/testing/YEAR-MONTHDAY/lxqt-4gb/BBB-eMMCflasher-debian-8.0-lxqt-4gbarmhf-YEAR-MONTH-DAY-4gb.img.xz 2. Next,unpack,unzip,orunarchivethedownloadedfileusingyourfavoritearchive tool.OnmyMac,IuseUnarchivesinceit’seasytouseandflexible.After unarchiving,therewillbean.imgfileavailableinyourchosenfolder. 3. Now,wewillflashthe.imgfiletothemicroSDcard.Theeasiestmethodistousea GUI-typetoolsuchasPiFiller(originallydesignedforRaspberryPibutworks equallywellontheBBB)fortheMac,orWin32DiskimageronyourWindowsbox. WaitforapromptfromtheimagingsoftwarebeforeactuallyinsertingtheSDcard intothedesktop’sslot.Dependinguponthespeedofyourdesktopbox’s environment,theflashing/writingprocesswilltakeanywherefrom15to30minutes. 4. RemovetheSDcardfromyourdesktopaftertheflashingfinishesandthenremove themicroSDcard.EnsurethatyourBBBispowereddownandtheninsertthecard intothemicroSDslotontheBBB. 5. PressandholdtheBootswitch,whichisthesmallbuttonontheBBBabovethe microSDcardslot.Takealookatthethefollowingimagetoconfirmthatyouare pressingtheBootswitchandnotoneoftheotherswitches: 6. Whileholdingthisbuttondown,insertthe5Vsupplyintothepowerjack. 7. Astheboardbootsup,thearrayofLEDsnexttotheEthernetjackattheotherendof theboardwillbeginflashinginasweepingpattern. 8. Whenthebootcompletes,allfourLEDsshouldbelitandnotblinking.Removethe powercableandthenremovethemicroSDcardfromtheBBB. 9. Now,plugthe5Vsupplybackintotheboardagain.TheBBBwillbootdirectlyfrom theeMMC. 10. Inyourterminalwindow,wewillnowSSHintotheboardwiththefollowing command: [email protected] 11. Whentheloginpromptsappear,usethefollowingcredentials: username:Debian password:temppwd Youshouldnowbereadyforactionwiththedefaultgraphicaldesktopshowingthe BeagleBoneBlacklogointhelower-rightcornerofthescreen.Thismeansthatyou arealmostreadytogo…. There’smore… GoodpracticetomanageyoursystemOSandfilesincludeshavingenoughroomtoadd morepackages,beingabletocloneyoureMMC,andbackingupyourcodeimage. Expandyourpartition UnlessyouuseanSDcardlargerthan8GB,you’relikelytorunoutofspacequicklyon yourcardevenafteramodicumofpackagesareinstalled.So,saveyourselfawholelotof hurtandexpandyourpartitionsize….now!Thefollowingstepswillbeuseful: 1. Changetotherootuserwiththiscommand: $sudo-i 2. Checkthediskspaceusageusingthefollowingcommand: root@beaglebone:~#df-h 3. Gotothisdirectoryasfollows: #cddir:/opt/scripts/tools 4. Checktheavailablefilesusingthiscommand: #ls Youwillseethegrow_partition.shscript.ThisisabashscriptincludedintheBBB distributionthatwillrunaroutinetoexpandyourSDcardspace. Now,runthefollowing: #bashgrow_partition.sh Alternatively,youcanalsorunthefollowingcommand: #shgrow_partition.sh 5. Finally,runninglsagainonyourdrivewillshowahigherpercentageofavailable space: #ls Backingupacodeimagetoafile 1. InsertamicroSDcardintoyourdesktopmachine’scardreaderandconfirmthatit’s recognized. 2. Onyourdesktopbox(Mac,inourcase),openTerminalandtypethefollowing: $diskutillist 3. Fromthelistshown,writedowntheIDforyourSDcard.Inmycase,itlookssimilar tothis: /dev/disk1 4. Now,wewillrunaroutinethatbacksupthecontentofthecardtoyourdesktopand simultaneouslyarchivesittosavespace: sudoddif=/dev/rdisk1bs=1m|gzip-9>~/Desktop/backupimage.img.gz 5. Inputyourpasswordattheprompt.Whenyoudoso,theroutinewillrunandmay takeseveralminutesdependingontheamountofdatayou’rebackingup. OSimageflashing–theSDcardboot Inthissection,youwilllearntherecipestoloadtheOSandbootfromamicroSDcard. MuchoftheprocessissimilartohowweflashtheeMMCinternaldrive;however,itis importanttotakenoteofthedifferences. Gettingready Youwillneedthefollowing: BeagleBoneBlackpowereddown A5VDCpowersupplyoraUSBtetheredtotheBBB. AMicroSDcard(4GBorgreater) AnSDcardreader.YouwillinsertthemicroSDcardintothecardreaderandthecard readerintoanSDportonyourdesktopmachine. AboardconnectedtoeitheranHDMImonitororanLCDcape(asexplainedearlier inthischapter). Howtodoit… Performthefollowingsteps: 1. Usingthewgetcommand,getthelatestsoftwareimageandputitonyourdesktop computer. ThelatestversionoftheshippingOSisathttp://beagleboard.org/latest-images.So, youwillneedtogettheexactURLandappenditaccordinglyinthefollowing command.NotetheURLdifferencefromthepriorrecipeforflashingtheinternal drive: $wgethttps://rcn-ee.com/rootfs/bb.org/release/YEAR-MONTH-DAY/lxde4gb/bone-debian-7.8-lxde-4gb-armhf-YEAR-MONTH-DAY-4gb.img.xz TheprecedinglinkreferencesaRev.Cboard,whichisthecurrentlyshipping version.IfyouhaveanotherversionoftheBBB,youcanfindsoftwareforprior releasesat http://elinux.org/Beagleboard:BeagleBoneBlack_Debian#Debian_Build_Instructions. Note Debiantestingversion YoucanalsoalternativelyinstallDebian8(Jessie)usingthesamestepsby substitutingthefollowingURLandappendingthemonth,day,andyearaccordingly: https://rcn-ee.com/rootfs/bb.org/testing/YEAR-MONTHDAY/lxqt-4gb/bone-debian8.0-lxqt-4gb-armhf-2015-05-04-4gb.img.xz 2. Next,unpack,unzip,orunarchivethedownloadedfileusingyourfavoritearchive tool.OnmyMac,IuseUnarchiveasit’seasytouseandflexible.Afterunarchiving, therewillbean.imgfileavailableinyourchosenfolder. 3. Now,wewillflashthe.imgfiletothemicroSDcard.Theeasiestmethodistousea GUI-liketoolsuchasPiFillerfortheMacorWin32DiskImageronyourWindows box. WaitforapromptfromtheimagingsoftwarebeforeactuallyinsertingtheSDcard intothedesktop’sslot.Dependingonthespeedofyourdesktopbox’senvironment, theflashing/writingprocesswilltakeanywherefrom15to30minutes. 4. RemovetheSDcardfromyourdesktopaftertheflashingfinishesandthenremove themicroSDcard.EnsurethatyourBBBispowereddownandtheninsertthecard intothemicroSDslotontheBBB. EitherwiththeUSBtetherora5Vpowersupply,poweruptheBBB. 5. Inyourterminalwindow,wewillnowSSHintotheboardwiththiscommand: [email protected] 6. Whentheloginpromptsappear,usethefollowingcredentials: username:debian password:temppwd UpdatingyourcurrentOSkernel Sometimes,youwanttostickwithwhatyouhavealreadyinstalledasitrunsfineanddoes thejob.Butmoreoftenthannot,youwantthelatestandgreatestkernel,including updatingtoDebian8.0,akaDebianJessie.Thefollowingstepsshowyouhow: 1. Ensurethatyouareloggedinastherootuserwiththefollowingcommand: $sudo-i root@beaglebone:~# 2. Checktheversionofthekernelthatyouhavecurrentlyinstalled: #uname-r 3.8.13-boneXX 3. Navigatetothedirectorywiththeupdatekernelscript: #cd/opt/scripts/tools/ 4. Runacommandonthekernelyoucurrentlyhaveinstalledthatpullsdowntoyour localdriveinformationregardinganychanges: #gitpull Note Wewillexplorethegitcommandinalaterchapter. 5. Now,wewillrunthescriptthattakesadvantageoftheinformationwejustpulled downandupdatesourOS: #./update_kernel.sh 6. Timetoreboot!Runthefollowingcommand: #reboot 7. Whentheloginpromptsappear,usethefollowingcredentials: username:debian password:temppwd 8. Finally,verifythatthescriptdidwhatweexpectedthroughthefollowingcommand: $uname-r 3.8.13-boneXX ComparetheprecedingscreenoutputwiththeversionyouwrotedowninStep2ofthis recipe.Youshould,hopefully,seethenewversionkernelgoodness. Seealso Ifyouknowaspecificversionyouwant,youcanalsoupdateormodifyyourkernelwith analternativemethodusingaseriesofcommand-linesteps: 1. Loginasrootasfollows: $sudo-i 2. Checkthekernelversionwiththiscommand: #uname-r 3. Updateyourrepositorieswiththiscommand: #apt-getupdate 4. Findavailablekernelversionsusingthis: #apt-cachesearchlinux-image Thescreenoutputwilldeliveralonglistofkerneloptions.Scrollthelistuntilyou findonewiththelabel:Linuxkernel,version3.8.13-boneXX(withtheXXbeinga two-digitnumber). 5. Installthekernelyouwantbyexplicitlyspecifyingaversionnumberfromthelistin thepriorstepasfollows: #apt-getinstalllinux-image-x.x.x-xx 6. Rebootyourboardasfollows: #reboot $uname-r Yournewkernelshouldnowbeinstalledonyourboard. Chapter2.BasicProgrammingRecipes AsthenextstepinlearninghowtocontrolandmanipulateyourBeagleBoneBlack,we willtakealookatthefollowinglanguages,tools,andsimpleprogrammingrecipesinthis chapter: IntroductiontoBoneScript ToggleLED UsingtheCloud9IDE Node.jsbasicrecipes AddinganewmoduletoNode.js UsingNode.jswithJohnny-Five Pythonbasicrecipes Addinglibraries RunningaPythonscripttocontroltheLEDs Introduction Inthefirstchapter,ourobjectivewastoensurethatallyounewchefswerereadywith sharpenedknivesandtherightcombinationofseasonings,oratleastequippedwitha basicworkingenvironmentwithhappy,flashingblueLEDsonyourBeagleBoneBlack andsomecommand-linecontrols. Inlaterchapters,youwilllearnhowtouseotherphysicalpiecesofthesystem,including controllingthephysicalpinsontheboard.Beforewegetthere,however,youwillneedto takeaquickdipintoahandfulofrecipesusingprogramminglanguagesthataretypical andessentialforbuildingrobust,compellingprojectsonBeagleBoneBlack.So,giveabig roundofapplausetoyoursoon-to-befaithfulfriends:BoneScript,Node.js,andPython. IntroductiontoBoneScript BoneScriptisBBB’shandyNode.jslibrary.WhatisNode.js,youask?Also,whybother withanotherlibrary?WewilltalkmoreaboutNode.jsinthenextsection.However,asfar asanotherlibrarygoes,we’rebotheringwithitbecauseit’sdesignedtoworkseamlessly withthehardwareofyourboard,makingphysicalcomputingdevelopmentunder embeddedLinuxfasterandsimpler.UsingArduino-likefunctions,BoneScriptexploitsthe vastdeveloperbaseofJavaScript. Typically,yourintentioninusingNode.jsandBoneScriptonBBB—justasitiswith Pythoninthenextsection—istogainaccesstotheheaderpins,theGeneralPurpose In/Out(GPIO)pins.AlthoughwewilldiscussmoreaboutGPIOsinalaterchapter,for nowourplanistobrieflyexploresomefundamentalmethodstocontrolthehardware. ToggleLED Inthissection,let’sdoaquickandeasyrecipewithBoneScript,onethatturnsonandoff theonboardLEDs,alsoknownasUSRLEDs.Wewilltacklemorecomplexrecipeswith BoneScriptinthenextchapter. Howtodoit… Inordertodothis,performthefollowingsteps: 1. RemoveallcablesandpowerfromyourBBB. 2. PowerupyourboardviatheminiUSBusingyourdesktopUSBport. 3. OntheBEAGLEBONE_BLACKdevicethatappearsonyourdesktop,browsetoandopen theSTART.htmfile(someversionsoftheOSmayhaveaslightlydifferentfilename, suchasBASIC_START.htm). Note NotethatonDebian8(Jessie),yourboardwillbelabelledBEAGLEBONEonthe desktopandnotBEAGLEBONE_BLACK. 4. ScrolldownthepagetoBoneScriptinteractiveguide,whereyou’llseean embeddedscriptthatyoucanruntointeractwithBBB. 5. ClickonRun. 6. AlltheLEDsshouldstayonfortwoseconds.Letthemreturntoblinking. 7. NowchangeUSR0fromb.HIGHtob.LOW. 8. Changethetimingfrom2000to12000. 9. Youshouldnowseetwodifferencesfromthedefaultscriptthatyoujustran.Firstly, theLEDsnowstayonforlonger(12seconds),andtheUSR0LED—theLEDclosest totheResetbutton—nowremainsoff. Voila!You’retalkingtothehardwareusingJavaScriptandBoneScript.! Seealso IfyourunintoanyerrorswhilerunningyourBoneScriptrecipes,suchasCannotfind module‘bonescript’,youmayneedtodotwothings: 1. ChecktheversionofBoneScriptthatyouarerunningonyourboardusingthe followingcode: $node-pe"require('bonescript').getPlatform().bonescript" 2. InstallthelatestversionofBoneScript;todothis,youneedtobetherootuserfirst. Then,youcanexecutethefollowingcommand: $sudo-i #TERM=nonenpminstall-gbonescript UsingtheCloud9IDE Asthenameimplies,Cloud9isacloud-hostedtoolkit.ForBBB,itprovidesanintegrated, opensourcedevelopmentenvironmenttobuildBoneScript-powered(JavaScript)code.Its strengthsareJavaScriptandNode.js(whichitactuallyusesonthebackend;we’lldiscuss thisinthenextsection),thoughitisalsoveryflexiblewithotherprogramminglanguages suchasPHP,Ruby,andPython. TheIDEcomespreloadedandreadytouseimmediatelyontheBBBfirmwarewithno setupnecessary.WithyourboardstillconnectedviaUSB,let’sdoasnappyrecipe. Howtodoit… 1. ToloadtheIDE,openabrowserwindowtothefollowingURL: http://192.168.7.2:3000/ide.html.TheIDEwillopentoawindowlikethis: 2. Next,changethecolorsettingstoimprovereadabilityintheUI.Thedefaultblack schemeisfunereal;let’schangeittoCloud9BrightThemeinstead. Note NotallUIscreenschangetothenewcolorscheme;there’satemporarybuginthis betareleaseofCloud9’sIDE. 3. Onehandyfeatureinthelowerportionofthescreenisacommandshellwindow. Thisgivestheuseranintegratedcommand-linecontrolwithintheIDEproper withouttheneedtopopopenanotherwindowforashellapplication. 4. UnlessyouwanttocustomizetheUIorlistentotheaudiotutorials,closethe Welcometab. 5. Createanewfilebyclickingonthe+sign. 6. Copyandpastethefollowingcodeinthenewwindow: varb=require('bonescript'); varledPin="USR0"; b.pinMode(ledPin,b.OUTPUT); varstate=b.LOW; b.digitalWrite(ledPin,state); setInterval(toggle,1000); functiontoggle(){ if(state==b.LOW)state=b.HIGH; elsestate=b.LOW; b.digitalWrite(ledPin,state); } ForyouArduinousers,thecodefeelskindoffamiliar,right?Forthoseofyouwhoare brandnewtophysicalcomputingandhardware,let’sbreakdownsomeofthelinesbefore executingthescript. Attheoutsetofthecode,weneededtoestablishcertaingroundrules,namelythatwewill beusingthefunctionalityofBoneScript.So,wehadtoincludetheBoneScriptlibrarywith allitsfunctionalitiesandcodingshortcutswiththefollowingscript: varb=require('bonescript'); Next,weneededtoestablishwhichpinorpinsweintendedtouse(USR0)andthencreatea variableofitsoastonothavetowritethepinnamerepeatedlythroughoutthescript.The followingcodehelpedusdothis: varledPin="USR0"; Oncewehadananointedpintoplaywith,weneededtosetitsmode—inotherwords, initializeit—sothatwecouldinteractwithitanddeclarewhetheritwillbeaninputor outputpin.Ifwewerecontrollingabutton,thepinwouldneedtoberecognizedasan input;however,inourcasewehadanLED,whichneededtobeintheoutputmode.Note alsob.,whichisusedinthenotation.Thiswasusedtotellthecodeinterpreter—Node.js —thatthesubsequentfunctionwillbefoundintheBoneScriptlibrary.Forthis,weused thefollowingcode: b.pinMode(ledPin,b.OUTPUT); Withthepininitialized,wedeclaredwhetherthepinbeganinastateofbeingon(HIGH)or off(LOW).Atthispoint,wealsoneededtotelltheinterpreterthatwewouldactuallybe writingtothepin,asopposedtocollectingdatafromitorreadingit,withthefollowing script: varstate=b.LOW; b.digitalWrite(ledPin,state); Ourtaskmovedontotellingtheinterpreterhowoftenwewillbedoingaparticularthing. Inourcase,wetoggledthelightonandoffin1000-millisecondintervalsbyexecutingthe followingscript: setInterval(toggle,1000); Itwasgreatthatweknewthefrequencyofourtoggleevent,butaswedidnotyettellthe interpreterwhatthetoggletermactuallydoes,wehadtoexplainitsmeaning.We describeditasafunctionthatalternatesbetweenthestatesofHIGHandLOW,whichwas appliedtothepinthatwedeclaredatthebeginningofourscriptwiththefollowinglines ofcode: functiontoggle(){ if(state==b.LOW)state=b.HIGH; elsestate=b.LOW; b.digitalWrite(ledPin,state); } Okay!Forthemoment,that’senoughofascriptbreakdown.Ifyouhavenotalready jumpedahead,let’scontinuewiththerecipe’sstepsandtakealookathowtheselines actuallyaffecttheLED. Now,performthefollowingsteps: 1. Createanewdirectorycalledprojectsandsavethefileinit,namingthefile major_tom_blinks.js. 2. Now,runthefileintheterminalwindowatthebottomoftheIDE.First,ensurethat younavigatetotheproperdirectoryusingthefollowinglinesofcode: $cdprojects $nodemajor_tom_blinks.js 3. TheUSR0LED(whichistheonboardLEDclosesttotheresetbutton)shouldnow havechangeditsconstant“heartbeat”-patternedblinktoslower,steadier1-second blinkintervals. 4. Now,pressCtrl+zorclickontheStopbuttonintheterminalpanewindowatthe bottomoftheIDE.Don’tforgettodothis;otherwise,you’relikelytorunintosome errorsorconfusionintheupcomingrecipes. 5. Finally,it’sagoodideatoresettheLEDssothatyouendupwhereyoustarted.For now,theeasiestwaytodothisisbyrunningtherestorescriptat http://beagleboard.org/Support/BoneScript/demo_blinkled/. Seealso Youcanfindmoreinformationathttp://beagleboard.org/Support/BoneScript. Node.jsbasicrecipes JavaScriptontheserver;letthatsinkinforamoment…. WhatisNode.js?Thequickanddirtyansweristhatit’sauniqueandveryfastserver environmenttohandlerequestsfromclientapplicationsandappsthatareauthoredin Javascript.It’sJavascriptontheserver.Morespecifically,it’sanI/Oframeworkthat: Isevent-driven Isnonblocking RunsontheV8JavaScriptengine ExecutesJavaScriptcodeontheserverside Isrichinrobustdeveloperlibrariesandmodules Node’sspeedmakesitparticularlyusefulinphysicalcomputingscenariosasitcanhandle requestsinrealtime.Afterall,whenagustofsuddenwindblowsandyourBBB-powered dronestartsteeteringmidair,youdon’twanttorelyonapokyLAMPstackandkeepthose gyroscompensating. ThegoodnewsaboutNode.js—andwe’lloftenjustcallitnode—isthatyoudon’thaveto installitbecauseitcomespreloadedontheBBBfirmware.ThebadnewsaboutNode.jsis thatitcanbeabitconfusingtounderstandforbeginners;itssheersimplicityisdaunting! However,onceyoureviewsomerecipes,you’lllikelyfindyourselfanewfangirl/fanboy ofnode. AddinganewmoduletoNode.js HereisarecipetoaddanewmoduleintoNode.js.Inthiscase,we’lluseNodemailer,a powerfulandhighlycustomizableAPIe-mailengine.Wechosethismodulebecausewe wantedtoactuallyhavethescriptdosomethinginterestingandnotjustspitoutanother onscreenprintcommand.Attheendofthisrecipe,youwillbeabletorunascriptthat sendsane-mailtoyourinbox. Gettingready OpenupLXTerminal.Alternatively,openuptheCloud9IDEinthemannerdescribedin theprevioussection. Howtodoit… Createadirectoryforyourprojectsusingthefollowingcommand: $mkdirprojects Performthefollowingstepsaftercreatingadirectoryforyourproject: 1. Browsetothisnewdirectoryandmakeanotheremailerdirectoryusingthe followingcommand: $cdprojects $mkdiremailer 2. Now,gotothenewdirectorywiththefollowingcommand: $cdemailer 3. Althoughit’snotmandatory,thefollowingcommandistheproperfirststeptosetting upyournodeenvironment: $npminit Youwillseeaseriesofpromptsthatyoucanfillout;youcanskipthembyhittingthe return(Enter)keyonyourkeyboard. Whatyouwilldowiththesepromptsandinputsiscreatethemetadatatopopulatea filecalledpackage.json.Thisfile’spurposeistogiveinformationtonpm,which allowsittoidentifytheprojectaswellashandletheproject’sdependencies. 4. Next,wewillusethefollowingcommandtoinstallthestarofthecurrentshow:a nodepackagecallednodemailer: $sudonpminstallnodemailer--save 5. Navigatetothenewdirectorycreatedbytheinstallationandopenupananowindow withanewfilename,asdescribedhere: $cdnode_modules/nodemailer $sudonanonodemailer-test.js 6. Copyandpastethiscodeinthenanowindow: //Thiscodehasbeenmodifiedfromthenodemailergithubexample. varnodemailer=require('nodemailer'); vartransporter=nodemailer.createTransport({ service:'Gmail', auth:{ user:'[email protected]', pass:'user_password' } }); //setupe-maildatawithunicodesymbols varmailOptions={ //senderaddress from:'GroundControl<[email protected]>', //listofreceivers to:'sender_name1@some_domain.com, [email protected]', //Subjectline subject:'ThisisGroundControltoMajorTom', //plaintextbody text:'Canyouhearme,MajorTom?', //htmlbody html:'<b>CanyouhearmeMajorTom?</b>' }; //sendmailwithdefinedtransportobject transporter.sendMail(mailOptions,function(error,info){ if(error){ returnconsole.log(error); } console.log('Messagesent:'+info.response); }); Note Theprecedingcodeisamodificationofnodemailer’sGitHubexample.Alsonote:if yourunintoproblemscopyingandpastingthecode,youcandownloadthecode from https://github.com/HudsonWerks/Nodemailer/blob/master/examples/nodemailertest.js. Finally,ifyouuseGmailforyouraccountinthisexampleandrunintologinerrors, therearenumeroustroublehootingtipshere:https://github.com/andris9/nodemailerwellknown/issues/3. 7. Savethenewfileusingthekeyboardcommand,Ctrl+xwithnano,andthentypeY for“yes”. Then,pressthereturn(Enter)key. 8. Now,runthefollowingcommand: $nodenodemailer-test.js 9. Ta-da!Ifallwentwell,youshouldreceiveane-mailfromGroundControlinyour inbox. There’smore… 6thingsyoushouldknowaboutNode.js:Thisisperhapsthebest(andmostsuccinct) articleonwhyNode.jshasbecomeafreighttrainforrapid,robustdevelopment,and canbefoundathttp://www.javaworld.com/article/2079190/scripting-jvmlanguages/6-things-you-should-know-about-node-js.html. TheNodeBeginnerBook:Theauthorofthisbookprovidesthefirst21pagesforfree andchargesfortherestofthebook,whichisdefinitelyworththe$20.00.Youcan finditathttp://www.nodebeginner.org/. Mixu’sNodebook:Althoughitwasoriginallywrittenseveralyearsago,itremainsan excellentin-depthintroductiontoNode.js.Thiscanbeeasilyfoundat http://book.mixu.net/node/. FromJavatoNode.js:Youcanfindthisat https://n0tw0rthy.wordpress.com/2012/01/08/from-java-to-node-js/. Forfurtherideasonwhichmodulesareoutthere,exploretheextensivelistofnode modulesfoundathttps://github.com/nodejs/node/wiki. Seealso Toexplorethisparticularmodule,includingnodemailer’swidevarietyoffeaturesand customizationoptions,checkouthttps://github.com/andris9/Nodemailer. UsingNode.jswithJohnny-Five Inthissection,wewillcoverarecipeforJohnny-Five,auniquelibrarybuiltin JavaScript/Node.jsthatisincreasinglygettingtheattentionoftheopensourcesoftware world.Althoughpositionedasaroboticslibrary,Johnny-Fiveisagreattoolsettoscratch theitchthatmanyJSdevelopershaveforhardwarenow. Oneofitsprincipaladvantagesisthatitgreatlysimplifiestheprocessofmanagingpins andallowsaprogrammertousemoreobviousnamingconventionsintheircode,suchas LEDs,buttons,sensors,andservos,ratherthanhighpins,lowpins,andsoon.Althoughit doesnotyethaveout-of-the-boxeasethatBoneScripthasforBBB,youshouldconsiderit aviableand,insomeways,morerobustalternative.Itisalsoamoremodularlibrarythan BoneScriptasthecodecanbeeasilyportedtoavarietyofplatforms.Finally,ifyouarean Arduinoaficionado,youwillappreciateitsfamiliarityasitisbasedontheArduino Firmataprotocol. Howtodoit… PerformthefollowingstepstouseNode.jswithJohnny-Five: 1. Asusual,goodpracticebeforeinstallinganewpackageistoupdateyour repositories.Youcanusethefollowingcommandlineforthis: $sudoapt-getupdate 2. Next,wewillinstallJohnny-Fiveasrootuserusingnpm(nodepackagemanager)and notapt-get,asfollows: $sudo-i #npminstalljohnny-five 3. Then,wewilladdaBeagleBone-specificpluginwiththefollowingcommand.This willmakeourboard’sI/Opinseasilyaccessible: $npminstallbeaglebone-io 4. Inaterminalwindow,openupthenanoeditorwithanewfilenameusingthis command: $sudonanojohnny5_led1.js 5. Copyandpastethiscodeinthenanowindow: varfive=require('johnny-five'); varBeagleBone=require('beaglebone-io'); varboard=newfive.Board({ io:newBeagleBone() }); board.on('ready',function(){ varled=newfive.Led(); //turntheLEDoffandonin1000msincrements led.blink(1000); this.repl.inject({led:led}); }); Note Ifyourunintoproblemscopyingandpastingthecode,youcandownloadthecode fromhttps://github.com/HudsonWerks/Johnny-Five/blob/master/johnny5_led1.js 6. Savethenewfileusingthefollowingkeyboardcommandwithnano,Ctrl+x;when promptedtypeyforyesandthenpressreturn(Enter)key: 7. Now,runthefollowingscript: $sudonodejohnny5_led1.js TheonboardLED(USR3)shouldbeginblinkingat1-second(1000ms)intervals. Wewillnotbreakdowneverypartofthescripthere;youcanfurtherinvestigateJohnnyFiveintheThere’sMore…section.However,onethingwewillpointoutisafeatureof thecodethatexpressesJohnny-Five’smodularityoverBoneScript,specificallythe followingline: varboard=newfive.Board({ io:newBeagleBone() WithJohnny-Five,thiscodesnippetisallyouneedtochangeifyouwanttorunthesame scriptontheRaspberryPi,Arduino,orUDOOboardorahugerangeofotherSOCs. “Writeonce,runanywhere”isgettingcloser…. There’smore… FormoreinsightintoJohnny-Five,it’sbesttostartbyexploringtheirwiki,whichisfullof examplesanddocumentation,athttp://johnny-five.io/.InadditiontotheBeagleBone Black,youwillnoticethatthelibrarysupportsahostofSOCsandmicrocontrollers. LearnmoreabouttheJohnny-Fivebeaglebone-iopluginandthespecificpinmappingfor theboardathttps://github.com/julianduque/beaglebone-io#beaglebone-io. Pythonbasicrecipes InadditiontoyourJavaScriptchops,someofyoureadingthismostlikelyhavesome Pythonskills.We’lltakealookatasimilarrecipetoactivatetheonboardLEDs;thistime, however,wewilldothisfromaPythonperspective. Gettingready Let’sconfirmthatyouhavePythoninstalledandworkingproperlyalongwithitsIDE. Afterthis,performthefollowingsteps: 1. Openaterminalwindowandtypethefollowing: $python 2. Atthe>>>prompt,type: >>>print"ThisisGroundControl" 3. Now,youshouldseethis: ThisisGroundControl 4. Toquit,pressCtrl+z. Addinglibraries ThecurrentDebiandistributionincludestheAdafruit_BBIOandPyBBIOlibraries,both ofwhichareextremelyusefulandcommonlyusedonBBBtocontrolthepinsofyour boardwithPython.Wewillworkwiththeselibrariesinthenextsection. Ifyou’reusingthecurrentDebian7WheezydistributionorDebian8Jessie,youcanskip tothenextsection.However,ifyouhavesomeotherversionofanOS,herearethesteps toinstallthetwolibraries. Howtodoit… PartOne:InstallingAdafruit_BBIOlibrary.Performthefollowingsteps: 1. Loginastherootuserwiththiscommand: $sudo-i 2. Usingthefollowingcommand,ensurethatyouupdateyourpackagelist: #apt-getupdate 3. Now,installthelibrary’sdependenciesthroughthefollowingcommand: #apt-getinstallbuild-essentialpython-devpython-setuptoolspythonpippython-smbus-y Note Forinstructionsoninstallingasoftwarepatchtomakeextrapinsaccessiblewiththe library(theSPIandUARTpins,inparticular),refertothefurtherchapters. 4. Now,wecaninstallthelibraryitselfwiththefollowingcommand: #pipinstallAdafruit_BBIO 5. Testyourpackageinstallationbytypingoutthiscommand: #python-c"importAdafruit_BBIO.GPIOasGPIO;printGPIO" Youroutputshouldlooksimilartothis: <module'Adafruit_BBIO.GPIO'from'/usr/local/lib/python2.7/distpackages/Adafruit_BBIO/GPIO.so'> PartTwo:InstallingPyBBIOlibrary.Performthefollowingsteps: 1. Loginastherootuserwiththefollowingcommandline: $sudo-i 2. Ensurethatyou’veupdatedyourpackagelistusingthefollowingcommand: #apt-getupdate 3. Now,installthelibrary’sdependencieswiththiscommand: #apt-getinstallpython-serialpython-setuptoolspython-devpythonsmbuspython-pip 4. Now,wecaninstallthelibraryitself.Usethefollowingcommandforthis: #pipinstall--upgradePyBBIO 5. Testyourpackageinstallationviathefollowingcommandline: #python-c"importbbioasGPIO;printGPIO" Ifallwentashopedwiththeinstallation,youroutputshouldlooksimilartothis: PyBBIOinitialized<module'bbio'from'/usr/local/lib/python2.7/distpackages/PyBBIO-0.9.4-py2.7-linuxarmv7l.egg/bbio/__init__.pyc'>FinishedPyBBIOcleanup RunningaPythonscripttocontrolthe LEDs Inthenextchapter,we’lllookatmorerobustwaystobeginusingtheGPIOpinlibrary.In themeantime,let’swrapupbydoinganonboardLEDblinksimilartotherecipewedid earlierinthechapter. However,insteadofBoneScript,we’lldoavariationoftherecipeinPythonand specificallypullonthePyBBIOlibrary’sfunctionality.Thisrecipewillworkonboth DebianWheezyandJessie. Howtodoit… PerformthefollowingstepstorunPythonscriptstocontrolLEDs: 1. OpenupLXTerminal. 2. Createapythonprojectdirectorywithinthebbb_recipe_bookdirectoryandnavigate toitasfollows: mkdirpython cdbbb_recipe_book/projects/python 3. CreateanewPythonfileusingthefollowingcode(notethe.pyfileformat): sudonanomajor_tom_blinks.py 4. Copyandpastethefollowingcodeintothewindow: #!/usr/bin/python #BlinksoneoftheBeagleboneBlack'son-boardLEDsuntilCTRL-Cis pressed.TheseLEDsincludeUSR0,USR1,USR2,USR3 #ImportPyBBIOlibrary frombbioimport* #importthetimemodulewhichallowsustosetthetimingforaloop event importtime #CreatevariablecalledledPinwhichreferstooneofthedesignated onboardUSRLEDs.YoucanchangethenumbertoanyoftheUSRLEDs listedabove. ledPin="USR3" #Createasetupfunction defsetup(): #SetoneoftheUSRLEDsasoutput pinMode(ledPin,OUTPUT) #Setupaloopandtheblinktimingtotwosecondintervals whileTrue: #StartthepinstateatLOW=off digitalWrite(ledPin,LOW) #Holdthisstatefor2seconds time.sleep(2) #ChangethepinstatetoHIGH=on digitalWrite(ledPin,HIGH) time.sleep(2) Note Ifyourunintoproblemscopyingandpastingthecode,youcandownloadthecode fromhttps://github.com/HudsonWerks/Pythonexamples/blob/master/major_tom_blinks.py 5. Runthisscript: $sudopythonmajor_tom_blinks.py 6. TheonboardUSR3LEDshouldnowbeblinkingatregular2-secondintervals. 7. Toquitthescript,pressCtrl+zonyourkeyboard. There’smore… Pythonisabigsubject,andthewebisjammedwithgreatresourcestolearnitmore deeply.Hereisasmall,selectsampleofstartingpointstoteachyourselfPython: MIT’sonlinecourseisondemand,free,andtaughtbyoneoftheircomputerscience department’sfavoriteteachers,Prof.JohnGuttag.Youcanfinditat https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-5. Courserahasseveralstrongonlinecourses.Mostoftheircoursesarenotavailableon demandbutforspecificschedulesthroughouttheyear.HerearetwoexcellentPython coursesoffered: UniversityofMICHIGANoffersPythonintheirProgrammingforEverybody series.Youcanfinditathttps://www.coursera.org/specializations/python. RiceUnversity’s8-weekcourseisanotherexcellentintroductorydivetobe foundathttps://class.coursera.org/interactivepython1-003. Python.orgisanexcellentplacetogetstartedwithitstonsoflinksonthebeginners’ pageatthelink,https://wiki.python.org/moin/BeginnersGuide/Programmers. Chapter3.PhysicalComputingRecipes UsingJavaScript,theBoneScriptLibrary, andPython Nowthatyou’rearmedtothe…er,fingertipswithyourLinuxcommandsandcanhappily controlyourBeagleBoneBlackremotelylikeapro,it’stimetogetphysicalwiththe board.So,tobeginwithourexercisesinphysicalcomputing,we’rewhippingupsome essentialrecipesonthefollowingtopics: ControllingexternalLEDs Usingbuttons–buttonpressfunction Usinganalogsensors Variableresistancesensor–photocell Usingmotors OurprogramminglanguageofchoicewillprincipallybeJavaScriptintandemwith BoneScript,whichisaNode.jsandbrowser-sidelibrary.Wewillalsoincludeorreference afewPythonscriptanaloguestobroadenourskillswiththehardware. Introduction Thebasicsofphysicalcomputingtypicallyrequireunderstandingandshapinginputand outputonyourhardware.Wewillbeginwithtakingalookattheoldchestnut, manipulatingLEDs,anexperienceyou’relikelytohavesomefamiliaritywithifyouhave readthelastchapter,orifyou’reanArduinoorRaspberryPiuser.Next,we’llplayabit withbuttonsbecausewhodoesn’tliketopushabutton?Then,itgetsmoreinterestingas weaddsensorstothemix.Afterthis,we’llgiveyousomebasicrecipesforlocomotion thatusesomemotors.Finally,we’llwinditupwiththeingredientsandstepsforsettingup aconnectionbetweenyourBBBandanArduinoboard. We’llmarchacrosstheBBB,draftthelargearmyofpinsthattheboardhasatour disposal,theGPIOs,ADCs,PWMs,andUARTs,aphalanxthatmakestheRaspberryPi lookfeeble.Alloftheseacronymsmayseemimpenetrable;however,throughoutthe courseofthisbookwewillsteadilylearnsomethingaboutallofthem. Headerpinarraywiththeirvariousfunctionsdesignatedbypinnumber AlthoughwewillhaveadashofPythoncodehereandthere,therecipesinthischapter willprimarilyconsistofBoneScript/JavaScriptingredientsanditspowerfulpotionsfor physicalcomputing.ForanextensivedocumentationoftheBoneScriptLibraryanditsupto-datereference,refertohttp://beagleboard.org/Support/BoneScript. Beforeweheadofftotherecipeland(andsincethischapterisactuallyabouthowtomake somebasicelectricalcircuits),weneedtotakeaquicklookatsomeofthefoundational principlesofelectricityandcurrent.Knowingafewthingsaboutthemwillpreventyou fromaccidentallyfryingyourboard. Theessentialsofelectronics HowmuchpowerdoesanLEDneed?WhatwouldhappenifIrana5Vcircuitwitha3V powersupply?Willmy12Vbatterypackkeeptherobotgoinglongenoughtogetthedata Ineed?Also,mostimportantly,canIattachtheSpottiswoodeGreatInductionCoilCape topins9_11and37ontheBeagleBoneBlack? Tip TheearlierversionsofBeagleBoneswerelargerthantheBlackversion.However,you shouldneverconnectanoldornewBeagleBoneBlacktoaSpottiswoodeGreatInduction Coil. Source:WilliamSpottiswoodeandinductioncoilfromWikimediaCommons/TheLondon, Edinburgh,andDublinPhilosophicalMagazine,1877.ImagecompositebyCharles Hamilton. Todiscovertheanswertotheseandother(potentially)boardburningquestions,youneed toknowabitaboutthethreepillarsofelectronicswisdomandwiring:current,voltage, andresistance: Current:Thecontinuousflowofelectrons,ortherateof“charge”throughagiven pointinacircuit. Voltage(potentialdifference):Thisindicatesthesizeoftheelectricalpotentialin yourcircuitthatallowselectronstoflow.Specifically,voltageisthedifferenceinthe electricalpotentialbetweentwogivenpointsthatallowselectronstomove.Thisis whyitisknownasthepotentialdifference. Resistance:ThisdenotesthatelectronsgethungupfromPoint-AtoPoint-B,thatis, thereisfrictionthatcanimpedetheirfreeflowofcurrent,whichwecallresistance. Howdoallthesethingsrelatetooneanotherwhenitcomestocircuitry? TheeasyanswerisOhm’slaw.Muchinkhasbeenspilledinexplainingthisfoundational principleofelectricity;wewillonlysayafewwordsandquicklythrowaformulaatyou, theonlyoneyouwillseeinthisbook:V=IxR. Knowinghowtousethisbasicformulawillhelpyoudeterminetherightcombinationof currentandresistancetoapplywhenyouwireupyourBBBcircuits.Hereisthe breakdownoftheformula: V:Thisspecifiesvoltage(expressedinvolts) I:Thisindicatescurrent(expressedinamps) R:Thisdenotesresistance(expressedinohmsandcommonlyseenasΩ) Aslongasweknowanytwoofthethreevariables,wewilluseOhm’slawtocalculatethe thirdandremainingnumber.Typically,youwillneedtouseOhm’slawtodeterminethe rightresistortousewhenyouwireupacircuit. Therearenumerousandexhaustivefreeexamplesavailableonlinethatshowyouhowto useOhm’slawforyourprojects.Hereareafewexcellentones: Sparkfun’stutorialonVoltage,Current,Resistance,andOhm’sLawisoneofthebest forbeginnersandisavailableathttps://learn.sparkfun.com/tutorials/voltage-currentresistance-and-ohms-law CollinCunningham,formerlyofMakemagazineandnowanAdafruiter,givesusthe videoversionskinnyathttps://www.youtube.com/watch?v=-mHLvtGjum4 AveryhandyonlineOhm’slawcalculatortoolisavailableat http://www.onlineconversion.com/ohms_law.htm Note Ifyoutakenothingelsefromthissection,atleastheedthisonewarning:beverycareful howyoupoweryourBeagleBoneBlack;otherwise,youmaydamageit. Headerpinsandpinmuxing Themagicalthingaboutmicrocomputersisthattheygiveyoutheabilitytointeractwith thephysicalworld.ThisinteractionisessentiallypossibleviatheGPIOsandotherpins. Thesepinsareintendedtogeneratedifferentvoltagelevelsandpulses.Thisisthe essentialpurposeofprogrammingaGPIO:youwilltelltheboardtogenerateaspecific levelofvoltageorpulseonaspecificpin. PerusingourcomplementofI/Opins,wecancounttworowsof46pinslotsonthetwo expansionheaders.Ifyoulookclosely,youwillseethatoneblockislabeledP8andthe otheroneP9.Allthereferencestoaspecificpinbeginwiththisblocknumberfirst, followedbyanumberbetween1and46.Therefore,theexamplepinslooksimilarto P8_2,P8_15,P8_24,P9_2,P9_15,andsoon. Butwhatdoyoudowithallthesepins?Notallofthemareactuallyavailable.Somehave beendraftedforotherpurposes.AccordingtotheBBBreferencemanual,theboardhas thefollowingbreakdownforpinpurposesandavailability: #ofPins Purposeofpins 65 GeneralpurposeanddigitalIOpins 8 PWMs 4 Timers 7 1.8Vanaloginputs 4.5 UARTs 2 I2C 2 SPI 2 5V 2 3.3V Note TheBBBalsoincludesanothersixmalepinstoaccommodateaserialdebugcableonthe mainboard(nottheheaders). Tounderstandthenitty-grittyofthepinsthatmaybeavailable,youcanrefertothe BeagleBoneBlackSystemReferenceManualat http://elinux.org/Beagleboard:BeagleBoneBlack.Page84describesthepinsontheP8 header,andpage86describesthepinsontheP9header.Therearealsonumerous referenceguidesonlinethathelpyouunderstandtheBBB’spinlayouts.Skiptothe There’smore…sectionforadditionalsources.Inthemeantime,thefollowingimagea snapshotviewoftheboard’sentirepinmux.Youcanalsoreferbacktothepinmapping diagramatthebeginningofthischapter. Theprocessofpinmuxing AcommonfrustrationamongnewBBBusersisthatthepinsdonotalwaysrespondas expected.Thisisbecause,bydefault,someheaderpinsareassignedtospecifictasks,such astheHDMIoutput,someareusedformultiplepurposes,andmanyofitsfunctionsare onlyavailableaftersometweaking.Forexample,pin21ontheP9headerwantstobea GPIOatsometime,whereasatothertimes,itwantstobeaPWM,aUART,anI2C,ora SPIpin. So,howdoyougetaroundthispinschizophrenia?Well,youhavetoreconfigureitforthis purpose,aprocessknownaspinmultiplexingorpinmux.Pinmuxingisfairly straightforwardandcanbeeasilyhandledfromthecommandline.Wewillencounterthis techniquelaterinthisandsubsequentchapters. AlthoughtheBBB’ssophisticatedpindesigncanacceptdifferenttypesofsignals,inthis chapter,wewillmainlytakealookatthetwotypesthatarecommonlyusedinphysical computing: Pulsewidthmodulation(PWM) Analogtodigitalconverter(ADC) Withinourtoolsetisanothersoftwareapplicationthatelectronicsandhardwaremakers relyheavilyon:Fritzing.Youmayalreadybefamiliarwithit,butifnot,Fritzingisan extremely,handyopensourcegraphicaltoolforcreatingdiagramsofbreadboards, schematics,andPCBlayoutswithouttheneedfortraditionalengineeringschematics. Note Beforewiringupyourbreadboard,it’sagoodideatoresettheBBBeachtimeyou performanewrecipebypoweringitdown.Thisensuresthatthepinsareresettotheir inputstate.Otherwise,ifthepinisbeingusedasaninputinanewrecipethatwas previouslyusedasanoutput,youmaydamageyourBBB. There’smore… HerearesomeofthesourcesandlinkstotheBeagleBoneBlack’spinlayouts: Oneofthebestpin-mappingguidesisEskimon’sinteractiveoverlayat http://eskimon.fr/beaglebone-black-gpio-interactive-map. Thefullexpansionheaderlayoutisat http://elinux.org/Beagleboard:Cape_Expansion_Headers AmoresuccinctdiagramofGPIOsisavailableat http://stuffwemade.net/post/beaglebone-pinout-new. CollarsthatyoucanattachtotheBBBthatprovideeasycalloutsfortheGPIOpins isavailableathttp://www.doctormonk.com/2014/01/beaglebone-black-collars.html. TakealookathowtouseBeagleBoneBlackGPIOsathttp://www.armhf.com/usingbeaglebone-black-gpios/. Aquickguideonhowtopinmuxisavailableat http://beaglebone.cameon.net/home/pin-muxing. DerekMolloy’sBeaglebone:GPIOProgrammingonARMEmbeddedLinuxtutorial andvideoisanothercomprehensiveandthoughtfulintroductionavailableat http://derekmolloy.ie/beaglebone/beaglebone-gpio-programming-on-arm-embeddedlinux/. ControllingexternalLEDs Inthelastchapter,welookedataquickblinkrecipeonhowtocontrolouronboard LEDs.Now,theobjectiveistohaveanexternalLEDonabreadboardblink.First,wewill takealookatthecircuitsymbolofabasicLEDsothatwecanrecognizeitsproperusage, asshowninthefollowingdiagram: Thetypicalsymbolforalight-emittingdiode(LED) Inthefollowingimage,youwillseewhatareal-lifeLEDactuallylookslike.Notso straightforwardaslookingatthesymbol,right? Note WithLEDs,polaritymatterstohaveaworkingcircuit.Payattentiontothefactthatthe anodeisthelongerend,whereasthecathodeistheshorterend.Althoughmixingthemup willnotcauseanydamage,thecircuitwillnotwork. Gettingready You’llneedthefollowingitemstosupplementyournowhappilyperkingBBB: LED:Justaplainvanilla,inexpensiveLEDisfine;thisisthetypeyou’llfindfor penniesatyourlocalhobbystoreoronline.Youmayalreadyhaveabunchinyour kit. Resistor:Anythingfrom700(700Ω)to1kisfine.Wewillusea700Ωversionhere (violet/black/brown/goldbands). 2xjumperwires:Theseareeasytoconnecttothebreadboard. Breadboard. Howtodoit… Now,let’sbeginwiththefollowingsteps: 1. Fromourfritzingtool,here’sthediagramwemadeforourwiring: 2. Now,wireupyourbreadboardusingthefollowingsteps: 1. First,puttheGroundwireintoGND(P8_2)ontheBBB. 2. Then,inserttheotherwiretotheP8_15pinontheBBB. 3. Onthebreadboard,puttheLED’sshorterend—thecathode(-)pin—intothe GNDrailandthelongerend—theanode(+)pin—intothesixthslotofthe breadboard. 4. Now,insertyourresistorandmakesurethatthetopendisalignedintheslot withtheGPIOwireandthebottomendisalignedwiththeLED’sanode. 3. OpenupCloud9IDEathttp://192.168.7.2:3000andcreateanewfilecalled blink_LED.js. 4. Then,copyandpastethefollowingcodeintotheopenIDEwindow: //Setup varb=require('bonescript');//Calllibrary varLED="P8_15";//Pinchoice varstate=0;//LEDstate b.pinMode(LED,'out');//Pinfunction setInterval(blink,500); functionblink(){ state=!state; b.digitalWrite(LED,state); 5. Beforerunningthecode,let’stakeacloserlookattheparts.First,asnotedinthe priorchapter,youneedtoinvoketheBoneScriptlibrarysoyouhaveaccesstoallits functions: //Setup varb=require('bonescript'); Pleasekeepinmindthatanythingafterthe//arecomments,andisn’tfunctional code. 6. Now,selectthepinnumberwhereyourLEDiswired.Youcanchangethisoption easily;justbesuretochoosefromanavailablepin.Then,makethechangeonyour boardaswell.Refertothepinlayoutreferencediagramatthebeginningofthis sectionformorebackgroundonthepinouts,asshowninthefollowingcode: varLED="P8_15"; 7. Thislinedefinesthevariablestateofourpin,whichinthiscasehasaLEDconnected toit.Naturally,thestatewillvaryaseitheronoroff,where0isequaltooffand1is equaltoon: varstate=0; 8. Followingthis,asthepinhasnopreassignedvalue,here,wehavetousepinModeto tellthepin(P8_15)whattypeofpinit’ssupposedtobe,eitheranINPUT(thiswould beusedwithabutton)oranOUTPUT.Inthiscase,aswewillcontrolaLED,ourGPIO willbeanoutput,asfollows: b.pinMode(LED,b.OUTPUT); Youcanalsowriteitthisway: b.pinMode(LED,'out'); 9. Fromthesetupcode,wethenshifttoinstructingtheLEDtoevoketheblinkfunction (whichwe’lldefineinthenextsectionofcode).Then,flashon/offaccordingto whateverintervalwespecify(inthiscase,every500milliseconds).Thislineis analogoustothecommonlyseenloopfunctioninArduinoscripts.However, JavaScriptandtheevent-drivenNode.jsenvironmentgreatlysimplifiesthecode,as follows: setInterval(blink,500); 10. Finally,wewilldefinetheblinkfunction.The!beforethestatevalueinvertsthe value,andastheLEDbeginswitha0(off)state(thisisn’tthesameas0changingto 1(on)).Thelastline(b.digitalWrite)—whichhappenstobeArduino-friendly syntax—establishesanoutputstatementfortheLEDanditson/offstate,asshownin thefollowingcode: functionblink(){ state=!state; b.digitalWrite(LED,state); } 11. Finally,let’sseewhatthescriptdoes.ClickRunintheCloud9IDE.YourLED shouldnowbeblinkingmerrilyat500millisecondincrements. Note YoucanfindmoredocumentationontheBoneScriptlibraryfunctionsat http://beagleboard.org/support/bonescript. WritinganalternativescriptwithPython Startingfromstep3,here’sthePythonversionoftherecipethatusestheAdafruitlibrary: 1. IntheCloud9IDEterminalwindow,openanewfilewindowintheeditorandname itblink_LED.py. 2. Copyandpastethefollowingcodetothewindow: importAdafruit_BBIO.GPIOasGPIO importtime GPIO.setup("P8_15",GPIO.OUT) whileTrue: GPIO.output("P8_15",GPIO.HIGH) time.sleep(1.0) GPIO.output("P8_15",GPIO.LOW) time.sleep(1.0) 3. Now,savethescript. 4. ClickRunintheCloud9IDE.YourLEDshouldbeginblinking. There’smore… Youcanfindmoresupportinthesetutorials: Sparkfun’smultipagetutorialonLEDsprovidesatop-notchfurtherstudyat https://learn.sparkfun.com/tutorials/light-emitting-diodes-leds Forabeginner,instructablesdeliversexcellentandadditionalbackgroundonLEDsat http://www.instructables.com/id/LEDs-for-Beginners/ Usingbuttons–buttonpressfunction Buttonscomeinallshapesandsizes.Somearequiet.Somearenoisy.Someare expensive.Somecostpennies.We’llnotonlyusethecheapandpeppy,pennyvariety,but alsoshowanexamplewithamoreinteresting,whizzypersonalityandmakeitdo somethingmorethanjustturntheswitchonandoff. Pull-up,pull-down,andfloating Frequentlywhenwiringupcircuits,youwillhearreferencestopull-up,pull-down,and floatingconfigurations.Whenyourdesignisapull-upcircuit,thismeansthattheresistor holdsthepositiveorsupplyvoltage(VCC)untilyoupushthebuttonpullingitupto ground.Thisisthemostcommonscenario,andoneyouencounterwhenyoudesigna circuitwithabuttonpresstoactivatesomething. Inthepull-downversionofacircuit,theresistorinthecircuitremainsatgroundunless youpush(orpulldown)thebutton,causingthecircuittoswitchfromgroundtopositive orsupplyvoltage(VCC). Floatingmeansthecircuitisneithertiedtogroundoraparticularvoltage.Thiscancreate asituationwhereapinmayaccumulatesomekindofchargeonit,thusthrowingoff incorrectvalues.Youcancreateamorereliablecircuitbywritingcodetocorrectforthese potentialfalsereadings. ThepurposeofthisrecipeistoreadthestateofabuttonpressandhaveitturnanLEDon andoff.Whenthebuttonisnotpressed,thestateoftheinputpinwillbea1orhighdueto theresistorpullingthepinup.Whenthebuttonispressed,theinputpinwillbegrounded lowandhavethevalueas0. Gettingready You’llneedthefollowingitemsforthisrecipe: 1xLED:Thisisthesameoneyouusedintheprevioussection. 1xpushbutton:Thisisasimple,onebutton,four-prongedtactileswitch.Bydefault, thebuttonpinsareopen(disconnected)andmomentarilyclosed(connected)when thebuttonispressed. Resistors:2x700(700Ω)to1kwillbefine.Wewillusethe700Ωhere (violet/black/brown/goldbands). 5xjumperwires:Thisiseasytoconnecttothebreadboard. Breadboard. Howtodoit… 1. Wireyourboardandbreadboardinthefollowingmanner: 1. ConnecttheGNDwiretoGNDatP9_2ontheBBBandtheotherendtoGND inthefirstslotatthetopofthesecondrowonthebreadboard. 2. Insertaredwireintothe3VslotatP9_3andtheotherendintothepowerrailon thebreadboard. 3. Thebuttonwillusethenextwire.ConnectawiretothepinontheP9_15BBB andtothefirstslotinthesamerowintheupper-leftcornerofthebuttononthe breadboard. 4. TakeanotherwireandconnectoneendtoP8_11onBBBandtheotherendto row2andcolumn1onthebreadboard. 5. ThelastwireservesasGroundforthebutton.Connectoneendofthiswireto theGNDrailandtheotherendnexttothebutton’sGNDleg. 6. Onthebreadboard,connecttheLED’scathodepin(theshorterend)totheGND railandtheanodeorthepositivelead(thelongerend)intothesixthrowofthe breadboard 7. InsertoneresistortoregulatethecurrenttotheLEDandtheothertoregulatethe flowthroughthebutton,asshowninthefollowingimage: 2. Now,openyourCloud9IDEathttp://192.168.7.2:3000andcreateanewfile calledbutton-led.js. 3. Then,usethefollowingcodetoturntheLEDonandoffwithapushbutton.Copy andpasteitintotheopenIDEwindow: //Setup varb=require('bonescript');//Readlibrary varLED="P8_11";//PinwhereLEDisconnected varBUTTON="P9_15"; b.pinMode(LED,b.OUTPUT); b.pinMode(BUTTON,b.INPUT); setInterval(readBUTTON,10); functionreadBUTTON(){ b.digitalRead(BUTTON,writeLED); } functionwriteLED(x){ b.digitalWrite(LED,!x.value); } Beforerunningthecode,let’slookathowthescriptbreaksdown.First,as always,evoketheBoneScriptlibrarywiththefollowingcode: //Setup varb=require('bonescript');//Readlibrary Now,choosethepinnumberwhereyourLEDiswired.Youcanchangethis optioneasily;justbesuretochoosefromanavailablepin(seethepinlayout referencediagramattheendofthissectionformorebackgroundontheGPIOs): varLED="P8_11";//PinwhereLEDisconnected Then,wewillsetthepinnumberforthebutton,asfollows: varBUTTON="P9_15"; Now,wewilltellthepreviouslyspecifiedpinstofunctioninanOUTPUTmode fortheLEDandinanINPUTmodeforthebutton,asshowninthefollowing code: b.pinMode(LED,b.OUTPUT); b.pinMode(BUTTON,b.INPUT); Youcanalsowriteitthisway: b.pinMode(LED,"out"); b.pinMode(BUTTON,"in"); Now,weneedtocheckthestatusofthebuttonatspecificintervals,inthiscase, every10minutes,asshowninthefollowingcode: setInterval(readBUTTON,10); Then,weneedtodefineanotherfunction,asshowninthefollowingcode,this timeonethattriggersaneventbasedonwhenthebuttonispressed: functionreadBUTTON(){ b.digitalRead(BUTTON,writeLED); } Finally,wewilldefineafunctionfortheLEDwhenthebuttonispressedwith thefollowingcode: functionwriteLED(x){ b.digitalWrite(LED,!x.value); } 4. Finally,werunthescriptbyclickingtheRunbutton.YourLEDshouldnowbe blinking.Changetheintervalvaluetospeedituporslowitdown. Note IfyougetanerrorintheIDE’sconsolewindow,sometimesthefixisassimpleas clickingontheResumebuttonintheupper-rightcornerpanelorjustrestartingthe script.Youcanalsoturnoffthedebuggertokeepthescriptrunning. There’smore… Theultimatecircuit/resistor/capacitorcheatsheet—werecommendacoupleofveryuseful smartphoneappsthatserveasexceptionallyhandyreferencetoolsforresistorand capacitorcodes,circuitcalculators,andotherusefulcomponentvalues.First,isAdaFruit’s CircuitPlaygroundappforiPhoneandAndroid.Althoughnotfree(butavailableforjust afewdollars),itsurebeatsgettingitwrongonthoseresistorcolorvaluebands.Second, fortheAndroidplatformonlyisElectrodroid,whichhasfreeandpro(USD$2.99) versionsavailableintheGooglePlaystore. Usinganalogsensors Nowit’stimetograbsomeanalogdata.Waitasecond?Analog?Isn’ttheworldwelivein —includingtheBBB’s—alldigital?Mostly,yes.Buttheworldofsensorsisvast,and manyofthemostubiquitous,mostuseful,andleastcostlysensorsareanalogdevices.A greatdealoftheembeddedsensingworld—motion,temperature,humidity,lightintensity, pressure,andaccelerometers—consistsofanaloganimals.So,howdowecaptureallthat analogdatagoodness? WithADC(analogtodigitalconverter)pins,ofcourse.AndtheBBBcomeswithseven pre-assignedanaloginputsonourboard,soit’snearlyplugandplay!Well,notquite.But atleastwedon’thavetofusswithpinmuxingrightaway. Temperaturesensors Forthisrecipe,we’reusingtheTMP36,averylowcost(USD$1.50)analogtemperature sensorthatyoucanfindatmanydifferentelectronicsstoresorsuppliers.Itoutputsan analogvoltagethatisproportionaltotheambienttemperature.Wewillwriteascriptthat takesthatproportionalvalueandreadsbackthetemperatureintotheCloud9console. Gettingready Temperaturesensor:AvailableatSparkFun(http://bit.ly/OCGFDj) 3xjumperwires:Easytoconnecttothebreadboard Breadboard Howtodoit… 1. MakesureyourBBBispowereddownfirst,thenwireupyourbreadboard.Here’s whatyourwiringshouldlooklike: Besurethatyou… PuttheGNDintothespecialanaloggroundGNDA_ADContheBBB.Inour diagram,that’stheblackwireintopinP9_34. Putthe3Vintothe3VontheBBB.Inourcase,that’stheredwireintopinP9_3. Note VeryImportant! TheanaloginputsontheBeagleBoneBlackacceptamaximumof1.8V.Neverapply morevoltagethan1.8Vtotheanalogpinsoryouwilldamageyourboard. Forthesensor(markingsfacingyou),matchupthepinsasfollows: Pin1(leftpin):Power/3.3V Pin2(middlepin):AnalogpinontheBBBwhichinourrecipeispinP9_38,orAIN3 Pin3(rightpin):GroundpinontheBBB 2. OpenupCloud9IDEathttp://192.168.7.2:3000andusethefollowingcodeto begincapturingtemperaturereadings: //Setup varb=require('bonescript');//Readlibrary varTMP36="P9_38";//Pinlocationforsensor //Checkthetemperatureevery4seconds setInterval(readTMP,4000); //Definethe'readTMP'function functionreadTMP(){ b.analogRead(TMP36,writeTMP); } //Definethe'writeTMP'function functionwriteTMP(x){ varmillivolts=x.value*1800;//1.8V vartemp_c=(millivolts-500)/10; vartemp_f=(temp_c*9/5)+32; console.log("Currenttemperatureis"+temp_c+"Cand"+temp_f+ "F"); } 3. Thecodeisbrokendownasfollows: EvoketheBoneScriptlibrary: //Setup varb=require('bonescript'); Now,choosethepinnumberwhereyoursensoriswired.Seethepinlayout referencediagramattheendofthissectionformorebackgroundontheADC inputoptions: varTMP36="P9_38";//Pinlocationforsensor Then,we’llcheckthetemperatureatspecificintervals,inthiscase,everyfour seconds: setInterval(readTMP,4000); Now,wedefinethereadTMPfunction: functionreadTMP(){ b.analogRead(TMP36,writeTMP); } Finally,wedefinethewriteTMPfunction,whichiswherethevoltagedata capturedisturnedintotemperaturereadings.Wecalculatethetemperaturefrom thevoltageinmillivoltswithasimpleformula,TempC=100x(readinginV)50: functionwriteTMP(x){ varmillivolts=x.value*1800;//1.8V vartemp_c=(millivolts-500)/10; vartemp_f=(temp_c*9/5)+32; console.log("Currenttemperatureis"+temp_c+"Cand"+ temp_f+"F"); } 4. Whenyouarereadytorunthecode,justclicktheRunbuttonintheIDE.Your outputshouldlooklikethefollowing(withyourlocaltemperature,ofcourse): Currenttemperatureis20Cand68F Currenttemperatureis22.4Cand72.32F Note Ifyougetsomefunkytemperaturereadings,rebootyourboardandrerunthescript. There’smore… Youcantryexactlythesameexercise,thistimewithPython —https://learn.adafruit.com/setting-up-io-python-library-on-beaglebone-black/adc. Seealso MoresupportforanaloginputscanbefoundatReadingtheanaloginputs —http://beaglebone.cameon.net/home/reading-the-analog-inputs-adc Variableresistancesensor–photocell Capturingthedatageneratedfromlightsensorsisoneofthosesatisfyingandhighly usefulexamplesofphysicalcomputing.Someofyoumayhaveusedlightsensors—also knownasCdScells,photoresistors,andphotocells—inyourArduinoorRaspberryPi projects.Ifso,thisrecipewillbeasnapforyou. Aphotocellisavariableresistor,whichinthiscasemeansthatitvariesitsresistance accordingtotheintensityoflightexposedtoit.Thevalueofthatvariableresistanceis turnedintodata,whichinturnmeansthesensorfunctionsasaneffectivemeasurement toolforambientlight.Inthisrecipe,weshowyouhowtoreadanalogvaluescaptured fromalightsensorusingBoneScriptalongwithanalternativePythonscript. Note CdSstandsforCadmiumSulfide,acompoundthatisnon-ROHscompliantduetothe cadmium,achemicalseverelyrestrictedinEuropeashazardouswaste. Gettingready Rustleuptheitemsinthelistbelowforthisrecipe: Photoresistor(photocell):Nothingfancyforourpurposeshere.We’reusingonethat costslessthanUSD$1.50inmanyelectronicsstoressuchasSparkFun (http://bit.ly/1kwejIt). Resistor:10,000(10kΩ);brown/black/orange/goldbands 3xjumperwires:Easytoconnecttobreadboard. Breadboard. Howtodoit… 1. First,makesureyourBBBispowereddown,thenwireupyourbreadboard.Here’s whatyourwiringshouldlooklike: Wewirethissensorupdifferentlyfromthetemperaturesensor,sotakecarewiththe diagram.Ifyouarereadingthisrecipeandwanttoseecolorversionsofthefritzing diagramsforbetterclarityonthewiring,youcanfindthemonlineat http://bit.ly/1MP2UNo: Lightsensor:Plugthelightsensor’swiresintothebreadboard,positioningthewires fourorfiveslotsapartfromoneanotherforeasierwiringmanagement. Resistor:Plugthe10kresistorintothebreadboardacoupleofcolumnsinfrontof thephotocellwithoneendoftheresistoralignedwiththebottomwireofthesensor. Voltagewire:PlugtheredwireintotheP9_32slotontheBBB.Thisisoneofthe board’sspeciallydesignatedpins(labeledVDD_ADC)for1.8Vreferencevoltage,a lowpowersourceforanalogsensorslikethis.Theotherendofthewireshouldbe insertedintothebreadboardaligningwiththephototcell’stopwire. Groundwire:Thebluewireisforground(GND),andforthiswewillalsousea specialgroundpinatP9_34for1.8V(GNDA_ADC). Note VERYIMPORTANT! TheanaloginputsontheBeagleBoneBlackacceptamaximum1.8V.Neverapply morevoltagethan1.8Vtotheanalogpinsoryouwilldamageyourboard. Sensorpin:PlugoneendoftheyellowwireintoP9_37ontheBBB,andtheother endintoabreadboardslotinfrontoftheresistor.Itshouldalignwiththebottomwire ofthelightsensor. 2. OpenupCloud9IDEathttp://192.168.7.2:3000. 3. Createanewfilecalledlight_sensor.js,andpastethefollowingBoneScriptcode intothewindow: varb=require('bonescript'); functionlightSensor(){ b.analogRead('P9_37',lightValue); } functionlightValue(reading){ varmillivolts=reading.value*1800; console.log("Lightoutputinmillivolts:"+millivolts+"\n"); } setInterval(lightSensor,1000); 4. PresstheRunbuttontobegincapturinglightintensityreadings.Yourconsoleoutput shouldlooksomethinglikethis.Yourreadings,ofcourse,willvaryaccordingtothe strengthofyourlightsource: Lightoutputinmillivolts:1387 Lightoutputinmillivolts:1386 Lightoutputinmillivolts:1159 Lightoutputinmillivolts:608 Movingyourhandoverorclosetothesensorshouldmaketheoutputnumbersrise andfallbasedonhowthelightsourcehitsthesensor.Noticethatdoingallthis requiresveryfewlinesofcode.So,let’stakeaquicklookatwhatsomeoftheparts ofthescriptaredoing 5. BesidesevokingtheBoneScriptlibrary,thefirstsectiondefinesareadfunctionona specificanalogpinthatwewillreferenceontheBBB: varb=require('bonescript'); functionlightSensor(){ b.analogRead('P9_37',lightValue); } 6. Inthenextsection,wedefineafunctionthatdetermineshowthesensordatabeing capturedwillbecrunched.Thatdataisexpressedinmillivoltsandvariesata constantrate: functionlightValue(reading){ varmillivolts=reading.value*1800; console.log("Lightoutputinmillivolts:"+millivolts+"\n"); } The\ninthecodesimplycreatesaspacebetweeneachoutputforbetterlegibility. OptionalPythoncode Besidesthecodeabove,youcanalsotestyourlightsensorwithaPythonscriptavailable onourGithubrepository.ThereisaReadMefileontherepo,butherearethebasicsteps: 1. DownloadthePythoncodewiththefollowingcommand: $gitclone https://github.com/HudsonWerks/light-sensor.git 2. BrowsetothedirectorywiththePythonscriptandrunit: $cdlight_sensor $sudopythonlight_sensor.py YouroutputshouldbeverysimilartowhatyousawintheBoneScriptexample. Usingmotors Whetherit’sarobot,anRCtoy,aCNC,a3Dprinter,orahigh-endindustrialmachine, motioncontrolisoneofthemostpopularsubjectsinphysicalcomputing. Inourexamples,we’llbeusingBoneScripttorunourdevices,beginningwithaDCmotor andthenfollowingwithaservomotor. However,firstyoushouldlearnalittleaboutthetypeofpinsthatwewilluseinthe followingrecipes. DCmotors They’refun.They’recheap.They’reeverywhere.Thelittlemotorsthathavebeendriving toysfordecadesstillremainamainstayforprojectswherelocomotionispartofthe picture.UnderstandinghowtodriveaDCmotorrequiresmorecomplexandpowerful mechanisms,suchasrobotics. Gettingready Youwillneedseveralitemsforthisrecipe: DCmotor:Thisisastandardissue2-leadmotorprevalentintoysandcheaperRC devices. H-BridgeICmotordriver:ThisTexasinstrumentcomponentSN754410is availableatSparkfun(https://www.sparkfun.com/products/315)andothersimilar sourcesforapproximately2.50USD.ItisalsocommonlyusedintheL293Dversion. Thislittlecircuitisanimportantpieceofthepuzzlebecauseitisthemechanismused tosendthevoltagethatdrivesthemotor’sdirectionandregulatesitsspeed.More detailsaboutthisICaredescribedlaterinthisrecipe. 13xjumperwires 1xpushbutton/switch 1x1kresistor 9Vbatteryandholder Breadboard Howtodoit… PerformthefollowingstepstotesttheDCmotors: 1. MakesurethatyourBBBispowereddownfirstandthenwireyourbreadboardas follows.Clearly,thisisathicketofwires,sobemethodicalasyoufollowthe diagram: Tohelpwiththediagramabove,herearesomefurtherdetailsforthewiringsetup: Hardware Pin# BBB P8_7 Blue BBB P8_13 Yellow Pin1(1,2EN/PWM)onH-bridge BBB P8_19 Green Pin7(2A,motorlogic1)onH-bridge BBB P8_8 Blue BBB P9_1 Black GNDonbreadboardrail BBB P9_7 Red MotorWire1 Color Location/purpose Pin2(1A,motorlogic1)onH-bridge GNDonbreadboardbutton—alignedwith1kresistor 5Vpowertobutton Attachedatpin3(1Y)onH-bridge MotorWire2 Batterywire1 Black GNDrailonbreadboard Batterywire2 Attachedatpin6(2Y)onH-bridge REDtoPWRrailonbreadboard Buswire1 Black GND Buswire2 Red VCC 2. OpentheCloud9IDEathttp://192.168.7.2:3000andnavigatetoFile|New FromTemplate|Javascript. 3. SavethenewfileasDC_motor1.js. 4. PastethenewdocumenttothefollowingBoneScriptcode: varb=require('bonescript'); varenablePin="P8_13";//pin1(1,2EN/PWM)onH-Bridge varmotorPin1="P8_7";//pin2(1A,motorlogic1)onH-Bridge varmotorPin2="P8_19";//pin7(2A,motorlogic1)onH-Bridge varbuttonPin="P8_8";//pinforbutton b.pinMode(enablePin,b.OUTPUT); b.pinMode(motorPin1,b.OUTPUT); b.pinMode(motorPin2,b.OUTPUT); b.pinMode(buttonPin,b.INPUT); functionloop(){ //ifthebuttonishigh,motorwillturnoff if(b.digitalRead(buttonPin)==b.HIGH){ b.digitalWrite(enablePin,b.HIGH); b.digitalWrite(motorPin1,b.LOW);//setpin2onH-Bridgelow b.digitalWrite(motorPin2,b.HIGH);//setpin7onH-Bridge high } //ifthebuttonislow,motorwillturnon else{ b.digitalWrite(enablePin,b.LOW); b.digitalWrite(motorPin1,b.LOW); b.digitalWrite(motorPin2,b.HIGH); } } setInterval(loop,50); 5. Tostartyourengines,clickontheRunbuttonintheIDE.Themotorshouldrotate whenyoupressthebuttonandstopwhenyoureleaseit. Howitworks… Hereissomecontextforwhat’shappeningwiththewiring: 1. H-Bridgemotordriver:Althoughourcomponentcandrivetwomotors(oneon eachsideofthechip),inourexample,wewillonlyrunone.Besidescontrollingthe directionandspeed,themotordriveralsoprotectstheBBBfromthehigheroutput neededtodrivethemotor.ThenameH-Bridgeisderivedfromthewaythecircuitis typicallydrawnwithfourswitches.Whenswitch1(s1)andswitch4(s4)areclosed andswitch2(s2)andswitch3(s3)areopen,thenapositivevoltageflowsacrossthe motor.Toreversethedirectionofthemotor,theswitchesarethenreversedfromtheir openorclosedstate. Inthefollowingillustration,theimageontheleft-handsideshowsthevoltage flowingacrosss1ands4foronemotordirectionandontheright-handsideacrosss2 ands3forthereversedirection.Inourrecipe’scode,wewillonlyturnthemotorin onedirection,sothevoltagewillonlyflowacrossonebridgecircuit,asshowninthe followingimage: Note TheprecedingimagehasbeentakenfromWikipedia. TheH-bridgecontrollerhas16pinsforinterfacing,althoughonlyafewofthemare usedinourrecipe: PinoutsonH-bridge 2. DCpower:InsteadofpoweringfromtheBBBdirectly,weoffloadthepowerforthe motortoaseparate9Vbatterysource.Thisbothensuresareliableandconsistent voltagetothemotorandremovesanypossibilityofdamagingtheboard. Servomotors Forthosenewtoservomechanisms,commonlyreferredtoasservos,itmaybeusefulto understandthebasicsofthedevicebecausetheingredientsinthereciperevealtheunique natureofthistypeofmotor. Servosaretypicallyusedasactuatorsinembeddedelectronicsscenarios,suchasCNC machinery,robotics,andautomatedmanufacturing,andevenforradio-controlledtoys.For theirsize,thesemotorsareincrediblypowerful,deliveraconsiderabletorque,and consumeasmallamountofpower. Aservoisreallyjustamotorwithanoutputshaftconnectedtoasensor.Thesensor providesfeedbackofapositiontocontrolthemotor’smotionandfinalposition.Theshaft isabletoturnaround180degrees. Inordertorunproperly,theservorequiresafairlyrobustcontroller.Communication betweentheservoandthecontrollercanbeeitherdigitaloranalogue.OntheBBBfront, theservorequiresPWMtosendpulsedsignals,whichwediscusslaterinthissection.The lengthofthepulsedrivesthepositionofthemotor. Regardlessofthesignaltype,theinputsignal’spurposeistosenddatathatdeterminesthe motoroutputshaft’sposition.Inmoresophisticatedservos,thesignalalsoincludesdata onthespeed.However,inourrecipe,wewillusealowcostservothatistypicallyusedin RCtoys.Thesekindsofdeviceshandleonlyshaftposition. Servosarealsodistinctivefortheirthreewires: Power(+5volts):Thisisoftenred Ground:Thisissometimesblack,butmoreoften,thisisbrownincheaperservos Control:Thisiscommonlyyelloworwhite Acrashcourseinpulsewidthmodulation Pulsewidthmodulation(PWM)isawaytosendveryfaston/offdigitalsignalpulsesto apin.Thesepulsescanbemodulatedinordertosmoothlycontrolcertainkindsofdevice like.LEDs,audiocomponents,andmotors. WhencodingaPWM-drivendeviceorcomponent,youarebasicallysettingapinHIGH orLOWinrapidsuccession.Often,youwillfindthatthreecontrolparameterscanbeset: Dutycycle:ThisisthepercentageoftimewhenthepinisHIGHoronoveraspecific spanoftime.Inyourcode,youexpressdutycycleasapercentage.Forexample,100 percentwouldbehighpowerbeingappliedandwouldbefullyon.Whereas,alow dutycycleof1percentwouldresultinlowpowersincepowerisoffformostofthe cycle. Period:Thisisthecombinedtimeittakestocompleteanon/offcycle. Frequency:Inourcase,frequencyishowmanytimespersecondthepulsesignal wentON(HIGH)andOFF(LOW).Takingtheinverseoftheperiodgivesusthe frequency.Gettingthefrequencysettingrightiscrucialsincesomedevicesmaynot workproperlyifyoursettingistoohighortoolow. Workingwithservoscomeswithtakingcarewiththepowerinputintoyourboard. Undernocircumstancedoa5Vdrawtorunthemotororyouwilllikelymeet Merlin’smagicsmoke.AndnothingcutsBBBrecipesdowntosizelikemagic smoke. Note Insideeveryservo,thereisapotentiometerthatprovidesfeedbacktothemotorabout itspositiononits180-degreesweep. Gettingready You’llneedafewthingsforthisrecipe: Servo:Thesesmallbutmightymotorscomeinmanyvarietiesandpriceranges.If youalreadyhavefancyonesinyourkit,congratulations!Ifnot,purchaseeithera standardorminisizebecauseourrecipewillworkwithboththesesizes.AdaFruit andSparkfunhavevettedcollections,althoughyoucancertainlygetthemcheaperon Amazon. Resistor:10,000(10kΩ)versionwithbrown/black/orange/goldbands 6xjumperwires Breadboard Howtodoit… 1. MakesureyourBBBispowereddownfirst,thenwireupyourbreadboardaccording tothefollowingfritzingdiagram: 2. Herearethedetailsforthewiringifthediagramisn’tclear: Connectyour10kresistortorow5ofyourbreadboardwiththeendsspanning thebridge.Inthisrecipe,theresistorisnotvital,butitisgoodpracticetokeep thevoltageundercontrolandprotecttheboardiftheservoismalfunctioning. Fortheservocable,attachthreejumperwiresandmatchthemasfollows: Thebrownservolead(GND):Thisistheblackjumperwire Theredservolead(PWR):Thisindicatestheredjumperwire Theorange(looksalmostyellow)servolead:Thisdenotestheyellowjumper wire Now,attachthesecondsetofjumperwirestotheBBBasfollows: ConnectoneendoftheGND(blackwire)totheP9_1pinontheBBBandthe otherendtothebreadboard,followingthediagram’sposition Connectoneendofthe3VredwiretotheP9_3pinontheBBBandtheother endtothebreadboard,followingthediagram’sposition Nowwe’llhookuptheyellowjumperwire,whichwe’llconnecttoourPWM outputontheBBB.Connectoneendtothe9_42pinontheBBBandtheother endtothebreadboardinthesamerowandontheleft-handsideoftheresistor, followingthediagram’sposition.WecouldalsohaveusedP9_14,P9_16, P8_13orP8_19. Finally,attachtheservo+jumperwirestothebreadboardasfollows: GNDblackwireintotheGNDrailcomingfromtheBBB 3Vredwireintothe3VpowerrailcomingfromtheBBB PWMyellowwireintobreadboardontheothersideoftheresistor 3. OpentheCloud9IDEathttp://192.168.7.2:3000: Usethefollowingcodetobeginfiringuptheservo.InordertocontrolthePWM signal,weneedtospecifytheperiod,run,anddutycycle.Here’sthescripttorunthe servo: #!/usr/bin/envnode //Includethebonescriptlibrary varb=require('bonescript'); //Servomotor'sPWMpin varservo='P9_42'; varduty_min=0.03; varduty_max=2.5; varposition=0; varincrement=0.1; //Setupthemodefortheservopin b.pinMode(servo,b.ANALOG_OUTPUT); updateDuty(); console.log('UsekeyboardControl-Ctostop'); functionupdateDuty(){ //Thisfunctioncalculatesandadjuststhedutycyclebasedona desiredpositioninrange0..1 varduty_cycle=(position*0.115)+duty_min; b.analogWrite(servo,duty_cycle,60,scheduleNextUpdate); console.log('DutyCycle:'+ parseFloat(duty_cycle*100).toFixed(1)+'%'+'Position:'+ position); } functionscheduleNextUpdate(){ //adjustpositionbyincrementand //reverseifitexceedsrangeof0..1 position=position+increment; if(position<0){ position=0; increment=-increment; }elseif(position>1){ position=1; increment=-increment; } //callupdateDutyafter500ms setTimeout(updateDuty,500); } 4. Themotorwillbeginbyfirstmovingtoastartingposition,thenmoveforwardin smallincrements.Then,itwillresetitsstartingpointandbeginmovingbackwardin smallincrements.IntheIDEterminalwindow,pressCtrl+Conyourkeyboardto stopthescript. There’smore… TocheckyourPWMpinmux,runthefollowingcommands: $sudo-i #cat</sys/kernel/debug/pwm Youroutputshouldlooksomethinglikethis: platform/48304100.ecap,1PWMdevice pwm-0((null)): platform/48304200.ehrpwm,2PWMdevices pwm-0((null)): pwm-1((null)): platform/48302200.ehrpwm,2PWMdevices pwm-0((null)): pwm-1((null)): platform/48300100.ecap,1PWMdevice pwm-0(PWM_P9_42):requestedenabled platform/48300200.ehrpwm,2PWMdevices pwm-0((null)): pwm-1((null)): Notethatourreferencedpininourcodethatwejustran,P9_42,ismarkedasrequested enabled. ForanalternativemethodofdrivingtheservousingPython,checkoutAdafruit’stutorial athttps://learn.adafruit.com/controlling-a-servo-with-a-beaglebone-black. Chapter4.ExploringGNU/LinuxRecipes UsingBash,Autotools,Debugger,and systemd Hereiswhatwe’vegotinstoreasrecipesinthischapter: Thebasicshellscript EpochTimeshellscript Compileandinstall CompileandinstallGitfromsource Debugging DebugasimpleC-codeapplicationfromthecommandlineusingGDB DebuganapplicationremotelyfromEclipseandGDBserver systemdservices Basiccommandsforsystemdservices Optimizeboottime Createasystemdservicetorunatboottime Introduction Inourlastchapter,wejumpedrightintohowtomakeourhardwaredanceoratleastblink forus.Thistime,youwilllearnmoreabouthowtobendthesoftwaretoyourwill. We’llbuildonsomefoundationalprinciplesfirstandthenheadtowardsgreater complexityofscripts,includinghowtocompileanopensourcesoftwarepackage,install itonyoursystem,andtroubleshootitwhenthingsgooutofwhack.Lastly,we’llexamine somecore,system-levelsoftwarecalledsystemd,aframeworkthathasbecomean essentialingredientinmodernLinuxdistributions. Thebasicshellscript Shellscripts AshellscripthasamyriadofpurposesonaLinuxbox.Youcanhavethemrunatbootup sothattheyinitiatecommandsorprocesseswithoutyouhavingtomanuallystartthem. Theycanbeusedtorunasequenceofevents.Theycanmanipulatefiles,executea program,printtext,andwalkyourdog.Well,thelastpartistrueifyourdogisarobot. However,we’regettingaheadofourselves. It’stimeforourfriendMajorTom.We’vemissedhim,butlet’sbringhimbacktoearthfor amomentwithaverysimpleshellscript. Howtodoit… Performthefollowingsteps: 1. Createanewdirectoryasfollows: $mkdirbin 2. Then,let’smovetothenewdirectoryusingthecdcommand: $cdbin 3. Now,createanewfilethatwillbecomeourshellscript,asshowninthefollowing code: ~/bin$sudonanomajor_tom_bash_script 4. Atthebeginningofthefile,it’sarequirementtotelltheshellthekindofscriptthat we’llrunsothatitcaninterpretthecodeaccordingly.Itcouldhavebeenanother recipeusingPython,butinthiscase,we’vegotabashscript: #!/bin/bash 5. Next,it’sagoodpracticetoaddacommentasfollows: #MajorTombashscript 6. Onthenextlineofthefile,entertheechostringcommand,whichoutputswhatever youinputtothescreen: echo"Commencingcountdown,engineson." Thisishowthecodelooks: #!/bin/bash #MajorTombashscript echo"Commencingcountdown,engineson." 7. Now,saveandclosethefile. 8. Then,fromtheterminal,youwanttorunacommandthatwillgivetheshellthe abilityandpermissiontoactuallyexecutethescript,asshowninthefollowingcode: ~/bin$sudochmod755major_tom_bash_script Addingthe755optioninstructsthescripttoallowreadandexecuteaccessto everyoneandwriteaccesstothefileowner(you)aswell.RefertoChapter1,Setting UpfortheFirstTime,forourreviewofthechmodcommand. 9. Finally,it’stimeforthemagic(.).Thistellsbashtorunthescript,and(/)tellsbash wherethefileislocated,asshowninthefollowingcode: ~bin$./major_tom_bash_script 10. Thisishowyouroutputshouldlook: debian@beaglebone:~bin$./major_tom_bash_script Commencingcountdown,engineson. Thisisaverysmallblastoff,butstillabeginning. EpochTimeshellscript Shellscripts AshellscripthasamyriadofpurposesonaLinuxbox.Youcanhavethemrunatbootup sothattheyinitiatecommandsorprocesseswithoutyouhavingtomanuallystartthem. Theycanbeusedtorunasequenceofevents.Theycanmanipulatefiles,executea program,printtext,andwalkyourdog.Well,thelastpartistrueifyourdogisarobot. However,we’regettingaheadofourselves. Epochtime,morecommonlyknownasUNIXtime(alsoPOSIXtime),iswidelyusedin Linux(UNIX)systemsasawaytodescribeinstantsintime.Specifically,itmeasuresthe numberofsecondsthathaveelapsedsinceJanuary1,1970,andisusedasatimestamp referencepoint. Withthisshellscript,wecanquicklycomparetheEpochtimeonourmachinewiththe UTCthatwearemoreaccustomedtousing. Howtodoit… Performthefollowingsteps: UnixtimecanbecheckedonmostUnixsystemsbytypingdate+%sonthecommand line.Performthefollowingsteps: 1. First,createthefollowingscriptinnano: $sudonanoepoch-time.sh 2. Then,pastethefollowingcodeinthenewwindow: #Epochtimeinmilliseconds #CTRL-CTOSTOP #WRITTENBYCHARLESHAMILTON #Simplescriptforshowingtheepochtimeat10-secondintervalsona BeagleBoneBlackrunningDebian #!/bin/bash #ResetstheRTCfromthesystemclock sudohwclock--systohc sudohwclock--show #Runscommandfordeterminingepochtime for((;;)) do echo-n"SinceEpoch[inmilliseconds]:" #OPTION1command.CommentoutifrunningOPTION2. echo$(($(date+%s%N)/1000000)) ##OPTION2command.Uncommenttorunthisversionandcommentout OPTION1. #cat/sys/class/rtc/rtc0/since_epoch|sed's/...$//' sleep10 done Note Ifyourunintoproblemswhilecopyingandpastingthecode,downloadthescript availableathttps://github.com/HudsonWerks/bash-script-samples/blob/master/epochtime.sh. 3. Now,runthefollowingscript: $sudobashepoch.sh 4. Yourscreenoutputshouldlooksimilartothis: TueOct2714:13:532015-0.062322seconds SinceEpoch[inmilliseconds]:1445969632617 SinceEpoch[inmilliseconds]:1445969642630 ThescriptdeterminestheEpochtimeinmillisecondsrelativetotheUTCtime. 5. StopthescriptbypressingCtrl+C. There’smore… Forsome,allyoucaneatisbuffetswithshellscriptsonthemenu: http://linuxcommand.org/writing_shell_scripts.php http://www.tldp.org/LDP/abs/html/why-shell.html Compileandinstall InChapter1,SettingUpfortheFirstTime,youlearnedthemagicalapt-getinstall routinetogetapackagethatyouwantonyourBeagleBoneBlack.However,you’ve alreadyencounteredsituationswhereyouwantedapackage(typicallyabbreviatedaspkg) andtherepositorycameupwithnada:E:Unabletolocatepackagexyz.Thisoften impliesthatthereisnoprecompiledbinaryforyoutoinstall,whichmeansthatwenow havetoputonourbiggirlandbigboybootsandcompilefromsourcefiles. Buildingsoftwarefromoriginalsourcefilesisoneoftheprerequisiteswhenyouwork withSOCs,suchasBeagleBoneBlack.ThisistrueinpartbecausetheBBBisaLinux environment.Manysoftwareapplicationshavetobecompiledinordertousethem. However,it’salsoafactthatyouwilloftenwantaversionofatoolthatdoesn’tcomewith apackagedbinarytosuityourusecaseortheprototypethatyou’llbuild.Nativepackages (inourcase,thearmhpackages)arealmostalwaysabetterfitthanprebuiltbinariesifyou havethetimeandfortitudetobuildthem. Therefore,mastering,creating,andbuildingfromsourcefilesgivesyoutremendous poweroverhowyoucustomizeandoptimizethesoftwarethatyouuseontheboard. Autotools,akatheGNUbuildsystem,isatoolsettobuildnativepackages.Thetoolchain isfamiliartoUnixusersforitsholytriadofcommands:configure,make,andinstall. LikealmostanythingrelatedtoLinux,thereisauniverseofinformationaboutautotools andthebuildandcompileprocessforthesourcecode.Asthisbookisameredustmotein thatuniverse,wecanonlycoverthebasicshere. Note Mostofthesoftwareyou’llwantisonlyreleasedinthetarball(sourcecode)form.These arejustcompressedarchiveswithextensions,suchas.tar.gz,.tar.xz,or.tar.bz2. Documentationstandards Intheopensourceworld,developersgenerallyshiptheirsourcecodewiththeREADMEfiles intendedtoprovideguidanceonthecompileprocessfortheirtarball.TheREADMEfilecan serveasastartingpointtobuildthepackagefromscratch.Unfortunately,theseREADME filescanoftenbecrypticorpoorlywritten.Althoughfrustrating,itisinevitablethatyou willfrequentlyfindyourselfGooglingformoreinformationabouthowtoinstalla package. CompilingonBeagleBoneBlack Althoughtheboard’s1.7GHzARMchipisprettysnappyformostembedded applications,compilingandinstallingsoftwaredirectlyontheBBBcanbeprettypoky andevenpainful.Ideally,buildingalargepackagewithmultipledependencieswillbefar speedieronadedicateddesktopwithbushelsofRAM.However,forthepurposesof simplicity,we’llforgeaheadwithhowtocompileonourboard. Autotoolscontainsseveralutilityprograms: Autoconf:Thiscreatesaconfigureshellscriptforthesourcecodethatrunsteststo determinethebuildenvironment. Automake:ThisgeneratesfilescalledMakefilesthattrackthedependenciesforthe codethatyourunwithamakeutility. Libtool:Thisisascriptthatprovidesafrontendtotheoftencomplexassortmentof sharedobjects,suchascompilers,linkers,andlibrariesthatanapplicationrequires. IntheWindowsworld,developersmorecommonlyknowthisanimalasdynamiclink librariesorDLLs. Formostoccasionswhenyoucompileandinstallasourcefilepackage,youwillrelyon threecommoncommands,whichmustberuninthedirectorywheretheyreside: 1. ./configure:Thisrunsascriptthatconfiguresthemakefile.Itservestocustomize thepackagetothesystemwhereitwillberunning.The./tellstheLinuxshellthat thescriptisinthecurrentdirectory. 2. make:Thisisthecommandthatexecutesthemakefilesinyoursourcecode.The makefilescontaintheshellcommandsthatcompilethenecessaryfilesfor assemblingthesoftwarepackage. 3. makeinstall:Thisissimplythemakecommand,butwithanadditionaloption calledtarget.IttakesthecompiledfilesfromStep2andinstallsthem. Themakeandmakeinstallcommandsalmostalwaysrequiresuperuserprivilegesto execute,sosudomakeandsudomakeinstallisyourfrequentcompanion. Whenyourunmake,youcanfurtherrefinewhatthescriptdoeswithothertargets.Here areothercommonlyusedoptions: makeall:Thisissomewhatredundanttojustusingmake,butyoumayoccasionally findaREADMEfilerecommendingit.Targetcompilestheentireprogram,includingits librariesanddocumentation. makeinstall-strip:Thisisthesameasmakeinstall,stripsoutdebugging symbols,andisnottypicallyrecommendedunlessyou’recertainthattheprogram hasnobugs. makeuninstall:Thisistheoppositeofmakeinstallbecauseitdeletesallthe installedfiles. makeclean:Thiscleansanderaseswhathasbeenbuilt(theoppositeofmakeall). makedistclean:Thiserasesanythingthatthe./configurecommandcreated. makecheck:Thisrunsatestsuiteifoneexistsforthesource. makeinstallcheck:Thisperformsinstallationchecksontheinstalledprogram(if needed). makedist:ThiscreatesadistributiontarballfortheprogramandoutputsPACKAGEVERSION.tar.gz. Seealso Foramoredetailedusageoftheautotoolstoolsetandfurtherexplanationonhowto changethedefaultbehaviorsandtheoptionstobuildcustomizedpackagesinorderto suityourspecificpurpose,refertohttps://autotools.io/index.html Refertohttps://www.gnu.org/software/libtool/formoredetailsonLibtool Youcandeepdiveintoautotoolsarcanawithabazillionexamplesat https://www.lrde.epita.fr/~adl/autotools.html Now,onwardandupwardwiththerecipes. CompileandinstallGitfromsource Ourfirstrecipeisabasicscenarioofbuildingfromasourcefileandtheninstallingiton yourBBB.Inthiscase,wewillworkwithGit,theillustrioussoftwareversioncontrol system. WecouldhavecheatedandjuststuckwiththeversionofGitthatisalreadyhandily installedonthecurrentDebiandistrofortheBBB.Let’scheckit: $git--version gitversion2.0.2 ThistellsusthatthecurrentprebuiltGitbinaryofferedforarmhontheDebianrepository isversion2.0.2.Yet,ifwegototheGitwebsite(http://git-scm.com/),youwilllearnthat thereisanewerversion.So,let’sinstallthelatestandgreatestfromthesource. Howtodoit… Performthefollowingsteps: 1. Togetthedependenciesorassociatedlibraries,we’llneedtostartbygrabbingthe librariesthatGitrequires:curl,zlib,openssl,expat,andlibiconvwiththe followingcommand: $sudoapt-getinstalllibcurl4-gnutls-devlibexpat1-devgettextlibzdevlibssl-dev 2. Asweareabouttodownloadthepackagesourcefilesandthecompiledcode,we shouldsetupadirectorywherewecanconsistentlymanageeverything,asshownin thefollowingcommand: $mkdir/home/debian/packages/ 3. Withthelibrariesinstalled,it’starballtime,sogetGitusingthefollowingcommand: $wget-P/home/debian/packages https://www.kernel.org/pub/software/scm/git/git-2.6.2.tar.xz The-Poptionpointswgettothespecifieddirectory. Note Theprecedingtarballversionwilllikelybesupersededbythemorecurrentcode. CheckforthelatestGittarballathttp://git-scm.com/.Thislinkwilllikelyreferyouto acoderepository.There,you’lllookforafilewiththegit-0.0.0.tar.xznaming convention,alongwithanotherpossibledigitdependingontheversion. 4. Navigatetothedirectoryanduntaritasfollows: $cdpackages $tar-xfgit-2.6.2.tar.xz 5. Then,gotothenewdirectorycreatedwiththefollowingcode: ~/packages$cdgit-2.6.2 Note Intheuntarredfolder,searchfortheINSTALLfile.Thisfileprovidesguidanceon alternativedirectoriesforinstallationpurposesthantheonewewillperformhere. 6. Now,wearereadytoinstallgit.Foreachstageofthisprocess,waitfortheterminal windowtodefaultbacktoyourworkingpromptbeforeproceeding.Wewillbegin with./configure: $./configure 7. Next,themakefileneedsourattentionwiththecommand: $sudomake Inthiscase,andifyou’rebuildingthepackagedirectlyonyourBBB,the compilationmaytakemorethan20minutes;otherpackagescantakeconsiderably longer.So,bepatientandwaitforthedefaultprompt. 8. Onceallthefileshavebeencrunchedandcompiled,weneedtoinstallthepackage,a stepthatcanoftenfinishquickly,asshowninthefollowingcode: $sudomakeinstall 9. Finally,let’sseehowweperformedcomparedtoourprior2.0.2versionwiththe followingcommand: $git--version gitversion2.X.x Voila!ThefreshestbakedversionofGitisnowatyourboard’sdisposal. Debugging Realitycheck:stuffbreaks,especiallywithsoftware.Andwhenyoursoftwareisbroken,it makesitreallyhardtogetthingsdonewithyourhardware.So,thetruthofthematteris (youalreadyknowthisifyou’reanexperiencedprogrammer)thatmostofyourtimewhen youcreatesomeshinynewsoftwarething,aconsiderableamountoftimeisspenton fixinganddebuggingyourcode. InLinuxLand,GDB(GNUprojectdebugger)rulestheroostasthestandarddebugtool.It isthegotoappthatprovidesawindowtowhatishappeninginthegutsofanother programandallowsyoutosaunterthroughthesourcecodelinebylinewhentheprogram runs.Conveniently,itcomespreloadedontheDebiandistributionforyourBBB. GDBprovidesfourkeythingsneededforfastandefficientdebugging: 1. Startsyourprogramandilluminatesanythingthatmayaffecttheprogram’sbehavior 2. Stopsyourprogramonthespecifiedconditions 3. Investigatesanerrororanomalyandtellsyouwhatwashappeningatthetimea programcrashed 4. Tweakscodeinyourprogram,allowingyoutoquicklystomponebugandgoonto getanother Seealso Checktheselinksformoreguidanceondebugging: http://www.dirac.org/linux/gdb/01-Introduction.php http://www.unknownroad.com/rtfm/gdbtut/gdbtoc.html http://elinux.org/EBC_Exercise_28_Remote_gdb_and_more http://elinux.org/EBC_Exercise_14_gdb_Debugging DebugasimpleC-codeapplicationfrom thecommandlineusingGDB GDBisfrequentlyusedtodigintoproblemsyoumayhavewithaCorC++programthat youmayhavewritten.Alternatively,youcanrunGDBtodebuganexecutableorbinary. Inthissection,wewillperformtheformer. OneofthemosttypicalentrypointstounderstandhowtodebugusingGDBisbyrunning simpleexamplesofexecutableswritteninCorC++.Manyofthesoftwareresources availablefordevelopingonhardwareplatformssuchasBeagleBoneBlack,commonly relyonCorC++.Thesearethecore,low-level(andmid-level)languagesneededfordeep manipulationofthemachinery.Indeed,mostofthebinariesthatyouwilloftenloadto yourBBBarewritteninoneorbothofthesetwolanguages.Theyalsoserveasavital bridgebetweenhigh-levelandlow-levelprogramming,whichwewillseeinlater chapters. IfyouarealreadyanArduinouserorevenaRaspberryPideveloper,thisisoldnews becauseyoualreadyknowthattheArduinoprocessinglanguageislargelyasimplified versionofC/C++.Ifyouareanewcomer,don’tworrybecausetheexamplesweuseare verybasicandwillnotrequireadvancedknowledgeofCorC++.Also,anykindofindepthanalysisateitherofthesetwoprogramminglanguagesisbeyondthescopeofthis book. WewillbeginbyservingupasmallpieceofCcodeontheBBBsothatyoucanseewhat thedebuggeroutputcanshowus.Then,basedonGDB’sforensics,wewillfixthecode. Howtodoit… PerformthefollowingstepstodebugaC-codeapplicationfromthecommandlineusing GBD: 1. Loginasarootuserwiththefollowingcommand: $sudosu-i 2. Now,navigatetoourprojectsdirectoryasfollows: #cdbbb_recipe_book/projects 3. Then,createanewsubdirectorycalleddebugandnavigatetoitwiththefollowing code: #mkdirdebug #cddebug Now,openthenanotexteditor,createtheCfile,andcallitmajor_tom_gdb.c,as showninthefollowingcode: #nanomajortom_gdb.c Copyandpastethefollowingcodetothenanoeditorwindowasfollows: //majortom_gdb.c #include<stdio.h> #include<stdlib.h> #include<string.h> size_tmajortom_len(constchar*s) { returnstrlen(s); } intmain(intargc,char*argv[]) { constchar*a=NULL; printf("ThenumberofcharactersinMajorTomstringa=%d\n", majortom_len(a)); exit(0); } Note Ifyourunintoproblemscopyingandpastingthecode,youcandownloadthecode fromhttps://github.com/HudsonWerks/debug-samples/blob/master/majortom_gdb.c 4. SaveandclosethefileandpressCtrl+x;whenpromptedtypeyforyesandthen pressreturn(Enter)key. 5. Now,wewillcompilethefileusingaC-compilercommandwithoptions: #gccmajortom_gdb.c-g-omajortom_gdb Hereisabreakdownoftheoptionsinthecommand: gcc:ThisisthebasiccompilecommandforaCprogram -g:ThisgeneratesthesymbolicdebugginginformationorsymbolsthatGDB canunderstandwithinacompiledprogram -o:Thisspecifiesthenameofthecompiledfile Thecompilerwilloutputafilecalledmajortom_gdb(nofiletype). Note ThecurrentDebiandistributioncomespreloadedwiththeC/C++compiler.Iffor somereason,yougeterrorsthatindicatethatthecompilewillnotrunorisnot present,installthecompilerwith$sudoapt-getinstallg++. Runthecompiledfileingdbusingthefollowingcode: #gdb./majortom_gdb Thisishowtheoutputshouldlook: GNUgdb(GDB)7.4.1-debian Copyright(C)2012FreeSoftwareFoundation,Inc. LicenseGPLv3+:GNUGPLversion3orlater <http://gnu.org/licenses/gpl.html> Thisisfreesoftware:youarefreetochangeandredistributeit. ThereisNOWARRANTY,totheextentpermittedbylaw.Type"show copying" and"showwarranty"fordetails. ThisGDBwasconfiguredas"arm-linux-gnueabihf". Forbugreportinginstructions,pleasesee: <http://www.gnu.org/software/gdb/bugs/>... Readingsymbolsfrom /home/debian/bbb_recipe_book/projects/debug/majortom_gdb…done. (gdb) 6. Notegdbattheendoftheoutput.Thisindicatesthatyouhavestartedadebugsession andcannowuseGDBcommandstocontrolthetool.So,nowenterthefollowing code: (gdb)run Boom.Youroutputshouldshowabug:thedreadedsegfault(thesegmentation fault).Theerroralsotellsusthatweattemptedtoaccessaninvalidmemoryaddress, asshowninthefollowingcode: Startingprogram: /home/debian/bbb_recipe_book/projects/debug/majortom_gdb ProgramreceivedsignalSIGSEGV,Segmentationfault. 0xb6f45904instrlen()from/lib/arm-linux-gnueabihf/libc.so.6 (gdb) ThegoodnewsisthatGDBjusttoldusthattheproblemlieswithstrlen,astandard Clibraryfunctionthatdeterminesthelengthofastring.However,thefunction requiresanonNULLstringinordertorunproperly.Thus,ourNULLvaluethrewoff thebug.So,nowwecanfixit. 7. Now,exitoutofGDBwiththefollowingcode: (gdb)quit 8. Then,openyourCfileagainasfollows: ~/projects/debug#sudonanomajortom_gdb.c Inline13,changeNULLtothe"GroundControltoMajorTom"stringwithdouble quotes,asshowninthefollowingcode: constchar*a="GroundControltoMajorTom"; 9. Now,save,close,andpressCtrl+x;whenpromptedtypeyforyesandthenpress return(Enter)key. 10. Recompilethefileasfollows: #gccmajortom_gdb.c-g-omajortom_gdb 11. Then,runthecompiledfileinGDBagain,asshowninthefollowingcode: #gdb./majortom_gdb 12. Now,let’sbeginthedebugsessionwiththefollowingcode: (gdb)run Ifallgoesasplanned,yourcodeshouldnolongersegfault,butshowtheoutput similartothefollowingcode: Startingprogram: /home/debian/bbb_recipe_book/projects/debug/majortom_gdb ThenumberofcharactersinMajorTomstringa=27 [Inferior1(process6020)exitednormally] (gdb) Thisenlightensustothefactthatourstring“GroundControltoMajorTom” contains27characters. 13. Finally,exitGDBnormallybyenteringthefollowingcode: quit See?Nothingtoit.Ccode.Crash.Debug.FixCcode.AllonaverylittleLinuxbox. Seealso InChapter7,AppliedRecipes–Sound,Picture,andVideo,wewillrunamoreadvanced recipe,wherewewillcompileaSIP/VOIPpackageforthepurposeofexploringsound andvideo.ThecompilationwillincludedebuggingexampleswithfurtheruseofGDB. Debuganapplicationremotelyfrom EclipseandGDBserver Youareabouttodiveintothearcane,butnecessaryworldofremotedebugging/crosscompiling.Inthischapter,wewillspecificallytakealookatarecipeforsettingupremote debuggingusingtheGDBserver. Wewillsetupaspecifickindofenvironmentonyourclientdesktop,anotherkindof environmentonyourBBB,anduseanIDEasawaytoeasethepotentialcollision betweenthesetwoworlds. Waitaminute!Didn’twejustdoadebugrecipedirectlyonBeagleBoneBlackusing GDB?Andcan’twejustdevelopandcompilerightonBeagleBoneBlack?Yesandyes. ButyourBeagleBoneBlackisnotquitepowerfulenoughtoserveasaserious developmentbox.Ideally,whatwewanttodoishandoffthatworktoafancier,faster, desktopbox.Otherwise,youwillspendmanyunnecessaryhourstesting,compiling, debugging,andwatchingrerunsofDoctorWhowhilewaitingfortheBBBtocompleteits tasks. Whydon’twejustmakesomethingononeboxandmoveitovertoanotherbox?Hmm. Notsofast.IfyouwanttocreateordebuganapplicationonanonBBBboardandoutputa binaryorchunkofcodetorunitonanARMLinuxboardliketheBBB’s,thenyouhave tohavetherighttoolset.Thistoolsetwilljugglebetweendifferingboardarchitecturesand operatingsystemrequirements. Unfortunately,gettingthistoolsetsetupproperlycanbequiteunpleasant.Notonlydoesit takeafairbitoftime,theprocessisalsofraughtwithmanyopportunitiesforerror.So,be patientandpersistentinfollowingthisrecipe. Beforegoingintotheminutiae,herearethehigh-levelstepstogetremotedebugging goingonBeagleBoneBlack: 1. Installandsetupavirtualmachine;youcanskipthisifyourclientdevelopmentbox isLinux. 2. Installandsetupacross-compileanddebugtoolchain. 3. InstallandsetuptheGDBserveronyourBeagleBoneBlack. 4. InstallandsetupEclipse,ourIDEofchoice. Nothingtoit,right?Notquite… Howtodoit… PartI:SetupVirtualMachine—MacOSX Onyourclientbox,wewillsetupavirtualmachine(VM)withaLinuxdistributionon board.Thereareanumberofsourcesforthis,butwewilluseOracle’sfreevirtualbox (onceagain,ifyouarealreadyusingthisbookanditsrecipeswithaLinuxboxasyour clientmachine,installingaVMisnotnecessary). Note Allthestepsinthissectionoccuroneitheryourdesktopclientboxoravirtualmachine, notonBeagleBoneBlack. DownloadandinstalltheVMfromhttps://www.virtualbox.org/.Whenfinished,openthe application.Performthefollowingsteps 1. DownloadaLinuxdistributionthatyouwillloadtoVirtualBox’svirtualmachine environment.Weusedani386netinstallofDebianWheezyavailablefrom debian.orgathttps://www.debian.org/releases/wheezy/debian-installer/(downloadis availableathttp://cdimage.debian.org/debian-cd/7.6.0/i386/iso-cd/debian-7.6.0-i386netinst.iso). Note YoudonotneedtohavetheVMrunDebianWheezyforARMHastheBBBdoes, butcanusealmostanyflavorofLinux. 2. Next,installandsetupaLinuxenvironmentontheVM.IntheopenVirtualBox window,clickonNew(VM). 3. GivetheVManame,somethingcleverlikeDebianWheezy. 4. Fromthedrop-downoptions: 1. ChooseLinux 2. Thenchoose,Debian(32-bit)accordingtothetypeof.isoyoudownloaded 5. Then,clickonContinue. 6. Allocate1024MBofmemoryinsteadofthedefault512MB.Then,clickontheNext button. 7. Fortheharddrive,unlessyouhaveanothervirtualharddisksetupandwanttouseit, leaveitwiththedefaultsetting:Createavirtualharddrivenow.Then,clickon Create. 8. Fortheharddrivefiletype,leavethedefaultVDIsetting.Then,clickonContinue. 9. Forthestorageonthephysicalharddrive,checkwhetheryouprefertheVMtohave afixeddrivespaceallocation(whichcanbefasteroncebuilt)oradynamicstorage capacity(whichwillonlyexpandasneeded).Ikeptmineatdynamicallyallocated. ClickonContinue. 10. Forthefilelocationandsize,clickonCreate.Thisclosesthesetupwindowand returnsyoutothemaindashboard. 11. Atthedashboard,youshouldnowseetheVMwejustcreated:DebianWheezy. BeforerunningtheVM,weneedtoconfigureitsomemore.So,clickonSettings. Followthesesettings: 1. General|Advanced|SharedClipboard.Choosebidirectionalbecauseyou willwanttosharetheclipboarddatainboththedirectionsbetweentheclient box(inourcase,MacOSX)andtheDebianVM.Youwillstillneedtofollow additionalstepstogetthisfunctionworking.Navigatetothefollowing: System|Storage|ControllerIDE—Clickonthe(+)sign(AddCD/DVD device)toopenabrowsedirectorywindow.ClickonChooseDisk. Navigatetothefolderwhereyoudownloadedthe.isofileofyourpreferred Linuxdistro.Thefilenamewillbesomethingsimilartodebian-x.y.z-i386netinst.isoorsomevariantonthearchitecturethatyouchose.Then,clickon Open. YourOSshouldnowbeloaded.Butnow,weneedtohavetheOSactuallyinstalledinits normalfashiononthevirtualdrivethatyousetup.Performthefollowingsteps: 1. Onthedashboard,whilemakingsurethatyournewDebianVMisselected,clickon theStartbutton. 2. Onyourfirstbootup,youwillbepresentedwithaDebiansetupwindow.Choose INSTALL. Youwillthenbetakenthroughquiteafewsetupwindows,includingchoosing language,regionandkeyboardpreferences,networkoptions,passwordanduser setup,andotherconfigurationoptionsthatIwillnotelaboratehere.Configureasyou seefit,whileclickingontheContinuebuttonuntilyouendupwiththeharddisk partitioningsequence.Makeyourchoicesthereaccordingtoyourpreference.Inmost cases,choosingthedefaultoptionshouldbefine. Note KeepinmindthatanentireOSisbeinginstalledonyourhostmachine,sothisstep willtakeawhile.Also,rememberthatthisnewOSisbeinginstalledontheVirtual Machineenvironmentandnotaffectingormodifyingyourclientdesktop. 3. OncetheDebianinstallationandsetupiscompleted,youwillendupattheDebian GUIloginscreen.Loginandyouwillfinallyarriveatthedesktop. 4. Let’sopentheterminalwindowinournewDebianenvironmentandperformabasic pingtestonBeagleBoneBlack.Wewanttomakesurethatwecancommunicatewith itviaourVMasfollows: $ping192.168.7.2 Youshouldgetconsistentpings. AddingcutandpastetoVM Wenowneedtoimplementanadditionalfunctionalitytothevirtualboxthatwilldrive youmadifyoudonotaddit:thecut-and-pastefunction.WhenyouuseMacOSXasyour clientmachine,VirtualBox,likemostvirtualmachinesoftware,doesnotincludecut-andpastebydefault.Instead,theyhavegivenusaseriesof15steps(yes,15!).Oracle/Virtual BoxreferstothisfunctionasGuestAdditions.Herewego: 1. Let’sbeginbyinstallingsomeexternalkernelmodulesonyourVM.So,witha terminalwindowopenintheDebianvirtualmachineonyourclientdesktop,runthe followingcommandasarootuser: $sudo-i ~#apt-getinstalldkms 2. Next,backonyourclientdesktop(MacOSX),wehavetolocateaveryburied.iso filethatcontainsthecodetoaddtheguestadditionswithitscutandpastefeature.In Finder,navigatetoApplications|Virtualbox.app|ShowPackageContents. Thiswillopenallthehiddendirectoriesinthepackage,includingourtargetdirectory andfile. Then,navigatetoContents|MacOS|VBoxGuestAdditions.iso. 3. FindandcopytheVBoxGuestAdditions.isofiletoaplacewhereyoucanfinditon yourmachine. 4. BackinyouropenVirtualBox,inDebianWheezy|Settings|Storage,clickonthe smallCDiconatthebottomofthescreenandselectChooseaVirtualCD/DVD diskfile. Anotherwaytoperformthesamethingisfromthedrop-downmenusatthetopof thescreen(notintheVM/Debianwindow,butthevirtualmachinemenuoptionsat theverytopofyourdesktopmachine.There,youcanchooseDevices|CD/DVD devices|IDE(IDEPrimaryMaster)|ChooseaVirtual/CD/DVDdiskfile. 5. BrowsetowhereyouputtheVBoxGuestAdditions.isofileandselectit.The.iso fileshouldnowappearintheCD/DVDdriveoptions.ClickonOKandrestartthe VM. 6. WiththeterminalwindowopeninyourDebianVM,runthefollowingtwo commands: ~#apt-getupdate ~#apt-getupgrade 7. Now,confirmthatyouhavethemakeandGNUCcompilerinstalled,whichshould alreadybeonthedistributionthatyouinstalled.Checkitwiththefollowingcode: ~#gcc--version 8. Ifyoudon’tgetanoutputthatshowstheversion,butacommandnotfounderror, youwillneedtoinstallitasfollows: ~#apt-getinstallmakegcc 9. RebootyourVirtualBoxmachine. 10. Determinetheexactversionofyourkernelwiththefollowingcode: ~#uname-a 11. Installthecorrectversionofthelinux-headerspackage.Replacethefollowing versionnumberswiththeversionnumbershowninthepriorstep: ~#apt-getinstalllinux-headers-2.6.26-2-68 Thismaytakesometime;justwaitfortheinstallationtofinishandreturntoyour terminalprompt. 12. RestartyourVMwiththefollowingcode: #reboot 13. Fromthescreenoptions,selectMachine|options|Generalandthenclickonthe Advancedtab.IntheSharedClipboarddropdown,selecttheBidirectionaloption. Thecut-and-pastefunctionalitybetweenyourclienthostbox(inourcase,MacOS X)andyourvirtualmachineenvironmentshouldnowbeenabled. 14. Beforemovingonethough,weneedtoverifythatthecut-and-pastefunctionis working.FromyourDebianWheezyvirtualmachinewindow,navigateto Applications|Accessories|geditTextEditorandopenanewfile,asshowninthe followingscreenshot: 15. Fromtheopenfilewindow,enterGroundControlandthenselectEdit|Copy.Then, navigatetoyourclientdesktop(Mac/Windowsmachine,andsoon),openasimple texteditor,andselectPaste.Hopefully,GroundControlwillbepastedtothe window. 16. Wewanttocheckthebidirectionalfunctionality,sonowenterMajorTomin (Mac/Windows)texteditoronthedesktopandpressCtrl+c(copy).Now,switch backtotheVMeditorwindowandthenselectEdit|Paste.MajorTomshouldbe pastedsuccessfullytothegeditwindow. 17. ReboottheVMandthenlogbackinastherootuserwiththefollowingcode: #sudo-i 18. Addyourusernametothesudogroupasfollows: #adduserusernamesudo 19. Then,usethefdiskcommandtocheckwhethersudoisworkingproperly.The-v optionwillchecktheversionoffdiskinstalledonyourVM.Youshouldgeta promptforauserpassword,asshowninthefollowingcode: #sudofdisk-v Thescreenoutputshouldshowtheversionoffdiskthatisinstalled,andthereshould benoerrorsaboutpermissions. 20. Installssh.WealreadyuseitontheBBB.Now,weneedtoaddittoourVM.SSH givesEclipsetheabilitytoconnectandtransferfilestoBeagleBoneBlackusingscp, asecurenetworkprotocol.Installitwiththefollowingcode: #sudoapt-getinstallssh PartII:InstallinggdbserveronBeagleBoneBlack WeneedthispackageonboardtheBBBsothatwecanrungdbfromafarorfromanother box.Performthefollowingsteps: 1. First,downloadtheDebianinstallationpackageofgdbserverforarmhf(theBBBnativearchitecture)onyourVMasfollows: #wget http://http.us.debian.org/debian/pool/main/g/gdb/gdbserver_7.4.1+dfsg0.1_armhf.deb 2. Now,usescptotransferthepackagetotheBBB,asshowninthefollowingcode: #[email protected]:~ 3. YoushouldgetapasswordpromptfortherootuseronBeagleBone.Loginand installthepackageasfollows: #[email protected] root@arm#dpkg-igdbserver_7.4.1+dfsg-0.1_armhf.deb 4. Whenfinished,logoutbyexitingtheSSHsession,asshowninthefollowingcode: root@arm#exit PartIII:Installingandsettingupthetoolchain Thispartandthenextonearethehairiestbitsoftheprocess;manyonlinetutorialsonthis subjectpurporttodeliveraworkingtoolchainlashedtoanIDE,thoughfewofthem actuallydeliver. Fortunatelyforus,engineerandbloggerAaronClarke’sveryclearstepsat http://bit.ly/1x7TGUYprovidesuperbguidelinesforasuccessfultoolchainandthe EclipseIDEsetup.Thevastmajorityofthecreditforthenexttwopartsoftherecipegoto Mr.Clarke. Note Wechosenottoincludescreenshotsoftheprocessbecausedoingsowouldhavemadethe recipeconsiderablylonger.However,youcanfindamoregraphicalversionofthisrecipe onlineatAaronClarke’sblog,whichincludesaversionforDebianJessieat http://blog.embeddedcoding.com/2015/05/beaglebone-black-development-part-6.html. Herewego. Performthefollowingsteps: 1. AttheterminalpromptonyourDebianVM,ifyouarenotalreadyloggedinasroot, dosonowwiththefollowingcommand: $sudo-i 2. Createanewdirectorywhereyouwilldownloadthetoolchainandthennavigateto thatdirectory,asshowninthefollowingcode: root@debian:/home/user#mkdirbbb-tools root@debian:/home/user#cdbbb-tools 3. Usingwget,downloadthetoolchainfromthefollowinglinktothedirectorythatwe justcreated: #wget-chttps://launchpad.net/linaro-toolchainbinaries/trunk/2013.10/+download/gcc-linaro-arm-linux-gnueabihf-4.82013.10_linux.tar.xz 4. Then,untarthefilewiththefollowingcode: #tarxfgcc-linaro-arm-linux-gnueabihf-4.8-2013.10_linux.tar.xz 5. Now,runtheechocommandtocreatethebbb-varsfile;thiswillbeusedtotestthat ourenvironmentissetupproperly,asshowninthefollowingcode: #echo"exportCC=`pwd`/gcc-linaro-arm-linux-gnueabihf-4.82013.10_linux/bin/arm-linux-gnueabihf-">bbb-vars 6. Verifythatthecommandworked.Thebbb-varsfileshouldappearinthedirectoryas follows: root@debian:/home/user/bbb-tools#ls bbb-vars 7. Setuptheenvironmentforaremotetestbysourcingthebbb-varsfile.Takealookat thecommandprecedingthe(.)isthefilelocation: root@debian:~#./home/user/bbb-tools/bbb-vars 8. Now,verifythatthetoolchainversionweinstallediscorrectusingthefollowing code: root@debian:~#${CC}gcc–-version arm-linux-gnueabihf-gcc(crosstool-NGlinaro-1.13.1-4.8-2013.10- LinaroGCC2013.10)4.8.220131014(prerelease)Copyright(C)2013Free SoftwareFoundation,Inc.Thisisfreesoftware;seethesourcefor copyingconditions.ThereisNOwarranty;notevenforMERCHANTABILITY orFITNESSFORAPARTICULARPURPOSE PartIV:InstallingandsettinguptheEclipseIDE Performthefollowingsteps: 1. WewillfirstinstallEclipseonourVMwiththefollowingcode: root@debian:~#sudoapt-getinstalleclipseeclipse-cdt Then,openEclipseandsetupaworkspacebyclosingthewelcomescreenand navigatingtoWindow|Showview|C/C++Projects. 2. CreateanewCprojectbynavigatingtoFile|New|CProject. 3. Givetheprojectaname:bbb_ground_control. 4. SelectProjecttype|HelloWorldANSICProject. 5. Then,selectToolchainCrossGCCandclickonNext. 6. Enterthebasicsettings,suchastheauthorname,inthenextwindow. 7. ClickonNexttobringuptheSelectConfigurationswindow. 8. Now,clickontheAdvancedsettingstobringupaPropertieswindow. 9. Fromtheleft-handside,navigatetoC/C++Build|SettingstobringupTool SettingsfortheDebugconfiguration. 10. ChoosetheToolSettingstab,thenfillthePrefixandPathfieldsinthefollowing manner: Prefix:arm-linux-gnueabihf- Note Besuretoincludethehyphen(-)attheendoftheprecedingprefix. Path:/home/user/bbb-tools/gcc-linaro-arm-linux-gnueabihf-4.82013.10_linux/bin 11. Then,clickonOK. 12. ThisbringsupanotherCProjectwindow,whichannoyinglyasksyoutorepeatwhat youjustdidinthepriorstep.Thismaybeabug,butdoitanyway: Prefix:arm-linux-gnueabihf- Path:/home/cah/bbb-tools/gcc-linaro-arm-linux-gnueabihf-4.82013.10_linux/bin 13. Then,clickonFinish. 14. Thesamplecoderunsandyougetanerror:Symbol'EXIT_SUCCESS'couldnotbe resolved.Aaargh! TheerrorsaysthatsomeCcodesymbolscannotberesolvedbythecompiler.Notto worrythough.ThiserrorcanbeignoredbecauseaccordingtotheEclipse documentation,itisinaccurateanddoesnotaffectthesuccessfuloperationofthe application. 15. Now,wewillbuildtheproject.OntheEclipsemainmenu,selectProject|BuildAll. Then,opentheConsolewindowtoseethebuildoutputmessages.Youshouldseethe compilerprefixbeingusedforthegcccompilerasfollows: 00:24:52****BuildofconfigurationDebugforproject bbb_ground_control****makeallBuildingfile: ../src/bbb_ground_control.cInvoking:CrossGCCCompilerarm-linuxgnueabihf-gcc-O0-g3-Wall-c-fmessage-length=0-MMD-MP-MF"src/ bbb_ground_control.d"-MT"src/bbb_ground_control.d"-o"src/ bbb_ground_control.o""../src/bbb_ground_control.c"Finishedbuilding: ../src/bbb_ground_control.cBuildingtarget:bbb_ground_control Invoking:CrossGCCLinkerarm-linux-gnueabihf-gcc-o" bbb_ground_control"./src/bbb_ground_control.oFinishedbuilding target:bbb_ground_control00:24:52BuildFinished(took172ms) 16. FortheEclipseremoteconnectionsetup,onthemainmenu,clickonRun|Run Configurations. 17. SelectC/C++RemoteApplication.Clicktwiceonthistoopenanotherdialog window. 18. Adrop-downoptionshouldshowbbb_Hello_WorldDebug.ClickontheNew buttoninthemiddleofthewindowtocreateaprojectdebugrunconfiguration.Click ontheNewbuttonnexttoConnectionintheMaintab. 19. ThisbringsuptheNewConnectionwindow. 20. SelectLinuxandclickonNext. 21. Thisbringsupawindowwiththeconnectioninformation.EnterBeagleBoneBlack IPaddressforHostnameandnametheConnectionnameandDescriptionbothas BeagleBoneBlack: Hostname:192.168.2.7 Connectionname:BeagleboneBlack Description:BeagleboneBlack 22. ClickonNext. 23. IntheNewConnection/Fileswindow,selecttheselect.sshfilesandthenclickon Next. 24. IntheNewConnection/Processeswindow,selectprocesses.shel.linux.Then, clickonNext. 25. IntheNewConnection/Shellswindow,selectssh.shells.Then,clickonNext. 26. IntheNewConnection/SshTerminalswindow,selectssh.terminalsandclickon Finish. 27. YouwillendupbackattheRunConfigurationswindow.ForConnection,choose BeagleBoneBlack,notLocal. 28. ClickonPropertiesnexttoConnection.Awindowwillcomeup,soselectRemote workspacelocation. 29. EnterapathtoyourprojectonBeagleBoneBlack.Forthesakeofsimplicity,you shouldprobablyfollowwhatwedidandinput/root. 30. ClickonOK.ThistakesyoubacktotheRunConfigurationswindow. Inthefollowingsteps,wewillperformtwokeythings:configureourremotepathson theBBBandgiveourapplicationpermissiontoexecute. 31. AtthebottomoftheRunConfigurationsscreenaretwofields.Inputthefollowing: remoteabsolutefilepathforC/C++application: /root/test_project/bbb_ground_control commandstoexecutebeforeapplication:chmod+x /root/test_project/bbb_ground_control Note ChooseapathonBeagleBoneBlackwherethebbb_ground_controlexecutablefile willbeplaced.Inourexample,itis/root/test_project/bbb_ground_control, wherebbb_ground_controlisthenameofthebinaryfilethatwewillcompile.The purposeofthechmod+xcommandistogiveourprogrampermissiontoexecute. 32. ClickonApply.Wearealmostthere.Bepatientandhangontight. 33. FromtheterminalwindowontheVM,wehaveacouplemorethingstoperformon theBBBitself,whichistomirrorwhatwejustinputinthetwofieldsinEclipse. First,loginwiththefollowingcode: #sudossh192.168.7.2 34. Answeryeswhenpromptedareyousure. 35. EntertherootpasswordfortheBBB:root.YoushouldnowbeloggedintotheBBB. 36. RunthecommandstoduplicatewhatwejustdidinEclipse,whichmeansthatwe needtocreateanewdirectory,navigatetoitandthenrunthefollowingcommandto givetheapplicationpermissiontoexecute: root@beaglebone:~#mkdirtest_project root@beaglebone:~#cdtest_project root@beaglebone:~#chmoda+w. 37. Now,exittheSSHsessiononBeagleBoneBlackwiththefollowingcode: root@beaglebone:~#exit 38. BackintheVMEclipsewindow,clickonRun. 39. Anotherpop-upwindowwillappear.Entertheuserandpasswordasroot.Clickon themandagreetothenextfewpromptsfromtheBBB. Thelastfewstepsarefocusedonhowtosetuparemotedebugsession. 40. Inyourterminalwindow,navigatetotheprojectDebugpathwiththefollowingcode: #cd~/bbb-eclipse-workspace/bbb_ground_control/Debug 41. Now,wewillperformalittleobscurebutnecessarystepwhenyourunGDB:create aninvisiblefilecalled.gdbinit.Thisisaninitializationfilethatresidesinthedebug directoryandautomaticallyloadsandparseswhenyourunGDB. Typically,youwouldpopulatethisfilewithanyrequiredcommands.However,for ourcurrentrecipe,thefileremainsempty,althoughitneedstoremainpresentfor GDB’sproperoperation. 42. Wecouldusenanotocreatethefilebecauseweusedthiseditorintheearlier chapters.However,thereisanothercommandthatactuallygeneratesthefileonthe fly,savesit,andplacesitinwhateverdirectoryyouhaveentered,asshowninthe followingcode: #touch.gdbinit 43. Makesurethatthefilewascreatedwiththefollowingcode: #ls Hmm.Itisn’tthere! Tofigureoutwhatishappening,thisisacasewhereusingdifferentoptionswitha commandisvital.Withthelscommand,wewanttoappendthecommandwiththeaoption.So,tryagainusingthefollowingcode: #ls-a Thegdbinitfileshouldnowappearinthedirectory’slineup. 44. BackintheEclipsewindow,selectWindow|OpenPerspective|Other.Then, selectDebug.Thiswillshiftthewindowviewstoadebug-centricUI. 45. Fromthetopmenu,selectRun|DebugConfigurations.Inthewindowthatopens, selectC/C++RemoteApplication|bbb_ground_controlDebug. Holdontight.Almostdone. 46. SelecttheDebuggertab.Thisshowsusmoretabsbecausewehaven’thadourfillof tabsoroptionsyet. 47. Now,selecttheMaintab.Here,weneedtopopulatethetwofields:GDBDebugger (theexecutableinthetoolchaindirectory)andtheGDBcommandfile(thedirectory wherewecreatedthe.gdbinitfile).Tofacilitatethisstep,youshouldbeableto browsetherelevantdirectoriesandgrabtherightpathsasfollows: GDBDebugger:/home/user/bbb-tools/gcc-linaro-arm-linux-gnueabihf-4.82013.10_linux/bin/arm-linux-gnueabihf-gdb GDBcommandfile:/home/user/bbb-eclipseworkspace/bbb_ground_control/Debug/.gdbinit 48. Then,clickonApply.Ilikethispart. 49. Now,wefinallygettotestthewholeshebangwithDebugrun.Letmerepeatand thistimewithbuglesandproperfanfare:wewilltesteverythingwejustdidandstart aDebugsession. So,atthebottomofthestillopenwindow,clickonDebug.Holdyourbreath!This willstarttheremotesessionwiththeBBBandfinishthecyclejustafterthemain() lineinyour.cfile. Note YoumaygetanotherloginpromptfromyourBeagleBoneBlack.Justdothesame drill:user=rootandpassword=root. Ifallwentasplannedandthegremlinsstayhome,youshouldseethefollowing outputonyourEclipseconsolescreen: Lastlogin:DAYMODATETIMEYEARfrom192.168.7.1 echo$PWD'>' chmod+x/root/test_project/bbb_ground_control;gdbserver:2345 /root/test_project/bbb_ground_control;exit root@beaglebone:~#echo$PWD'>' /root> root@beaglebone:~#chmod+x /root/test_project/bbb_ground_control;gdbserver:2345 /root/test_project/bbb_ground_control;exit Process/root/test_project/bbb_ground_controlcreated;pid=2910 Listeningonport2345 Remotedebuggingfromhost192.168.7.1 50. Sincetheultimategoalofallthiseffortwastoactuallyperformsomedebuggingona program,nowyoucanreallygettowork.Makesureyourbbb_ground_control.c windowisselected.Then,atthetop,chooseRun. 51. Fromthedrop-downlist,youwillseethebasketofdebugcommandsnowreadyfor yourable,debug-twitchyfingers. 52. Ifyoumadeittothispoint,thisrecipehasonelastsetofcommandingredients: #Gotoactualcabinetonactualshelf #Takeoutbottleofsinglemaltscotch #Pourdram,perhapstwo #Leanbackheadanddrink #CongratulateMajorTomonagoodtestflight There’smore… Athoroughreviewofhowtodebugisbeyondthescopeofthisbook.Fortunately,there areampleresourcestolearnmore.Hereareafew: RMS’sgdbdebuggertutorialisavailableat http://www.unknownroad.com/rtfm/gdbtut/gdbtoc.html ForadeeperunderstandingofGDBandthe.gdbinitfile,referto http://www.dirac.org/linux/gdb/03-Initialization,_Listing,_And_Running.php systemdservices First,itwasn’tatypotolabelthissectionassystemdinalllowercaseletters.Itisoneof themandatesofLinuxthatanydaemon,whichiswhatsystemdis,shouldbeinlowercase. Also,daemonsmustalsocomewiththelowercasesuffix:d. Sowhatissystemdexactly?Briefly,itisabackgroundprocessandasystemmanagement daemonformanaginguserspacesystemservices.Systemdwillbecomestandard plumbingformostmajorLinuxdistrosandisanintegralpartoftheBBBDebian distribution.ItisthefirstprocessinitiatedonbootupintheLinuxuserspaceandthelast processtoterminateonshutdown.Basically,systemdstartstheshowonyourLinuxOS andturnsoutthelightsasit’sleaving. Soundfamiliar?Ifitdoes,that’sbecausesystemdistheheirtoinit:Linux’slongtime daemonofdaemons. MasteringsystemdonyourBBBhelpsusbetterunderstandsystemdependenciesbecause systemdservesasarobustframeworkforthesedependencies.Hereareacoupleof examplesofwhyyou’dwanttomanipulatesystemdprocesses: Bootup:Sincemuchishappeningwithyoursystematbootup,itmakessensetohave tightercontrolanddeeperinsightintothestartupprocesses.Forexample,youmay wanttooptimizeyoursystemtosqueezeoutmoreCPUresourcesforhigher resolutionvideodisplay.Withsystemd,it’seasiertocontrolthatloadenvironment. Jobscheduling:Youmayhavecreatedabeautifulprototypeforaweather measurementdevice.However,youhadinmindawireless,battery-drivendesign,so powerconsumptionisaconcern.Inthiscase,youcanusesystemdtoschedule runtimes(systemdCalendarTimers)forthesensorstocaptureandtransmitdataand thenreverttosleepmodewhennotneeded,therebyprolongingthebatterylife. There’smore… Beforewemoveontotherecipes,you’llfindagreatdealofdeeperinsightintosystemd bytakingalookatsomeofthefollowingreferencedmaterial: Thedefinitive(freedesktop.org)resourceforsystemdisavailableat http://www.freedesktop.org/wiki/Software/systemd/ Thequickreferencecheatsheetforsystemdcommandsisavailableat http://dynacont.net/documentation/linux/Useful_SystemD_commands/ mansystemd:Thisisthecommandfortheveryextensivemanualforthedaemon.It yieldsmoreinformationthanyouwouldprobablyeverwanttoknowaboutsystemd. However,itisthereifyouwantit. Ifyouwantthefullbackgroundonhowsystemdcametobe,oneofthecreatorsof thetoolprovidesthefullstoryandcontextat http://0pointer.de/blog/projects/systemd.html Seealso systemdisfarfromperfect.ManyLinuxheadsgripeaboutitbeingtoopowerfuland potentiallybecomingoverlycomplicatedforusers.Hereissomebackgroundonthis controversy: Arobustslashdotthreadprovidesplentyofrantsontheprosandconsat http://news.slashdot.org/story/14/02/14/166255/ubuntu-to-switch-to-systemd EricStevenRaymond(ESR),anopensourceguru,iscurrentlyonthefenceabout systemdathttp://interviews.slashdot.org/story/14/03/10/137246/interviews-esranswers-your-questions Despitethedisagreementsoveritslong-termimpactonLinux,systemdisheretostayat leastfortheforeseeablefuture.So,itbehoovesyoutolearnsomerecipes. Basiccommandsforsystemdservices systemdismodifiedviaaconfigurationfile,ratherthanashellscript.Beforeyouperform anythingtooambitious,wewilltakealookathowwestop,start,enable,anddisablea service. OurexamplewillresetandreconfigureakeyservicethatwillruninyourDebian distribution:thesystemd-timedated.servicebydefault. Howtodoit… Performthefollowingsteps: 1. Navigatetothesystemddirectory(rootuser)withthefollowingcode: #cd/lib/systemd/system 2. Let’sseewhatservicesarerunning,usingacommandthatservesasthecontrolutility forsystemd,asshowninthefollowingcode: #systemctl Youshouldseealong,fatlistofservicesthatshowtheircurrentstatusonthesystem. Theitemsappendedwiththe.servicefilenamearesystemdservicesand controllableviathecommandline. 3. Runthiscommandtostoptheservice: systemctlstopsystemd-timedated.service 4. Now,disabletheserviceusingthefollowingcode: systemctldisablesystemd-timedated.service 5. Then,dotheoppositeandenableitasfollows: Systemctlenablesystemd-timedated.service 6. Althoughyourservicemaybeenabled,youneedtoactuallystartitsothatthesystem hasaccesstoitsroutine,asshowninthefollowingcode: systemctlstartsystemd-timedated.service 7. Finally,checkwhethertheserviceisrunningcorrectlywiththefollowingcode: systemctlstatussystemd-timedated.service There’smore… AhandylistofsystemdcommandsisavailableasadownloadablePDForanonline referenceathttp://www.cheatography.com/tme520/cheat-sheets/systemd/. Optimizeboottime Youcanusesystemdtospeedupyourstartuptime.Thisrecipeisnotadefinitive recommendationforwhichservicesmaybeexpendable.Instead,itprovidestheoverall methodtotesttheimpactofdifferentservicesonyourboottime. Howtodoit… Performthefollowingsteps: 1. Navigatetothesystemddirectory(rootuser)asfollows: #cd/lib/systemd/system 2. Next,determinehowlongyouroverallsystemistakingtogetgoingwiththe followingcode: #systemd-analyze 3. Youcanquicklyfigureoutthepokierservices.Justpointthefingeratthemwiththe followingcommandthatrevealsallthesystemdservicesthataresortedbytheirboot times: #systemd-analyzeblame 4. Fromthisoutput,youcanimmediatelypinpointsomeoftheculprits.Wewillassume thatyou’rerunningthecurrentDebiandistro,soyou’llseethingssimilartothe followingcommand: wicd.service(7205ms) apache2.service(3430ms) wpa_supplicant.service(1938ms) ... 5. Someofthesemaybeexpendablestartupservicesandworthdisabling.Experiment bydisablingthedifferentservicesandseehowitaffectsyourboottimes.Hereisan example: #systemdsystemctldisablewicd.service Createasystemdservicetorunatboot time RememberthoseancientdaysofChapter2,BasicProgrammingRecipes,whenyouwere justlearninghowtosendane-mailwithNode.js?No?Youskippedthatrecipe?Well,you maywanttodothatonebeforeyoudiveintothisone.Inthisrecipe,we’llperform somethingsimilarandhavethescriptrunatbootup.InsteadofhavingNode.jsperform thejob,it’llbePythonandsystemd. ThescenarioisthatyouneedtocontrolyourBBBremotelyviaSSHorVNC,butthe boardisoffsiteorrunningheadless.Asyouhavelearnedpreviously,inordertocontrol theBBBremotely,wehavetoknowtheboard’sIPaddress.Ifyou’reinfrontoftheboard, it’seasyenoughtochecktheIPatthebottomofyourscreenviatheGUIpopup.However, ourboardis100milesawayandisn’tattachedtoadisplay.Systemd(withahealthydash ofPython)comestotherescue! Let’stakealookathowwecanhavesystemdsendusthismagicalIP-addressede-mail. Howtodoit… Performthefollowingsteps: 1. Loginasrootwiththefollowingcode: sudo-i 2. Then,createanewPythonfilecalledemail-ip.pyandsaveit,asshowninthe followingcode: sudonanoemail-ip-BBB.py 3. HereisthePythoncode(thecodeisderivedfromtheexamplecodeonstackoverflow athttp://bit.ly/1kUppmT): #!/usr/bin/python ##LookupyourBBB'sipaddressandemailit## importsocket importdatetime,time importsys #Importsmtplibfortheactualsendingfunction importsmtplib #Importtheemailmoduleswe'llneed fromemail.mime.textimportMIMEText try: b=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) b.connect(("8.8.8.8",80)) bbb1_ip=b.getsockname()[0] b.close() exceptSocketError: printsys.exc_info()[0] except: printerror time.sleep(5) msg=MIMEText("BeagleboneBlackipaddress:%s"%bbb1_ip) From='[email protected]' To='[email protected]' #includemodulefordateandtime msg['Subject']='BBBipaddressat'+str(datetime.datetime.now()) msg['From']=From msg['To']=To #SendthemessageviaourownSMTPserver,butdon'tincludethe #envelopeheader. s=smtplib.SMTP('smtp.gmail.com',587) s.starttls() s.login('[email protected]',your-password') s.sendmail(From,[To],msg.as_string()) s.quit() Inourrecipe,we’veusedaGmailaccountastheserverandusercredentials, althoughyoucanuseanyserviceyouprefer.JustreplacetheGmaildetailswithyour preferredprovider. 4. Navigatetothesystemddirectorywiththefollowingcode: #cd/lib/systemd/system 5. Now,createanewservicefileasfollows: #nanoemail-ip.service 6. Copyandpastethefollowingcodetothenanowindow.Let’stakealookatthe systemdcodeinitsentiretyfirst.Then,we’llbreakdownitsmeaningasfollows: [Unit] Description=EmailcurrentIPAddress [Service] WorkingDirectory=/home/debian/ ExecStart=/usr/bin/pythonemail-ip-bbb.py SyslogIdentifier=emailip Restart=on-failure RestartSec=5 [Install] WantedBy=multi-user.target 7. Whatdoesthisallmean?First,let’sbeginwithinputtingahuman-readablenamefor thesystemdservice,whichdescribesthepropertiesoftheprocessyou’dliketorun, asshowninthefollowingcode: [Unit] Description=EmailcurrentIPAddress 8. Next,wewilldescribewherethefileisthatwillberunonbootupwiththefollowing code: [Service] WorkingDirectory=/home/debian/ 9. Then,wewilltelltheserviceaboutthecommandorscripttobeexecutedforthefile: ExecStart=/usr/bin/pythonemail-ip.py 10. Now,thesystemlogsshouldcapturetherundata,sowehavetogivetheservicea uniquenameforthatpurposeasfollows: SyslogIdentifier=emailip 11. Wehavetopreparefortheapplicationexitingwithanerror,tellitnottodespair,and tryagainwiththefollowingcode: Restart=on-failure 12. Now,notonlyshouldtheservicetryagain,butkeeptryingtorelaunch,inthiscase, every5seconds,asshowninthefollowingcode: RestartSec=5 13. Oncetheserviceisenabled,wewanttogiveitarun-leveltarget,inourcase,tellitto launchaspartofagroupofprocesses—themulti-userprocesses—thattriggernear theendofthebootcycleasfollows: [Install] WantedBy=multi-user.target 14. Savethefileandthenenabletheserviceyoujustcreated: root@beaglebone:/lib/systemd/system#systemctlenableemail-ip.service 15. Now,reboot.Ifeverythingwentasplanned,youshouldgetane-mailinyourinbox thattellsyoutheIPaddressofyourBeagleBoneBlack.Prettyhandy! Chapter5.BasicProgrammingRecipes withtheLinuxKernel Inthischapter,wewillcoverthefollowingrecipes: Kernelapplicationbinaryinterface Installingthelatestkernelimage Installingandbuildingacustomkernel Interactionswiththekernel–sysfsentriesandcontrollingtheGPIOs DeviceTreeanditsroots DeviceTree/basicbuild DeviceTree/advanced–addingDToverlaytorunacustomcape Universalcapeoverlay RunningascripttocheckDTusageonGPIOpins Introduction Wewillnowlearnsomethingabouttherealgutsofourplatform,theLinuxkernel.Of course,understandingallthebitsaboutthekernelisforanotherverylargesetofbooks anddiscussion.Wewon’tbedoingthathere! Whatwedowanttoexploreishowtoupdate,build,andmodifythekernelinwaysthat willgiveustightercontroloverourhardwareandmakethedevelopmentprocessless opaque.Then,we’llconcludethechapterbyworkingwithoneofthekeydifferentiators forBeagleBoneBlack,theDeviceTree,whichisacleverwaytodescribethehardwarein oursystem. Thebestpartisthatifyoudoalltherecipes,you’llbeforeverknownasColonelkernel. Well,lieutenantkernel.Allright,maybeprivatekernel.Butit’sastart…. Kernelbuildingbasics Whatisthismysteriouskernelthingofwhichwespeak?Whatdoesitlooklike?Where doesitlive?Well,ononelevel,itismerelyafile.Let’stakeapeek.Openupaterminalon yourBBBandtypethefollowingcommands: $cd/boot $ls Thecommandshoulddeliverthisoutput: Thereitis:thekernel,thefilethatbeginswiththename,vmlinuz.However,thefileitself —anexecutableone—doesnotreallydoanythinguntilyouloaditintomemoryandhave itrun.Thathappens,ofcourse,whenyouhavetherightbootsequenceestablished,which shouldbehappeningbydefaultonyourBBBDebiandistro. Whenthekernelbeginsrunning,itperformsseveralkeytasks,suchasprocess management,filemanagement,andI/Omanagement.Thelatteriswhatwewillmainly lookatinthischapterasitisthemostclearlyrecognizable—andrelevant—functionthat thekernelperformsforphysicalcomputingorwhilebuildinghardwareprototypes.Forus, I/OmeansmostlyGPIOpins,peripheraldevicessuchascapesanddaughterboards,and otheradd-onsasthisiswheremostoftheactionisforthisbook. Seealso Understandingthebootsequencegivesyouadeeperunderstandingofthevarious processesandeventsoccurringonyourBBBandcanplayakeyroleindevelopmentand debugging.Thefollowingprovideanexcellentbackgroundonthebootcycle: InthecontextofusingArduPilot,adrone-centrictoolset,developerAnujDeshpande takesyouthroughthestepsathttp://diydrones.com/profiles/blogs/booting-up-abeaglebone-black AlthoughthisexamplefromprofessorMarkYodershowsanAngstromdistribution bootwithanearlierkernel,oneofthebettertutorialstodescribetheBBBbootcanbe foundathttp://elinux.org/EBC_Exercise_21a_Boot_Sequence AcommonlyreferencedprocessmapcreatedbyAlexanderHollerdeliversan excellentgraphicalrepresentationofthebootsequenceat http://ahsoftware.de/Beaglebone_Black_Boot_explained.svg Kernelapplicationbinaryinterface Now,let’sdoaquick,simpletaskwithacommandtofindoutwhichkernelweare running.Thecommandcanserveasafirst-level“diagnostic”toolwhenweneedto troubleshooterrorsorincompatibilitieswithanysoftwarewewanttoaddorcompilefor oursystem. Gettingready Thisisasimplesetup,soallyouneedtodoisconnectyourboardviaUSBtoyourhost computerandfireitup.Then,openaterminalwindow. Howtodoit… Thestepstodothisaresimple: 1. Firstly,loginastherootuserusingthefollowingcommand: $sudo-i 2. Now,runacommandthattellsusafewimportantthingsaboutthekernel.Let’s choosethe-aoptiontoshowallinformationaboutthesystem,asfollows: root@beaglebone:~#uname-a Linuxbeaglebone3.8.13-bone67#1SMPWedSep2401:36:09UTC2014 armv7lGNU/Linux Fromthiscommand’soutput,wediscoverseveralitemsofinterest,asfollows: Thekernelversion:Accordingtoouroutput,theinstalledversionoftheLinux kernelis3.8.13.Thereareotherlater,experimentalversions(forexample,3.14.x) thatmanyBeagleBoneBlackdevelopersarecurrentlyusing.However,version3.8is thecurrentstableinstall. KernelABI:Ourversionis“bone67”,aflavorspecifictoourboardandonethat providesanoptimizedenvironmenttorunabasicBBBsystem.Thenumber“67”is theversionnumberandnotsignificantinitself,butitprovidescontextforwhenwe encounterincompatibilitiesorerrors. Howitworks… So,whatisthekernelABI?Basically,itisaninterfacelayerbetweenthekernelanduser spaceapplications.OnewayofunderstandingitisbycomparingittoanAPI,afamiliar concepttoanyprogrammer.WhenyouuseanAPI,youcanaccessthefeaturesofan externalcomponent,athird-partysoftwarefeature,oranOS.AnABIiskindofsimilarto acompiledversionofanAPI. Thinkaboutthesoftwarethatwebuiltandcompiledfromsourceinourpriorchapter. Oncecodeiscompiledatthekernellevel,anapplicationaccessesthebinarydatathrough theABI.JustlikeanAPI,anABIdefinesthestructuresandmethodsthatyourcompiled applicationwillusetoaccessanexternallibrary,forinstance.ExceptwiththekernelABI, ithappensatthelowermachine-languagelevel. Installingthelatestkernelimage AllthewaybackinChapter1,SettingUpfortheFirstTime,weusedasetoftoolsthat camewithourDebiandistro.Inthatcase,weusedatool(abashscript)toexpandour partition.Inthiscase,we’lluseanotherscriptfromthattoolsetthatrunsaroutineto updateourkernelimage.Let’sgogetit.WithdeveloperRobertNelson’sslickscripts (https://eewiki.net/display/linuxonarm/BeagleBone+Black),theprocesstoupdateorbuild thekernelonDebianfortheBBBhasbecomeasnap. Gettingready Asinourprecedingrecipe,connectyourboardviaUSBtoyourhostcomputer,bootup, andthenopenaterminalwindow. Howtodoit… Let’sgetstarted!Todothis,performthefollowingsteps: 1. Firstly,loginasrootwiththefollowingcommand: #sudo-i Followingthis,checkthecurrentversionofyourkernelthroughthefollowing command: #uname-a Linuxbeaglebone3.8.13-bone67#1SMPWedSep2401:36:09UTC2014 armv7lGNU/Linux Note Writedowntheversionnumbersothatwecanrefertoitattheendoftherecipe. 2. Youthenneedtogotothescriptsdirectorythatcomespreloadedwithyourversion ofDebianfortheBBB.Youcandothisbytypingoutthefollowingcommand: $cd/opt/scripts/tools 3. Runthefollowinggitcommandtoupdateyourlocalfiles: $gitpull 4. Youhaveseveraloptionsforthetypeofinstallyouprefer:thestable,testing,or customrelease.Accordingtoyourpreference,appendthecommandwithoneofthe followingoptions: Forthestablerelease,usethefollowingcommand: $./update_kernel.sh Forthetestingrelease,thefollowingcommandwillbeuseful: $./update_kernel.sh--beta-kernel Runningthisscriptinstallsaversionofthekernelthatisstillinthetestphase. Althoughtechnicallynotarelease,thetestingversionsofthekernelcanstillbequite stableandrobust,albeitwithsomebugs. Forthecustomrelease,runthefollowingcommand(thishastobeonrcnee.net): $./update_kernel.sh--kernelv.0.00-bone00 Forthecustomoption,youcanreplacetheversionnumberwiththeexact versionyouwanttorun.TheseversionswouldbeavailableatRobertC. Nelson’ssiteathttp://www.rcn-ee.net/deb/. 5. Rebootwithyournewkernelimageandthencheckthatitshowsthenewerkernel nowinstalledwiththefollowingcommand: debian@beaglebone:~$uname-a Linuxbeaglebone3.8.13-bone[xx]#1SMP[daymodatetimeUTCyear] armv7lGNU/Linux The(xx)boxshouldnowreflectanupdatedversionrunning. Installingandbuildingacustomkernel Thisrecipewillbuildthekernelandmodulesfromscratchandcopythemtoadeployor temporarydirectory. Gettingready ConnectandpowerupyourboardviaUSBtoyourhostcomputer;then,openaterminal window. Howtodoit… Toperformthisrecipe,followthesesteps: 1. First,loginastherootuserandthendownloadthekernelfilefromRobertC. Nelson’sgitrepo: $sudo-i #gitclonehttps://github.com/RobertCNelson/bb-kernel.git 2. NavigatetothenewdirectorythatgitcreatedforyouonyourBBBwiththis command: #cdbb-kernel/ 3. Atthispoint,youhavetwooptionsforthekernelversionyouprefertouse:either v3.8.xorthelatestexperimentalv3.14.x.You’llnoticethatthegitcommandalso generatesatmpdirectoryforthebuild: Forthe3.8.xWheezybranch(thisversioncomeswithfullcapesupport)usethis command: ~/bb-kernel#gitcheckoutorigin/am33x-v3.8-btmp Forthev3.14.xJessiebranch(whichcomeswithbetterUSBandEthernet supportbutwithoutfullcapesupport)usethefollowingcommand: ~/bb-kernel#gitcheckoutorigin/am33x-v3.14-btmp 4. Now,wewillbuildthekernelwiththiscommand: ~/bb-kernel#./build_kernel.sh Besuretotakenoteofthespacebetween#and.inthecommand.Otherwise,your commandwillnotbeexecuted.Also,bewarethatthisbuildcyclemaytakeawhile, sobepatientforittofinish. Note SinceLinux,BeagleBoneBlack,andtheopensourcecommunityatlargemovepretty fast,whatwedeemexperimentalinthisbookmaybenearlymainstreamwithina shortperiodoftime.Forexample,notethatthecurrentmovetowardthenewDebian 8Linuxkernel“Jessie”(asopposedtothecurrentversion7nicknamed“Wheezy”)is wellunderway.In2015,itwilllikelyhavemovedfromtheDebian/testingreposto thestablereposandisexpectedtobepartoftheBBBshippingfirmware. Interactionswiththekernel–sysfsentries andcontrollingtheGPIOs WhenfirststartingoutwithphysicalcomputingandaLinuxboard,suchastheBBBin particular,itislessdauntingtousepreexistinglibrariesalongwithfamiliarprogramming tools.ThisiswhyweusedtoolssuchasPythonlibrariesandBoneScripttogainaccessto BeagleBoneBlack’sGPIOpins,methodsthatabstractthekernellayerfromtheuserspace layer. However,itisusefultounderstandthenatureofthisabstractionabitbetter,particularly whenitcomestotheGPIOpins.TheLinuxkernelusesavirtualfilesysteminterface—or sysfs—toreadandwritetothepins.Sysfseasilyandeffectivelyexposesdriversforthe hardware—buttons,LEDs,sensors,add-ons,andsoon.So,youcancontrolthem. Manipulatingthissystemgivesusinsightintohowthekernelandhardwarecan interoperate.Inthissection,we’lllookathowtoactivatethesysfsinterface. Toreiterate,insteadofprogrammingwithauserlandlibrary,thistimewewantamore directunderstandingofwhat’shappeningwiththeplatform.So,wewillcontrolsomepins usingacodethattransparentlyaccessestheLinuxkernel.Todothis,itmeansblinkyLED time;exceptthatthistime,wewillmapapindirectlyintothefilesystem. Note We’vereferenceditbefore,butyoucanneverberemindedtoomanytimesofthevalueof agoodGPIOreferencediagram.Hereitisagain: http://elinux.org/Beagleboard:Cape_Expansion_Headers. Gettingready Accesstothevariouspinsintheheadersontheleft-andright-handsidesoftheBBBis donethroughtheLinuxkernelusingitsGPIOinterfaces.Todemonstratehowtogivethis aspin,wewillattachanLEDtodesignatedGPIOandGNDpinsdirectlyontheboard’s header. Thefollowingareneeded: ABBBpoweredviaUSB. LED—acheapLEDoftheilkweusedinthepriorchapters. Resistor—anywherefrom700(700Ω)to1kisfine.Wewillusea700Ωhere(the violet/black/brown/goldbands). Twojumperwiresthatareeasytoconnecttothebreadboard. Abreadboard. Howtodoit… Nowthatyou’reready,let’sbeginasfollows: 1. EnsurethatyourBBBispowereddown. 2. Now,wireupyourLEDaccordingtothediagramfollowingtheseinstructions: TwojumperwiresrunfromP8_2(GND)andP8_14ontheP8headerofthe BBBontothebreadboard. Insertoneendoftheresistor(directiondoesnotmatter)intotheslot correspondingtotheP8_14jumperwireandtheotherendafewslotsabove. LineuptheLED’sanode(positive/longer)endintothebreadboardslotatthe upperendoftheresistor,whilethecathode(shorter/ground)endgoesintothe slotlinedupwiththegroundwire. 3. YouthenneedtopowertheBBBbackup,logginginastherootuserwiththis command: $sudo-i 4. Navigatetothegpiodirectoryusingthefollowingcommand: #cd/sys/class/gpio 5. Whiledoingthis,takestockofthedirectorywithls-lsothatyoucancompare whatyouseenowwithwhatwilloccurafterthenextstep.Wewilladdthe-loption toviewtheoutputinalistformat,asfollows: #ls-l --w-------1rootroot4096Oct2110:26export lrwxrwxrwx1rootroot0Dec311999gpiochip0-> ../../devices/virtual/gpio/gpiochip0 lrwxrwxrwx1rootroot0Dec311999gpiochip32-> ../../devices/virtual/gpio/gpiochip32 lrwxrwxrwx1rootroot0Dec311999gpiochip64-> ../../devices/virtual/gpio/gpiochip64 lrwxrwxrwx1rootroot0Dec311999gpiochip96-> ../../devices/virtual/gpio/gpiochip96 --w-------1rootroot4096Oct2110:32unexport 6. Oncethisisdone,sendanechocommandasfollows: #echo26>/sys/class/gpio/export 7. Now,takealookatthedirectorytoseehowithaschanged: #ls-l total0 --w-------1rootroot4096Apr2316:24export lrwxrwxrwx1rootroot0Apr2316:24gpio26-> ../../devices/virtual/gpio/gpio26 lrwxrwxrwx1rootroot0Dec311999gpiochip0-> ../../devices/virtual/gpio/gpiochip0 lrwxrwxrwx1rootroot0Dec311999gpiochip32-> ../../devices/virtual/gpio/gpiochip32 lrwxrwxrwx1rootroot0Dec311999gpiochip64-> ../../devices/virtual/gpio/gpiochip64 lrwxrwxrwx1rootroot0Dec311999gpiochip96-> ../../devices/virtual/gpio/gpiochip96 --w-------1rootroot4096Dec311999unexport Thisechocommandhascreatedavirtualdirectory,whichnowallowsyoutodirectly interactwiththeLinuxkernelfromuserspace.Thekernel’svirtualfilesystem (VFS)isanabstractionofafilesystemandgivesyouawaytousestandardfunctions formanipulatinganythingthatcouldbeafileonyoursystem.Youshouldalsonote thatpin26onwhichwejustranechocorrespondstopinP8_14thatwewiredupon theBBB. 8. Gotothenewdirectorycreatedfromtheechocommandandtakealookinsideusing thefollowingcommand: #cdgpio26 #ls Theoutputshowstheoptionsnowavailabletocontrolthepinasfollows: active_lowdirectionedgepowersubsystemueventvalue 9. DeterminethecurrentGPIOvalue.Youshouldseeitsinitialvalueas0oroff,as follows: #catvalue 0 10. Now,let’slightherupbysendingthefollowingcommands: #echoout>direction #echo1>value Voila!Youshouldgetasexy,glowingredthingonyourBBB. 11. Repeatthesamecommandbutchangethevaluebackto0,whichshouldturnthe LEDbackoff,withthiscommand: #echo0>value 12. AvariationonthisistouseanotheroneoftheVFSoptions;inthiscase,thiswillbe thehigh/lowdirection: ThisturnstheLEDon: #echohigh>direction Andthen,itturnsoff: #echolow>direction. 13. Tofinishup,itisconsideredgoodpracticetocleanupyourpinusagebeforemoving ontosomeothertask.Usethefollowingcommandlinesforthis: #cd/sys/class/gpio #echo26>unexport Notethattheexportedgpio26hasnowevaporated: #ls #exportgpiochip0gpiochip32gpiochip64gpiochip96unexport YoumaythinkthatthisexerciseisjustanotherblinkingLEDyawn.Butreally,wedid somethingquitedifferentthistime;wereacheddirectlyintothekernelfromtheuser space,addedavirtualdirectorytoenablecontroloverapin,andthencontrolledthispin viathecommandline.Seeingitworkhereatadeeperlevelwillbearfruitasweadvance towardfancierrecipesinlaterchapters. There’smore… Formoreinformation,refertothefollowingsources: Pinstates Understandingpinstatescanbequitechallenging.Accordingtoyourusecase,notonly cantheybesetasinputoroutputpins,buttheycanalsobesetaspull-up,pull-down,or floating.Formorediscussionandbackgroundonconfiguringyourpinsforthesepurposes, reviewChapter3,PhysicalComputingRecipesUsingJavaScript,theBoneScriptLibrary, andPython,wherewediscussedGPIOpins. Othertutorials ForacoupleofinterestingsysfsmethodstoturnofftheUSRLEDheartbeatpattern, whichmanyfindannoying,followalongwithoneofthesetutorials: Howto:DisableBeagleBoneUSRHeartbeatLEDlights: http://experimentswithlinuxrelatedtech.blogspot.com/2014/12/how-to-disablebeaglebone-usr-heartbeat.html ProfessorMarkYoder’sclass,EBCExercise10FlashinganLED: http://elinux.org/EBC_Exercise_10_Flashing_an_LED DeviceTreeanditsroots LinusTorvaldswassadandmad.ARMwasmakingLinussadandmad.Thereweretoo manycooks,toomanyingredients,toomanynewhardwarevariationsintheworldof ARMdevices.Thearchitecturehadbecomesopopularintheembeddedcomputingworld thatathicketofthird-partydeviceswerebeingcookeduptoworkwithARM.Custom hardwaredriversandcustomkernelswereeverywhere.ThiswasmakingtheLinuxkernel playgroundincreasinglychaotic. So,Linusroared:gobacktothekitchen,cooks,andmakeabetterrecipe!So,theydid.Or, sothestorygoes.ThuswasbornDeviceTree…. Forbeginners,DeviceTreecanbeabitdifficulttowrapone’sheadaround.However,in ordertouseBeagleBoneBlackinmoreinterestingprojects,anunderstandingisoften critical.Basically,DeviceTreeisadatastructuretodescribethehardwarethatyouaddon toyourboard.WithDeviceTree,thedetailsofadeviceareavailabletotheboardwithout needingtobehardcodedintothekernel.Priortoitsexistence,thekernelimage—the singlebinary(vmlinuz)thatwelookedatearlierinthechapter—containedanydescription neededforthehardware.Beginningwithversion3.8oftheLinuxkernelforARM, however,anotherbinarywasloadedatbootalongwiththekernel,DeviceTreeBlob (DTB). BeagleBoneBlack—withits3.8kernel(theshippingversion,atleast)—isoneofthefirst ARMdevicestoincorporatetheneworderofthingswithDeviceTree(DT).Itsbenefits fortheBBBaremany: Upstreamdev:Thisprovidesuswiththeabilitytoreceiveandcontributetoallthe benefitsofupstreamkerneldevelopment. Kernelbuildsimplification:Thisavoidsthehassleofmaintainingacustomkernel. Capedevelopment:Developersofcapeexpansionboardsenjoyastandardizedlogic inthekernel.Thisgreatlysimplifieslifeforthecapemakerandenduseras recompilingthekerneltomakethecapefunctionisrarelyarequirement. Toreiterate,DeviceTreeisabinarythatdescribesthesystemhardwareandloadsatboot time.Its“tree”nomenclaturereferstothefactthatitiswritteninahierarchicalnodeor treedatastructure.Thenodesdescribethephysicaldeviceinthesystem. TheDeviceTreeoverlay DeviceTreeiswhatisusedbythekernelduringbootupandiscommontoallmodern ARMdevices.OnBeagleBoneBlackanditsearliercousins,DeviceTreealsocomes accompaniedwithakindof“patch”oroverlay.Appliedatruntime,DeviceTreeoverlay helpsreconfigurehardwareresourcesontheboard,suchascapes,GPIOpins,LCDs,and soon,andishandledbybone-capemgr(thecapemanager). AlthoughwewilldoarecipeontheDeviceTreeoverlay(dtbo)inalatersection,itmight behelpfultobrowsethefollowingdirectorytotakealookatmanyofthedtbofilesthat comewiththefirmware: #cd/lib/firmware #ls-l Thesampleoutputlookslikethis: -rw-r--r--1rootroot1056Apr2316:57BB-ADC-00A0.dtbo -rw-r--r--1rootroot2885Apr2316:57BB-BONE-AUDI-01-00A0.dtbo -rw-r--r--1rootroot2288May182014BB-BONE-AUDI-02-00A0.dtbo -rw-r--r--1rootroot2583May182014BB-BONE-AUDI-02-00A0.dts -rw-r--r--1rootroot4273Apr2316:57BB-BONE-BACON-00A0.dtbo -rw-r--r--1rootroot3259Apr2316:57BB-BONE-BACONE-00A0.dtbo -rw-r--r--1rootroot4536Apr2316:57BB-BONE-BACONE2-00A0.dtbo -rw-r--r--1rootroot3592Apr2316:57BB-BONE-CAM-VVDN-00A0.dtbo There’smore… HereareafewotherkeythingstokeepinmindaboutDeviceTreeandtheBBB: Manyembeddedarchitectureshaveawidevarietyofnondiscoverablehardware, daughterboards,add-ons,andsoon Dependingonthearchitecture,thishardwareisdescribedusingeitherC-code directlywithinthekerneloraspecialhardwaredescriptionlanguageinDeviceTree OtherarchitecturesbesidestheBBB’sARMalsouseDeviceTree,including PowerPC,OpenRISC,ARC,andMicroblaze ADTSiscompiledintoabinaryDeviceTreeBlob(DTB)datastructureandpassed atboottimetothekernel ThebootloadermustloadboththekernelimageandDeviceTreeBlobinmemory beforestartingthekernel DeviceTree/basicbuild OntheBBB,therearethreeessentialstepstocreateandrunaDeviceTreefile: 1. Createasourcefile(dts). 2. Compileitandmakeabinary(dtb)—alsoknownasblob—ofthefile. 3. Ensurethatthekernelknowswheretofindthenewblob. Let’sstartwithasimplerecipe,onethatturnsoffoneoftheonboardLEDs:specifically, USR0,whichistheLEDthatblinkswiththe“heartbeat”pattern.Therearesimplerways todothis,aswedidthesamethingwithBoneScriptinChapter3,PhysicalComputing RecipesUsingJavaScript,theBoneScriptLibrary,andPython.However,itremainsa usefulintroductoryrecipetounderstandDeviceTree’sinteractionwiththekernel. Gettingready Forthenextrecipe,simplypowerupyourboardviatheUSBport.Internetconnectivityis notrequired. Howtodoit… Youneedtoperformthefollowingsteps: 1. Loginasrootwiththiscommand: $sudo-i # 2. Grabthefilethatweneedforthisrecipe.Goingforwardinthebook,wewillmore commonlyhaveyouuseourGitHubrepositorytogetthecodeinsteadof downloadingafiledirectlyaswedidinearlierchapters.Usethiscommand: #gitclonehttps://github.com/HudsonWerks/device-tree.git 3. Browsethedownloadedfolderandopenupthefollowingfile: #cddevice-tree #nanobspm_USR0_10-00A0.dts Takealookatthecodevisibleinthenanowindow.Theintentionofthisstepisfor youtoreviewthecodestructurebeforeweactuallymoveittoitsappropriate directory: /* *Thisisa(mostly)template-generatedfilefromBoneScript,modified fromKilobaser.com'sDevice-TreeOverlayGenerator */ /dts-v1/; /plugin/; /{ compatible="ti,beaglebone","ti,beaglebone-black"; /*identification*/ part_number="BS_PINMODE_USR0_0x0"; /*statetheresourcesused*/ exclusive-use= "USR0", "gpmc_a5"; /*theLEDissettopulldownoroff*/ fragment@0{ target=<&am33xx_pinmux>; __overlay__{ bs_pinmode_USR0_0x0:pinmux_bs_pinmode_USR0_0x0{ pinctrl-single,pins=<0x0540x0>; }; }; }; fragment@1{ target=<&ocp>; __overlay__{ bs_pinmode_USR0_0x0_pinmux{ compatible="bone-pinmux-helper"; status="okay"; pinctrl-names="default"; pinctrl-0=<&bs_pinmode_USR0_0x0>; }; }; }; } 4. Now,closethewindowbypressingCTRL+x,thentypeN(forno),andrunthe followingtomovethefiletoitscorrectdirectory: #mvbspm_USR0_10-00A0.dts/lib/firmware/ 5. Compilethefileusingthiscommand,whichshouldfinishwithinseconds: #dtc-Odtb-o/lib/firmware/bspm_USR0_10-00A0.dtbo-b0-@ /lib/firmware/bspm_USR0_10-00A0.dts Thecommandcanbasicallybebrokendowninthefollowingfashion: dtc[options]<inputfile> -O:Thiscapital“O”(notzero)istheoutputflagthatisfollowedbythetypeofoutput desired,whichisadtbfileorDeviceTreeBlob(alsoknownasbinary)inthiscase -b:Thismeansthatyouwantthefile(blob)tobeloadedatboottime 0:This“zero”showsthephysicalbootID,whichis0 -@:Thisampersandmeansthatthecompilerwillgenerateasymbolnode,which makesitpossibletodynamicallyloadtheDeviceTree <filename/sourcefile>:Thecommandendswiththesourcefiletarget 6. Assumingyoureceivednoerrormessage,confirmthatthecompiledidwhatyou expectedandbuiltthebspm_USR0_10-00A0.dtbofileusingthefollowingcommand: #ls 7. Next,wewanttoenabletheoverlayfilethatwejustcreatedwiththefollowing command: #echobspm_USR0_10>/sys/devices/bone_capemgr.*/slots Youwillnowseetheheartbeat-flashingUSR0LEDturnonimmediately.Hallelujah! Thatdarnedblinkisannoying,isn’tit? Note Althoughatthetimeofwritingthisbookthecapemanagerisatversion9,weusethe wildcardoption(*)toensurethatlaterversionsofbone_capemgrwillstillrespondto thiscommand. 8. Weshouldnowlookatwhatjusthappenedbydoingthefollowing: #dmesg|tail-10 Yourscreenoutputshouldlooksimilartothis: [33.848704]IPv6:ADDRCONF(NETDEV_CHANGE):eth0:linkbecomesready [153.829529]bone-capemgrbone_capemgr.9:part_number'bspm_USR0_10', version'N/A' [153.829601]bone-capemgrbone_capemgr.9:slot#7:genericoverride [153.829617]bone-capemgrbone_capemgr.9:bone:Usingoverrideeeprom dataatslot7 [153.829633]bone-capemgrbone_capemgr.9:slot#7:'OverrideBoard Name,00A0,OverrideManuf,bspm_USR0_10' [153.829723]bone-capemgrbone_capemgr.9:slot#7:Requestingpart number/versionbased'bspm_USR0_10-00A0.dtbo [153.829738]bone-capemgrbone_capemgr.9:slot#7:Requesting firmware'bspm_USR0_10-00A0.dtbo'forboard-name'OverrideBoardName', version'00A0' [153.834371]bone-capemgrbone_capemgr.9:slot#7:dtbo 'bspm_USR0_10-00A0.dtbo'loaded;convertingtolivetree [153.834620]bone-capemgrbone_capemgr.9:slot#7:#2overlays [153.835294]bone-capemgrbone_capemgr.9:slot#7:Applied#2 overlays. Whenwerundmesg,ittellsusmoreaboutthesequenceofevents,includingwhether thepreviouscommandsweresuccessful.The-10optionoutputsthelastten messagesfromthekernel.Youcanmakethenumberhigherorloweraccordingto howmanymessagesyouwantstdouttodisplay. 9. Furtherforensicsareusefulforagreaterinsightintotheprocess,sonavigatetothe followingdesignateddirectoryandrunthefollowing: #cd/sys/devices/bone_capemgr.* #catslots 0:54:PF--1:55:PF--2:56:PF--3:57:PF--4:ff:P-O-LBone-LT-eMMC-2G,00A0,TexasInstrument,BB-BONE-EMMC-2G 5:ff:P-O-LBone-Black-HDMI,00A0,TexasInstrument,BB-BONELT-HDMI 7:ff:P-O-LOverrideBoardName,00A0,OverrideManuf,bspm_USR0_10 Theprecedingoutputtellsussomethingimportant:thattheDeviceTreeblobthatwe justbuiltisrecognizedbythekernelandslottedintoposition. Beautifulkernelmagic. DeviceTree/advanced–addingDT overlaytorunacustomcape BeagleBoneBlackintroducedtheideaofDeviceTreeoverlaysthatprovideevenmore functionalitytoDTbymodifyingthetreeinuserspace,typifiedinourpriorexample. WithDToverlay,thereisnoneedtoreboot. Wesawinourearliersectiononsysfsusagethedirectory/extension.capemgr,which referstocapemanager.TheBeagleBonekernelusescapemanagerasawaytoprovide dynamicloadingandunloadingofdevicetreefragmentsbothatcompiletimeandfrom userspaceafterthedevicehasbooted.Wewilldemonstratethisagainhere;exceptthis time,wewilluseDTtoenableacustomcape,onewhichdeliversaudioI/Ofunctionality totheBBB. Gettingready InadditiontoyourusualBBBsetup,wewilluseAudioCapeRev.B,availablefrom CircuitCo(http://boardzoo.com/index.php/beaglebone-black/bone-audio.html).Attachthe capetoyourBBB’sheaderstack,followingtheorientationshowninthefollowing pictures: Note IfyourantherecipeinthepreviouschaptertosendtheIPaddressofyourBBBtoyour emailaddress,youcanrunyoursystemremotelyandinaheadlessway. Besuretomatchtheheaderpinrows(P8andP9)ontheaudiocapetothoseofthe BeagleBoneBlack. Theoutputjackisgreenandtheinputjackislightblue. Inordertodothelastpartofthisrecipe,youmayalsowanttoeitherplugamicrophone intotheinputjackonthecapeoruseaUSBmicintheUSBport. Howtodoit… Nowthatyou’reprepared,let’sgetstarted: 1. First,downloadandunziptheDToverlayfromthemanufacturer (http://elinux.org/images/1/10/BB-BONE-AUDI-02-00A0.zip).Forthefastest method,justdownloadittoyourclientmachine. 2. Inatexteditoronyourclientmachine,openupafilewiththename,BB-BONE-AUDI02-00A0.dts. 3. OnyourBBB,loginasrootandnavigatetothefirmwaredirectory: #cd/lib/firmware Asanoptionalstep,youcancheckthecontentsofthedirectory.Youshouldsee dozensofDeviceTreeoverlayfiles(.dtbo).Otherwise,youcanskipthis. 4. OpenananowindowontheBBBwiththefollowingfilename: #nanoBB-BONE-AUDI-02-00A0.dts 5. CopytheDeviceTreeoverlayfilecontentsfromthetexteditorwindowonyour clientmachineintothenanowindowonyourBBBbyexecutingthefollowingcode: /* *Copyright(C)2012TexasInstrumentsIncorporated- http://www.ti.com/ * *Thisprogramisfreesoftware;youcanredistributeitand/ormodify *itunderthetermsoftheGNUGeneralPublicLicenseversion2as *publishedbytheFreeSoftwareFoundation. */ /dts-v1/; /plugin/; /{ compatible="ti,beaglebone","ti,beaglebone-black"; /*identification*/ part-number="BB-BONE-AUDI-02"; version="00A0","A0"; … 6. Then,compiletheDeviceTreeoverlayasfollows: [email protected] 7. Now,we’llopenupnanotoeditthebootfile.Youcanoptionallyopenthesamefile bybrowsingyourclientMacorPCdesktopanddrillingdownintotheBEAGLE_BONE/ volumewiththefollowingcode: #nano/boot/uEnv.txt ##AudioCape(needsHDMIAudiodisabled) cape_disable=capemgr.disable_partno=BB-BONELT-HDMI cape_enable=capemgr.enable_partno=BB-BONE-AUDI-02 Onceopened,wewanttouncomment(remove#)fromthesectionlabeledDisable HDMI,andthefollowingcommandcomesinhandy: optargs=capemgr.disable_partno=BB-BONELT-HDMI Note TakenoteoftwothingswhilemodifyingtheuEnv.txtfileforthisstep: YouonlyneedtodisableBB-BONELT-HDMI.BB-BONELT-HDMIasitwillnot conflictwiththeaudiocape. Youmay,however,runintoadifferentoverlayconflictifyouranotherrecipes orDTexperiments.Ifso,besuretoalsocommentoutanynewlinesyoumight haveaddedforotherrecipesasthesemaypreventtheAUDI-02overlayfrom loading. Finally,youneedtocloseandsavetheuEnv.txtfile. 8. Now,runtheexportcommand: #exportSLOTS=/sys/devices/bone_capemgr.*/slots 9. Afterthis,gotothefollowingdirectory: #cd/sys/devices/bone_capemgr.* 10. Then,runtheechocommand. #echoBB-BONE-AUDI-02>slots Thiscommandtakestheoutputofecho,BB-BONE-AUDI-02,andwritesitintheslots file,whichinturnenablesthedriversanddeviceforAUDI-02usingtheDeviceTree overlay. 11. Now,reboottheBBBasfollows: #reboot 12. ConfirmthattheDToverlayloadedproperlybygoingtothedesignateddirectoryand runningthefollowingcommand: #cd/sys/devices/bone_capemgr.9# #catslots 0:54:PF--1:55:PF--2:56:PF--3:57:PF--4:ff:P-O-LBone-LT-eMMC-2G,00A0,TexasInstrument,BB-BONE-EMMC-2G 5:ff:P-O--Bone-Black-HDMI,00A0,TexasInstrument,BB-BONELT-HDMI 6:ff:P-O-LBone-Black-HDMIN,00A0,TexasInstrument,BB-BONELT-HDMIN 7:ff:P-O-LOverrideBoardName,00A0,OverrideManuf,BB-BONE-AUDI-02 YoushouldseeinthelastlineourAUDI-02devicenowenabled. 13. So,let’stestthedefaultaudiooutputfirst.Forthis,usethefollowingcommand: #speaker-test Youshouldhearwhitenoiseplaying.Toquit,pressCtrl+c. Note AvoidusingCtrl+zastheprocesswilllikelynotendgracefullyandpreventyou fromrunningadditionaltestsonthecape. 14. Finally,wecanoptionallytesttheinputandtheoutput.Thisassumesthatyouhavea microphonepluggedintotheinputjackonthecapeoraUSBmicviatheUSBport. 15. First,captureanaudiosampleusingthefollowingcommand: #arecord-Ddefault:CARD=devicename-r44100-c1-fS16_LE-twav-vv -d10example.wav Then,playitbackbysimplyusing: #aplayexample.wav There’smore… Onceyougetthecapeworking,youwillprobablyfindthataudiolevelsaretoolow.So, weneedtoadjustthiswiththefollowingcommandsusinganinstalledaudioapplication calledamixer,whichispartofAdvancedLinuxSoundArchitecture(ALSA)‘sutilities toolset.ALSAisthemultifacetedlayerthatconnectstothekernelandprovidesaudio functionalitytouserspace: $amixersetPCM5dB $amixerset'RightPGAMixerMic3R'on $amixerset'LeftPGAMixerMic3L'on Additionally,ifyouwanttopluginamusicplayeroranotheraudiosource,youneedto switchaudiofromintoout: $amixerset'RightHPMixerPGARBypass'on $amixerset'LeftHPMixerPGALBypass'on Finally,usethesecommandstoadjustthegain: 1. Toincreasevolume(forexample,to10%),runthefollowing: $amixersetPGA10%+ 2. Todecreasethevolume(forexample,to5%),runthefollowing: $amixersetPGA5%- 3. Totogglemute,runthefollowing: $amixersetPGAtoggle Seealso Thereisawealthofsupportinginformationtosatisfyyourcuriosityandtakeyour understandingofDeviceTreetonewheights: EntireLINUXKERNELINANUTSHELL(O’Reilly)isavailableasadownloadable PDFathttp://free-electrons.com/doc/books/lkn.pdf AgeneraloverviewofDTwithexamplescanbefoundat http://www.circuidipity.com/bbb-dt.html AdiscussionaboutusingDToverlaysanditsrelevancetocontrollingGPIOscanbe foundathttps://groups.google.com/forum/#!topic/beagleboard/c2LFLEUg6Aw EnablingDevicetreeoverlayonstartuponBeagleBoneBlackcanbefoundat http://hipstercircuits.com/enable-device-tree-overlay-on-startup-on-beagleboneblack/ LotsofgoodtipsonDTandoverlaysareavailableat http://hipstercircuits.com/category/device-tree/ ThecanonicalreferencesiteforDeviceTreeisat http://devicetree.org/Device_Tree_Usage Thereare45slidesprovidingadeeperdiscussiononDeviceTreeathttp://freeelectrons.com/pub/conferences/2013/elce/petazzoni-device-tree-dummies/petazzonidevice-tree-dummies.pdf Takeadvantageofthisgreatfindofasitethathelpsyoueasilygeneratedevicetree overlays,whichprovideeasypinmuxing—http://kilobaser.com/blog/2014-07-28beaglebone-black-devicetreeoverlay-generator LinusTorvalds’originalrantabouttheARMdevicemessthatledtotheemergence ofDeviceTreeisatthefollowingsite.Itdoesn’tgetmoregeekythanthis —http://article.gmane.org/gmane.linux.ports.arm.omap/55060 Universalcapeoverlay DeveloperCharlesSteinkuehlerdevelopedanenormouslyusefuladditiontothe BeagleBoneBlackandDTworldwithhisuniversalcapeoverlay.Nowincludedbydefault onthecurrent3.7and3.8kernels,thecodegreatlysimplifiespinandcapemanagement viasimplecommand-linecalls.Thetoolsetcan,insomecases,obviatetheneedtouse manytypesofsysfscalls,someofwhichyoulearnedearlierinthechapter. Gettingready ABBBhookedupandpoweredviaUSB. Howtodoit… Performthefollowingsteps: 1. Beginbylogginginastherootuserandthenloadingthecapeoverlayusingthe followingcommands: $sudo-i #echocape-universaln>/sys/devices/bone_capemgr.*/slots Thiscommandloadsalldevicesandexportsgpio.Thepinscurrentlydefaulttogpio inputs.However,withthenextsetofcommands,wecaneasilychangetheirstate. 2. Let’sconsidertheexampleoftheP8_12pinandrunacommandtofindoutitsstate: #config-pin-qP8.12 P8_12Mode:gpioDirection:outValue:0 Youwillrecallfromearlierrecipesthatthe0valuemeansthatthepinissetatlowor off. 3. Then,wecaneasilychangeitsstatewiththefollowingcommands: #config-pinP8.12hi #config-pin-qP8.12 P8_12Mode:gpioDirection:outValue:1 Now,thevaluewillchangefrom0(low)to1(high).Indeed,thisisamuchsnappier methodtomanipulatepinsthanthesysfsapproachwediscussedearlier. 4. Thetoolsethasadditionalfunctionalityandoptionsthatyoucanfurtherexplorewith thefollowingcommand: #config-pin-h There’smore… Thedeveloper’ssite,https://github.com/cdsteinkuehler/beaglebone-universal-io,has extendedexamplesandusagefortheoverlay RunningascripttocheckDTusageon GPIOpins WhenmodifyingorworkingwithDeviceTreefiles,wefrequentlyneedtocheckpin usagesothatwedonotinadvertentlytrytowritetoclaimedorunsuitablepins. ThefollowingrecipeemploystwoscriptsthatyoucanrunwithNode.jsandhelpsus locatewhichpinsarefree.ThescriptsexistthankstothecodingworkofProfessorMark YoderatRose-HulmanInstituteofTechnology. Gettingready YoudonotneedanythingmorethanyourbasicBBBkitforthisrecipe,whichisaboard connectedtoyourhostcomputerviaUSB. Howtodoit… Torunthisscript,youneedtofollowthesesteps: 1. YoufirstneedtoopenuptheCloud9IDEandcreateanewscriptcalled freeGPIO.js. 2. IfyourantherecipeDeviceTreeBasicBuildearlierinthischapter,youwillfindthe filefreeGPIO.jsinthedirectorythatyougotfromourGitHubrepo.Thiswas availablebyrunningthefollowingcommand: gitclonehttps://github.com/HudsonWerks/device-tree.git Otherwise,youcancutandpastethesamecodebelowintotheIDEwindow.Ifyou runintoproblemswiththecut-and-pasteversionhere,thenjustgrabthesamecode fromthedirectoryfileontheGitHubrepo. #!/usr/bin/node //ListsallgpiopinswithMUXUNCLAIMEDandGPIOUNCLAIMEDin$PINMUX //Usage:freeGPIO.js#ListfreeGPIOsusingP8orP9pinnumber // //Approach: //1.searchPINMUXforallentrieswith"(MUXUNCLAIMED)(GPIO UNCLAIMED)" //2.Anentrylookslike"pin8(44e10820):(MUXUNCLAIMED)(GPIO UNCLAIMED)" //3.Extracttheaddress(44e10820)andsubtract0x44e10800togethe offset //4.Formattheoffsetas0x020,withleading0'stogive3digits //5.SearchfortheaddressinthemuxRegOffsetfieldinb.bone.pins //6.Printthematchingkey varPINMUX="/sys/kernel/debug/pinctrl/44e10800.pinmux/pinmux-pins", b=require('bonescript'), exec=require('child_process').exec; exec('grep"(MUXUNCLAIMED)(GPIOUNCLAIMED)"'+PINMUX, function(error,stdout,stderr){ varlist,//Arrayofunusedpins pin,//pinoffsetinform0x020 addr,//pinaddress,44e10820 keylist=[];//Listofallunusedheaderpins, P9_12 if(error){console.log('error:'+error);} if(stderr){console.log('stderr:'+stderr);} //console.log(stdout); stdout=stdout.substring(0,stdout.length-1);//Get ridofextra\n list=stdout.split('\n'); //console.log(list); for(variinlist){ //list[i]isofform"pin8(44e10820):(MUX UNCLAIMED)(GPIOUNCLAIMED)" //Gettheaddressfromthe2ndfieldandremove the()'s addr=list[i].split('')[2].substring(1,9); //Findtheoffsetandreturnas0x020,thatis, zeropaddedto3digits. pin='0x'+('000'+ (parseInt(addr,16)-0x44e10800).toString(16)).slice(-3); //console.log(pin+""+list[i]); for(varjinb.bone.pins){ if(b.bone.pins[j].muxRegOffset===pin){ //console.log(b.bone.pins[j].key); keylist.push(b.bone.pins[j].key); break; } } } keylist.sort(); console.log(keylist.join('')); }); 3. IntheCloud9IDE,clicktheRunbutton. P8_10P8_11P8_12P8_13P8_14P8_15P8_16P8_17P8_18P8_19P8_26P8_7 P8_8P8_9P9_11P9_12P9_13P9_14P9_15P9_16P9_23P9_24P9_26P9_27 P9_30P9_41P9_42USR0USR1USR2USR3 ThisscriptgaveusalistofpinsthatarenotcurrentlyinusebytheBBBandcanbe exploitedforotherpurposes. 4. Next,wewillcreateanduseasecondscriptthatwewillnamefindGPIO.js,ascript whichwillidentifymoreinformationaboutanunusedpin.Togetthecode,youcan cutandpastethecodebelowintotheIDE,orfollowthesamestepdescribedinthe priorstepofgettingitfromourGitHubrepo.LookforthefilefindGPIO.jsinthe device-treedirectorythatyoudownloaded. #!/usr/bin/node //Programtotestlookingupinformationin /usr/share/bone101/static/bone.js //Usage:findGPIO.js7#Lookupinfoforgpio7(internalpin number) //findGPIO.jsP9_12#Lookupusingheaderpinnumber (external) //findGPIO.jsP9_12P9_13…#Lookupmultiplepinsanduse oneline //#outputforeach. //Returnscurrentpinmux varPINS="/sys/kernel/debug/pinctrl/44e10800.pinmux/pins", PINMUX="/sys/kernel/debug/pinctrl/44e10800.pinmux/pinmux-pins", b=require('bonescript'), exec=require('child_process').exec; /* process.argv.forEach(function(val,index,array){ console.log(index+':'+val); }); */ functionpinMux(gpio,flag){ varaddr='('+(0x44e10800+ parseInt(gpio.muxRegOffset,16)).toString(16)+ ')'; //console.log('grep"'+addr+'"'+PINS); exec('grep"'+addr+'"'+PINS, function(error,stdout,stderr){ varmux,//Currentmuxsetting out,//outputstring dir='down';//Directionofpulluporpulldown if(error){console.log('error:'+error);} if(stderr){console.log('stderr:'+stderr);} stdout=stdout.substring(0,stdout.length-1);//Get ridofextra\n //console.log(stdout); mux=parseInt(stdout.split("")[3],16);//Getthemux field out=gpio.key+'(gpio'+gpio.gpio+")mode:"+ (mux&0x7)+ "("+gpio.options[mux&0x7]+")"+ gpio.muxRegOffset; if(!(mux&0x8)){//Pullupordownisenabled if(mux&0x10){ dir='up'; } out+='pull'+dir; } if(mux&0x20){ out+="ReceiverActive"; } if(mux&0x40){ out+="SlewControlSlow"; } console.log(out); }); if(flag){ exec('grep"'+addr+'"'+PINMUX, function(error,stdout,stderr){ if(error){console.log('error:'+error);} if(stderr){console.log('stderr:'+stderr);} stdout=stdout.substring(0,stdout.length-1);//Get ridofextra\n console.log(stdout); }); } } vargpio, flag=process.argv.length<4, i; for(i=2;i<process.argv.length;i++){ gpio=process.argv[i].toUpperCase(); if(gpio[0]==='P'|gpio[0]==='U'){ if(flag){ console.log(b.bone.pins[gpio]); } pinMux(b.bone.pins[gpio],flag); }else{ console.log("Lookingforgpio"+gpio); for(variinb.bone.pins){ if(b.bone.pins[i].gpio===parseInt(gpio,10)){ if(flag){ console.log(b.bone.pins[i]); } pinMux(b.bone.pins[i],flag); } } } } 5. Torunthisscript,wedonotjustclicktheRUNbuttonintheIDE.Instead,wetype thefollowingcommandintotheIDE’sbashterminalwindow.Notethatweappend thecommandwithoneofthepins,specificallyanyofthepinsthatwesawoutputas availableinthepreviousscript’soutput(hereweusedP8_13).Theoutputrevealsa greatdealofinformationaboutthispin,asfollows: #nodefindGPIO.jsP8_13 {name:'EHRPWM2B', gpio:23, mux:'gpmc_ad9', eeprom:15, pwm: {module:'ehrpwm2', index:1, muxmode:4, path:'ehrpwm.2:1', name:'EHRPWM2B'}, key:'P8_13', muxRegOffset:'0x024', options: ['gpmc_ad9', 'lcd_data22', 'mmc1_dat1', 'mmc2_dat5', 'ehrpwm2B', 'pr1_mii0_col', 'NA', 'gpio0_23']} P8_13(gpio23)mode:7(gpio0_23)0x024pulldownReceiverActive pin9(44e10824):(MUXUNCLAIMED)(GPIOUNCLAIMED) Amongotheritemsofinterest,whatwelearnfromtheprecedingexampleisthatthe P8_13pinisoneofthePWMcadre—morespecifically,EHRPWM2B,thetypeofpinwe learnedaboutinChapter3,PhysicalComputingRecipesUsingJavaScript,the BoneScriptLibrary,andPython,thatcontrolsdeviceslikemotors. Chapter6.RunFaster,RunRealTime Inthischapter,wewillcoverthefollowingrecipes: Installingatesttool ModifyingthekernelusingRT-PREEMPT ModifyingthekernelusingXenomai Programmablereal-timeunits–anintroduction AsimplePRUtestwithanassembler RunninganultrasonicrangesensorwiththePRUs UsingPythonwiththePRUs Introduction Thingsaregettinginteresting:nomoreblinkyLEDsfromsysfs.It’srealtime…timeto learnabouthowtomakeyourBeagleBoneBlackperformreal-timetricks. ThisisnottosaythattheBeagleBoneBlackispokey.Thechallengeisthat,nowadays, innovators,developers,productdesigners,andengineersalwaysdemandfaster,more predictableresults,especiallyinscenarioswheresmalllatenciescanmakethedifference betweensuccessorcrash.Crashinthiscasemeaningbang,crashgoesthedevice,notjust asoftwarecrash. So,inthischapter,wewillexaminerecipesthathelpboosttheresponsivenessofyour BBBundercertainconditions.Toperformthis,wewillexplorethefollowingtopics: Kernelmodificationsforthepurposeofcreatingreal-timeenvironmentsusing: RT_PREEMPT Xenomai Programmablereal-timeunits Andnowforsomethingcompletelycontradictory:Linuxisnotrealtime.Itisfastand efficient,butitisnotareal-timesystem. Harummph!Butisn’tLinuxsupposedtobethesexy,betteralternativetoallthosebloated, expensivelyclosedsystemsoutthere?Itdepends. Tobeginwith,it’simportanttounderstandwhatLinuxMavens—particularlythe embeddedfolks—meanwhentheyrefertorealtimeontheirsystems.First,it’snotjust aboutspeedierperformance.Althoughsqueezingoutfasterresponsetimesisalwaysa goal—andthiscanbeoneofthebenefitsofenablingareal-timeenvironment—that’snot anendinitself.Realtimeisalsoaboutensuringrock-solidpredictabilityonthesystem, forexample,event-xmustoccurwithinaverystricttimeframe.Nootherevent,thread,or interruptcantakepriorityorgetinthewayofareal-timeevent…noexcuses! Youmayaskwhyisthisaproblemanyway?Afterall,aren’tLinuxandoursuperduper BBBsupposedtobesuperfast?Yes.Butallsystemsexperiencedelaysinprocessing events.Wehaveallseenevidenceofthis,eveninmundanecircumstanceswherenotmuch washappening.Forexample,fromtimetotime,yourcursordoesn’tquitemovefrom pointAtopointBonthescreenasquicklyasyouexpect.Alternatively,whenyouclicked onataskbaritemandthepop-upwindowdidn’tappearaslightningfastasitdidwhenyou clickedonitfiveminutesago. Thiskindoflatencyistypicalforallsystems,andLinuxisnotimmunetoit.Inourcase, wewillrefertothisphenomenonaskerneljitter.Also,certainscenariosabsolutelycannot abidebyanykindofjitters.Forexample,amillingmachinecan’thave“late”commands initsI/O;otherwise,theprojectcouldberuined.Therefore,therehastobeasolutionthat deliversreal-timeperformance. FortheBeagleBoneBlack,thereareinfactthree(actuallyfour)choicestomakeyour systemrealtime,sometimesreferredtoasanRTOSorreal-timeoperatingsystem.The recipesfollowinorderofleasttomostrealtimely: 1. PREEMPT_RT 2. XENOMAI 3. PRUs 4. PRU+Xenomai Now,wewilltakealookathowtodefinereal-timecategories.Thereareshadesofreal time;notallscenariosrequirenanosecondmanagementorresponsetime.Further, engineersanddevelopersoftenhavetheirownspinonwhattheydefineasrealtime, whichisonceagaindeterminedbytheirownscenariorequirements.However,forour purposes,we’lldefinerealtimeusingthefollowingspectrumofcategories: Soft:Thisiswhereusecaserequirementsforrealtimearemetmostofthetime. Considertheexampleofmusicplaybackonyoursystem.It’smostlysmooth,but hiccupshappensometimesonplayback.Thisstandardistypicallyadequateformost desktopusecases. Life-safetyhard:Thisspecifiesthatthesystemmustdeliveronreal-time requirements100percentofthetime.Ifitdoesn’t,itmightresultindeathorinjury. Noneofourrecipes—andcertainlynotourlovelyBBB—willdeliverthisstandardof responseorreliability.Irepeatthatourrecipesandusecasesdonotcoverthese scenarios.Onlycustom,dedicatedsystems,andcertainlytheonesthatcostmorethan USD$45.00canperformthisway. 100percenthard:Thisindicatesthatthesystemdeliversreal-timeperformance100 percentofthetime.ThismaysoundlikeLife-safetyhard,buttheonlythingatstake isnonhuman.Theworstthingthatcanhappenisthataproductgetsbotchedina millingmachine,oryourUAVfelldownandwentboom.Butnobodygothurt,and nobodydied. 95percenthard:Thisdenotesthatoursystemisnearlyperfect(withonly5percent errormargin).Thisiscommonlyacceptable,forexample,whenyou’recapturingdata fromsensors.Theremaybesomegapsinthedatastream,butnothingegregiousthat throwsoffyouroutcomesoranalysis.Youcanjustresampleforanotherdataset. Note TheprecedingdefinitionsareinspiredbythepaperHowfastisfastenough?Choosing betweenXenomaiandLinuxforreal-timeapplications (https://www.osadl.org/fileadmin/dam/rtlws/12/Brown.pdf). Onthesubjectofreal-timesystems,embeddeddevelopersliketothrowaroundtheterm “determinism”.Theyaren’tgettingphilosophical.Inareal-timecontext,they’rereferring toeventandtemporally-drivenoutcomesthatarepreciselydetermined.Thatis,withan event,youhaveaninputandadetermined(locked)setofoutputs,whereasinthetemporal pieceforarealtimeenvironment,thetimingisdeterminedaswell. So,whywouldn’tyouuserealtimeallthetime? Theansweriseffort,money,time,andprojectrequirements.Andsometimesthereare distincttrade-offswhenusingarealtimevariantinyourkernelorsystem.Forexample,an eventyoumarkforrealtimeresponsemayhumalongperfectly;however,thiscanendup beingadragonoverallsystemperformance. Thefollowingtableisalatencytable: System Typicalinstruction/interruptcyclelatency LinuxOS Thisspecifies1second PREEMPT_RT Thisdenotes200milliseconds Xenomai Thisdenotes20-50milliseconds PRU Thisspecifies5-10nanoseconds Source:CharlesSteinkuehlerandhisMachineKit(LinuxCNC)millingmachineusecases: TypicallatencywithaXenomai-patchedkernelfortheBBBisabout25uS,withworst casearound70-80uS. Note Formoreinformation,refertohttp://www.embedded.com/design/operatingsystems/4204740/Getting-real—time—about-embedded-GNU-Linux Installingatesttool BeforewecanconvertourBeagleBoneBlacktoablazingreal-timewonder,weneeda waytomeasurelatencyintheLinuxkernel.Apopulartoolforthispurposeiscyclictest. Cylictestmeasurestheamountoftimethatpassesbetweenwhenatimerexpiresandwhen thethreadthatsetthetimeractuallyruns.Itusestimesnapshots,onejustbeforeaspecific timeinterval(t1),thenanotheronejustafterthetimerfinishes(t2).Wecanthencompare thesetwosnapshotvaluestopinpointexcessivelatencysourceswithinthekernel. Gettingready Theusualminimalsetupisallyouneed:aBBBpoweredoverminiUSBwithInternet connectivityenabled. Howtodoit… Cyclictestisn’tavailableasaprebuiltbinary.So,wewillhavetocompileitfromsource: 1. Loginasroot: #sudo-i 2. Gogetthesourcefilesforcyclictest: #gitclonegit://git.kernel.org/pub/scm/linux/kernel/git/clrkwllms/rttests.git 3. Navigatetothenewdirectorythatgitcreates: #cdrt-tests 4. Compilethatbaby: #makeall 5. Makeacopyofthebinaryinthe/usr/bindirectorysoyoucantypecyclictest fromwhateverdirectoryyoufindyourself: #cp./cyclictest/usr/bin/ 6. Bangonthetool’sdocumentationtomakesureitinstalledproperly: #cyclictest--help 7. Now,let’srunasimpletesttoseewhatkindofdatathatcyclictestcaptures: #cyclictest--smp-p95-m Thesampleoutputshouldlooklikethefollowing: #/dev/cpu_dma_latencysetto0us policy:fifo:loadavg:0.000.010.051/2214471 T:0(4464)P:95I:1000C:31326Min:39Act:58 Avg:69Max:785 ThisoutputtellsusthatourCPUhadanaveragelatencyof69microseconds,which isadecentvalue.Yet,wealsohadamaximumlatencyof785microseconds.Ouch! What’shappeningthere?Let’sdebug(ortrace)that. Alas,wecan’tdoatraceuntilwe’vecustomizedthekerneltorunatraceroutinewith cyclictest.So,that’swhatwe’lldointhenextsectionsincewealsoneedtomodifythe kerneltoaccommodateanewpatch. Inthemeantime,let’squittheprogramwithCtrl+C. Seealso FAQonrealtimewithPREEMPT-RT —https://rt.wiki.kernel.org/index.php/Frequently_Asked_Questions Thehomeofthedevelopersofcyclictest —https://rt.wiki.kernel.org/index.php/Cyclictest Moredetailsonhowtosetupandconfigurecyclictest —http://people.redhat.com/williams/latency-howto/rt-latency-howto.txt Long,butusefulvideoexplainingthedeeperfunctionalitiesandvirtuesofcyclictest —https://www.youtube.com/watch?v=f_u4r6ehZKY ModifyingthekernelusingRTPREEMPT Todiveintotherealtimerealm,we’llbeginbyexploringapieceofcodethatyouapplyto theLinuxkerneldirectly,onewhichisoftenconsideredthedefactostandardforreal-time applications,apatchcalledPREEMPT_RT. First,nomenclature.Intheliterature,ourpatchcanbefoundreferredtoas CONFIG_PREEMPT_RT,PREEMPT_RT,RT-Preempt,orsimplyLinuxRTpatch. Whew!Can’tanyonedecide?We’lldefaulttocallingitRT-PREEMPTsincethatisthe mostcommonusage. TheRT-PREEMPTpatchforcesontooursystemwhatisknownasnativerealtimepreemption.Thismeansthatthepatchisapplieddirectly—ornatively—ontothekernel,and allowsyoutopreempttheentirekernel’seventsandprocessesinfavoroftargetedevents ortasks.ItmakessectionsoftheLinuxkernelpre-emptiblethatareordinarilyblocking. Forexample,let’ssaywehavetwoprocesses.Weassignahigherprioritytothesecond processthanthefirstone.Thepatchenablesatimetickinterrupttopreemptthefirst(or anyotherprocess)sincethesecondoneisgiventhehighestpriority.Thisway,theprocess firesandfinishesexactlyonschedule. RT-PREEMPTalsohappenstoenjoytheleast“realtimeliness”inthischapter’sbasketof tricks.Becausethepatchutilizesapre-emptionprocess,thekernelstopswhateveritis doingandfocusesondeliveringtherealtimeevent.Thisisgoodforyourrealtime requirement,butnotsogoodholisticallysinceitoftenresultsinanoverallsystemslow down. ThisisnottosaythatRT-PREEMPTisaduffer.Muchoutstandingworkhasgoneintothis codetooptimizeit,andmakeitasusefulaspossibleformanyscenarios.Infact,RTPREEMPTisoftenconsideredasoftwarestandardpreciselybecauseitfulfillsthe majorityofrealtimerequirementsfordevicesandsystems. Thelastthingwewillsaybeforemovingontotherecipeisthatweareonlygoingtogive youthemethodforapplyingRT-PREEMPTontoDebianJessie,andintentionallyignore DebianWheezy.Why?Becausemuchhair-pullinghasbeenoccurringovertheyearsto getRT-PREEMPTontothe3.7-3.8kernel.AndforbuddingLinuxandBBBusers,the processcouldmakeyougobald.Thegreatnews,though,isonceyouarecommittedto usingtheJessiekernel(3.14.x),it’saneasyfewstepstogetupandrunning. Gettingready Allyouneedistheusualminimalsetup:aBBBpoweredovertheUSBtetherwith Internetconnectivityenabled. Howtodoit… 1. Loginasrootuser: $sudo-i # 2. ChecktheversionofJessiethatyouarerunning: #uname-r 3.14.39-ti-r61 Note Yourversionmayvaryandwillfollowtheconvention3.14.XX-ti-rXX. 3. Runacommandthatwilldoacustomsearchforavailablereal-timeJessiekernels: #sudoapt-cachesearchlinux-image|grepti-rt Althoughtheversionnumbersmayvarysomewhat,yoursearchshouldhavepulled downsomethinglikethefollowingintoyourscreenoutput: linux-image-3.14.38-ti-rt-r60-Linuxkernel,version3.14.38-ti-rt-r60 linux-image-3.14.39-ti-rt-r61-Linuxkernel,version3.14.39-ti-rt-r61 linux-image-3.14.40-ti-rt-r62-Linuxkernel,version3.14.40-ti-rt-r62 ... 4. Next,fromtheavailablelistshownfromstepone,installtherealtimekernelversion thatmatchesyourcurrentlyinstalledkernel: #sudoapt-getinstalllinux-image-3.14.XX-ti-rtX And…youaredone!RT-PREEMPTisnowbakedintoyourkernel. There’smore… IfyouarefeelingabitmasochisticandjusthavetotryapplyingRT-PREEMPTontoyour DebianWheezykernel,youcanpieceittogetherfromthefollowingresources: https://github.com/beagleboard/kernel/tree/3.8-rt http://www.osadl.org/Realtime-Preempt-Kernel.kernel-rt.0.html ModifyingthekernelusingXenomai Becauseit’samagicspellhandeddownfromGandalftheGrey,thisrecipewillonlywork bysayingitaloudthreetimesfast:Xenomai,Xenomai,Xenomai!Allright.Itsoundslike anincantation.But,unfortunately,it’sonlyasoftwarelayerontopofakernel. Thegoodnews,however,isthataddingXenomaitothekernelmixcanmagicallybring real-time(ish)oomphtoourBeagleBoneBlack.So,whatisitexactly?Itisasetofpatches bringingseveralusefulingredients: Real-timesupportfromthehardwareinterruptleveltouserspaceapplications. Adual-kernelmixcomposedoftheprimaryLinuxkernelandthesecondaryXenomai kernel. AsubsystemunderneathLinuxthatdoesnotrelyonthekerneltopre-empt designatedevents(likeourpreviousmethod). ButwhyshouldweuseitinsteadofPREEMPT_RT?Withitsfocusonembeddedsystems, Xenomaiisusefulforseveralreasons: Lowerssystemoverheads. Legacyporting:Easiertoportlegacyreal-timesystems.AsabuddingBBBerand embeddedLinuxneophyte,youmaynotbeportinglegacysystemsanytimesoon.But ifyouwere,thenXenomaiwouldbeaneasierwaytodoitsinceyoucanlashyour oldsystemtogethertotheLinuxkernelbyusingXenomaiasabindinginterface. Highlyconfigurable:Xenomaicanbeconfiguredtosetthreadpriorities/timerIRQ, forexample,tohighorlowbasedonyourpreference(99isthehighestinXenomai) withtheresultthateventsnevergetinterrupted. Worksbetterwithversion3.8ofthekernelandabove. Gettingready Theusualminimalsetupisallyouneed:aBBBpoweredoverminiUSBwithInternet connectivityenabled. Howtodoit… Althoughtherearemethods(notedlaterinthissection)forinstallingXenomaifrom source,ourrecipewillillustrateasimplemethodforgettingyourkernelmodified: 1. Inordertorunthisrecipeproperly,youwillneedtostartbyappendingyour repositories.Beginbyopeningupyoursourcelist: $sudonano/etc/apt/sources.list Intheopeneditwindow,pastethefollowingtextintotheendofthefile.Choosethe optionbasedontheversionofDebianyouareusing: Wheezy deb[arch=armhf]http://repos.rcn-ee.com/debian/wheezymain #deb-src[arch=armhf]http://repos.rcn-ee.com/debian/wheezymain Jessie deb[arch=armhf]http://repos.rcn-ee.com/debian/jessiemain #deb-src[arch=armhf]http://repos.rcn-ee.com/debian/jessiemain 2. Saveandclosetheeditwindow,thenupdateyourrepositories: $sudoapt-getupdate WithDebianWheezy,youmayencounteranerrorofthefollowingilk: W:GPGerror:http://repos.rcn-ee.comwheezyRelease:Thefollowing signaturescouldn'tbeverifiedbecausethepublickeyisnot available:NO_PUBKEYD284E608A4C46402 3. So,runthiscommandtofixit: $sudoapt-getinstallrcn-ee-archive-keyring 4. Updateyourrepositoriesagainandtheerrorshouldbegone: $sudoapt-getupdate 5. Checktheversionofyourinstalledkernel: $uname-r 6. Next,wewillrunasearchcommandtofindtheversionofXenomaithatissuitable forourkernel.MakesureyourunthecommandappropriatetoWheezyorJessie: Wheezy $sudoapt-cachesearchlinux-image|grep3.8.xx-xenomai| Jessie $sudoapt-cachesearchlinux-image|grepxenomai Atthetimeofwritingthischapter,yourDebianoutputwilllooklikethefollowing. Jessiewillvaryslightlyaccordingtoyourinstalledversion: linux-image-3.8.13-xenomai-r67-Linuxkernel,version3.8.13-xenomair67 linux-image-3.8.13-xenomai-r69-Linuxkernel,version3.8.13-xenomair69 linux-image-3.8.13-xenomai-r70-Linuxkernel,version3.8.13-xenomair70 linux-image-3.8.13-xenomai-r71-Linuxkernel,version3.8.13-xenomair71 linux-image-3.8.13-xenomai-r72-Linuxkernel,version3.8.13-xenomair72 7. Now,wewillinstalltheXenomaikernel.Replacethexwiththeversionofthebone kernelthatyouhaveonyourboard(Takealookatstep6ifyoudonotremember): Wheezy $sudoapt-getinstalllinux-image-3.8.XX-xenomai-rX Jessie $sudoapt-getinstalllinux-image-3.14.XX-ti-xenomai-rXX 8. InstallthetoolsetforrunningbasicXenomaitests: $sudoapt-getinstallxenomai-runtime 9. ConfirmthatweinstalledXenomai: $uname-r Wheezy 3.8.XX-ti-xenomai-rXX Jessie 3.14.XX-ti-xenomai-rXX 10. ChecktheversionofXenomai(youmayhavealaterone): $cat/proc/xenomai/version 2.6.4 It’slookinggood!YounowhavearealtimeXenomaienvironmentsetuponyour BBB. 11. Toroundouttherecipe,wewanttorunacoupleofteststobothcheckthatthekernel layerisinstalledanddeterminelatency.First,loginasrootuser: $sudo-i # 12. Runtheuser-modelatencytest: #xenolatency Youroutputshouldlooksomethinglikethis: RTT|00:00:01(periodicuser-modetask,1000usperiod,priority99) RTH|----latmin|----latavg|----latmax|-overrun|---msw|---latbest|-latworst RTD|1.583|1.999|6.541|0|0|1.583| 6.541 RTD|1.583|2.958|35.916|0|0|1.583| 35.916 RTD|0.916|2.083|30.624|0|0|0.916| 35.916 RTD|0.958|2.041|15.749|0|0|0.916| 35.916 RTD|1.124|2.083|28.791|0|0|0.916| 35.916 RTD|1.583|2.083|31.541|0|0|0.916| 35.916 RTD|-0.084|2.916|35.791|0|0|-0.084| 35.916 RTD|0.916|2.083|28.041|0|0|-0.084| 35.916 13. Finally,runatesttoseehowtheboardperformsunderload.Thisparticular command—xeno-test—requiresseveraloptionstobeincludedinorderforittorun ausefultest: #xeno-test-l"dohell-s192.168.0.5-m/mnt-l/ltp"-p100-ghisto Let’stakeacloserlookatthevariouspartsofthisscriptsowecanunderstandwhatit does: dohell[-b<path>][-s<server>][-p<port>][-m<path>][-l <path>|<duration>] There’smore… IftheprecedingeasyrecipeforgettingtheXenomaikernelinstalleddoesnotexactlysuit yourspecificneeds,youhaveacoupleofotherwaystoattackit:Useaprebuilt, downloadablesoftwareimagecalledMachineKitoryoucaninstallitfromsource. MachineKit: DeveloperandengineerCharlesSteinkuehlerhascreatedanessentiallyturnkeyreal-time Debianimagethatrequiresnotmuchmorethandownloadingandflashingapre-built kerneltoamicroSDcardortheeMMC.Asitsnamesuggests,MachineKittargets machineusers(CNCs,3-Dprinters)andcomeswithLinuxCNC,Xenomaiandotherreal timeingredientsalreadyloaded.Theimagecansaveendusersanenormousamountof timeininstallingandsettinguptheirmachines. Downloadthesoftwareat http://elinux.org/Beagleboard:BeagleBoneBlack_Debian#BBW.2FBBB_.28All_Revs.29_Ma Instructionsareathttp://blog.machinekit.io/p/machinekit_16.html Athissite,youwillalsofindanextensivelistofcapesdesignedspecificallyfor controlling3-DprintersandCNCs—http://blog.machinekit.io/p/hardware-capes.html Installfromsource Thereareseveralexcellenttutorialsfordoingacustombuild: ProfessorMarkYoder’stop-notchlesson—http://elinux.org/EBC_Xenomai InstallingXenomaionBeagleboneusingDebiandistribution —https://randomlinuxhacks.wordpress.com/2015/02/22/installing-xenomai-onbeaglebone-using-debian-distribution/ XenomaiontheBeagleboneBlackin14easysteps —http://brunosmartins.info/xenomai-on-the-beaglebone-black-in-14-easy-steps/ Seealso Tofurtherexplorethelatencycommandanditsnumerousoptions,checkouttheguide writtenbytheXenomai.orgteam—http://www.xenomai.org/documentation/xenomaihead/html/latency/ AnotherusefultoolfortestingtheXenomaikernelisklatency,atestthatrequireseither compilingXenomaifromsourceasoutlinedhere,ormakingkernelconfigurationchanges thatarebeyondthescopeofthisrecipe.However,inthefollowingThere’smore…section areseveralmethodsforinstallingXenomaifromsource. Programmablereal-timeunits–an introduction Nowit’stimeforhardwaremagic,forseriousrealtime,andashiftawayfrommere softwaremodsonthekernel. It’stimeforProgrammableReal-TimeUnitsAndIndustrialControllerSubsystem,also knownasPRU-ICSS,orPRUs.How’sthatforamouthful?Moretechno-acronymsare alwayssohelpfulanddelicious.OK.Let’sdeconstructit. PRUsarespecializedchipsontheBeagleBoneBlackthatgiveyourealtimetaskcontrol overyoursystem.Thesetwo32-bitmicrocontrollersareactuallyseparateCPUsfromthe mainCPUandtheoperatingsystem.That’sright:PRUsareseparatehardware.This meanstheyarenotreliantonthecorekernelandaremoreefficientataccessingI/Opins anddrivingrealtimeevents. HavingonboardPRUsisoneoftheBBB’sbigdifferentiatorsinthemicrocomputer market.Real-timehardwarecontroltypicallyrequiresaddingondaughterboardssuchas FPGAs(anotherbigscaryacronym)thatboostyoursystem’smojo.UsingPRUsrequires nooverheadontheBBB’smainprocessor,andthehardwarecanbemanagedwithout worryingaboutinterruptsfromtheOS. ThisisahugedistinctionandadvantagefromourpriorexamplesofRT-PREEMPTand Xenomaipatches,bothofthemsoftwaresolutionsforrealtimechallenges. PRUsexistasparallelbutdistinctprocessorsontheboard Tofurtherclarify,thePRUsubsystemisnotahardwareacceleratorthatspeedsup algorithmcomputing.However,PRUSdo: Reducelatency:DigitalI/Osrespondinnanoseconds,notmillisecondslikewesaw inoursoftwareRTscenarios. Extendconnectivityandadd-ons:AlthoughtheBBBisoftenpositionedasa hobbyistorprototypingplatform,PRUcapabilityopensupusecasestoprofessional embeddedcomputingscenarios,unlikeotherplayersinthemarketsuchasthe RaspberryPi. Managepower:Withtheabilitytoreducepowerconsumptioninrealtime,farbetter controloverthesystem—anditsuses—becomespossible.Fortheembeddeddev crowd,that’sarealboon. Deliver100percenthardrealtime. Note TexasInstruments—theinventoroftheBBB—doesn’tactually“support”youruseofthe boardwiththePRUs.Theyprovideexamples,andevenencourageuseofthePRUs,but stillcaveatthewholethingbysayingthatthecodeis“forDIYerstouseattheirownrisk.” Maybethey’reafraidsomeonewillusethePRUstomakeafluxcapacitor? Ononelevel,itonlytakestwothingstomakethePRUsfly:youenablethem,andthen yourunaCprogram(oranotherwrapperwithPython)tomakeuseofthem. Easy,right?However,buriedwithinthosetwoseeminglystraightforwardtasksaresome challenges.Becausewearemanipulatinganentirelysecondsetofhardwareseparatefrom themainprocessor,handlingPRUsontheBBBisquiteadifferentanimalfromnearlyall theotherrecipesinthisbook. Itdoesn’thelpthatcurrentdocumentation—thoughextensive—isscattered,sometimes useful,butmoreoftenpoorlywritten.Thegoodnews,though,isthatBeagleboard.organd theopensourcecommunityhavemadeconsiderableprogressinsimplifyingthetasks aheadofus. Note Althoughyoucouldcross-compilethefollowingrecipesonanotherclientmachine,we willdevelopthemnativelyontheBBB. Nowlet’sprepandenablethePRUs. EarliermethodsofinteractingwiththePRUswereatruckloadofhurt.Theprocess requiredmanysteps,includingcreatingandcompilingadevicetreejusttorunasample application. However,cookingwithPRUshasbeensimplifiedconsiderablywiththerecipebelow. Andhappily,youcanuseeverythingforbothDebianWheezyandJessieversions. Gettingready Theusualminimalsetupisallyouneed:aBBBpoweredoverminiUSBwithInternet connectivityenabled. Howtodoit… 1. Loginastherootuser: $sudo-i 2. InstalldriverLibraryandPRUtoolset: #apt-getinstallam335x-pru-package&&ti-pru-cgt-installer Note TheinstallationincludesanumberofitemsrequiredtooperatethePRUsfromuser space: PASMassembler:Beingratheruniqueinnature,thePRUsdon’tspeak BoneScriptorJavaScriptorPythonorC.Instead,theycommunicateusing Assembly,andrequirethePASMassemblertocompileandrunitscode.You mayhavelittleexperiencewithAssembly;youmayhavenone.Don’tdespair: afterrunningthecommandabovethetoolcomesreadytouse. libprussdrv:Thisconsistsofthedriverlibraryandlibraryheaders. 3. InasimilarveinaswedowithGPIOpins,tomakeuseofthePRUswehaveto enablethem.AndinteractionwiththePRUsrequirestheuseofaDeviceTree fragment.WiththecurrentWheezyandJessiedistributions,theDToverlaycomes pre-compiledandreadytouseonyoursystem,ahugetime-saveroverearlier versionsofthesoftware. Beforeloadingafragment,letusfirstlookatthesystem’sDeviceTreeslotswhereit willappearsowecanseeunderstandthebefore-and-afteroutput: #cat/sys/devices/bone_capemgr.9/slots 0:54:PF--1:55:PF--- 2:56:PF--- 3:57:PF--- 4:ff:P-O-LBone-LT-eMMC-2G,00A0,TexasInstrument,BB-BONE-EMMC-2G 5:ff:P-O-LBone-Black-HDMI,00A0,TexasInstrument,BB-BONELT-HDMI 7:ff:P-O-LOverrideBoardName,00A0,OverrideManuf,BB-UART4 Nothingshows,yet,intheoutputabovethatindicatesPRUvisibilityor communicationwiththekernel.Thenextcommandchangesthatstatus. 4. Usingtheechocommand,loadthedevicetreefragment.ThisenablesthePRU: #echoBB-BONE-PRU-01>/sys/devices/bone_capemgr.9/slots Thecommandshouldreturnyoutothepromptwithoutanymessageorerror: # 5. Withthecatcommandagain,checktomakesurethatthefragmentloaded: #cat/sys/devices/bone_capemgr.9/slots 0:54:PF--- 1:55:PF--- 2:56:PF--- 3:57:PF--- 4:ff:P-O-LBone-LT-eMMC-2G,00A0,TexasInstrument,BB-BONE-EMMC-2G 5:ff:P-O-LBone-Black-HDMI,00A0,TexasInstrument,BB-BONELT-HDMI 7:ff:P-O-LOverrideBoardName,00A0,OverrideManuf,BB-UART4 8:ff:P-O-LOverrideBoardName,00A0,OverrideManuf,BB-BONE-PRU-01 Anewoverlayshouldappearinthelastslot,namelyBB-BONE-PRU-01.Yourslot numberforthePRUmaydifferaccordingtootherdriversanddaughterboardsyou alreadyhaveloaded. Note IfyourantheuniversalI/Odevicetreerecipeinourpriorchapter,youmaygetthe followingerror:-bash:echo:writeerror:Fileexists Ifso,don’tdespair.AllthismeansisthatuniversalI/OproperlyloadedyourPRU devicetreealready.So,you’regoodtogo! 6. Runanadditionalcommand,lsmod,whichshowsallmodulesloadedintothekernel. Wewanttoconfirmthattheuio_prussdriverconnectedproperly,sinceitisthe modulethatopensagatebetweenuserspaceapplicationsandthePRU,allowing themtospeaktooneanother: #lsmod ModuleSizeUsedby uio_pruss40660 g_multi504072 libcomposite150281g_multi 8192cu4490330 omap_rng40620 mt7601Usta6014040 7. Tobesafe,weshouldalsorundmesginordertopeekatthekernelmessagesandsee ifanyothererrorsoccurred.Addtheoptionspipe(|)and(less)soyoudon’tgetone bigoutputdumponthescreen. #dmesg|less Scrollthroughtheoutputbytappingthespacebaratthebottomoftheterminalscreen untilyoustartseeingoutputforbone-capemgrbone_capemgr.9.Keepadvancingto thenextscreenuntilyoubegintoseethefollowing: [2268.218496]bone-capemgrbone_capemgr.9:part_number'BB-BONE-PRU01',version'N/A' [2268.218670]bone-capemgrbone_capemgr.9:slot#8:genericoverride [2268.218713]bone-capemgrbone_capemgr.9:bone:Usingoverrideeeprom dataatslot8 [2268.218761]bone-capemgrbone_capemgr.9:slot#8:'OverrideBoard Name,00A0,OverrideManuf,BB-BONE-PRU-01' [2268.219031]bone-capemgrbone_capemgr.9:slot#8:Requestingpart number/versionbased'BB-BONE-PRU-01-00A0.dtbo [2268.219079]bone-capemgrbone_capemgr.9:slot#8:Requesting firmware'BB-BONE-PRU-01-00A0.dtbo'forboard-name'OverrideBoard Name',version'00A0' [2268.219140]bone-capemgrbone_capemgr.9:slot#8:dtbo'BB-BONE-PRU01-00A0.dtbo'loaded;convertingtolivetree [2268.219821]bone-capemgrbone_capemgr.9:slot#8:#2overlays [2268.241573]omap_hwmod:pruss:failedtohardreset [2268.248299]bone-capemgrbone_capemgr.9:slot#8:Applied#2 overlays. 8. Beforemovingontoanactualtestapplication,weshouldaddanadditional ingredienttomakeourprecedingechocommandstick.Althoughthisstepisoptional, youshouldstillgothroughtheprocessofdoingitsothatwhenwerebootwewillnot losetheloadedDTfragment.So,letussetupourenvironmenttoloadthefragment onboot: #nano/etc/default/capemgr 9. Intheopeneditwindow,youshouldseethefollowing: #Defaultsettingsforcapemgr.Thisfileissourcedby/bin/shfrom #/etc/init.d/capemgr.sh #Optionstopasstocapemgr CAPE= Appendittothefollowing: #Defaultsettingsforcapemgr.Thisfileissourcedby/bin/shfrom #/etc/init.d/capemgr.sh #Optionstopasstocapemgr CAPE=BB-BONE-PRU-01 10. RebootyourBBB,loginasrootuser,andcheckthatthefragmentloaded: #cat/sys/devices/bone_capemgr.9/slots 0:54:PF--- 1:55:PF--- 2:56:PF--- 3:57:PF--- 4:ff:P-O-LBone-LT-eMMC-2G,00A0,TexasInstrument,BB-BONE-EMMC-2G 5:ff:P-O-LBone-Black-HDMI,00A0,TexasInstrument,BB-BONELT-HDMI 7:ff:P-O-LOverrideBoardName,00A0,OverrideManuf,BB-UART4 8:ff:P-O-LOverrideBoardName,00A0,OverrideManuf,BB-BONE-PRU-01 Allright,nowwecanmoveontoanactualtestofthePRU. AsimplePRUtestwithanassembler AlthoughtherearemanycomplexandfarmoresophisticatedtestsforthePRUs,our intentionistocreateaveryminimaltestrecipethatyoucanobservefromuserspace. Todothis,wewilluseaCprogramthatrunsdirectlyonourBBB’sARMprocessor.From Linuxuserspace,itwillgiveabighugtothePRU,uploadanassemblercodebinary,run it,thenpassandfetchinformationbetweentheARMandthePRU. Thebasicstepsare: 1. Createaprograminassemblylanguageforthededicatedhardware(thePRU) Note ThePRUonlyspeaksassembly! 2. CreateaprograminCforthemainCPU(BBB’sARM) Note ThisprogramreachesoverandhandshakestheassemblercodeontheotherPRU. 3. RunaPRUtestwiththecombined(compiled)magicofthefirsttwosteps. Gettingready Theusualminimalsetupisallyouneed:aBBBpoweredoverminiUSBwithInternet connectivity.Youwillalsoneedtohaveexecutedtheprecedingrecipeonpreppingand enablingthePRUs. Note BesurethatyouareproperlyconnectedonlinesothattheBBBtimeclockaccurately reflectsthecurrenttime.Otherwise,youmayrunintoerrorsincompilingthebinaryfile. Howtodoit… 1. WebeginbylogginginasrootandcloningarepositoryonGithubcontainingthe files: $sudo-i #gitclonehttps://github.com/HudsonWerks/bbb-pru.git Note TheexamplefilesintherepoarebasedoncodefromdeveloperDouglasG.Henke (http://mythopoeic.org/bbb-pru-minimal/). 2. Browsetothesamplefilesdirectory: #cd/bbb-pru/simple-tests Note Youshouldseethreefiles—major-tom-pru.c,major-tom-pru.p,Makefile—anda README. 3. TheMakefilewillrunthePRUassemblerapplicationandgenerateabinaryfromthe combinationofthe.pfileandthe.c: #make Theoutputshouldlookasfollows: pasm-bmajor-tom-pru.p PRUAssemblerVersion0.86 Copyright(C)2005-2013byTexasInstrumentsInc. Pass2:0Error(s),0Warning(s) WritingCodeImageof6word(s) cc-Wall-Werror-c-omajor-tom-pru.omajor-tom-pru.c ccmajor-tom-pru.o-lpthread-lprussdrv-omajor-tom-pru 4. Thecompiledbinarycreatedbyassembleriswhatwenowusetorunatestprogram onthePRU(besureyouincludethesudo): #sudo./major-tom-pru Youroutputshouldlooklikethefollowing: waitingforinterruptfromPRU0… PRUtestprogramcompleted.MajorTom'sblastoffeventnumber1 Itshouldtakeapproximately3secondsbetweenthefirstlineandthesecond.The blastoff(event)numberwillincreaseeachtimeyourunit. Inthemajor-tom-pru.pfile,trychangingtheDELAYCOUNTdefaultnumber(currently setto3seconds)toanothernumber.Then,runmakeagain,andrunthenewmajor- tom-prubinaryagain.Youshouldbeabletoseedifferencesinthedurationaccording toanynewvaluesthatyouset. Hooray!Youhavenowfinishedtacklingoneofthemorearcaneandadvancedfeaturesof theBeagleBoneBlack.Now,let’sdoitagaininthenextsection… Seealso Atthebeginningofthisrecipe,wealsoinstalledacommandlineversionofTexas Instrument’sPRUCodeGenerationTools(ti-pru-cgt-installer).Theinstallcomes notonlywiththeassemblerpackage,butCcodecompiletools,aswell.Thistoolset makesitpossibletomoreeasilydevelopPRUprogramsinCinsteadofassemblycode. Youcandownloadtheextensivemanualathttp://software-dl.ti.com/codegen/nonesd/downloads/download.htm. Runninganultrasonicrangesensorwith thePRUs Thefasttwitcheyemuscleonarobotisonlyasgoodasitsprocessor.Andwithmany roboticprojectswheremobilityandmotionispartofthedesign,thespeedandreliability ofthetwitchcanbethedifferencebetweenasuccessfulforayorasmashandcrash. Whichiswherenanosecondresponsetimeandreliability—aPRUspecialty—iscrucial. Tothatend,letuslookatamoreambitiousrecipethatcooksupawaytousethePRUs withoneofthosecheapandubiquitousultrasonicrangesensors,thekindthatare commonlyfoundonbasicroboticdevices.Thesensorusessoundtosendaping,similarto whatasubmarinedoestomeasurethetimebetweensendingandreceivingasignalfor determiningdistancefromanobject. Gettingready Therequirementsareasfollows: BBBpoweredover5Vpowersupply.IfyouonlypowertheboardviatheUSBtether, youwilldeliververyunreliablepowertothesensor,sobesureyoumaintaina5V supply. Internetconnectivity. HC-SR04sensor. Breadboard. Jumperpins. Resistors—1x1kand1x2k. Howtodoit… Performthefollowingstepstorunanultrasonicrangecenter: 1. HookupyourbreadboardandBBBaccordingtothediagrambelow.Makenoteof twocrucialitems: Resistors:Asyoushouldrecall,theBBBcanonlyacceptamaximumof3.3V onitspins.Therefore,thewiringdesignrequirestworesistors,a1kanda2k.In tandem,theyservetostepdownthevoltagefromthesensor’sEchopin(5V) beingsentbacktotheBBB. Confirmthatyouhavebothresistorsinplace;otherwise,youmaydamageyour belovedBBB! Power:Therangesensorneedsa5Vsupply.Anythinglesswillyield unpredictableresults. Thefollowingtabledisplaysthewiringconfiguration: Pinpurpose Pinnumber GND P9_1 OrP9_2 VCC/VDD_5V P9_5 OrP9_6 Trigger P8_12 Echo P8_11 With1kand2kohmresistors Besuretodoubleandtriple-checkyourwork.Otherwise,youcouldendupfrying yourboard. 2. Loginasroot: $sudo-i # 3. ClonethefilesthatwewillbeusingfromGitHub: #gitclonehttps://github.com/HudsonWerks/Range-Sensor-PRU.git 4. Browsetothenewdirectory: #cdRange-Sensor-PRU Takealookinsidethedirectorytogetasenseofwhatkindoffileswewillbeusing: rangepru.dts:DeviceTreesourcefilefromwhichwewillbuildaDeviceTree overlay,ordriverforourtestapplication rangepru.c:ContainstheapplicationcodewritteninC rangepru.p:ContainstheassemblycodewhichwillberunagainstourCfiletobuild thebinary Makefile:Buildsabinarythatwewillultimatelyusetorunourrangesensortest withthePRUs 5. Weneedtoaddacustomdevicetreeoverlaytothemix.Theoverlayservesasa driverforthesensorandmapstotheGPIOsweareusing.Inthecurrentdirectory,we willmodifythe.dtsfiletoincludethetargetGPIOsseeninourfritzingdiagram: #sudonanorangepru.dts 6. Intheopeneditwindow,scrolldowntothefollowingsection: exclusive-use= "<TRIGGERPINHERE>","<ECHOPINHERE>", "GPIO44","GPIO45"; Changeittothefollowing: exclusive-use= "P8_12","P8_11", "GPIO44","GPIO45"; Saveyourchangesandclosethenanowindow(Ctrl+X,thentypeyforyes,and pressReturn(Enter)key). 7. Next,weneedtocompileaDeviceTreeoverlayfile(dtbo)withtheDTcompiler, addingallappropriateflags: [email protected] Note SeeChapter4,ExploringGNU/LinuxRecipesUsingBash,Autotools,Debugger,and systemd,forarefresheronDeviceTree,thecompileranditsoptions. 8. Nowweneedtocopythecompiledoutputfile—rangepru-00A0.dtbo—tothe directorywheretheoverlaysarereferenced: #cprangepru-00A0.dtbo/lib/firmware 9. Althoughweputtheoverlayinitsproperdirectory,wehavetoloadit,justlikea driverhastoloadinordertorecognizeanewpieceofattachedhardware.So,runthe following: #echorangepru>/sys/devices/bone_capemgr.*/slots 10. Takealookattheslotsandseethattheoverlayisreadyforaction: #cat/sys/devices/bone_capemgr.9/slots Youroutputshouldlooksimilartothis: 0:54:PF--- 1:55:PF--- 2:56:PF--- 3:57:PF--- 4:ff:P-O-LBone-LT-eMMC-2G,00A0,TexasInstrument,BB-BONE-EMMC-2G 5:ff:P-O-LBone-Black-HDMI,00A0,TexasInstrument,BB-BONELT-HDMI 7:ff:P-O-LOverrideBoardName,00A0,OverrideManuf,rangepru 11. Confirmtheoverlaytookhold: #dmesg Youroutputshouldlooksimilartothis: [1462.225670]bone-capemgrbone_capemgr.9:part_number'rangepru', version'N/A' [1462.225742]bone-capemgrbone_capemgr.9:slot#7:genericoverride [1462.225758]bone-capemgrbone_capemgr.9:bone:Usingoverrideeeprom dataatslot7 [1462.225773]bone-capemgrbone_capemgr.9:slot#7:'OverrideBoard Name,00A0,OverrideManuf,rangepru' [1462.225856]bone-capemgrbone_capemgr.9:slot#7:Requestingpart number/versionbased'rangepru-00A0.dtbo [1462.225870]bone-capemgrbone_capemgr.9:slot#7:Requesting firmware'rangepru-00A0.dtbo'forboard-name'OverrideBoardName', version'00A0' [1462.230469]bone-capemgrbone_capemgr.9:slot#7:dtbo'rangepru00A0.dtbo'loaded;convertingtolivetree 12. WeshouldalsocheckthatthePRUmoduleisloadedasexpected: #lsmod Youroutputshouldlooksimilartothis.Youshouldseetheuio-prussdrvdriver: ModuleSizeUsedby uio_pruss40580 g_multi505192 libcomposite150321g_multi 8192cu4491770 cpufreq_userspace20130 evdev72442 omap_rng40540 Whew!Thatwasthefirstpartoftherecipecompleted.Okay,letusnowmoveright alongtocreatingtheactualfilewewillusetocapturedatafromtheultrasonicrange sensor. 13. UsingtheMakefilescript,wewillruntwoactions:onewillcreateanAssemblycode binarytointeractwiththePRUsfromthefilerangepru.p;theotherwillgeneratea compiledCprogramfromthefilerangepru.cthatservesasbothaninterfacetothe assemblybinarywhiletakingthesensordataanddisplayingitinahuman-readable fashion. #make Note Usingsudonanomake,itmightbeusefultolookunderthehoodforamomentto seewhatthescriptisdoing. 14. Themagicalmakecommandcreatesanewexecutablefile—rangepru—inour directory.Wewillnowrunittomonitorandoutputdatabeingcapturedbyour ultrasonicrangesensor: #./rangepru IfalliswellinBBB-land,youshouldbegettingscreenoutputthatlooksakintothis. Carefullymovethesensoraroundtowatchthedistancechange(note,yournumbers willvaryaccordingtothedistanceyoursensorisfromanobject: >>InitializingPRU >>Executingrange-sensorcode 1:Distance=70.21cm 2:Distance=71.95cm 3:Distance=71.95cm 4:Distance=7.68cm 5:Distance=64.27cm 6:Distance=4.09cm 7:Distance=5.20cm 8:Distance=53.25cm 9:Distance=6.62cm 10:Distance=2.28cm 11:Distance=2.34cm 12:Distance=10.13cm >>PRUDisabled. Outstanding!Youhavenowsuccessfullyhookedupasensorthatisubiquitousin robotbuilding,andtaughtithowtodancewithyourBBBanditsfancyPRUs. UsingPythonwiththePRUs Contrarytopopulargeekbelief,ancientEgyptiansdidnotwriteonPyPRUSS.Butif they’dknownPython,theymighthave. Actually,theoldestthingaboutPyPRUSS—aPythonlibraryforthePRUs—isthatitwas primarilyfocusedontheearlierAngstromfirmwarefortheBBB,adistributionnow lookingincreasinglymummified.WhichisnottosaythatPyPRUSSdoesnotstillremain agreatuserlandtouchstoneforPythonistasandPRU-ophiles. Infact,eventhoughthereisnopre-compiledbinaryintheDebianrepositoriesfor PyPRUSS,ittakesallof90secondstocompileandinstallfromsource,andbeginrunning PythononthePRUsquickly. Gettingready Theusualminimalsetupisallyouneed:aBBBpoweredoverminiUSBwithInternet connectivity.Youwillalsoneedtohavedonethefirstrecipeinthissectiononprepping andenablingthePRUs. Howtodoit… 1. Loginasroot: $sudo-i 2. Grabthesourcefiles: #gitclonehttps://github.com/HudsonWerks/pypruss.git 3. Navigatetothedirectorywejustcreated: #cdpypruss 4. RunthescriptforinstallingthePyPRUSSlibrary: #pythonsetup.pyinstall 5. Makesureyourlibraryismappedproperly: #exportLD_LIBRARY_PATH=/usr/local/lib 6. Browsetheexampledirectory: #cdexamples 7. Takealookatwhatisavailableinthatdirectory: #ls 8. Now,wewillrunsomeexamples.Webeginwitheveryone’sfavoriteblinkything: #cdblinkled 9. Next,compileanassemblybinaryfile: #make 10. RunthePythonfile: #pythonblinkled.py Oops!Youmayhavegottenanerror.Ifyoudidn’t,justskipthenextstep.Butifyou did,thenitprobablylookedlikethis: ERROR:couldnotinsert'uio_pruss':Numericalresultoutofrange modprobefailed :Nosuchfileordirectory Traceback(mostrecentcalllast): File"blinkled.py",line7,in<module> pypruss.modprobe()#Thisonlyhastobecalledonceprboot SystemError:errorreturnwithoutexceptionset Errorsalwaysshowsussomethingimportant:thatuio_prusshastobeloadedbefore thePRUscanbepinged,justlikewesawinourpreviousrecipe. 11. Thus,wewillloadthatfragment: #echoBB-BONE-PRU-01>/sys/devices/bone_capemgr.9/slots 12. Now,tryrunningthepythonscriptagain: #pythonblinkled.py Assumingallgoeswellnow,youshouldthenseethreeoftheuserLEDsblink10timesin rapid,seizure-inducingsuccession. Seealso TherearevariousresourcesforlearningmoreaboutPRUs.Thereisquiteabittolearn abouthowtousethePRUsontheBBB,mostofitwellbeyondthescopeofthisbook. However,wehavecompiledalistofusefulbackgroundinformation,tutorials,and projectstofurtheryourexplorationoftheseuniquerealtimesubsystems. PRUwikiwiththemostup-to-dateinformation —http://elinux.org/Ti_AM33XX_PRUSSv2 Beagleboard’sofficialoverviewofPRUs.Moredetailthanyou’lllikelyneed,but goodcontext,andahelpfultableofcommandsforPASM —https://github.com/beagleboard/am335x_pru_package/blob/master/Documentation/01AM335x_PRU_ICSS_Overview.pdf TexasInstruments’officialoverviewofPRUs —http://processors.wiki.ti.com/index.php/Programmable_Realtime_Unit_Software_Develop PRUCproject—fromdevicetreetoprogramexecution,anextensiveanduseful threadonPRUusage—https://groups.google.com/forum/#!categorytopic/beagleboard/pru/VW361VUkCcI AnassortmentofPRU-centricprojects —http://processors.wiki.ti.com/index.php/PRU_Projects AnothertakeonsettingupandrunningPRUs —http://www.embeddedrelated.com/showarticle/586.php Anearly,someconsiderseminalpostonusingPRUswiththeBBWhite,notthe Black—http://boxysean.com/blog/2012/08/12/first-steps-with-the-beaglebone-pru/ Debuggersandeditors: VisualPRU,asexy,browser-basededitoranddebuggerforthePRUs —https://github.com/mmcdan/visualpru PRUdebug,afunctionalCLI-centricappfordebuggingyourPRUcode —http://sourceforge.net/projects/prudebug/ BeagleRT:MostprojectsonthesubjectofusingRTontheBBBfocusondriving motorsformachinetoolsorotherindustrialapplications.BeagleRT,however,isa fascinatingprojectthatusesXenomaiandPRUsontheBBBintheserviceof creatinghackableDigitalMusicalInstruments(DMIs).Thisnovelusecaseforan ultra-low-latencysensor/audioplatformrequiresahighlevelofmachine responsivenesstofulfillaperformer’sexpectationsandperformancetechniques,thus theneedforpredictabletimingfromtheboard: Projectoverview—http://www.eecs.qmul.ac.uk/~andrewm/hackable.html Opensourcecode—https://code.soundsoftware.ac.uk/projects/beaglert PRUspeak:AnimplementationoftheBotSpeakroboticslanguageforthePRU. ThisprojectenablesdynamiccontroloftheBeagleBoneBlack’sPRUfromtheLinux userspaceonARM: http://botspeak.org/supported-platforms/beaglebone/ https://github.com/deepakkarki/pruspeak PRUCAPE:TexasInstrumentsdesignedalow-costcapetofacilitateusageofthe PRUs Goodverbiageonitspurposeandusage—http://linuxgizmos.com/beaglebonecape-eases-access-to-the-sitara-socs-pru/ Youcanpurchaseithere—http://www.ti.com/tool/PRUCAPE#buy Chapter7.AppliedRecipes–Sound, Picture,andVideo Inthischapter,wewillcoverthefollowingrecipes: Wiringupaminiampandspeakers Creatingahigh-qualityaudioplatformwithVolumio Usingvideosanddisplaysinprojects TestingaminiLCDcape MakingavideochatclientprototypeusingLinphone Introduction Weneedtogetalittledirtier.Sofar,weplayeditsafewithphysicalcomputingrecipes. Buthowfarcanyougobyjustplugginginsomewiresintoabreadboard?Tomakethe BBBareallyusefultool,wehavetoheatuptheiron—thesolderingiron—andmakesome nice,shinyjoints.Manygreatadd-ons,suchasPCBs,sensors,headers,andperipheral devicesarriveatyourdoorstepunsoldered,fulloffiddlybits,orjustdownrightunsuitable outofthebox.So,solderingisamustonthemicrocomputinglandscape. However,thisisonlyonepartofthepictureforthischapteronpicture,sound,andvideo. Wewillalsoexploredifferentadvancedmethodstoaddarangeofcapes,PCBadd-ons, andsomeUSBdevicesformorecomplexrecipesusingdigitalsound,pictures,andvideo andlookatthefollowing: Wiringupaminisoundamplifierandspeakers Creatingahigh-qualityaudioplatformwithVolumio Usingvideosanddisplaysinprojectsthatincludethesedevices: OLEDPCB MiniLCDcape Makingavideochatclient Here’sthetruthaboutBeagleBoneBlack:whenitcomestoaudioandvideo,theBBBis notforthefaint-hearted.OtherthanasingleUSBport(whichisobligatoryforallkindsof reasonsbeyondjustaudioorvideoadd-ons),theBBBisatoughsystemtolearnfor hardwareandLinuxnewcomers.Thereisnoonboardcameraport;youhavetopiggyback onUSBorbuyadedicatedcape.ThereisnoonboardaudioI/Opin,USBdevice,or dedicatedcaperequiredeither.So,ifyouarelookingforaquickandeasy,media-rich developmentbox,thendareIsayit:RaspberryPimightbeabetterchoice. Asaresultofthisdifference,theBBBisoftencriticizedfornotbeingbetteratRich Media.However,thedifferenceisintentional;RPi’sengineersintendedtomakean educational,hobbyistboardwithadesktop-likeexperiencetoencompassRichMediause cases.Ontheotherhand,theBBB’sengineersdesignedtheirplatformtocreateadvanced prototypesforembeddedapplicationswherehigh-endgraphicsandsoundarenot commonlyrequired. Withthesecaveats,BeagleBoneBlackstillremainsmorethanuptothechallengeof deliveringsoundandpictureinmany,veryusefulscenarios,includingstreamingmusic andvideos. BringingaudioontoBeagleBoneBlack TheabsenceofonboardaudiooutputorinputisarealpainwhenitcomestotheBBB. Yet,thereareseveralmethodsofattackingthischallenge.Firstly,youcangocheapand easywithasimpleUSBsounddongle;twovarietiesareshowninthefollowingpicture attachedtoapoweredUSBport: Secondly,youcanaddadedicatedaudiocape(aswedidinChapter5,Basic ProgrammingRecipeswiththeLinuxKernel).Thirdly,youcandoitthehard(ish)way usingadedicatedPCBandbypiggybackingontheGPIOpins.Whybotherwiththe latter?ThisisbecauseusingUSBisofteninadequateforcertainapplications.Whenyou requirefaster,moreRT-styleperformance,runningaudiopacketsacrossUSBcanbe disappointing.Wealsowanttostretchourlimbsandaddsomecomplexitysothatyou havemoretypesoftechnologiestodrawuponinfutureprojectsandprototypes. Wiringupaminiampandspeakers Togetsomerockingaudiogoing,wethoughtaboutwiringaBeagleBoneBlackuptoa personalfavoritedeviceofours:ac.1960Gruntalamplifierandradio: Wethenthoughtbetterofitanddecidedtogowithsomethingaweebitsmallerforour recipe:theTPA2016PCB,whichcontainsaTexasInstrumentschipsetandispackagedas afinalproductbyAdafruit: Itdoesn’tpackquitethevolumeasanancienttube-basedamp,butthissurface-mount PCBampisaheckofalothandierandeasiertousethanourantiquebeauty.Also,it deliversnearly3Wofpowerforourtunes,plentyofvolumeformanysituations. Additionally,itsI2Cinterfaceallowsustocontrolaudiogainviasoftwareinsteadofusing jumpers,switches,orotherphysicalhardware. Inthisrecipe,youwilllearnhowtosetupandtestthedeviceonabreadboardwith speakersandBeagleBoneBlack.Afterwards,inalaterrecipe,we’lluseitaspartofourkit tosetupalisteninglibraryontheBBB. I2Cbackgroundandusage I2C(pronounced“eye-squared-C”or“eye-two-see”)isahardwarebusintendedfor motherboardsanddaughterboardstocommunicateeasily.Itisfrequentlyleveragedin embeddedapplicationsandtypicallyusedinaccelerometers,magnetometers,andother sensors,aswellasotheradd-onsrequiringlowvoltage.Inourcase,wewilluseittoruna verysmallaudioamplifier. Otherthanitspowerleads,thebusonlyusestwowirestocommunicate:SCLandSDA. Thefirstoneistheclockline,SCL,whichisusedtosyncanydatapassingoverthebus. Thesecondline,SDA,carriestheactualdata.I2Calsoutilizesasimplemaster/slave relationshipbetweendevices,withthebusallowingtherolestobeinterchangeable.I2Cis alsogoodatnoisefiltering,whichisarelevantfeatureforourrecipe. WorkingwithI2CpinsontheBBBisprettystraightforward.TherearethreeI2Cbuses implementedontheBBB,butonlyoneoftheseiseasytouse: I2C0:Thisisusedforsomeonboardcomponents,suchasHDMI,EEPROM,and powermanagement.Ifwedisableit,itwillinterferewiththesecomponents,soitis typicallynotusedunlessneeded. I2C1:Thisisavailableforusebutrequiresenabling. I2C2:Thisisusableoutofthebox(ExpansionportP9;refertotable11intheSRM). Thesearethepinsthatwewilluse. Note I2Sbus I2CshouldnotbeconfusedwithIntegratedInterchipSound(I2S),anotherserialbus availableontheBBB.UnlikeI2C,whichisbidirectional,I2Sonlyhandlesdatainone direction.Coincidentally,I2SistypicallyusedasaninterfacetocommunicatePCMaudio databetweendevices,commonlywithaDigitaltoAnalogConverter(DAC)audio device,thoughwewillnotuseitinouraudiorecipes.Thereareseveralhelpfultutorials onmakingaDAC,interfacewithI2SandconnectingittotheBBB,suchastheoneat http://bit.ly/1HQMc1N. Gettingready Herearethematerialsweneed: PCBampkit:ThiscanbeTPA2016orsimilar.Adafruithasseveralchoices,which youcanaccessathttps://www.adafruit.com/search?q=amplifier. Speakers:Youcanuseanysetofspeakersthattakemonoorstereominiconnector cables. Audioinputjack:Eitheroneofthefollowingtwomethodswillwork: 3.5mmStereoHeadphoneJack(breadboard-ready):Thisisverycheapand availableatSparkfun(https://www.sparkfun.com/products/8032)orAdafruit (https://www.adafruit.com/product/1699)foraroundUSD$1.00. 3.5mmstereoplugto“pigtail”cable:Thisisbasicallyasimplestereomini cableusingastandardplugononeendandaleftandrightspeakerwithwirestripped“tinned”leadsontheother.Theleadsbreakout,soyoucanplugthem intoabreadboardeasily.ItischeapandavailableatAdafruit (https://www.adafruit.com/product/1700)forUSD$1.95. Mp3orportablemusicplayer:ThiscanbeaniPodorsmartphonewith3.5mm audiojackoutputandcontainingsamplemusicoraudiofiles. 2-plug(male)audiocable:Astandard3.5mmcablethatyoulikelyalreadyhave aroundthehouse. Solderingiron Lead-freesolder MiniPhilipsheadscrewdriver Jumperwires Breadboard Howtodoit… ToprepthePCBamp,wefollowedsomeoftheguidanceprovidedbyAdafruit’stutorial toworkwiththeirboard(https://learn.adafruit.com/adafruit-tpa2016-2-8w-agc-stereoaudio-amplifier).Performthefollowingsteps: 1. Yourtasksbeginwithsolderingan8-pinheaderstriptothe8-holedsideofthePCB ampandthensolderingthespeakerterminalblocksintothemarkedslotsalongthe oppositesideoftheboard.Thisisshownforyouinthefollowingimage: Note Thisrecipeisnotageneralhow-toonsoldering.Ifyouhaveneversolderedawireor jointonaPCB,consultthefollowingexcellenttutorials: HowtoSolder—Through-holeSoldering:https://learn.sparkfun.com/tutorials/howto-solder–through-hole-soldering/ NYU’sITPsolderinglesson:https://itp.nyu.edu/physcomp/Labs/Soldering Adafruit’sexcellentguidetosoldering:https://learn.adafruit.com/adafruit-guideexcellent-soldering Instructablesecretsofgoodsoldering:http://www.instructables.com/id/How-tosolder-the-secrets-of-good-soldering/ Afterthis,youcanbeginbyinsertingthelongpinsofaheaderstripwith8pinsinto thebreadboard,shortpinsstickingup,asshowninthefollowingpicture: AsitisimportanttogetyourPCBampmountedonanevenplane,theeasiestwayto dothisisbyusingtheleftoverpinstosupporttheboardontheoppositeedge.To clarify,thesepinswillnotbesoldered;theyareonlytherefortemporarysupport. YouthenneedtosolderuptheheadersonthePCBamp,asyoucanseeonthelefthandsideinthispicture.Weusedlead-freesolder;so,whenfinished,thejointswill lookdullinsteadofthetypicallyshinycastfromawell-pouredleadedjoint. 2. SolderthespeakerterminalblockstothePCBamp.Verifythatyourconnectionsare solid.Youmaynoticethattheblocksdon’tsitneatlyparalleltooneanother.This appearstobeduetoaslightdesignimperfectioninthePCBamp,butthere’snothing toworryaboutfunctionally. 3. Snipoffthewhiteconnectorthatcomesalreadyattachedtotheendsofthespeaker wires: Followingthis,withawirestripper,cutawaythewireends,asyoucanseeinthe followingimage: 4. Next,attachthefinishedPCBamptoabreadboard.Then,insertthespeakerwires intothespeakerterminalblocks.Theblackwiresgointothe(-)groundconnectors, andthewhitewiresintothe(+)powerconnectors.UseasmallPhilipshead screwdrivertofirstreleasetensionintheblock.Finishbytighteningitafterthewires areinserted.Theendresultisshowninthisimage: 5. Sinceweplantousesoundinthisrecipe—whichiswhatanaudioamplifierisgood for—weneedtoalsoaddsomemeansforsoundinput.Youcanuseeitherthe breadboard-readyheadphonejack,whichyouwillseeinthenextpicture,orthe pigtailcable,asdescribedatthebeginningofthisrecipe. 6. Hookupyouraudioplayertotheotherendoftheaudiocable.Inourcase,weused anoldiPodthatwehadinadrawer.Ifyourefercloselytothefollowingimage,it showshowallthepartsshouldfittogetherbeforeyouhavehookedituptoyour BBB: 7. ChooseanaudiotrackonyourplayerandpressPlay.Nowthatweknowwehave solidaudiooutputwithallhardwaresoldered,snipped,breadboarded,andwired properly,wewillrunanaudiotestusingPython. 8. Now,wewanttowiretheampuptoourBeagleBoneBlack,followingtheFritzing diagram.Althoughitlookslikeathicketofminijumperwires,theschemeisreally simple.Infact,youwillnoticethatontheBBB’sGPIOpins,thereareonlytwopins inuseotherthanpowerandground. Incasethereisanyuncertaintyfromthediagram,hereisatableclarifyinghowto wireitup: FUNCTION BeagleBoneBlack TPA2016 amplifier Breadboard component Power P9_5(5V)orP9_3(3.3V)—5Vforfull capacityoftheamp VDD Ground P9_1 GND I2C P9_19(SCL) SCL I2C P9_20(SDA) SDA Audioinput—left speaker L+ L+on3.5mm headphonejack R+ Audioinput—right speaker R+on3.5mm headphonejack Audioground L-toR- Audioground R- R-on3.5mm headphonejack 9. Let’sgetprogramming!Tostart,openuptheBoneScriptIDEandcreateanew.py filecalledaudio-amp-test1.py. 10. DownloadthePythonscriptfromourGithubrepowithfollowingcommand: $gitclonehttps://github.com/HudsonWerks/audio-amplifier.git 11. Browsertotheaudio-amplifierdirectorycreatedandopenupthepythonscriptina nanowindow: $$cdaudio-amplifier $sudonanoaudio-amp-test1.py 12. Now,copyandpastethecodeintotheCloud9IDEwindow. 13. Restartamusictrackonyourmediaplayerthat,inourcase,isaniPod.Youshould beabletohearthetrackplayingthroughthespeakers. 14. Now,clickontheRunbuttonontheCloud9IDEtotestthescript.Audiolevels shouldshiftupanddownasyouinputthe(+)or(-)signatthecommandprompt. Success(wehope)!Giveyourselfahigh-fiveforgettingdirtierwithyourboardand addingsomePCBadd-onstothemix. Creatingahigh-qualityaudioplatform withVolumio VolumioisawonderfulopensourcealternativetotheiTunesstraightjacket.Foraudiophile geekswhohappentobemicrocomputerorelectronicgeeks(youknowwhoyouare!)and RPienthusiastsinparticular,Volumioiswell-knownforitsfastidiousnessatservingup high-qualityaudio,beitweb-basedradioorhigh-resolutionaudiofiles.Thesystemhas nowbeenportedtotheBBBfromitsearlierincarnationasRaspyFi. Essentially,VolumioleveragesaLinuxmusicservercalledMusicPlayerDaemon (MPD).MPDprovidesaclientenvironmentwithaweb-centricGUI(sansplugins)anda robustnetworkingarchitecturetoserveyouraudiofiles. OneofthemanyappealingaspectsofVolumioisthatitis(nearly)file-agnostic,soyou canplayvirtuallyanyaudiofiletypewithintheenvironment.Fornow,thisincludes FLAC,WAV,MP3,AAC,ALAC,M4A,andplaylist(PLS)files. EachnewversionofVolumioseemstoleapforwardinstabilityandeaseofuse.However, itdoescomewithcaveatsasnoopensourcetoolisever“finished.”Volumio,insome respects,typifiesthepleasuresandperilsofopensourcetoolsandbendingthemtoyour willonmicrocomputers.There’snooutoftheboxperfection.Someoftherecipesinthis chapteruseanumberof“prepackaged”toolsetstogetyouwhereyouwanttobefaster, andVolumioisstill,technically,abetarelease. Forexample,otherthanaperfunctorysettingupandinstallingprocedure,developersdo nothaveanicehandysetofobviousinstructions.Instead,youhavetospendafairamount oftimeperusingtheirforum(volumio.org/forum/)tofindanswerstocommonquestions. Examplesinclude:howdoISSHintoVolumio?What’sthepasswordforremotelogin? HowdoIaddanewinternetradiostation?Whyismyexternalharddrive,whichischockfullwithmusicfiles,notrecognizedbyVolumio?HowdoIgracefullyshutdownmyBBB ifVolumiocrashes?Theseareburningquestions,indeed.Thankfully,youboughtthis book,sotheanswerstothesequestionsarerighthere. Gettingready TogetVolumioupandrunning,youneedthefollowing: AUSB-poweredhub:AsweneedseveralUSBdevicestogetthesystemoperating reliably,youwillneedtoaddapoweredhubtoyourconfiguration. Akeyboard:PlugoneintotheUSBhub.Wewilluseitforterminalaccessincase weloseorcannotgetaremoteSSHsessionandwanttodoagracefulshutdownof thesystem.However,weonlyneedittemporarilyandcandisconnectitlater. AnLCDMonitor:YouneedoneofthesepluggedintotheHDMIport.Aswiththe keyboard,themonitorisonlynecessaryforfirstbootandsystemtweaking. Connectivity:WewillfirstuseanEthernetcablepluggedintotheBBBforsetup. Afterwe’vegotaconfirmedpingandstablesetup,wewillremovethecableanduse aUSBWi-Fidongleinourpoweredhubtoestablishawirelessenvironment. Audioout:Foroutputaudiointhisrecipe,youcanusethreedifferentmethods— easy,intermediate,oradvanced,whichareasfollows: Easymethod—theUSBaudiodongle:Therearenumerousflavorsofthese devicesinthewild.Unlessyoufeelcompelledtouseanexpensiveone,theycan bepurchasedcheaply;thekindpicturedatthebeginningofthischaptercamefor roughlyUSD$10.00.Youshoulduseapoweredhubtosupplypowertothe dongleinsteadofthroughtheBBB’sUSBport. Intermediatemethod—theRevBaudiocape:Althoughslightlymore complex,usingtheaudiocapethatwealreadyusedinChapter4,Exploring GNU/LinuxRecipesUsingBash,Autotools,Debugger,andsystemd,isamore robustandelegantsetupthanusingtheUSBaudiodongle.Refertothesame chapterforcapesetupandaudiotesting. Advancedmethod—thePCBaudioamplifier(daughterboard):Ifyouwere withusintheprevioussection,wejustdidarecipewiththis,andnow,wecan useitforreal.Refertotherecipementionedbeforetosetupthisconfiguration, includingtheimagesandtheFritzingdiagram. Note Foraudiophiles,oneoftheattractivefeaturesofVolumioisthatitsupportstheuseof DACboxes.Althoughsexy,useful,andpowerful,DACboxescanbequite expensive.Wedon’thaveone,sowe’renotincludingthehookupmethodologyin thisrecipe.AtVolumio’ssupportforum(http://volumio.org/forum/),youwillfind amplediscussionaroundusingDACboxes. Speakers:Connectthespeakersthatyouusedinthepriorrecipeorusetheaudioout jackonaUSBaudiodongle. Speakercable:Youcanusemonoorstereojacks Mediastorage:Audiofilescanbeservedfromavarietyofstoragedevices,suchas USB,NAS,andsoon.Sincewehaditonhand,weusedapoweredUSBharddrive. Howtodoit… Nowthatyou’reready,let’sbegin: 1. StartbydownloadingtheVolumioBeagleBoneBlackdiskimageonyourclient machine(notyourBBB).Thecurrentversionisavailableathttp://volumio.org/getstarted/. Followingthedownload,extractthedownloadedarchive.Youshouldendupwitha .imgfileonyourlocalbox. 2. InsertanSDcardreaderwithaminimum4GBmicroSDcardinstalled.AsVolumio claimstorequireaveryminimalinstall(piggybackingonDebianWheezy),youmay beabletogetawaywithasmalleramountofstoragethan4GB. 3. Flashthe.imgfiletoyourSDcard.AsweareusingaMacbox,wewilluseour trustytool,PiFiller,whichweusedandexplainedinpriorchapters.OnaWindows box,youcanuseWin32DiskImager. 4. ConfirmthatyouhaveadequatestorageremainingonyourSDcard.Todothis,run thecheckfromaterminalwindowonyourclientmachinewiththefollowing command: $df-ah Youroutputshouldshowsomewherearound22percentcapacityused. 5. FromtheprecedingGettingreadysection,youshouldhavealltherequiredhardware connected.RemovetheSDcardfromyourclientmachine,insertitintheBBB,and boot. Ihaveseensomeflakyperformancesonfirstboot,soyoumayneedtorebootagain togettheloginscreentoappear.IfyouhaveusedVolumioonRaspberryPi,youwill findbootingupontheBBBconsiderablyfaster. 6. Younowneedtosetupterminalaccess,firstdirectlyontheBBBandthenremotely. Technically,neitherisarequirementtorunVolumioasthere’salovelyweb-based GUItocontrolthetool;we’llgettothatnext.However,youwillinevitablyneedto troubleshootvariousissues,andterminalaccessisreallythebestwaytodoso.So, firsttypethefollowingcommandontheBBB: #user:root pw:Volumio Youshouldnowseethefollowingscreenoutput;dateandversionmayvary,of course: 7. Now,repeattheprevioussteponyourclientdesktopboxforSSHaccesswiththe sameuser(root)andpassword(volumio)credentials: [email protected] IfyouhaveanyproblemslogginginandyouareonyourownlocalLAN,youcan alsodothefollowing: [email protected] 8. Checkthatyouhaveasolidinternetconnection(fromeitheryourSSHremote sessionordirectlyontheBBB)bytypingin: #pingwww.google.com Yourscreenoutputshouldshowstablepingresponses.Ifitdoesnot,youmayneedto rebootandrepeatsteps7through10. Toquitthepingcommand,remembertopressCtrl+Conyourkeyboard. 9. Wearenotquitereadytoplayyourfabulousmusiclibrary,butwecandoatesttoget aquickfeel-goodhit.So,openupabrowseronyourdesktopclientandtypeinthe address,http://volumio.local. Voila!AfancyGUIwithallkindsofknobs,buttons,andslidersappears! Tip OneoftheappealingthingsaboutVolumioisthatitsmaincontrollerisaweb-based opensourceUIandnotabloatedproprietarypieceofsoftware.Thismeansthatwith atouchofHTMLandadashofjQuery,youcanmodyourowncontrollerUI. 10. IntheGUI,clickonBrowse|WEBRADIO.Youwillseealistofstreamingradio stationsthatcamepreloadedwiththeinstall.Let’schooseonethathasareliably consistentstreamingURL:“theBeeb”,whichisalsoknownasBBCWorldRadio. Afterclickingtwiceonthelink,themellifluoussoundsofaBritishnewscasterwill pourfromyourspeakers. Note YoumayfindthatmanyofthepreloadedWEBRADIOstationshaveoutdatedor nonfunctioninglinks,leadingyoutobelievethatyourinstallationisnotworking properly.However,thisisnotthecase;yousimplyneedtofixorupdatethelinks manually. 11. UnderthePlaybacktab,youwillseeavolumecontrolakintoaniPod’s“click wheel.”Fiddlewithitabit,andyouwillnoticethatthevolumeleveloftheoutput doesn’tchange.Frustrating,right?Thismeansthatadjustingsoundlevelsrequires anothertweak. 12. IfyouconnectedyoursystemtoDAC,ignorethisstepasyouwillhavehardware controlstoadjustthevolume.Otherwise,gotoMENU|SETTINGS,clickonthe dropdownforVolumeControl,andselectSoftware. 13. Followingthis,rebootusingaterminalcommandorviatheGUIunderneaththe MENU|SYSTEMtab. 14. Oncerebooted,let’spushtherecipeabitfurtherbygrabbingacoupleoffiles remotelyandloadingthemintoVolumio.Wewillusethefamiliarwgetcommand: #wgethttp://hudsonwerks.com/beaglebone-blackrecipes/downloads/volumio-sample-media.tar.gz 15. Untarthearchivedfileswiththefollowingcommand: #tar-zxvfvolumio-sample-media.tar.gz 16. UsethiscommandlinetoputthefilesinthecorrectVolumiodirectory: #mvSpace-Oddity-Hadfield-CLIP.m4a/var/lib/mpd/music/USB Then,runthefollowing: #mvwbgo_jazzFM_NJ.pls/var/lib/mpd/music/WEBRADIO/ 17. Themedialibrarynowneedstobeupdatedtoreflectthenewadditions.So,viathe VolumiowebGUIonyourdesktopclient,gotohttp://volumio.local. 18. Then,navigatetoMENU|LIBRARYandclickontheUPDATELIBRARYbutton. Atthispoint,ifyouhavethemediafromthissimplerecipe,theupdatewilltakeonly afewseconds. 19. It’stimetotestourfiles;wewillbeginbyusingthem4afile.Again,onthewebGUI, gototheBrowse|USBtab.Then,clickonSpace-Oddity-Hadfield-CLIPtwice. YoushouldhearabriefsampleofaremixofDavidBowie’ssong,“MajorTom”, fromthealbum,SpaceOddity.Inthiscase,itwillbesungbyUSastronautChris HadfieldonboardtheInternationalSpaceStation.Itisaremakeofaclassic,butthe astronautdoesagreatjobofit. Note Wewouldhavepreferredusingthewholetrack,butwelimitedthelengthoftheclip toconformtotheFairUselegalrestrictions.Foralongerversionofthesong,the videoisavailableonlineathttps://youtu.be/KaOC9danxNo. 20. Now,let’stestournewlydownloadedwebradiostationplaylist.Ontheweb interface,gotoBrowse|WEBRADIO.Then,clickonwbgo_jazzFM_NJ. 21. Withanearlyfinishedsetup,wecancuttheEthernetcordandrunVolumioviaWiFi.GotoMenu|Networkandinputyournetwork’snameandpasswordinthe appropriatefields.Then,clickonSaveChanges,andVolumiowillresettheweb interface. 22. Next,removetheEthernetcable.Ifyoudonotalreadyhaveitopen,typeinthe Volumioserveraddress,http://volumio.local,againonyourdesktopclient browser. YoushouldbeabletocontrolVolumiofluidlynowwithouttheEthernetconnection. 23. Assumingyouhaveasmartphone,pullitoutandopenupabrowsertothesame addressthatyoujustenteredonyourdesktop:volumio.local. Voila!Youarenowfreedfromthedesktopandhaveremotecontrolofyourmedia libraryfromanysmartphone: AlthoughtheVolumiointerfacecanbeabitcrowdedonsmallsmartphonescreens, youshouldseeatighter,highlyusabledesignontabletclients. 24. Next,weneedtochecktheversionofVolumio.Doingthiswilloutputthecompatible filetypesthatthesoftwarecanplay: #mpd--version Tip Thescreenoutputshouldyieldnotonlytheusualcopyrightboilerplate,butan extensivelistoftheaudiofiletypesthatareplayablewithVolumio.Checkthatyour musiclibrary’sfiletypesareinthelist,particularlyintheverylengthy[ffmpeg] section. 25. Next,youneedtoupdatetheMPDdatabasesothatitcataloguesallfilesonyour attachedstoragedrive.YoucanusetheVolumioGUIforthis;navigatetoMENU| Library|UpdateMDBdatabase.Youcanalsodothesamethingwiththe followingcommandline: #sudoservicempdrestart Dependingonthesizeofyourlibraryandregardlessofthemethodyouuse,the databaseupdatemaytakeawhile.So,getacolddrink,asandwich,orgoforajog—a longone. Ifallwentasplanned,yourmusiclibraryshouldnowbecatalogued.GotoLibrary, selecttheyourUSBmusicdirectory,andverifythateverything’svisible. 26. Wealsohaveapotentialbugfix.DependingonyourversionofVolumio,thisis whereyoumayencountersomequirks.Becauseofalingeringbugintheinthelast fewversionsoftheMPDserverenvironment(whichisnotVolumio’sfault),many filetypescompatiblewithFFMPEGaredisabledbydefault. ThismeansthattheGUI-basedupdateMDBdatabasefunctionthatwejustexecuted maycapturesomeofthemetadataforamusicfile,includingitsname,butnotthe actualmediadataitself.So,let’sfixthisinthecommandlineasfollows: #nano/etc/mpd.conf ScrolldowntotheFFMEG=disablelineandchangedisabletoenable.Following this,savethempd.conffileandcloseit. 27. Now,let’stestourmediafilesviatheGUI;gotoBrowse|USB,selectyouralbumor musictrack,andchooseafavoritemusicfile.(Notethatitdoesn’thavetobeaDavid Bowietrack). Withallthisdone,weareleftwithonethingtodo:turnitupto11! There’smore… Hereissomesupplementaryinformationaboutplaylists,whichyoucanusetoextendthis recipe.Asinmostmusiclibraryenvironments,Volumiousesplaylists(.plsfiles)asa meanstocategorizeororganizeyourmediaintocustomplaysequences.Herearetwo basicmethodsofaddingplayliststoVolumio: Thedraganddropmethod:Withany.plsfilesyoumayhave,simplydragand dropthefileintoyourWEBRADIOfolder. Manualmethod:Youmayhavealreadyfoundthatsomeofthedefaultwebradio stationslisteddon’twork.Thereisagoodchancethattheproblemisnotyourin hardware;it’smorelikelythatthestation’sURLhaschanged,whichisoneofthe vagariesofwebradio.So,youwillneedtotweaktheaddressintheplaylistfile. Here’swhatwedo: 1. Openupa.plsfileinatexteditor.YoucandothisonyourBBBorlocallyon yourmedialibrarydrive.Thedriveisconnectedtotheserverasashareddrive, soyoushouldseeitappearonyourclientboxdesktop.Hereiswhatyoushould seewhenyouopenthefile: [playlist] File1=http://xxx.yyy.zzz:port Title1=stationname Length1=-1 Numberofentries=1 Version=2 2. Wewilltypicallymodifytwoitemsinthisfile.First,wewillusethefollowing commandtomodifythewebradioaddress: File1=http://xxx.yyy.zzz:port Inthisline,inserttheURLofthestreamyouareadding;theportsettingisoptional. Here’sanexample: File1=http:/http://xstream1.somafm.com:8000 Then,wewantthenameofthestationtoappearintheVolumioplayerwhilethe audioisstreaming: Title1=stationname Forexample,ifwewantedtocallourstationSpaceStationSoma,wewouldrunthe followingline: Title1=SpaceStationSoma Seealso ThefollowingaresomekeylinkstogainmoreinformationaboutVolumio,whichalso illustratemanywaystotroubleshootissues: TheveryactiveVolumiosupportforumisavailableathttp://volumio.org/forum/ M4Afilesupportisavailableathttp://volumio.org/forum/m4a-support-t14.html TofixWi-Fidropoff/freezingissues,navigatetohttp://volumio.org/forum/volumiofor-feeback-thread-t781-70.html Usingvideosanddisplaysinprojects It’sonethingtojustpluganHDMImonitorintotheminiHDMIportonyourBBBand getapicture.Inmanycases,thisismaybeallyoucareaboutforaproject.However,for bonafideembeddedormobilescenarioswhereyouneedadisplay,usingtheHDMI optioncanbeoverkill;yourneedsarelowpower,smallformfactor,andjustenough displaytoconveybasicinformation. Inthissection,wewilltakealookattwootheroptionsfordisplay:aminiOLEDdisplay availableasabreadboard-ablePCBandacustomBBBcapedesignedwithaverysmall LCDpanel. HookingupaminiOLED Inthisrecipe,wewilltakealookataverysmall1.3inchOLEDdisplaywitharesolution of128x64pixels.Ithasamonochromescreen,whichmeansthatwewillnotbewatching LawrenceofArabiaonthisdevice.Instead,wewillexploresomemethodsforbasic controlandinputandtakeapreliminarypeekattypicaldesignchoicesforembedded devices. Thenicethingaboutexperimentingwithadevicelikethisisthatwecanmakeuseof anothersetofpinsavailableonBeagleBoneBlack:theSerialPeripheralInterfaceor SPIpins.TheBBBpackstwoSPIports,andwewilluseoneofthese.Someofthe advantagesofthisinterfaceincludehigherthroughoutandlowerpowerconsumptionthan I2C,whichweusedinanearlierrecipeinthischapter. Tip Tobeclear,thisrecipewillnotresultinanalternativedesktopdisplay.Instead,itisthe basisforbuildingamorerobust—albeitconsiderablysmaller—low-powereddisplay optionforyourcustomizedprototypingrequirementsandtests.Todemothescreen,we willrunPythonscriptsastheyareaneasierentréeintothehardware. Gettingready You’llneedthefollowingitems: OLEDPCB:WewillusetheSSD1306driverchipversion,whichisavailable (mostly)preassembledatAdafruithttps://www.adafruit.com/product/938).Theboard requiresonlyaminorsolderingjobtoattachthepinsandcostsaroundUSD$25.00. TheBBB,bothpoweredandremoteSSHcalled,viatheUSBcable:Let’sgo headless…nocheating!There’salsoapracticalreasontoeschewanexternalmonitor inthisrecipe:wewillbedisablingtheHDMIport,soyouwouldlosethesignal anyway. 6xjumperwires Abreadboard Adafruit’sOLEDcomeswithitsowntutorialandPythonexamplescripts.Althoughwe willrelyontheAdafruitPythonBBIOlibrary,wewillactuallyuseanadditionalPython librarydevelopedbyGuyCarpenterandmodifiedbyEthanZoncaalongwithourown customexamplecode. Howtodoit… Nowthatyou’reready,let’sgetstarted: 1. Wireupyourboardandbreadboardinthefollowingmanner: Tobeclear,hereisthehookupintableform: OLEDScreen BBBpin Function GND GND:P9_1 Ground VIN VDD_3V3:P9_3 Power CS CSO:P9_28 Slaveconnector RST GPIO:P9_24 Resetdisplay DC GPIO:P9_16 CLK P9_31 Clock Data P9_30 2. InordertouseSPIpins,weneedtoenableaDeviceTreeoverlay,whichiseasytodo asitisalreadycompiledonthesystemandmostefficienttoloadatbootup.So,first callSSHintoyourBBB,openaterminalwindow,andthenbrowsetothefollowing directory: $cd/boot 3. Now,openthefile,uEnv.txt: $sudonanouEnv.txt 4. Then,addthefollowinglinesattheveryendofthedocument: ##ThislineaddedtoenabledevicetreeoverlayforSPIDEV optargs=capemgr.enable_partno=BB-SPIDEV1 5. Saveandclosethefile,andthenrebootyourBBBasfollows: #reboot 6. Logbackinastherootuserandconfirmthatthe/dev/spidev1.0and /dev/spidev1.1filesarevisible,indicatingthattheSPIdriversareavailablefor access: $sudo-i #ls-l/dev/spidev* Youshouldgetanoutputsimilartothis: crw-rw---T1rootspi153,1Mar120:46/dev/spidev1.0 crw-rw---T1rootspi153,0Mar120:46/dev/spidev1.1 7. Next,weneedtoinstallanumberofPythonlibrariesandtheirdependencies.Some ofthemmayalreadybeavailableonyoursystem,butrunthefollowingcommands justtobecertain: #apt-getupdate #apt-getinstallbuild-essentialpython-devpython-pippython-imaging python-smbuspython-dateutil #pipinstallspidev #pipinstallpil #pipinstallAdafruit_BBIO Note Youcouldrunallthepipinstallcommandsoffoneline;however,forclarity’ssake, wewillshoweachindividualpackageinstall. 8. Next,wewanttoactuallydosomethingwiththedisplayandalltheselibraries.So, downloadaGitHubrepowithsamplecode: #gitclonehttps://github.com/HudsonWerks/OLED-SSD1306.git 9. Browsetoasubdirectoryofexampleinthedirectoryofcodewejustdownloadedand takealookatwhatisinside: #/OLED-SSD1306/samples #ls 10. Beforelookingatwhatisinsidethecode,let’srunthemainexampletoseeifallof thehardwarewiringiscorrect: #pythonoled-test1.py Ifallwentwell,youwillseetextcyclingonthescreenwithmessagesfromground control. 11. WewanttotakeabrieflookatthePythoncode,sowewillnowrunthefollowing command: #nanooled-test1.py 12. Finally,openuptheCloud9IDE(http://192.168.7.2:3000/ide.html),createa new.pyfilecalledoled-test1.py,andthencopyandpastethecodefromyournano windowintotheIDEfilewindow.Fromhere,youcanbegincustomizingthecode, startingwiththemessagesdisplayedonthescreen. 13. Onceappended,savethefileandclickontheRUNbuttonintheIDE.Anupdated scrollingtextmessagewillappearonyourOLEDdisplay. Note BeforerunningaPythonscriptintheCloud9IDE,remembertosavethedocumenteach time.Otherwise,theIDEmayrunacachedversionthatdoesnotcontainyournew changes. There’smore… Thefollowingissomesupportinginformation: YoucandigdeeperintothenuancesofmodifyingtheSPIdevpinsat http://elinux.org/BeagleBone_Black_Enable_SPIDEV Youcanalsoexperimentwithpy-gaugette,aPythonalternativetotheAdafruit PythonlibrarytocontrolSPI(andotherGPIOpins),includingathorough explanationofusinghigher-qualityfontswiththedisplayat http://guy.carpenter.id.au/gaugette/2014/01/28/spi-ssd1306-oled-for-beagleboneblack/ TestingaminiLCDcape Inthissection,wewillcookupanintroductoryrecipetousetheminiLCDdisplaycape designedbyCircuitCo. Withamere1.8inchesofscreenterritory,youmightwonderwhatkindofscenarios wouldberelevantforanadd-onsuchasthis.Youmightalsothinkthatthedesignisabit oddasthePCBboardspacedwarfstheactualscreensize.Keepinmindacoupleof things,though,whendecidingtopurchasethecapeandtestingit: TheBBBisanembeddedcomputing-centricdevelopmentenvironment,notdesktopcentricasRPiis.Assuch,anadd-onsimilartothisminidisplaycapeaddressesthe needsoftypicalusecasesforanembeddeddevice.Thesearesituationsthat commonlyrequireextremelylowpowerandminimaldisplay,ifany. Theneedforfastprototyping,durability,andtestingdrivethedesignofacapesuch asthisresultsinanoverallformfactormuchlargerthanthescreenitself.Looking morecloselyatthecape,wediscoveranumberofexcitingthings: Opensourcedesign:Thecapedesignanditscomponentsareallopensourced, withthecoreelement—thedisplayitself—referencedandclearlysourcedso thatyoucanmakeyourownmodsonceyou’vegotyourprototypedeviceready toflyoramble.Herearethedesignfilesandschematic (http://elinux.org/CircuitCo:MiniDisplay_Cape)andthecomponentvendor’s URLforthedisplay (https://www.crystalfontz.com/product/CFAF128128B0145T). Lowcost:Attheprecedingreferencedsource,youwillseethatinahighquantitypurchaseofthedisplay(notthefinishedcape),thepricedramatically dropsperunit.So,youcanmodelalow-costscenarioformultiplefinal productionunitsofyourdevicewithoutincurringthefinishinganddesigncosts ofathird-partysupplier,suchasCircuitCo. Gettingready Inthisrecipe,wewillcookabitmoreprofessionallysothatourenvironmentlooksmore likeatrueembeddeddevice.Thus,ourkitisminimal: AminiLCDcape:Resolution128x128(purchasedfrom http://boardzoo.com/index.phpforaround$USD30.00). Let’sgoheadlessagainandwireless,whichmeanswewillneedthefollowing: AUSBcable:WewilljustpowerupviaaminiUSBcable. AWi-Fidongle:InsertthisdirectlyintotheEthernetportonyourBBB.Remote SSHcallingsansanannoyingEthernetcableisthegoal.Althoughmanyusers wouldsuggestyoutonotuseadonglewithoutapoweredUSB,mytestshave deliveredstableconnectivitywithoutanyexternalhub,makingthewholerecipe andsetupmuchcleaner. Tip NotethatthiscodeisavariationofProfessorMarkYoder’scode (https://github.com/MarkAYoder/BeagleBoard-exercises/tree/master/miniDisplay),which is,inturn,amodificationoftheCircuitCoexamplecode (http://elinux.org/images/e/e4/Minidisplay-example.tar.gz). Howtodoit… Witheverythingprepared,whatareyouwaitingfor? 1. First,carefullyinsertthecapeintotheheaderpinslotsontheBBB.Asthecape boardhasarecessedsidetoaccommodatetheBBB’sEthernetport,itisdifficultto gettheorientationwrong: Thecapefullyinsertedintothepins. Tip Youmaybealittletentativegettingthepinsfootedproperlyasthepinsareavery tightfit.Onceinserted,removingthecapeisabittrickyduetothesnugness,soit’s besttoeaseitoutslowlyfromtheboardheaders. 2. Withthecapefullyinserted,powerupyourBBBviaUSB. YouthenneedtologinviaSSHandthenasroot,withthefollowingcode: debian@beaglebone:~$sudo-i root@beaglebone:~# 3. Nowthatyou’reloggedinandready,youneedtodownloadandcompilesome samplecodeforthedisplay.Thiscodeisaslightmodificationofanopensource archivedversion: #wgethttps://github.com/HudsonWerks/minidisplay-cape.git 4. Finally,navigatetothenewdirectorycreatedandcompilethetestapplication: #cdminidisplay-cape #make 5. ThecapewillneedaDeviceTreeOverlay;however,beforewetakeactiononthis, let’stakealookatwhatcapemanagershowsusaboutwhatiscurrentlyloadedusing thefollowingcommand: #cat/sys/devices/bone_capemgr.*/slots 0:54:PF--- 1:55:PF--- 2:56:PF--- 3:57:PF--- 4:ff:P-O-LBone-LT-eMMC-2G,00A0,TexasInstrument,BB-BONE-EMMC-2G 5:ff:P-O-LBone-Black-HDMI,00A0,TexasInstrument,BB-BONELT-HDMI 6. Next,wewillrunthefollowingcommandtoloadDeviceTreesothatthecapeis recognized.ThisismadeconsiderablyeasierwiththeinclusionofuniversalDevice TreeOverlaywiththelatestversionsoftheBBBfirmware: #config-pinoverlayBB-SPIDEV0 7. Checkthattheoverlayloadedasexpectedbyexecutingthefollowingcommand: #cat/sys/devices/bone_capemgr.*/slots Youroutputshouldlooksimilartothiswiththelastitemintheslot listyourloadedoverlay: 0:54:PF--- 1:55:PF--- 2:56:PF--- 3:57:PF--- 4:ff:P-O-LBone-LT-eMMC-2G,00A0,TexasInstrument,BB-BONE-EMMC-2G 5:ff:P-O-LBone-Black-HDMI,00A0,TexasInstrument,BB-BONELT-HDMI 7:ff:P-O-LOverrideBoardName,00A0,OverrideManuf,BB-SPIDEV0 8. Now,runthetestapplication: #./minidisplay-test Ifallgoesasplanned,thedisplaywillbeginwithacolorbartestscreenandthenendwith animageshowingMajorTom’sviewofEarthfromtheInternationalSpaceStation (ISS). Makingavideochatclientprototype usingLinphone Inthisrecipe,wewillfirstcompileandinstallLinphone,awell-knownopensourcechat client,withtheassumptionthatwe’llusebothaudioandvideo.Aftercompilingand running,wewilltestandoptimizethepackage. Gettingready Sincewewillrunamorepowerintensive,graphics-andGUI-centricenvironmentforthe nextseveralrecipes,youwillneedtosetupyourBeagleBoneBlackboardaccordingly: LCD:AttachanHDMILCDtothemicroHDMIportoranLCDcapeifyouhave one.Aswewillberunninganx-session,headlessisnotpossible. ApoweredUSBhub:Wewilluseabushelofperipherals,soplugthepoweredhub intotheUSBportandmaketheBBBhappy. Keyboardandmouse:ThepackageswewillinstalldonotlikeVNCsessions,so youwillneedtoincludeaUSBkeyboardandmouseinyourpoweredUSBhub. USBwebcam:Aswearedoingvideochatsessions,wehavetohaveacameraand microphone;aUSBwebcamisthefastestoption. Howtodoit… Onceready,it’stimetobegintherecipe.Pleasenotethatthisissplitintotwoparts,and youneedtocompletetheminorder.Theobjectiveistofirstgothroughtheprocessof installingapre-compiledversionofthesoftware.Then,basedonthatoutcome,seehow wecanimprovethefunctionalityofthetoolbycompilingitfromsourcefiles. PartI–compilingandinstallingaLinphonebinaryfromtherepository Tobeginthisrecipe,youwillfirstlyneedtocompileandinstalltheLinphonebinaryfrom therepositoryasfollows: 1. InstallingLinphone:Thisistheeasypart;youcanactuallyinstalltheLinphone binaryviaapt-get,asfollows: $sudoapt-getupdate $sudoapt-getinstalllinphone Withthis,you’llendupwiththelatestprecompiledbinaryofLinphoneonyour BBB.So,let’schecktheversionthatwegetusingthefollowingcommand: $dpkg-plinphone Takenoteoftheversionfromthescreenoutputaswewillrefertoitlater. 2. SettingupanSIPaccount:OpenuptheapplicationunderInternet|Linphone.You willbegreetedwithaGUI-basedwizard,whichincludessettingupanSIPtelephone numberontheapplication.SIPisasignalingprotocolthatworkswithVoiceOverIP (VOIP)telecommunications.NumerousfreeSIPserversareavailable(justGoogle “freeSIPaccount”).Here,wewillmakeiteasyandusethefreeoneofferedby Linphone.org,thedevelopersofthetool. 3. Doingadesktopinstall:Wealsowanttoinstallthebinaryonyourdesktopclientso thatwecantestatwo-waycallconnectionwiththeBBB.Downloadablebinariesfor otherplatforms(MacorWindowsversions)areavailableat http://www.linphone.org/technical-corner/linphone/downloads.Followtheonscreen wizardtosetupanaccountasyoujustdidinthepreviousstep. 4. Makingavideocall:Onceyou’veauthenticatedyournewSIPtelephonenumber andconfiguredyouraccountonLinphone,youcanmakeavideocall. Youprobablyranintoproblemswhilerunningtheapplication.Diditrunslowly?Didit takeupmostofyourCPU’sresources?Couldyoumakeaconnectiontothedesktopclient andrunavideochatsession?WhenitcomestoCPUhogs,suchasvideoandaudio,the BBBdoesnotshine.However,wehaveaplanforthis;thus,takealookatthenextpartof thisrecipe. PartII–compilingandinstallingLinphonefromsource Now,wewillcompileandinstallLinphonefromsourcetonotehowthetwoversions compare. Gettingready Ifyoucompletedthefirstpartofthisrecipe,uninstalltheprebuiltbinaryofLinphone beforecreatinganewoneandinstallingitfromsource.So,removeitcompletelyby running: ~$sudodpkg--purgelinphone Howtodoit… Let’sgettoit: 1. Beginbyupdatingandupgradingyourpackagesandthensetupadirectorytokeep thesourcefileswiththefollowingcommands: $sudoapt-getupdate&&sudoapt-getupgrade $mkdirpackages $cdpackages Tobesurewehavecertainbasicpackages,installthefollowing: $sudoapt-getinstallautomakeautoconfgnu-standardsgettextbuildessentialpkg-configgitlibtoolantlr3libantlr3c-devintltool 2. Next,wewillgettheessentialpackagesbyexecutingthefollowingcommands: $gitclonegit://git.linphone.org/polarssl $gitclonegit://git.linphone.org/belle-sip $gitclonegit://git.linphone.org/linphone--recursive 3. Then,wewillinstallthelatestOracleJDK.Thisisatrickybutnecessarysetofsteps becauseanotherpackagethatweneedtocompile—antlr—isdependentonthe correctinstallationoftheJDK. 4. Tostart,weshouldfirstlookattheversionoftheJDKthatcomespreloadedonthe currentDebianBBBdistribution(notethatyourversionmayvary).Thefollowing commandwillbeusefulforthis: $java-version javaversion"1.6.0_32" Theoutputshouldlooksomethingsimilartothis: OpenJDKRuntimeEnvironment(IcedTea61.13.4)(6b32-1.13.4-1~deb7u1) OpenJDKZeroVM(build23.25-b01,mixedmode) 5. Let’smovealongtoinstallingthenewSDK.Todothis,wewillswitchfrompure commandlineinteractionovertotheBBB’sdesktopGUI.OpenuptheChromeweb browserinyourapplicationsmenuinthelower-leftcorner.Browsethefollowing OraclesiteanddownloadthecurrentJDKforARMdevices,thehardfloatversion, intoyour/homedirectory.Youwillneedtoagreetothelicensingtermstogetthefile, whichiswhywecannotusewgetorgittograbthefile: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-arm-downloads2187472.html Tip Whentryingtodownloadviayourbrowser,youmayencountertheerror,Failed. Insufficientpermissions.ThistellsusthatwhenusingtheGUI’sfilebrowser window,wedonothavewriteprivilegestothe/homedirectorybydefault.Change permissionsthisway: $sudochown<user>/home Afterrunningthiscommand,youshouldnolongerhaveread/writeproblems,and youwillbeabletodownloadtheJavaarchivewithouterror. 6. Withthepermissionstoaccessthefile,gotoyour/home/userdirectoryasfollows: $cd/home/user Youshouldseethe.gzfilethere. Forasanitycheck,wewillconfirmthatweareintherightdirectorywiththeoutput asfollows: $pwd /home/user Tip Asareminder,userwilllikelybedebian,unlessyouchangeittoanothername. Wecanthenconfirmthatourdownloadedfileisintherightplace: $ls Desktopbinjdk-0a0-linux-arm-vfp-hflt.tar.gzpackages 7. YouthenneedtounpacktheJavaTARfileinyour/homedirectorywithTAR.Note thatyoushouldbesuretoreplacetheproperfilenameofthecurrentversion availablewiththefollowingXXfilenames: /home$tar-zxvfjdk-8uXX-linux-arm-vfp-hflt.tar.gz WecanverifythatouruntarcommanddiditsjobandcreatedthenewJavadirectory using: $ls Desktopbinjdk-8u6-linux-arm-vfp-hflt.tar.gzjdk1.8.0_XXpackages 8. Next,wesetupPATHandJAVA_HOMEsothatthecompiledLinphonebinarywillknow wheretofindtheworkingdirectoryforJava.WewilldothisbyaddingPATH informationtothe.bashrcfile: $sudonano~/.bashrc 9. Intheopennanowindowandattheendofthefile,pastethefollowing: exportPATH="/home/debian/jdk1.8.0_07/bin:$PATH" exportJAVA_HOME="/home/debian/jdk1.8.0_07" Note Reminder! Here,/debianistheusernameandmaybedifferentinyourcasebasedonanyearlier changesyoumayhavemade;theJDKversionshownhereshouldbereplacedwith theversionthatyoudownloadedandunarchivedearlier. YoushouldthensaveandclosethefilebypressingCtrl+X;whenprompted,typeY foryes,andthenpressthereturnkey(Enter). Followingthis,rebootyourBBB. 10. Intheterminal,confirmthattheversionoftheSDKyoujustinstalledisnowbeing referencedproperlythroughthefollowingcommand: $java-version Crossyourfingers,andyouwillseeanoutputsimilartothis: Javaversion"x.y.z_00" Java(TM)SERuntimeEnvironment(buildx.y.z_00-xyx) JavaHotSpot(TM)ClientVM(build00.0-xyz,mixedmode) Ifso,hurray!Wecanmoveon!Ifnot,youneedtorepeattheprecedingstepsto installtheJDK. 11. Next,weneedtoinstallthebelle-sipandlinphonedependencies,asfollows: $sudoaptitudeinstalllibswscale-devlibavcodec-devlibv4l-dev libglew1.6-devlibxml2-devlibgsm1-devlibsqlite3-devlibupnp-dev libsdl1.2-dev 12. Thisnextstepisnotdifficult,butitwillslowdowntherecipeasweneedtobothget anotherlibrary(libvpx)andcompileitfromsourcefiles.Thislibrary,whichweget fromGoogle,installsaneon-optimizedversionoflibvpx(anHTTPandwebfile managementlibrary).Usethefollowingcommandforthis: $gitclonehttps://chromium.googlesource.com/webm/libvpx-bv1.3.0 Youcanthenchangethedirectoryvia: $cdlibvpx 13. Followingthis,runconfigurewiththefollowingoptions: $CC=ccAR=arAS=asLD=gccCXX=g++./configure--enable-vp8-target=armv7-linux-gcc--disable-examples--disable-docs--enableerror-concealment--enable-realtime-only--enable-spatial-resampling-enable-multithread--disable-vp9--enable-pic 14. Now,runmakewiththefollowingoptionandthenruninstall.Thesetwo commandswilltakeseveralminutestocomplete: $make-j2 $sudomakeinstall 15. Now,wewillgoafteranaudiocodecknowntoefficientlydeliverhigh-qualityaudio, calledspeex.WewillcompileitwithNEONoptimizationsenabled.Gotoyour packagesdirectoryandthenrungitclone,asfollows: $cdpackages $gitclonegit://git.linphone.org/speex Changethedirectoryandbeginthecompileprocessbyrunningthefollowing command: $cdspeex&&./autogen.sh Youthenneedtorunconfigurewiththefollowingoptions: $./configure--enable-armv7neon-asm--with-pic--enable-fixed-point-disable-oggtestCFLAGS="-mfpu=neon"--disable-ogg Now,goaheadwiththefollowingoptionandrunmakeinstall.Youwillnotethat youcancombinethesetwocommandswiththedoubleampersand(&&): $make-j2&&sudomakeinstall 16. Next,compileandinstallbelle-sipasfollows: $cdpackages/belle-sip $./autogen.sh $./configure $make&&sudomakeinstall 17. Then,compileandinstalllinphoneusingthefollowingcommand: $./autogen.sh $./configure--disable-x11--enable-gtk_ui=no--disable-xv--enablesdl $makeV=1CFLAGS="-Wno-error"&&sudomakeinstall Note Weusedthewno-errorflagherebecausethemediastreamerdependencywould otherwisekeepalertingusaboutunusedfunctions. 18. Weneedtorelinkwith: $exportLD_LIBRARY_PATH=/usr/local/lib Youcanverifythatlinphonepassesthetestsvia: $cdtester&&./liblinphone_tester 19. Wearenearlyfinished.Wewillnowsetupthevideooutputbyforcingthevideo displaytouseaSimpleDirectMediaLayer(SDL)output,whichwilloptimize videoplayback.Wewilldothisbylaunchingacommand-linetoolthatcomeswith Linphone,calledlinphonec: $linphonec Attheprompt,typethefollowing: >quit 20. Simplyexecutingthiscommandtransparentlygeneratesafilecalledlinphonerc, whichwenowneedtoeditasfollows: $sudonano~/.linphonerc 21. Withthisfilewindowopen,findthe[video]sectionandtypeorreplacethe followingattheendofthesection: displaytype=MSVideoOut 22. WearenowreadytolaunchLinphone.Whenyoulaunchtheapplicationforthefirst time,youmayencounterthefollowingerrororsomethingsimilar: liblinphone.so.6:cannotopensharedobjectfile Ifso,youneedtoresetthelocationoftheLinphonelibrariesastheerrorindicates thatyouhaveinstalledthepackageina“nonstandard”directoryonyourBeagleBone Blackboard. 23. ThiscommandwillhelpLinphonerelinkthesharedlibrarylocation: $exportLD_LIBRARY_PATH=_the_path_to_your_linphone_libs 24. YoucannowlaunchLinphonefromitscommand-linetoolasfollows: $linphonec Intheterminalwindow,Linphonewilllaunchandallowyoutoconfigurethesettings inthenexttwosteps. 25. SettingupanSIPaccount:UnliketheGUI-basedwizardthatyouexperiencedwith theinitialprepackagedinstall,settingupandregisteringisabitmoreminimal.As youhavealreadyregisteredanSIPaccount,youcanjustregisteryourSIPaddress withthefollowingcommand: >linphone/register<sip-address><sipdomain><password> 26. Makingavideocall:Totestyourconnection,makeacalltoyourclientbox,which shouldalreadyhaveaninstalledandregisteredversionofLinphonefromthefirst partofthisrecipe: >linphone/call<sip-address-of-client-box> Welldone!It’snotaneasyinstall,butit’sagood,intermediaterecipethatyieldsarobust, sophisticatedtoolrunningonyourBBB. Chapter8.TheInternetofThings Inthischapter,wewillcoverthefollowingrecipes: Location-basedrecipes–hookingupGPS Location-basedrecipes–BluetoothLEandBeacons UsingsensorsanddatawithThingSpeak Makingthingssmarter–buildingawirelessdigitalpictureframe Introduction TheInternetofThingsisalargebasketfulofthings.Itisinfactsolargethatnoonecan seeitsedgesyet.Itisanevolvingandquicklyexpandingrepoofproducts,concepts, fledglingbusinessventures,prototypes,middleware,ersatzsystems,andhardware. SomedefineIoTasconnectingthingsthatarenotnormallyconnected,thusmakingthem abitmoreusefulthantheywereasunconnecteddevices. WewillnotshowyouhowtoturnoffthelightsinyourhouseusingtheBBB,orhowto autoraisethegaragedoorwhenyoudriveontoyourstreet.Thereareabunchoftutorials thatdothatalready.Instead,wewilltakealookatsomeoftherecipesthatprovidesome fundamentalelementsforbuildingIoT-centricprototypesordemos. Location-basedrecipes–hookingupGPS AcommonquestionintheIoTrealm:whereisthatdarnthing?ThatInternetofThings thing?Beingabletotrackandpinpointthelocationofadeviceisoneofthemosttypical featuresofmanyIoTusecases.So,wewillfirsttakealookatarecipeonhowtouse everyone’sfavoritelocationtech:GPS.Then,wewillexploreoneofthenewer innovationsthathasspunoutofBluetooth4.0,beacons,atechnologyforcapturingmore preciselocation-baseddatathanGPS. TheUARTbackground Inthegalaxyofembeddedsystems,developersusedozensofdifferentserialprotocols. MorecommonandfamiliartomostconsumersarecomponentssuchasUSBandEthernet. Then,thereareprotocolsfamiliartoengineers,suchasSPIandI2C,whichwehave alreadyexploredinthisbook.Forthisrecipe,wewilluseyetanotherflavorofserial, UART,anasynchronousorclock-lessprotocol.Thiscomesinhandyinavarietyof scenariostoconnectIoT-centricdevices. Universalasynchronousreceiver/transmitter(UART)isacommoncircuitblockused formanagingserialdataandhardware.AsUARTdoesnotrequireaclocksignal,ituses fewerwiresandpins.Infact,UARTusesonlytwoserialwires:RXtoreceivepacketsand TXtotransmitthem. TheframeworkforthisrecipecomesfromAdaFruit’stutorialfortheRPi.However,the differencebetweenthesetwoboardsarenontrivial,sothisrecipeneedsquiteafewmore ingredientsthantheRPiversion. Gettingready Youwillneedthefollowingcomponentsforthisrecipe: GPSPCB:Youcanprobablyfindcheaperversions,butwewilluseAdaFruit’swellregardedandubiquitousPCB(http://www.adafruit.com/product/746ataroundUSD $40.00). Antenna:Again,Adafruit’ssuggestedSMAtotheuFLadapterantennaisthe simplestandcheapatUSD$3.00(https://www.adafruit.com/product/851) 5Vpower:Poweringviathe5VDCinlieuofsimplyconnectingviatheminiUSBis advisable.TheGPSmodulesconsumeagoodbitofpower,afactapparenttoallof us,givenhowtheGPSfunctionalityisawell-knowndrainonoursmartphones. InternetconnectivityviaWi-FiorEthernet. Breadboard. 4xjumperwires. Howtodoit… FortheGPSsetup,thestepsareasfollows: 1. InsertthePCBpinsintothebreadboardandwirethepinsaccordingtothefollowing fritzingdiagram: P9_11(bluewire):ThisdenotesRXonBBBandTXonGPSPCB.Atfirst,itmay seemconfusingtonotwireTXtoTX,andsoon.However,onceyouunderstandthe pin’sfunction,thelogicisclear:atransmit(TX)pinpairswithapinthatcanreceive data(RX),whereasareceivepinpairswithapinthattransmitsdata. P9_13(greenwire):ThisspecifiesTXonBBBandRXonGPSPCB P9_1:ThisindicatesGND P9_3:Thisspecifies3.3V 2. Now,carefullyattachtheantennatotheboard’suFLconnector. 3. Next,poweryourBBB.Here’swhereitgetsabittricky. WhenyourBBBstarts,youwillimmediatelyseetheFixbuttonontheGPSboard thatwillbegintoflashquickly,approximately1xpersecond.Wewillcomebackto checktheintegrityofthemodule’ssatelliteconnectioninalaterstep. 4. InordertogainaccesstotheUARTpinsontheBBB,wehavetoenablethemusinga DeviceTreeoverlay.Untilrecently,thiswasamultistepprocess.However,nowthat theBeagleBoneUniversalI/Opackagecomespreloadedonthecurrentversionsof thefirmware,enablingthepins(inthecase,UART4)inasnap.Let’sbeginby logginginasrootwiththefollowingcommand: $sudo-i 5. Then,runtherelevantUniversalI/Ocommandandcheckwhetheritwenttotheright place,asshowninthefollowingcode: #config-pinoverlayBB-UART4 #cat/sys/devices/bone_capemgr.*/slots 6. Now,rebootyourBBBandcheckwhetherthedeviceispresentinthedevicelistby usingthefollowingcommand: $ls-l/dev/ttyO* crw-rw----1roottty247,0Mar120:46/dev/ttyO0 crw-rw---T1rootdialout247,4Jul1302:12/dev/ttyO4 7. Finally,checkwhetheritisloadingproperlywiththefollowingcommand: $dmesg Thisishowtheoutputshouldlook: [188.335168]bone-capemgrbone_capemgr.9:part_number'BB-UART4', version'N/A' [188.335235]bone-capemgrbone_capemgr.9:slot#7:genericoverride [188.335250]bone-capemgrbone_capemgr.9:bone:Usingoverrideeeprom dataatslot7 [188.335266]bone-capemgrbone_capemgr.9:slot#7:'OverrideBoard Name,00A0,OverrideManuf,BB-UART4' [188.335355]bone-capemgrbone_capemgr.9:slot#7:Requestingpart number/versionbased'BB-UART4-00A0.dtbo [188.335370]bone-capemgrbone_capemgr.9:slot#7:Requesting firmware'BB-UART4-00A0.dtbo'forboard-name'OverrideBoardName', version'00A0' [188.335400]bone-capemgrbone_capemgr.9:slot#7:dtbo'BB-UART400A0.dtbo'loaded;convertingtolivetree [188.335673]bone-capemgrbone_capemgr.9:slot#7:#2overlays [188.343353]481a8000.serial:ttyO4atMMIO0x481a8000(irq=45)is aOMAPUART4 [188.343792]bone-capemgrbone_capemgr.9:slot#7:Applied#2 overlays. Note TipstogetaGPSFix YourbestmethodtogettheGPSmoduleconnectedistotakeitoutdoors.However, asthisisnotalikelyoptionwhenyoudevelopaproject,puttingitagainstoreven justoutsideawindowwilloftensuffice.Ifitiscloudy,andifyoudon’thavea reasonablyclearskyviewfromyourmodule’santenna,donotexpectaquick connection.Bepatient.Whenafixismade,theflashingLEDwillcycleveryslowly atabout15-secondintervals. EvenifGPSmodulesdonothaveafix,beawarethattheywillstillsenddata.This canbeconfusingbecauseyoumayrunsomeofthefollowingcommandsandthink thatyourconnectionisfine,butyoujustkeepgettingjunk(blank)data.However,to reiterate,theflashingLEDneedstohavesloweddownto15-secondintervalsto verifythatyouhaveafix. 8. Althoughtheoutputisnotpretty,thefollowingcommandisausefulfirststepin makingsurethatyourdevicesarehookedupbecauseitwillshowtherawNMEA datacomingoutoftheGPS: $cat/dev/ttyO4 Note NMEA-TheNationalMarineElectronicsAssociations’GPSlanguageprotocol standard. 9. Verifythatyourwiringiscorrectandthatthemoduleisgeneratingdataproperly (irrespectiveofasatellitefix)asfollows: $sudoscreen/dev/ttyO49600 Theoutputshouldimmediatelybeginandlooksomethingsimilartothis: $GPGGA,163356.000,4044.0318,N,07400.1854,W,1,5,2.65,4.0,M,-34.2,M,,*67 $GPGSA,A,3,13,06,10,26,02,,,,,,,,2.82,2.65,0.95*04 $GPRMC,163356.000,A,4044.0318,N,07400.1854,W,2.05,68.70,031214,,,A*46 $GPVTG,68.70,T,,M,2.05,N,3.81,K,A*09 $GPGGA,163357.000,4044.0322,N,07400.1853,W,1,5,2.65,3.7,M,-34.2,M,,*68 $GPGSA,A,3,13,06,10,26,02,,,,,,,, 10. Now,quittheprogramusingoneofthethefollowingmethods: Ctrl+a,enterorcopyandpaste:quitwiththecolontothehighlightedboxatthe bottom,orpressCtrl+a+k+y. InstallingtheGPStoolset 1. Thenextsetofingredientsintherecipeconsistsofinstallingandtestingacommon toolsettoparseGPSonLinux.Asalways,beforeinstallingsomethingnew,itisgood practicetoupdateyourreposwiththefollowingcommand: $sudoapt-getupdate 2. Installthetools,includinggpsd,aservicedaemontomonitoryourGPSreceiver.The packageexposesallthedataonlocation,course,andvelocityontheTCPport2947 ofyourBBBandefficientlyparsestheNMEAtextthatpoursoutoftheGPS receiver,asshowninthefollowingcommand: $sudoapt-getinstallgpsdgpsd-clientspython-gps Fortheprecedingcode,gpsd-clientsinstallssometestclients,andpython-gps installstherequiredPythonlibrarytocommunicatewithgpsdviaPythonscripts. Note Aftertheinstallation,youmayfinditusefultorunmangpsdandreviewthe package’swell-writtenandinformativemanual.Itnotonlyprovidesthedetails aroundwhatyoujustinstalled,butitalsoprovidesthegeneralGPS-relatedcontent. 3. Iftheplanetsorcommunicationsatellitesarealigned,youcanrunthiscommand fromthenewlyinstalledtoolsetandbegintodisplaytheGPSdata: $sudogpsmon/dev/ttyO4 YoushouldseeaterminalGUIthatlookssimilartothefollowingscreenshot: 4. Toquit,pressCtrl+Corenterqandthenreturn(Enter)key. 5. Now,wewilltesttheotherprincipaltoolthatyoujustinstalledwiththefollowing command: $sudocgps-s TheoutputincludesthecurrentdateandtimeinUTC,thelatitudeandlongitude,andthe approximatealtitude. Troubleshooting—Part1 Youmayrunintoproblemshere.Commonly,onafirsttimesetupandrunning,cgpsmay timeout,closebyitself,andleadyoutobelievethatthereisaproblemwithyoursetup.If so,thenextstepscanleadyoubackonthepathtoGPSnirvana: 1. WewillbeginbystoppingalltherunninginstancesofGPS,asshowninthe followingcode: $sudokillallgpsd 2. Now,let’sgetridofanysocketsthatthegpsdcommandsmayhaveleftbehindwith thefollowingcommand: $sudorm/var/run/gpsd.sock Thereisasystemdbugthatwewilltypicallyneedtoaddress. 3. OpenthesystemdGPSDserviceusingthefollowingcommand: $sudonano/lib/systemd/system/gpsd.service 4. Pastethiscommandtothewindowwiththefollowingscript: [Unit] Description=GPS(GlobalPositioningSystem)Daemon Requires=gpsd.socket [Service] ExecStart=/usr/sbin/gpsd-n-N/dev/ttyO4 [Install] Also=gpsd.socket 5. Then,restartthesystemdserviceasfollows: $sudoservicegpsdstart 6. Youshouldnowbeableruneitherofthefollowingservicesagain: $sudogpsmon/dev/ttyO4 Alternatively,youcanrunthefollowingcommand: $sudocgps-s Troubleshooting—Part2 Sometimes,theprecedingfixesdon’tfixit.Hereareseveralmoresuggestionsfor troubleshootingpurposes: 1. SetupacontrolsocketforGPSwiththefollowingcommand: $sudogpsd-N-D3-F/var/run/gpsd.sock Note Theexplanationofthecommand-lineflagsoroptionsareasfollows: -N:ThistellsgpsdtoimmediatelyposttheGPSdata.Althoughthisisusefulfor testingpurposes,itcanalsodrainpower,soleaveitoffifyourusecaseis battery-powered. -F:Thiscreatesacontrolsocketfordeviceadditionandremoval.Theoption requiresavalidpathnameonyourlocalfilesystem,whichiswhyourcommand isappendedwith/var/run/gpsd.sock. 2. Wemayalsoneedtoinstallapackagethatletsusexamineanyportconflictthat couldbeoccurring,asshowninthefollowingcommand: $sudoapt-getinstalllsof 3. Thisinstalledutilitywillopenanddisplaythesystemfiles,includingdiskfiles, namedpipes,networksockets,anddevicesopenedbyalltheprocesses.Thereare multipleusesforthetool.However,weonlywanttodeterminewhethertheGPS moduleisspeakingcorrectlytotheport2947andifthereareanyconflicts.So,we willrunthefollowingcommand: $sudolsof-i:2947 Thisishowtheoutputshouldlook: COMMANDPIDUSERFDTYPEDEVICESIZE/OFFNODENAME systemd1root24uIPv469070t0TCPlocalhost:gpsd (LISTEN) gpsd5960nobody4uIPv469070t0TCPlocalhost:gpsd (LISTEN) 4. YoumayalsowanttocheckwhetheranyinstancesoftheGPSarerunningandthen killthemwiththefollowingcommand: $psaux|grepgps $sudokillallgpsd ForafinalbitofcookingwiththeGPSboard,wewanttorunaPythonscriptanddisplay thedataintidy,parsedoutput.ThecodewasoriginallywrittenfortheRPi,butitis useableontheBBBaswell. 1. Gogetitwiththefollowingcommand: $gitclonehttps://github.com/HudsonWerks/gps-tests.git 2. Now,browsetothenewdirectorythatwejustcreatedandtakealookatthefilethat wewillusewiththefollowingcode: $cdgps-tests $sudonanoGPStest1.py 3. Let’sperusethescriptabittounderstandsomeofitskeyparts: ThescriptrequiresanumberofPythonlibraries: importos fromgpsimport* fromtimeimport* importtime importthreading KeepinmindthatgettingafixandthenobtainingagoodGPSdatacantakeseveral momentsbeforethesystemsettlesintoacomfortableflow,asshowninthefollowing code: #Itmaytakeasecondortwotogetgooddata #printgpsd.fix.latitude,',',gpsd.fix.longitude,'Time: ',gpsd.utc Ifyoufindtheoutputoverwhelming,youcanalwaysmodifytheprintcommandsto simplifythedisplayasfollows: print print'GPSreading' print'----------------------------------------' print'latitude',gpsd.fix.latitude print'longitude',gpsd.fix.longitude print'timeutc',gpsd.utc,'+',gpsd.fix.time print'altitude(m)',gpsd.fix.altitude print'eps',gpsd.fix.eps print'epx',gpsd.fix.epx print'epv',gpsd.fix.epv print'ept',gpsd.fix.ept print'speed(m/s)',gpsd.fix.speed print'climb',gpsd.fix.climb print'track',gpsd.fix.track print'mode',gpsd.fix.mode print print'sats',gpsd.satellites time.sleep(5) 4. Nowclosethescriptandrunthefollowingcommand: $pythonGPStest1.py Inafewseconds,thenicelyformattedGPSdatawillbedisplayedinyourterminal window. There’smore… Sparkfun’stutorialonGPSisdefinitelyworththereadat https://learn.sparkfun.com/tutorials/gps-basics/all ForfurtherGPSDtroubleshooting,referto http://www.catb.org/gpsd/troubleshooting.html Location-basedrecipes–BluetoothLE andBeacons Inthepast,youmayhavehadtheopportunitytouseBluetoothdevicesinyourprojects. However,inallprobability,thatwouldhavebeenanearlierversionofBT,nowcommonly referredtoas“classic”Bluetooth.Beforewejumpintoanactualrecipeonhowtouse thesesmallradiodevices,weshouldtakealookatsomeofthesignificantdifferences betweentheclassicversionofBluetoothandtheBluetoothLowEnergy(BLE)spec becausetheyareverydifferentanimals.Althoughtheyarebothavailableaspartofthe4.0 spec,wewillworkonlywiththeBLEpieceforourrecipe. ClassicBluetooth Withtheclassicversionofthestack,onedevicebasicallyconnectstoanotherdevice,data isexchangedserially,andthedatadoesnotpersist.Forexample,whenyousetupaBT headset,theaudiocomespipingintoyourears,andthedatagoesonafterthethroughput. Furthermore,theconnectiondoesnotrevealorshowanythingaboutwhat’shappeningin themiddleofthatpipewiththedataitself. BluetoothLowEnergy Althoughmorechallengingtoworkwithandstillnascentwithitsdocumentation,BLE (sometimesreferredtoasBluetoothSmart)isafarmorerobustenvironmentformanaging data,particularlyintheworldofIoT.Severalkeyelementsdistinguishitfromitsearlier kin: Centraldeviceversusperipheraldevicerubric:InaBLEecosystem,therewillbe abroadcast(peripheral)devicethatsendsoutdataanda(central)deviceordevices thatreadsfromthisbroadcast.Thedevicerelationshipisanalogoustoacommunity bulletinboardwithabunchofreadersoraclient/serverrelationship.However,in BLE-land,thenormalassumptionsareflipped:theserverisaverylow-powered device,whereastheclientistypicallyamoresophisticateddevice,suchasa smartphone,alaptop,atablet,orotherwirelessdevice. Notone-to-one:BLEallowsmultiplesimultaneousconnectionstothesameserveror peripheraldevice. Lowpower:TheconnectionsbetweendevicesareveryshortinBLE.Thisresultsin extremelylowpowerusage.Devicescanoperatewithsimplelithiumcoincell batteries. Broadservicesandcharacteristicsschema:Thedatapresentedbyaperipheralis structuredasservices,whicharethensubdividedintocharacteristics.Servicesare akintothenoticesonabulletinboard,whereascharacteristicsaresimilartothe individualparagraphsofthesenotices. Youcaneasilyhookuptodifferentservicesandcharacteristicswithafewlinesof code.Forexample,youcaninteractwithabatteryserviceandeasilydeterminethe powerlevelsremainingforadevice.Alternatively,yourusecasemayberelatedto healthorfitness,whichmeansthatyoucanleveragetheonboardhealthservicethat includesacharacteristic(suchasheartbeatdata). BeaconsandiBeacons WhereGPSleavesoff,Beaconsbegin.ThisemergingBLEtechnologyisquickly becomingthenextbigthinginlocationsensing.Althoughproven,powerful,and ubiquitous,GPScanonlydeterminethecoordinatesofanobjectwithin20-30feet. However,theBLEBeacontechnologyiscommonlyreferredtoashyperlocalinits sensitivitybecauseitisaccuratewithinarangeof100metersdowntoinches.Thusfar, mostoftheinterestaroundtheBeacontechnologyisfocusedonhowmarketersand advertiserswanttouseitinordertosendyoutargetedoffers…Yuck! ThisislargelyduetothefactthatApple’smarketing-centricversionoftheprotocolcalled iBeaconshasbeenthemostcommonlyreferencedandeasiesttypetogetrunningquickly. However,theintrinsicBLEBeaconstack,iBeaconorotherwise,isveryexcitingfor severalreasons: Itdeliverslowcostradiosignaling Itprovidesfairlyrapidandsimpledevelopmentrequirements ItrequiresverylowpowerwithitsuseofBLE ItbroadcastsfarmorepreciselocationdatathanGPS ForIoT-likescenarios,bothindoorandoutdoor,Beaconsprovidemuchpromisefar beyondannoyingmarketingmessages.Also,youcanactuallybuypremadebeaconsfor verylittlemoney,sometimesforonlyafewdollars(USD). Itmayseemlikeoverkilltobeusingafull-blownmicrocomputer,suchastheBBB,to serveasaBeacon.However,ourintentionistocreateourownBBBversionsothatwe havemoreflexibilityinunderstandingandbuildingtheconstituentpartsofaBeacon network.Doingthisasanopensourcerecipeallowsyoutopulltheleversyourself. AfurtherpointtoclarifyhereisthatBLEBeaconsdonotactuallysendcontentthatauser receivesontheirsmartphoneapp.Thebeaconsimplyprovidestherudimentarydatatoa mobileapp,whichallowsthatapptodetermineitslocationinavenueoroutdoorspotand inturnsendstheuserlocation-specificdata.Alternatively,itcancaptureandmakeuseof thatdatainotherways. Furthermore,iBeaconsdonottrackusersbasedonanykindofprofilingrequirements;the interactioncanbe—andgenerallyis—completelyanonymous,soconcernsaboutprivacy arenegligible. WithBeacons,thereareseveraldatafieldsthatyoutypicallywanttowatch.Thishelpsin differentiatingonebeaconfromanother.Forinstance,let’ssaythatweareintheMuseum ofNaturalHistoryinNewYorkCitythathasabeaconnetwork.Herearetherelevantdata fields: UUID:ServicesareidentifiedbyuniquenumbersknownasUUIDs(Universal UniqueIdentifier),whichyoumaybefamiliarwithfromotherprojects.Therefore, themuseumwouldhaveitsownuniqueUUIDstring. Themajorfield(ID):Inputtingaspecificvalueinthisfieldcanspecifyamore generallocation,forexample,aparticularfloorinthemuseum. Theminorfield(ID):Inputtingavalueinthisfieldwillspecifyaparticulargallery onaspecificfloor. TXPower:Thisisusedtotrytoestimatethedistancebasedonthesignalstrengthof theWi-Ficonnection(theRSSIvalue)inaparticularroom. ThemajorandminorIDscanbeusedtotriggercertainbehaviorsinyourapplicationwhen itdiscoversoneofyourbeacons.Allofthesefieldscometogethertomakepinpointing locationsextremelyaccurate. Gettingready TheBBBispoweredupviaUSBandconnectedonlineeitherviaWi-FiorEthernetwith twoadditionalitems: USBBluetoothLE(BLE),alsoknownasBluetooth4.0adapter—wewillusea Targusdongle(productIDACB10US1).ThisusestheBroadcomBCM20702 chipset.TherearefarcheaperonesthatshouldworkfineontheBBBthatcostaround USD$10.00-15.00.HereisalistofcompatibleBluetoothdonglesfortheRaspberry Pi(http://elinux.org/RPi_USB_Bluetooth_adapters).Manyofthoselistedwilllikely workwiththeBBB,althoughtheyhavenotallbeentestedforcompatibility. SmartphonewithBluetoothLE—iPhonesstartingfrom4Stoanyofthecurrent modelsareBLE-compliant.OntheAndroidside,thereareexceptions.Bydefault, thecurrentmodelsofanAndroidphonerunson4.3orhigherBLE.However,any Androidphonesthatcannotrunonversion4.3orhigherwillnotworkwiththissetof recipes. Howtodoit… Part1—Settingupyoursmartphone Asmentionedearlierinthechapter,weneedtoinstallsomeappsonoursmartphonein ordertomakethisrecipemeaningfulanddemonstratetheBBB’sbeacon-ness. FortheiPhone,weinstalledandtestedtwodifferentfreeappsfromtheAppStore,oneis calledLocate(byRadiusNetworks)andtheotheriscalledBeaconTool.(Thedevelopers mustgottenupveryearlyinthemorningtocomeupwiththosenames…). LocatehasafewmorefunctionalitiesthanBeaconToolbecauseitletsussetthemajor andminorvaluesfortheBeacon. Part2—SettingupasimpleIoTtestenvironment YoucantestandtracktheiBeaconusingawebservice.Thereareseveralbusinessesin thisspace.WeusedaplatformcalledEvoThings,whichisafree,opensourceplatform. EvothingsallowsyoutouseasimpleIDEonyourdesktopandthendemonstratean iBeaconapponasmartphonewithaBeacon-enabledBBBinthemiddleofthemix. Performthefollowingsteps: 1. DownloadandinstallEvothingsStudio(http://evothings.com/).Theinstallation requiresaWorkbenchdesktopandamobileapp,allofwhichisexplainedontheir website. 2. AfterdownloadingEvothingsStudio,youwillfindaMacOSXandaWindows versiononthedesktop.Installyourpreferredclient. 3. Forthemobileapp,installandstarttheEvothingsclientapponyourmobiledevice. AndroidandiOSareavailableattheirrespectiveonlinestores. TherearenumerousdemosandexamplesthatcomewithEvothings.Althoughtheytendto befocusedonhowtouseanArduinoasabeacon,thecodeisveryflexible(andopen source),soeverythingiscustomizableforotherplatforms.Forourfirstquickexample,in yourdesktopEvothingsWorkbench,openthefollowingfileinatexteditor: Evothings_Studio/examples/ibeacon-scan/index.js Then,scanabouthalfwaydownthepagetofindthefollowingcode: //AddyourownmanufacturerUUIDstothislist. {uuid:'B9407F30-F5F8-466E-AFF9-25556B57FE6D'}, {uuid:'F7826DA6-4FA2-4E98-8024-BC5B71E0893E'}, {uuid:'8DEEFBB9-F738-4297-8040-96668BB44281'}, {uuid:'A0B13730-3A9A-11E3-AA6E-0800200C9A66'}, Now,addyourgeneratedUUIDfromtheearliersteptolineupwiththefollowingsyntax: {uuid:'3784B5B0-2DA7-11E4-8C21-0800200C9A66'}, Note Otherthantheirownidentity,iBeaconsdonotpushnotificationstothecentral(receiving) devices.However,amobileapponyourphonecanusesignalsreceivedfromiBeaconsto triggertheirownpushnotifications. Part3:SettinguptheBBB Let’sstartwiththeessentialpackageonhowtocontrolandinteractwithBluetooth devices(LEorotherwise)andtheLinuxBluetoothstackBlueZ.OnthecurrentDebian distrothatcomeswithanynewlypurchasedBBB,BlueZshouldbealreadyinstalled. Performthefollowingsteps: 1. First,updateandupgradetheBBBwiththefollowingcommand: $sudoapt-getupdate 2. Then,wewillverifythatBlueZisinstalledusingthefollowingcommand: $bluetoothd-v Ifyouseeaversionnumberappear,skiptostep4;otherwise,proceedtothenext step. 3. Now,installBlueZwiththefollowingcommand: $sudoapt-getinstallbluez Note YoumaywanttoinstallBlueZfromitssource.Hereisthecodeforit: sudomkdirbluez cdbluez sudowgetwww.kernel.org/pub/linux/bluetooth/bluez-x.xx.tar.xz CheckforthecurrentversionofBlueZbeforerunningwget. 4. Then,connectthedongletotheUSBportandverifythatitisrecognizedwiththe followingcommand: $lsusb 5. Now,wewanttosetupBluetoothcommunicationsbetweentheBBBandanyother BLEdevicesthatrequireusingaseriesofBlueZcommands.Todothis,wewilluse thehciconfigtoolandbeginbytakingalookattheaddressoftheUSBadapteras follows: $hcitooldev Devices: hci000:19:0E:15:DE:87 6. TheprecedingoutputshowsonedevicepresentwiththeID0thatisprependedwith hci;thisispartoftheprotocol’snamingconvention.WewilltakethisIDandappend ittothecommand,includethe(-a)optiontooutputinformationaboutallthedevices present,andcheckthedongle’sreadystate,asshowninthefollowingcode: $hciconfig-ahci0 Yourscreenshouldshowthefollowingcode: hci0:Type:BR/EDRBus:USB BDAddress:00:19:0E:15:DE:87ACLMTU:1021:8SCOMTU:64:1 DOWN RXbytes:1267acl:0sco:0events:47errors:0 TXbytes:747acl:0sco:0commands:47errors:0 Features:0xbf0xfe0xcf0xfe0xdb0xff0x7b0x87 Packettype:DM1DM3DM5DH1DH3DH5HV1HV2HV3 Linkpolicy:RSWITCHSNIFF Linkmode:SLAVEACCEPT 7. EnsurethatitsaysDOWN,whichisnotwhatwewant.So,up,up,andawaywego: $sudohciconfighci0up 8. Then,verifythatthecommandworkedbyrepeatingourearlierstep.Yourstdout shouldlooksimilartothefollowingcommand: $hciconfig-ahci0 hci0:Type:BR/EDRBus:USB BDAddress:00:19:0E:15:DE:87ACLMTU:1021:8SCOMTU:64:1 UPRUNNING RXbytes:990acl:0sco:0events:44errors:0 TXbytes:738acl:0sco:0commands:44errors:0 Features:0xbf0xfe0xcf0xfe0xdb0xff0x7b0x87 Packettype:DM1DM3DM5DH1DH3DH5HV1HV2HV3 Linkpolicy:RSWITCHSNIFF Linkmode:SLAVEACCEPT Name:'BCM20702A' Class:0x000000 ServiceClasses:Unspecified DeviceClass:Miscellaneous, HCIVersion:4.0(0x6)Revision:0x1000 LMPVersion:4.0(0x6)Subversion:0x220e Manufacturer:BroadcomCorporation(15) 9. Now,wewillsetupthedongletobeginwhatisknownasadvertisingintheBLE parlance.Wewillperformthisinthelowenergy(le)modeusingtheflag3;thissets theconnectionmode: $sudohciconfighci0leadv3 Note AfurtherwordaboutnomenclatureintheiBeacon/BLElandscapeisthatyouwill oftenseereferencestothewordadvertisingwhenyoudevelopwithBLE.Thetermis usedgenericallytorefertoapacketofdatathatisbeingsentfromaBTdeviceto makeitspresenceknown;ithasnothingtodowithApple’soriginal advertising/marketing-centricpurposesforiBeacon. 10. Bydefault,theBLEdonglewillscanforotherdevices.However,wewanttoturn thisfunctionoffbecauseitcaninterferewithadvertisingasfollows: $sudohciconfighci0noscan 11. ThelastcommandaddstheUUID,asshowninthefollowingcommand: $sudohcitool-ihci0cmd0x080x00081E02011A1AFF4C00021537 84B5B02DA711E48C210800200C9A6600000000C8 Theinstantyousendtheprecedingcommand,youshouldseeanotification/popupon yoursmartphone.WiththeiLocateappontheiPhone,itshouldsayEnteredregion: BBBbeacon1. (Thisassumesthatasmartphoneappisalreadyinstalledandsetuptorecognizethe BBBbeaconUUID). Congratulations!Youarenowabletobroadcasthyperlocaldatawithouttheneedforabig GPSsatellite. There’smore… ThefollowingreferencesprovidemoredetailonBTLE: ClassicversusBTLEdiscussion:Thisgivesyouanexcellentdrill-downintothe natureofBLE’sdistinctivenessfromBluetoothClassicat http://makezine.com/2014/06/16/the-bluetooth-le-doc-a-thon-at-itp-camp/ BTLEdocumentation:ThisprovidesvariousexamplesfromaDoc-a-thonat https://github.com/tigoe/BLEDocs/wiki Estimoteteardown:MakemagazinetakesapartanEstimoteiBeacon,acommercial, mostlyclosedproductathttp://makezine.com/2014/01/03/reverse-engineering-theestimote/ Tile:Informationonthisnew,verycheap,andsmallBeaconcanbefoundat http://tiletogether.tumblr.com/post/98897004442/tile-is-coming-to-android#notes TroubleshootyourBluetoothinstallation (https://wiki.archlinux.org/index.php/bluetooth) Bubbleapp:Thisappthatstrivestosimplifytheprocessofsettingupandinteracting withiBeaconcontentbyusingtagstoconnectwebsitestothingsintherealworld. Learnmoreathttp://discoverbubble.com/ UsingsensorsanddatawithThingSpeak Havingsomefacilitytohookupsensorsisalmostderigueurwhenyoutalkaboutthe InternetofThings.Furthermore,learninghowtogetyourarmsaroundthelargedatasets thattypicallypouroutofthesesensorshasbecomeacrucialpieceoftheIoTpuzzle.Inthe nextsection,wewilltakealookatarecipethatintroducesonemethodformanagingthis data. WewillbepiggybackingonarecipefromChapter3,PhysicalComputingRecipesUsing JavaScript,theBoneScriptLibrary,andPython,andwillusetheTMP36temperature sensorinparticular.However,thistime,youwilllearnhowtousethedatacomingoutof thesensoranddisplayitinamoreaccessibleIoT-stylemanner. Gettingready Thefollowingmaterialswillbeneeded: BBBpoweredvia5Vsupply. EthernetorWi-Ficonnectivity. Breadboard. 3xjumperwires. TheTMP36temperaturesensor—thisisthesamesensorastheoneweusedin Chapter3,PhysicalComputingRecipesUsingJavaScript,theBoneScriptLibrary, andPython.Asareminder,thislow-costsensorisreadilyavailablefromnumerous sources,includingsupplierssuchasSparkfun (https://www.sparkfun.com/products/10988). Howtodoit… PerformthefollowingstepstousesensorsanddatawithThingSpeak: 1. IfBBBisnotalreadyoff,turnitoff. 2. Usingthefollowingfritzingdiagram,wireyourpowereddownBBB: YoumayrememberthisconfigurationfromChapter3,PhysicalComputingRecipes UsingJavaScript,theBoneScriptLibrary,andPythonasthewiringisexactlythe same:GNDusestheanaloggroundP9_34(GNDA_ADC),3VPWRatP9_3,andthe sensorpinatP9_38. 3. PoweryourBBBandloginviaSSH. 4. SignupforanewaccountatThingSpeak(https://thingspeak.com/),afreecloud servicefordatapublishingandcreatingIoT-styleproducts. 5. FollowthepromptsontheThingSpeaksiteonhowtosetupachannelforyour account.Justforfun,let’snamethechannelasGroundControlTemperature. 6. AtthebottomofthesameChannelSettingsscreen,createasecondfieldcalled FieldLabel2,asshowninthefollowingscreenshot: 7. Youcannowseetheblankslatechartsthathavebeencreatedforthechannelthat willreceivedatafromtheBBB’ssensor: 8. FromyourGitHubrepo,downloadtheBoneScript(Node.js)codeforthisrecipeto yourBBBwiththefollowingcommand: $gitclonehttps://github.com/HudsonWerks/tmp36-sensor-thingspeak.git Note TherepoalsoincludesaPythonscriptexample;however,wewillonlyreviewthe nodeversionoftherecipehere. 9. NavigatetothenewdirectorythatwejustcreatedandopentheNode.jsfilewiththe followingcommand: $cdtmp36-sensor-thingspeak $sudonanotmp36-thingspeak.js 10. Inabrowseronyourclientdesktop,opentheCloud9IDEandcreateanew JavaScriptfile.Then,copyandpastethecodefromtheopennanowindowonyour BBBtotheCloud9file. 11. BeforetryingtosenddatatoThingSpeak,weshouldfirstverifythatoursensor, wiring,andbasiccodearefunctioningproperly.Now,inyourCloud9window,click ontheRUNbutton.Ifallgoeswell,theconsoleoutputintheIDEshouldshow readingssimilartothefollowingcode: debuggerlisteningonport15454 Sensorreadingstarted. Outputat10-secintervals. TemperatureatGroundControlforTue,11Aug201519:20:21GMT Fahrenheit:64.4 Celsius:18 _____________ TemperatureatGroundControlforTue,11Aug201519:20:31GMT Fahrenheit:63.86 Celsius:17.7 Ifyouarenotgettingreadingsfromthesensor,gobackandcheckyourwiring. 12. Next,wewillhookupourcodetotheThingSpeakchannelthatwesetupinthefirst partofthisrecipeusingthegeneratedAPI.BackontheThingSpeakChannelstab, drilldowntothenewchannelyoucreatedandsearchfortheAPIKeystaboption. Selectthistabandthencopy(Ctrl+C)theWriteAPIKeygenerated,asshownin thefollowingscreenshot: 13. BackintheCloud9window,online30ofthetmp36codewindow,pasteyour ThingSpeakWriteAPIkeytothedesignatedpartofthecodeasfollows: //PosttemperaturedatatoThingSpeak request.post('http://api.thingspeak.com:80/update',{form:{api_key: 'THINGSPEAK_WRITE_API_KEY_HERE',field1:temp_f,field2:temp_c}}); 14. Now,it’stimetoseeyourtemperaturereadingsthatisdisplayedontheThingSpeak cloudservice.So,asyouagainclickonRUNintheIDE,yourCloud9console shouldbeoutputtingtemperaturereadingsasbefore.Withinafewmoments,backon theThingSpeakchannel,datapointsshouldbeappearingat10-secondintervalson thescreen,plottingthefluctuationsofGroundControlTemperatureofyourroom, asshowninthefollowingscreenshot: 15. Lastbutnotleast,wewanttomakethesensordatavisiblethroughyetanother method,thistimeusingTwitter.AsTwitterisfreeandreadilyavailableonyour smartphone,itservesasausefulchanneltofunnelIoTdata.ThingSpeaksimplifies theprocessconsiderablybyhavingawebhookthatletsyouplugintoaTwitter account. IfyoudonothaveaTwitteraccount,setoneupnow.Andevenifyoudohaveone, createanewdevelopmentaccountthatisseparatefromyourprimaryfeed. Otherwise,yourfollowersmaynotappreciategettingyourtemperaturesensortweets. 16. OntheThingSpeaksite,selectAppsfromthemenuandthenThingTweet. 17. UndertheThingTweetApp,selectLinkTwitterAccount.Thiswillredirectyouto TwittersoyoucanauthorizeThingSpeakaccesstoyouraccount.Ifyouwantto proceedwiththerestofthisrecipe,youwillneedtogivepermissionfor authorization. OnceyouhaveconfirmedtherightTwitteraccount,Twitterwillsendyoubackto ThingSpeak. 18. Aftertheauthorizationprocess,theThingSpeakappgeneratesaThingTweetAPI Keythatwewillneedtouseinourcode,asshowninthefollowingscreenshot: 19. CopyandpastethisnewAPIKeytoline33ofthecodeintheCloud9window, whereitsaysTHINGTWEET_TWITTER_API_KEY_HEREandthetwoCHANNEL-IDsto thedesignatedspotsinthecode: request.post('https://api.thingspeak.com/apps/thingtweet/1/statuses/upd ate',{form:{api_key:'THINGTWEET_TWITTER_API_KEY_HERE',status:"The currentGroundControltemperatureis%%channel_CHANNEL-ID_field_1%%F, %%channel_CHANNEL-ID_field_2%%C"}}); } Note AlltheparametersfromtheTwitterAPIstatuses/updatearepossible,including geolocation.YoucanlearnmoreabouttheThingSpeakAPIanditsTwitterappon theirsiteathttps://thingspeak.com/docs/thingtweet/. 20. Lastbutnotleast,clickonRUNintheIDE.Let’skeepourfingerscrossedbecause yourBBB’sGroundControlTemperaturewillbegintosendtemperatureupdatesto yourTwitteraccount. ThreecheersforGroundControlTemperature! Seealso YouwillsoonlearnthatthereisavastarrayofnewventuresplayingintheIoTcloud servicessandbox.Asmostofthemarenascentbusinessesinanewlyemergingindustry,it isdifficulttopredictwhowillemergeasgo-toplatformsinthefuture.However,ahandful ofplayersareworthmentioningfortheireaseofuseortheirstrongpositioningonthe marketplace: Clouddeployment:Deployingsoftwareupdatestomultipleremotedeviceswill becomeanincreasingchallengeastheIoTcontinuestogrow.Twoplayers,Resin.io (https://www.resin.io/)andDocker(https://www.docker.com/),areleadingthecharge increatingaplatformforcontainerizingyourapplications,makingiteasytodeploy packagestoallyourdevicesoverthecloud. Datadisplayandhosting:ManybusinessesintheIoTspacearetryingtomakeit easierforyoutomanageanddisplayyourIoTdatainaslickerpackageand simultaneouslyhostwiththem.Hereareacoupleofthem: Initialstate(https://www.initialstate.com/) Ubidots(http://ubidots.com/) Messagingandalerts:Dweet.io/Freeboard(http://dweet.io/) ConnectingtowebservicesthroughopenAPIs:Ship.iot(https://shipiot.net) ToolsetstohookupIoTdevicesincludingthefollowingsample: IBM’sNodered.js(http://nodered.org/) AdafruitI/O(https://www.adafruit.com/io) Makingthingssmarter–buildinga wirelessdigitalpictureframe Takingmundaneobjectsandconnectingthemtooneanotherisoneofthekeyintentions ofthewholeIoTphenomenon.Inournextrecipe,wewillcreateadigitalpictureframe. However,oursisisnotthetypicaloff-the-shelfversionwhereyouloadimagesfroman SDcard.Instead,wewilluseacombinationofwebservicesthatarecommonlyusedin IoTtogetherwithawirelessimageplayertoupdatethedigitalpictureframedynamically andseamlesslyfromasmartphone. Gettingready Thematerialsneededareasfollows: Asmartphonewithinternetconnectivity TheBBBpoweredby5V AWi-Fidongle AnLCD(5inchesorlarger) Youwillalsoneedtosetuptwowebserviceaccounts: Dropbox:Thefreeplanisadequate(http://www.dropbox.com) IFTTT:Thisisafreeservice(http://www.ifttt.com) UsingIFTTT Forthisrecipe,wewillincorporatetheIfThisThenThat(IFTTT)webservice. Althoughnotperfect,IFTTTisafun,rapiddevelopmenttoolforprototypingIoT scenariosandusecases.ThereareotherwaystoperformwhatIwilloutlinelater;you couldhookupotherpopularthird-partyapps,suchasInstagram,Flickr,andTwitter. However,Iprefertokeeptheadditionalinstallationsataminimumandestablishmoreof aleastcommondenominatorenvironmentthatprovidesasimplerdevelopmentpath. Forlong-termseriousproductbuilds,IFTTTisnotagoodchoicebecauseitistoo“black box”,tooopaqueinitsfunctionalitytorelyonforfinaldesigns.However,forrapid protoypingandideagenerating,itishighlyuseful.WithIFTTT,youcaniteratequickly andnimblyusingahostofdifferentwebservicesthatwillalwaysleadtonewideasand directionsforyourdevelopment. Howtodoit… Partone:Thesmartphonesetup Performthefollowingsteps: 1. Onyoursmartphone,shootaphotographwithacameraapp. 2. Savethephototoacustomalbumonyourphonethatyouneedtocreate.Nameit NowPix. 3. SetuptheIFTTTtriggeronyourphonetosendthesavedalbumfiletoDropbox. SettingupandtestingtheDropboxscriptontheBBB Performthefollowingsteps: 1. IfyoudonotalreadyhaveaDropboxaccount,signupforafreeaccountat https://www.dropbox.com/home. 2. DownloadandinstallacustombashscriptcalledDropboxUploader.Thisisa wonderfullyusefulopensourcetoolcreatedbydeveloperAndreaFabrizi.Thescript providesaneasymethodtointeractdirectlywiththeDropbox’sAPIauthentication process,soprovidingyourusernameandpasswordisnotnecessary. 3. Now,makesurethatyouareinyourhomedirectory: $cd 4. Then,clonetheDropboxUploadercodeusingthefollowingcommand: $gitclonehttps://github.com/andreafabrizi/Dropbox-Uploader/ 5. Makesurethatthedirectorywascreated,asshowninthefollowingcommand: $cdDropbox-Uploader 6. Setpermissionswiththefollowingcommand: $chmod+xdropbox_uploader.sh $./dropbox_uploader.sh 7. Then,runthescriptasfollows: ~/Dropbox-Uploader$./dropbox_uploader.sh Youshouldseethescreenoutputwithasetofinstructions: Thisisthefirsttimeyourunthisscript. Backtoyourdesktopclient Beforerespondingtotheterminalprompts,youwillnowneedtosetupaDropboxApp viayourdesktopclient(PCorMac).ThisappwillhooktotheDropboxUploaderscript. Performthefollowingsteps: 1. OpenthefollowingURLonthedesktopinyourbrowserandloginusingyour Dropboxaccountathttps://www2.dropbox.com/developers/apps. 2. ClickonCreateAppandthenselecttheDropboxAPIapp. 3. SelectFilesandDatastores.Therestofthefieldsshouldbefilledoutinthe followingmanner: Canyourappbelimitedtoitsownfolder? No Whattypeoffilesdoesyourappneedaccessto? Specificfiletypes—Myapponlyneedsaccesstocertainfiletypes, liketextorphotos. Lastquestion,whattypeoffileswillyourappuse? Images 4. Givetheappanameinthelasttextfield.MineiscalledNowPixtoremainconsistent withthedirectory/albumnamethatwesetupontheiPhone.Then,finishbyclicking ontheCreateAppbutton. 5. Now,generateanAppkey. BacktotheBBB Thenextseriesofstepscontinuewiththeverification/authenticationprocessusing Dropbox.Performthefollowingsteps: 1. Intheopenterminalwindowandattheappropriateprompt,pastetheAppKey generatedinthepreviousstepandfollowtheonscreenprompts. 2. Whenyournewappissuccessfullycreated,entertheAppKey,AppSecret,andthe permissiontypeshownintheconfirmationpageasfollows: #AppKey:YOUR_API_KEY_HERE 3. Hitthereturn(Enter)keyafteryouinputtheappropriatedata,giventhenextseveral terminalprompts. Now,AppSecrethasbeengenerated.CutandpastethatstringfromtheDropboxto theterminalwindow,asshowninthefollowingcode: #Appsecretabcdefghijklmnop1234 Permissiontype,AppfolderorFullDropbox[a/f]: Appfolder(f) Appkeyisabcdefghijklmnop1234,Appsecretisabcdefghijklmnop1234and AccesslevelisFullDropbox.Looksok?[y/n]: [y/n]:y Hitreturnandyouarefinishedatleastwiththeinstallation. Note IfyouaccidentallyinputthewrongAppKeyandAppSecret(whichIdidsinceI haveseveralDropboxapps),youcanresettheaccessbyrunningthefollowingscript: $./dropbox_uploader.shunlink Testingandrunningthescript Wenowneedtoverifythatthescriptoperatesasexpected:downloadingimagesfrom Dropboxandplacingtheminaspecifieddirectory. 1. First,wewillverifythatthecontentofourIFTTTdirectoryontheDropboxcanbe accessedandreadproperly,sowewilllisttheimagesthatarethere: $cdDropbox-Uploader $./dropbox_uploader.shlist/IFTTT/iOS_Photos/NowPix 2. Gogettheactualimagesanddownloadthemtoyourdirectoryusingthefollowing command: $./dropbox_uploader.shdownload-s/Apps/NowPix/home/debian/NowPix Weaddedthe-soptionthatskipsthealreadyexistingfileswhenyou download/upload;otherwise,thedefaultparameteristooverwritethefilesinthe targetdirectory. 3. Verifythatyoudid,infact,gettheimageswiththefollowingcommand: $cdNowPix $ls 4. Assumingthatyourscriptexecutedproperlyandtheimagesweredownloadedtothe rightdirectory,wenowneedtosetupaprocessinorderforthescripttorun transparentlysothatyoudon’thavetoruniteachtimeyouwanttodownload images.Toperformthis,wewillsetupacronjobthatautomaticallyrunsthescriptat specifiedintervals.Wewillbeginthispartbyopeningcrontabinourdefaulteditor withthefollowingcommand: $crontab-e The-eoptiontellstheshelltoopenourdefaulteditor,whichinourcaseisnano. Note Youshouldtakenoteofthesecommentsfromtheoriginalscriptdeveloper: ##Runningascronjob DropboxUploaderreliesonadifferentconfigurationfileforeachsystemuser.The defaultconfigurationfilelocationisHOME_DIRECTORY/.dropbox_uploader.This meansthatifyoudothesetupwithyouruserandthentrytorunacronjobasroot,it willnotwork. So,whenyourunthisscriptusingcron,keepthefollowingthingsinmind: Remembertosetupthescriptthattheuserusedtorunthecronjob. Alwaysusethe-foptiontospecifythefullconfigurationfilepathbecause sometimesinthecronenvironment,thehomefolderpathisnotdetectedcorrectly. Forsecurityreasons,Irecommendyoutonotsharethesameconfigurationfilewith differentusers. 5. Addthefollowingcodetotheendofthefilethatopensonyourscreen: */3****/home/debian/Dropbox-Uploader/dropbox_uploader.sh-s download/IFTTT/iOS_Photos/NowPix/home/debian/ Thenumber3isthefrequencyinwhichthecronjobwillrun,whichinourcaseis every3minutes.Wehaveitsetforsuchahighfrequencyonlyfortestingpurposes. Whenwearefinishedwithourtesting,youshouldchangethisnumbertoahigher one,perhapseveryfewhoursorlonger,dependingonhowoftenyouplantoadd photostoyourNowPixdigitalpictureframe. Therestofthelinewithalltheasteriskscorrespondstothefollowinglayoutfora cronjob: minute(0-59),hour(0-23,0=midnight),day(1-31),month(1-12), weekday(0-6,0=Sunday),command 6. Withcron,itisagoodideatoverifythatthejobhasrunasexpected.Youcan performthiseasilywiththefollowingcommandthatchecksane-mailfilethat crontabautomaticallyrunsonceacronjobhasbeensetup: $tail-f/var/mail/debian Youshouldseealogofthesysteme-mailsthatcrontabwillsend,includingthe outputfromthedownloader.shscript.Thisoutputshouldmirrorthekindofoutput yousawwhenyouwererunningtheearlierbashscriptintheterminalwindow. 7. Next,weneedtoinstallandsetupapackagethatwillopenandcycletheimagesthat wewilldownloadontheBBB.Forthis,wewillusefeh,alightweightandpowerful imageviewer,asshowninthefollowingcode: $sudoapt-getupdate $sudoapt-getinstallfeh 8. fehrequires-xsothatyoucanruntheappremotelyviavncasfollows: $feh-x 9. Now,wecanviewallourphotostakenonoursmartphoneasaslideshow: $feh-FD10/home/debian/NowPix FDisthecommandtorunaslideshow,whereasthenumberafterFDisanadjustable playdurationfortheimage. Theprogrammustalsopointtothedirectorywiththeimagesthatwillrunasa slideshow.UsetheEscbuttononyourdesktoptoexitfromtheslideshow. Youmayseeanotherpermissions-relatederrorwhenyoutrytoexecutethefeh program.Theerrormaysaysomethingsimilartothefollowingcode: InvalidMIT-MAGIC-COOKIE-1 Ifso,runthefollowingcommandtodeletethe.Xauthorityfile: $rm.Xauthority* 10. Next,wewillcreateasystemdservice(rememberthat?!)thatrunsthecommandto loadtheimagesanddisplaytheminalooponbootup.So,loginasroot,asshownin thefollowingcode: $sudo-i 11. Navigatetothesystemddirectorywiththefollowingcode: #cd/lib/systemd/system 12. Now,createanewservicefileasfollows: #sudonanonowpix.service 13. Then,pastethefollowingcodetotheeditorwindow: [Unit] Description=RunNowPiximagesusingFehonboot [Service] Type=simple ExecStart=/usr/bin/feh-FD10/home/debian/NowPix Environment=DISPLAY=:0 SyslogIdentifier=fehslideshow Restart=on-failure RestartSec=5 [Install] WantedBy=multi-user.target 14. Startthesystemdservicewiththefollowingcode: #systemctlstartnowpix.service 15. Finally,runthefollowingcommandthatenablestheservicetostartatbootup: #systemctlenablenowpix.service 16. Now,rebootyourBBB.Ifalliswell,youshouldnowhavepicturescyclingonyour screenupdatedfromyournewphotosonyoursmartphone. Seealso Crontabsisabiggersubjecttolearnandusefulinmanyscenarios,whereyouwanttotime eventsonyourBBB.Formoreinformation,referto: https://help.ubuntu.com/community/CronHowto http://www.unixgeeks.org/security/newbie/unix/cron-1.html Chapter9.TheBlackinOuterSpace Inthischapter,wewillcoverthefollowingrecipes: GrabbingtheInternationalSpaceStationflyoverdataandvisualizingit TrackingusingRTL-SDR AirplanetrackingwithRTL-SDR SatellitetrackingusingGPredictandRTL-SDR SatellitetrackingusingtheSatNogsNetworkclient/groundstationandRTL-SDR Addingotherinterfaces–ISStrackingandtexttospeech Introduction Therearethousandsofsatellite“birds”upthere.Buzzingaroundatallhoursoftheday andnight—whethercommercial,military,oreducational—thesesatellitessendand receivedatafromprofessionalandamateurgroundstationsaroundtheglobe.Andas satellitesgetcheaper,thenumberofthemhasproliferated,leadingtoanincreasing problemforpotentialcatastrophiccollisionsinspace. Trackingallthatactivityisachallenge.So,whynotemployyourownBBBinthis endeavor? AmateursatellitewatchershavebeenaroundnearlysincethedawnofSputnik,anactivity thatfellundertherubricofhamradio,orHamSat.Nowadays,thereisahostofinteresting toolsavailablethatplaynicelyonLinuxaswellasmicrocomputers,suchasBeagleBone Black. Foryoursmartphonealone,youcanfinddozensoffree,downloadabletrackingapps. Giventheirbasicpurpose—tellingyouwhenasatellitemightpassnearbyorpassively receivingbasicmonitoringdata—theydeliverquickhitsofexcitement.However,these appsarelimitedinfunctionality,flexibility,andpurpose.Whatwewanttodoisstretch what’spossibletotrackasatellite,bringingthisinformationanddatadowntoEarthina morepliableformsothatyoucanexploreotherusefulandcreativepurposesforit. So,tobeginoursatellitetrackingadventures,wewillbeginwitheasyrecipes.Then,we willcontinuewithmoreadvancedscenariosandrobusttoolsthatwillgiveyougreater controloverthevarietyofdatathatyoucaptureandsimultaneouslyampupuser experience. GrabbingtheInternationalSpaceStation flyoverdataandvisualizingit Theeasiestscenarioofallbeginsbypiggybackingonpreexistingwebservicesandthen makingtheinteractionalittlemoreinterestingbycombiningitwithsometasksexecuted byBeagleBoneBlack. IFTTTfortheISS WeusedtheIFTTTwebserviceinourpreviouschaptertoprovidepartofthemachinery tosendphotoscapturedonoursmartphone.Here,wewilluseittohelpustrackthe InternationalSpaceStation(ISS),butwewilltaketheinteractionabitfurther. Gettingready Thematerialsneededareasfollows: TheBBB,headlessorconnectedtoanexternalmonitorandtetheredoverUSBwith Ethernet(orWi-Fi,ifyouchoose) AsmartphonewithcellorInternetconnectivity Howtodoit… Performthefollowingsteps: 1. Theeasiest,mostbasicwaytogettheISS’sflyoverdataisbysigningupforSMS alertsfromNASA’swebsiteathttp://spotthestation.nasa.gov/index.cfm. Thefirstfewtimesyougetthealert,itisathrilltoknowwhenyoucanpotentiallygo outsideandwatchthespacestationflyoveryourhead.Hereisatypicalmessage showingthedirectionaldatapoints: Subject:SpotTheStation Time:TueApr218:18PM,Visible:4min,MaxHeight:80degrees,Appears: NW,Disappears:SE Soon,however,youmaywanttodomorewiththisinformation.Todothis,thenext stepswillbuildonrecipeofpullingimagesintoarotating“screensaver”cycleusing thefehpackagefromChapter8,TheInternetofThings.Howeverthistime,wewill usefreshspaceimagery.Additionally,wewilladdingredientstograbflyoverdata anddisplayit. So,let’sslightlymodifythestepsandcodefromtheearlierchapter. 2. Fromyoursmartphone,gototheIFTTTSpaceChannel(https://ifttt.com/space)and activatetheversionaccordingtowhetheryouuseanAndroidoriPhone. 3. Onceyou’vedonethis,IFTTTsuggestsusefultriggerpairings,“Thischannelgoes wellwith…”.ChooseGoogleDriveasthepairing. 4. Activatethefollowingtwotriggers: AddNASA’sImageoftheDaytomyDropbox LogeachtimetheISSpassesoverheadtoaGoogleDocsspreadsheet Now,wewilltweakourDropboxUploaderscriptandcronjobsfromthelast chapter.Asareminder,thecronjoblooksforanewimagefileinDropboxat specifiedintervalsandcyclesitintoafehimageplaybackqueueonyourscreen, whiletheDropboxUploaderscriptactuallydownloadsnewimagesintoaspecified directoryonyourBBB. So,ifyousuccessfullyexecutedtherecipeforNowPixinChapter8,TheInternetof Things,proceedtothenextsteps.Otherwise,returntoChapter8,TheInternetof Things,andfollowthestepstodownloadanddisplaytheimages. 5. CreateaSpacedirectoryonyourBBBthatmirrorsyourSpacedirectorycreatedby IFTTTonyourDropboxaccountusingthefollowingcommand: $mkdirSpace 6. Now,confirmthatthecontentofyourIFTTTdirectoryonDropboxcanbeaccessed andreadproperly;listtheimagesthatarethere.Thisiswhyweputadummyimage hereinanearlierstep,asfollows: $cdDropbox-Uploader $./dropbox_uploader.shlist/IFTTT/Space Yourterminaloutputshouldlooksimilartothis: >Listing"/IFTTT/Space"...DONE [F]sample_image_name_here.jpg 7. DownloadtheactualimagestoyourBBB’sdirectorywiththefollowingcommand: $./dropbox_uploader.shdownload-s/IFTTT/Space/home/debian/Space Yourterminaloutputshouldlooksimilartothis: >Download"/IFTTT/Space"...DONE [F]sample_image_name_here.jpg 8. Checkthatyoudid,infact,gettheimagesthroughthefollowingcode: $cdNowPix $ls 9. Setupacronjob(refertothepriorchapterformoreinformationonrunningacron job)torunthedownloaderscript,asfollows: $crontab-e 10. Appendtheopenfilewiththefollowingline: */3****/home/debian/Dropbox-Uploader/dropbox_uploader.sh-s download/IFTTT/Soace/home/debian/Space Next,wewanttohaveourspaceimagesdisplayonscreenwheneveranewoneis added.Thiswillusefeh,thepackageweexploredinChapter8,TheInternetof Things.So,ifyousuccessfullyexecutedtherecipeforNowPixinpreviouschapter, proceedtothenextstep.Otherwise,returntoChapter8,TheInternetofThingsand followthesestepstousefeh. 11. Modifythefehscriptaccordingly: $feh-FD10/home/debian/Space 12. Next,wewantourBBBtoparsetheflyovertimedata—botharchivedandnearfuture —andturnitintonice,visualdisplays.So,atthispoint,wewilldepartfromthe earlierstepsandaddapowerfuldatavisualizationlibraryusedinPython, matplotlib.Wewillalsoaddthebasemaplibrary,whichextendsthefunctionalityof matplotlibbyaddingatoolkittoplot2DdataonmapsinPython. Sonow,installthePythonlibrariesasfollows: $sudoapt-getinstallpython-matplotlib $sudoapt-getinstallpython-mpltoolkits.basemap 13. CreateapythonfilethatwillserveasourtestISStrackingtoolbasedontheoutput fromthespreadsheetthatwewillgenerateonDropboxusingthefollowing command: $sudonanoiss_track1.py 14. FromourGithubrepo,downloadthecodeforthisrecipewiththiscommand: $gitclonehttps://github.com/HudsonWerks/space-satellite.git 15. Browsethenewdirectoryandopenupthefollowingtile: $cdspace-satellite $sudonanoiss_track1.py Takealookattheopenedcode.ItpiggybacksonthewonderfulOpen-NotifyAPI developedbyrocketmakerandsatellitewonk,NathanBergey,andisnicely commentedandbrokendownintoclearsections,includingacalltoanAPI,the visualmapprojectioncode,thecolorvaluesforthemap,thecoordinatesthatwe wanttotrack,andthetimingforthedataupdates. 16. Ifyouarerunningheadless,wewilluseamethodherethatyoumaynotbefamiliar with,calledX-session.ThisisbasicallyanSSHremotesessionthatcanrunXcommandsandloadgraphicalwindowswithinyourregularSSHterminal.So,on yourdesktopclientbox,openupanotherterminalwindow,thistimewiththe following: $ssh-Xdebian@<ip-address_here> 17. RunthePythonscript: $sudopythoniss_track1.py Youmayencounterthefollowingerror: File"/usr/lib/python2.7/lib-tk/Tkinter.py",line1712,in__init__ self.tk=_tkinter.create(screenName,baseName,className,interactive, wantobjects,useTk,sync,use)tkinter.TclError:nodisplaynameandno $DISPLAYenvironmentvariable Ifso,hereishowyoucanfixit: $sudoxauthadd`xauthlist` Ifallgoesasexpected,yourscreenoutput(overtheX-sessionterminal)willlook similartothis: ThebluedotshowsthecurrentlocationoftheISSwithitscoordinatesupdatedevery minute. 18. QuitthescriptbypressingCtrl+C. There’smore… HighdefinitioncameraviewsfromtheISScanbefoundat: http://eol.jsc.nasa.gov/ForFun/HDEV/ http://columbuseye.uni-bonn.de/ TrackingusingRTL-SDR Oneofthemoreexcitingadd-onstoourBBBsatelliteandobjecttrackingrecipesisan extremelylow-costUSBdonglecalledRTL-SDR.RTLisshortforRealtekRTL2832U controllerandtunerchipset,whichisinsidethisdongleandcanbepurchasedforaround USD$20.00. Besidesbeingcheap,thebestpartofthestoryisSDR,whichstandsforSoftwareDefined Radio.SDRiskindofwhatitsoundssimilarto:insteadofusinghardwarecomponents, suchasamps,mixers,filters,andmodulators,itisradiowithitskeyfunctionsdrivenby software. SDRcanreceivesignalsoveraverywidebandoffrequencies(forexample,from50to 2500MHz)withoutactuallyrequiringspecializedhardware.Usingvarioussoftware modules,SDRalsoperformsdifferentradioprotocols.Theresultisthatthissoftware—in conjunctionwithanRTLdongle—nowreplaceswhatusedtobeawidevarietyof specializedradiocomponents. Forradioenthusiasts(includingoldschoolhamradiooperators)andhackersalike,the flexibilityofSDRiscompelling;youcannowtransmitandmonitoranythingacrossavast radiospectrumfromcordlessphonestoBluetoothdevices,microwaveovens,caralarms, videodevices,ZigBee,airplanes,andevensatellites. TheRTL-SDRdongle Seealso SDRisalargetopicandwewillonlyexploreahandfulofrecipesusingit.Youcanlearn moreaboutitsapplicationsattheprincipalsourceforallthingsrelatedtoRTL-SDRat http://www.rtl-sdr.com/about-rtl-sdr/. Becauseofitsmanyuses,certainapplicationsofSDRandsimilarradioscannersmaybe illegalinsomecountries.Beforeproceedingwithanyofthefollowingrecipes,ensurethat youwillnotencounteranyrestrictionsonusageat https://en.wikipedia.org/wiki/Scanner_%28radio%29#Legislation. AirplanetrackingwithRTL-SDR Beforedivingintosomeofthemorechallengingandarcane“upperatmosphere”options touseRTL-SDR,wewilldoarecipethat’salittleeasierandmoredowntoEarth,namely trackingplanes. Thisrecipeisderivedfromavarietyofsources,includingDavidScheltema’stutorialon MakeMagazine(http://makezine.com/projects/tracking-planes-with-rtl-sdr/),whichisa DebianvariationonanRPiversion.ItalsocomesviathepostsofDavidTaylorof Edinburgh,Scotland(satsignal.eu/raspberry-pi/dump1090.html)andDrewFustiniof Chicago,Illinois(element14.com/community/community/designcenter/single-boardcomputers/blog/2014/04/07/sdr-and-sbc-cheap-thrills-with-radio-waves)forAngstromon theBBB.Additionally,AdafruithasalessonfortheRPi,whicheitherborrowsfromoris inspiredbythereferencesmentionedbefore.Allofthesemisssomesteps,however,to makeitflyonthecurrentBeagleBoneBlackDebiandistros,beitWheezyorJessie. Gettingready Herearethematerialsneeded: TheRTL-SDRdongle. Anantenna—Youcouldspendhundredsofdollarsonthispartofyourkit.However, therearenumerouslow-costandplentypowerfulantennasthatwillgetyouagood signalforallofourrecipes.Here,weuseaDiamondantenna (http://www.aesham.com/glass/magnet/diamond-antenna-mr-75s/),anditonlycosts USD$38.00. Anantennaadapter—Ifyouuseanantennaotherthanthesmallonethatoftencomes withthedongle,suchastheonementionedbefore,youwillneedtobuyaseparate adapter.Don’tworry!They’recheap,too,andourswasonlyaboutUSD$6.00 (http://amzn.to/1WoB7Lq). PoweredUSB. EthernetorWi-Ficonnectivity. Howtodoit… Performthefollowingsteps: 1. AttachtheantennatotheRTL-SDRdongleviatheUSMLadapter. 2. PoweryourBBBviaa5Vpowersupply,plugtheSDRdongledirectlyintotheUSB port,andconnectviaEthernet. 3. Alwaysensurethatyourpackagesareuptodate;let’supgradethemhereusingthe followingcommand: $sudoapt-getupdate&&sudoapt-getupgrade 4. Checkthatthedongleisrecognizedwiththiscommand: $lsusb Theoutputshouldlooksimilartothis,withtheRealtekSDRdongleappearing: Bus001Device002:ID0bda:2838RealtekSemiconductorCorp.RTL2838 DVB-T Bus001Device001:ID1d6b:0002LinuxFoundation2.0roothub Bus002Device001:ID1d6b:0002LinuxFoundation2.0roothub 5. Loginasrootwiththiscommand: #sudo-i 6. Aswewillcreateastripped-downfirmwaretoolsetforRTL-SDRhere,weneedto compilesoftwarefromsourcefiles.Wefirstneedtoinstallcmake,atoolthatwe cameacrossinanearlierchapter.Asareminder,cmakeisanalternativemethodto buildpackagesandcanbeinstalledasfollows: #apt-getinstallcmake 7. Then,installtheUSBlibraryforRTL-SDR,asfollows: #apt-getinstalllibusb-1.0-0-dev 8. Next,wewillgrabtheRTL-SDRlibraryandconfigureandcompileitwithmake. Thelastcommandherewilltakeafewminutestocomplete: #gitclonegit://git.osmocom.org/rtl-sdr.git #cdrtl-sdr #cmake./-DINSTALL_UDEV_RULES=ON #make 9. Now,installitwiththefollowingcommand: #makeinstall 10. Headbackuptotherootdirectory,whereweneedtobringtheaircraftscannerspecificpackageonboard.Thisrequiresanotherseriesofdownloading,settingup, andinstallingingredients,whichgoesasfollows: #cd #gitclonehttps://github.com/antirez/dump1090.git #cddump1090 #make 11. Configurethepathforthesharedlibraries: #echo"/usr/local/lib/">>/etc/ld.so.conf 12. Let’srunatest,ensuringthatweareinthedump1090directory: #cd/home/debian/dump1090 #./dump1090 IfyourRTLdongle/scannerisoperatingasitshould,thecommandwillbeginquickly dumpinganynearbyaircrafttostandardoutput.Ifyouusethesmallantennathat camewithyourdongle,itsrangewillbeverylimited.PressCtrl+Ctointerruptthe command. 13. Thelaststepistoputthisgallopingdatainaneasier-to-readformat.Intheterminal window,pastethefollowingcommand: $./dump1090--interactive--net--net-http-port8081 Thislastcommandanditsoptionstelldump1090tobeginoutputtingdatainamore viewableform.Oneversionofthisoutputisimmediatelyvisibleinyourterminal window,withthedatarefreshedcontinuouslyandsortedintotidycolumnsbyflight number,altitude,speedofaircraft,latitude,andsoon. Evenmoreinterestingisthe--net-http-port8081option,whichsendsthedatavia HTTPtoaspecifiedport—inthiscase,the8081port.Withthisoptionenabled,we canopenabrowserandaccessawebpagewithsomeJavaScript,andtheGoogle MapAPIisavailableaspartoftheinstalledpackage. 14. So,openabrowserandpastethefollowingaddressintothewindowusingoneofthe following: http://beaglebone.local:8081/ http://192.168.7.2:8081/ http://your_bbb_ip:8081/ YouwillimmediatelyseeaGoogleMapalongwithasidebarwindowshowinga rollupofthedata.Movethemaparounduntilitispositionedatyourcurrentlocation, andyoushouldseeplaneiconsappearing.Clickingonaniconpullsthisparticular flight’sdataintotheframe. Watchtheiconscloselytoseewhatkindofgeneralrangeyourreceiverandantenna aregettingbeforetheaircraftdisappearsfromthescreen. 15. Toquittheprogram,typeCtrl+CintheBBB’sterminalwindow. There’smore… CheckouttheRaspberryPiversionofRTL-SDRusedasaportableSDRscannerat https://learn.adafruit.com/freq-show-raspberry-pi-rtl-sdr-scanner?view=all. PublicLabhasawonderfulwriteupdescribinghowplanetrackingusingRTL-SDR yieldedinformationaboutFBI’ssurveillanceaircraftat http://publiclab.org/notes/ajawitz/06-11-2015/raspberry-pi-as-marine-traffic-radar. SatellitetrackingusingGPredictand RTL-SDR SatNOGSisanopensourceinitiativetobuildanetworkofgroundstationsaroundthe worldtotracksatellites.ThousandsoflowEarthorbit(LEO)satellitesareitsprincipal focus.Itsgoalistoprovideatoolsetandtechstack(hardwareandsoftware)thatislow costandeasytobuild. TheprojectsupportsVHFandUHFbandsforsatellitereceptionwiththedefault configuration.Itssoftwareautomaticallytracks,receives,andrecordssatellitesasthey passoverheadwhileautomaticallyschedulingobservationsandrecordingthemtoan onlinedatabasesharedamongotherparticipatinggroundobservers. Forthepurposeofsimplicity,wewillnotcoverhowtobuildthewholehardwarepartof thesystem,whichincludesahighgainantenna,trackingmotors,andastandardRTL-SDR dongleasareceiver.Inourrecipes,wewillonlyusethedongleandalow-costantenna. Youarewelcometogetmoreambitiouswiththehardware.Moredetailsareatthe SatNogswebsite(https://satnogs.org/). Settingupthesoftwarestackrequirestwopieces:asatellitetrackerandagroundstation. Satellitetracker Forthetrackingsoftware,theysuggestoneoftwopackages:eitherGPredict,apopular andvenerableopensourcesolutionforsatellitetrackingandorbitprediction,oracustom opensourceclientthattheSatNogsteambuiltinPython.Thelatterismorerobustand interoperatesmoreeasilywiththeantennaandrotormechanism.However,sincewewill notillustratethebuildoutoftherotorandthehardwarepartsofthesystem,wewilldoa recipearoundGPredict. GroundStation Onthegroundstationside,youcouldagainuseGPredict,whichincludesthiskindof functionality.However,inourrecipewewillbuildtheSatNogsNetworkcustomclientas itletsustastesomenewcodingflavors.Onceinstalled,thetoolgivesoperatorsan efficientwaytobothplantheirobservationsandcombinetheirtrackingdatawithmultiple groundstationsaroundtheworld. GPredict SatNogssuggeststwotoolsforsatellitetracking:theirowncustompackageandGPredict. WewillonlylookathowtouseGPredictasthispackageismorewidelyusedandcan serveasajumpingoffpointforsatellitetrackingbeyondjusttheSatNogsinitiative. Gpredictisareal-timesatellitetrackingandorbitpredictionapplicationthatcantrackan unlimitednumberofsatellitesanddisplaythedataintablesandnumerousgraphical views.TheapplicationactuallyexistsformorethanjustLinuxdistributions;itincludes theWindowsandMacOSXversions.However,unlikethecommercialOSversions,we willbuildarecipesetonouropensourcemicrocomputerthatgivesusgreaterflexibility onseveralfronts,suchasthefollowing: Dedicateddevice:ABBBSatNogsplatformgivesyoutheabilitytocreatea dedicatedsatellitetrackingdeviceinlieuofturningoveryourdesktoporlaptop exclusivelytosatellitetracking. Optimalplacement:Thepositionofyourgroundstation’santennaiscriticalasit impactsthequalityofyourdataandexperience.Creatingadevicethatcanbe enclosed,protected,andpositionedinalocationoptimizedforbettersatellitetracking isabetterlong-termstrategythanleavingyourlaptopontheroofofabuilding. Customalertsandsignals:Adevicethatcandeliveracustomsignalindicating whenthesatellitesareapproachingopensupnumerouspossibilitiesforphysical computing,IoT-enablement,andamoreindelibleuserexperience. Gettingready Thefollowingarethematerialsneeded: AnRTL-SDRdongle. Anantenna—Fortherecommendedlow-costantennathatweareusing,seethe Diamondantennainthepriorrecipeonplanetracking (http://www.aesham.com/glass/magnet/diamond-antenna-mr-75s/).Attachthe antennatotheRTL-SDRdongleviatheuSMLadapter. Anantennaadapter—Ifyouuseanantennaotherthanthesmallonethatoftencomes withthedongle,suchastheonementionedbefore,youwillneedtobuyaseparate adapter.Don’tworry!They’recheaptoo,andourswasonlyaboutUSD$6.00 (http://amzn.to/1WoB7Lq). PoweredUSB. EthernetorWi-Ficonnectivity. Howtodoit… Herearethestepsthatyouneedtoperform: 1. Installpackagedependenciesthroughthefollowingcommands: $sudoapt-getinstallautomakebuild-essentialmake $sudoapt-getinstallintltoollibgoocanvas-dev $sudoapt-getinstalllibgtk2.0-devlibcurl4-openssl-dev 2. Grabthesourcefileanduntaritasfollows: $wget http://downloads.sourceforge.net/project/gpredict/Gpredict/1.3/gpredict -1.3.tar.gz $tar-zxvfgpredict-x.y.z.tar.gz 3. Navigatetothenewdirectorycreatedwiththiscommand: $cdgpredict-1.x 4. Runtheusualstepstocompileandinstall,asfollows: $sudo./autogen.sh $sudo./configure $sudomake&&sudomakeinstall Note WerecommenddownloadingtheGPredictmanualat http://sourceforge.net/projects/gpredict/files/Gpredict/1.3/gpredict-user-manual1.3.pdf/download. 5. Onceyou’vegotGPredictinstalled,youwillwanttouseitsgraphicalinterfaceasit enjoysarobustGUIandiseasiertooperatethanthecommandline.Ifyoudon’thave anexternalmonitorconnectedtoyourBBB,powerdownandthenattachit. Alternatively,justcontinueheadlessandrunGPredictviavncserver: $vncserver 6. OpenupGPredict.Then,updatethetwo-lineelement(TLE)files.TLEisaformat originatedbyNASAtodisplayKeplerianelements.CommonlycalledKeps,theseare setsofnumbersallowingsatellitetrackingprogramstocalculateasatellite’sposition inspacewhilegivingusspecificinformationaboutitsorbitataspecificmoment. Kepsmustbeupdated,however,whichiseasytodointheUpdatemenu. Note HereisanexampleofaKeplerianelementfortheInternationalSpaceStation: 6May,2004 ISS 125544U98067A04127.92349537.0001709500000-014786-307232 22554451.6276176.05250011067106.0444249.603815.69246258311835 7. GPredictusestheterm“module”forwhatyouuseasyourdatasetofthesatellites youwanttotrack.So,createonebynavigatingtoFile|CreateNewModule| MODULENAME|.XX. 8. Fromthelittledownarrowbuttonintheupper-rightcornerofthescreen,select Clone.Thiswillcreateacloneofthemodulethatyouwillcustomizeandconfigure forthisrecipe. 9. Next,gotoConfigure|GroundStation+andgiveyoursaname.MineisNYC becausethat’swhereIlive. 10. Determineyourlocation,eitherusingapresetvaluefromtheSelectoptionorby fillingintheLatitudeandLongitudefields.I’vedonethelattertogetamoreprecise location.VariouswebsitescanprovideyouwithGPScoordinates.Iused http://mygeoposition.com/asitincludeselevationasavariable. 11. Now,wewanttochooseoursatellites.Althoughtherearecountless“birds”upthere intheheavens,forsimplicity’ssake,wewillstickwithourtouchstone,theISS.If youclonedthemoduleasdescribedintheprecedingsteps,youwillonlyneedto removethenonISSsatellitesastheISSisalreadyinthelist.However,youmayalso choosefromthemorethan1200satelliteslistedintheGPredictdatabase. 12. Onceyoumakeyourselection,themainwindowwillbeginpopulatingthedatawith theISS’sposition.Therearenumerousoptionstocustomizetheviewsofyour modules,whichyoucanlearnfromtheverythoroughusermanual. TheGpredictuserinterface Whatabeautifulviewyou’vegotonyourBBB! There’smore… TolearnmoreaboutTLEs,thevenerableRadioAmateurSatelliteOrganization,aka AMSAT,explainsitwellathttp://www.amsat.org/amsat-new/tools/keps_tutorial.php. Otheramateurandeducationalsatellitetrackingprojectscanbefoundat http://funcube.org.uk/. SatellitetrackingusingtheSatNogs Networkclient/groundstationandRTLSDR Inthepreviousrecipe,wecompiledandinstalledthepartthatactuallytracksthesatellite. Now,weneedtoaddthepieceofthesystemthatallowsustomanagethepotentialflood ofdata,shareitwithothers,andhavethemsharetheirdatabackwithus. NotethatthishasbeentestedsuccessfullyonDebianWheezy(3.8)andDebianJessie (13.4). Gettingready Thematerialsneededareasfollows: AnRTL-SDRdongle. Anantenna—fortherecommendedlow-costantennathatweareusing,refertothe DiamondAntennainthepriorrecipeonplanetracking (http://www.aesham.com/glass/magnet/diamond-antenna-mr-75s/). Anantennaadapter—ifyouuseanantennaotherthanthesmallonethatoftencomes withthedongle,suchastheonementionedbefore,youwillneedtobuyaseparate adapter.Don’tworry!They’recheaptoo,andourswasonlyaboutUSD$6.00 (http://amzn.to/1WoB7Lq).AttachtheantennatotheRTL-SDRdongleviatheuSML adapter. PoweredUSB. EthernetorWi-Ficonnectivity. Howtodoit… Herearethestepsyouneedtoperform: 1. Checkthatpipisinstalledandthepackagemanagementsystemusedtoinstalland managepackagesiswritteninPythonthroughthefollowingcommand: $piplist AsPython2.7.9andlaterversions(onthePython2series)andPython3.4andlater versionsincludepipbydefault,youmayhavepipalready.Ifnot,youcaninstallit thisway: 2. Downloadget-pip.pyathttps://bootstrap.pypa.io/get-pip.py. 3. Then,runthefollowing: $sudopythonget-pip.py 4. Installpackagedependenciesviathefollowingcommand: $sudopipinstallvirtualenvwrapper Note virtualenvisatooldesignatedtoaddresstheproblemofdealingwithpackages’ dependencieswhilemaintainingdifferentversionsfordifferentprojects.For example,ifyouworkontwoPythonDjangowebsites,onethatusesDjango1.2and another0.96,thereisnowaytokeepbothversionsifyouinstallthemintothe standard/usr/lib/python2/site-packages.virtualenvcreatestwoisolated environments. vitualenvwrappertakesvirtualenvastepfurtherbyprovidingcommandsthatcan beinvokedfromtheterminalwindow. 5. Sothatyourprogramknowswheretofindvirtualenvwrapper,modifyyourbash profilewiththefollowingcommand: $sudonano~/.bashrc 6. Attheendoftheopenfile,appenditwiththefollowing: exportWORKON_HOME=$HOME/.virtualenvs source/usr/local/bin/virtualenvwrapper.sh 7. Reloadthebashscriptwiththefollowingcommand: $sudosource~/.bashrc 8. Timetoinstallthedependencies.Usethefollowingcommands: $sudoapt-getinstalllibxml2-devlibxslt1-devpython-dev $sudopipinstalldjango $sudopipinstalldjango-dotenv 9. Now,it’stimetogetthecustompackagecreatedbytheSatNogsteam.First,wewill clonethesourcecodefromtherepositoryasfollows: $gitclonehttps://github.com/satnogs/satnogs-network.git 10. Setupthevirtualenvironment.Onthefirstrun,youshouldcreateitandlinkitto yourprojectpath.Thefollowingcommandswilldothis: $cdsatnogs-network $mkvirtualenvsatnogs-network-a. (Notethe.symbolattheendofthecommand,anddon’tusesudo.) 11. Setyourenvironmentalvariablesasfollows: (satnogs-network)debian@beaglebone:~/satnogs-network$cp.env-dist.env Note Takenotethatyouarenowinavirtualdirectory(satnogsnetwork)debian@beaglebone:~/satnogs-network$ 12. Activateyourpythonvirtualenvironmentwiththefollowingcommand: $workonsatnogs-network 13. Installthelocaldevelopmentrequirementsasfollows: $pipinstall-rrequirements/dev.txt ThisstepmaytakeawhileandconsumemostofyourBBB’sresourcesasit downloads,compiles,andinstallsthedevelopmentplatformtoshareyourSatNog trackingdata. 14. Createandsetupthedatabasewiththefollowingcommand: $sudo./manage.pymigrate 15. Wearenearlytherenow.Createasuperuserusingthiscommand: $./manage.pycreatesuperuser Followthepromptstoinputausername,e-mailaddress,andpassword. 16. Next,wewilladdsomedemodataintothedatabasesothatthereissomethingtolook attheendoftheroadasfollows: $./manage.pyinitialize 17. Whew!Timetoruntheserver.Usethefollowingcommand: $sudo./manage.pyrunserveryour_ip_address_here:8000 Ifyouexperienceproblemsgettingthebrowsertoresolveanaddress,shutdownthe server(bypressingCtrl+C),andrerunthecommandwiththefollowingnetwork address: $sudo./manage.pyrunserver0.0.0.0:8000 Theaddress,0.0.0.0,allowsyoutoreachtheserverfromanymachineinyour network. 18. Andnowthelaststop:openupabrowseronyourdesktopmachinetotheIPaddress andtheportyouusedinthepreviousstep.TheSatNogsNetworkweb-basedGUI shouldopenwithavarietyoffunctionsforstartingasatellitetrackingproject. YoucansignupasaGroundStationoperatorbyfirstconfirmingyouruser credentials.Lookintheterminalwindowforthefollowingoutput,whichcontainsa verificationlink: User<NAME>atexample.comhasgiventhisasanemailaddress. Toconfirmthisiscorrect,goto http://your_ip_address_here:8000/accounts/confirmemail/generated_string_here/ 19. Onceyou’vevalidatedyouremailaddress,youcanaddaGroundstationonthe SatNogNetwork(https://network-dev.satnogs.org/)similartotheonesinthe followingscreenshot: Now,thenexttimeyourebootorshutdowntheserverandthevirtualenv environmentandwanttorunSatNogsagain,justjumprighttothefollowingthree mainsteps,andyouwillbeofftotheraces: $cdsatnogs-network $workonsatnogs-network $sudo./manage.pyrunserveryour_ip_address:8000 Addingotherinterfaces–ISStracking andtexttospeech It’stimetomakethedogtalk.Or,atleast,makeBeagleBoneBlackalittlemoreverbal. Here,wewillshowyoutheingredientstohavetheboardtellus—insteadofshowingus— whentheInternationalSpaceStationisgettingclose. Gettingready Thematerialsneededare: AUSBAudiodongle—Wewilluseaninexpensive,low-profileversion (http://bit.ly/1KxQatr),thoughanyUSBversionisfine Anaudiospeakerwithaminijackthatplugsintotheaudiodongle AUSB-poweredhub A5Vpowersupply AnInternetconnection,EthernetorWi-Fi PowerupyourBBBviathe5Vsupply,openaterminalwindowonyourclientbox,then SSHintotheboard. Howtodoit… Therearefivepartstothisrecipe: Audiosetupandtesting InstallingTexttoSpeech(TTS)andtesting PythoncodingtocalculatetheISS’scurrentdistancefromyou Bashscripting Doingacronjobtoautomaticallyrunallofthese PartI:AudioSetupandtesting Performthefollowingsteps: 1. AlthoughyoumayhavesomeofthesetoolsonboardyourBBBalready,weshould checktomakesure.Thefollowingcommandswillbeuseful: $sudoapt-getupdate $sudoapt-getinstallalsa-basealsa-utils $sudoapt-getinstallmplayer 2. Checkthatthesystemseesyouraudiodonglewiththiscommand: $lsusb Bus001Device002:ID1a40:0201TerminusTechnologyInc.FE2.17-port Hub Bus001Device001:ID1d6b:0002LinuxFoundation2.0roothub Bus002Device001:ID1d6b:0002LinuxFoundation2.0roothub Bus001Device003:ID0d8c:013cC-MediaElectronics,Inc.CM108Audio Controller 3. Takealookatwhichaudiodevicesareavailablethroughthefollowingcommand: $aplay-l ****ListofPLAYBACKHardwareDevices**** card0:Black[TIBeagleBoneBlack],device0:HDMIhdmi-hifi-0[] Subdevices:0/2 Subdevice#0:subdevice#0 card1:Device[USBPnPSoundDevice],device1:USBAudio[USBAudio] Subdevices:1/2 Subdevice#1:subdevice#1 4. OntheBBB,ALSAgivespreferencetotheHDMIport’saudiochannel,whichwe needtochangetotheUSBsounddongle.First,wehavetodisabletheHDMIaudio outputwiththiscommand: $sudonano/boot/uEnv.txt Editthefollowingline: ##DisableHDMI #cape_disable=capemgr.disable_partno=BB-BONELT-HDMI,BB-BONELT-HDMIN Afterediting,theprecedinglineshouldlooksimilartothis: ##DisableHDMI cape_disable=capemgr.disable_partno=BB-BONELT-HDMI,BB-BONELT-HDMIN 5. Savetheopenfile(bypressingCtrl+O)andthenenterandexitnano(bypressing Ctrl+X). 6. Next,wewillmodifytheALSAconfigurationfilesothatitrecognizesouraudio dongleasthedefaultdevice: $sudonano/etc/modprobe.d/alsa-base.conf 7. Duplicatethefollowingline: #Keepsnd-usb-audiofrombeingloadedasfirstsoundcard optionssnd-usb-audioindex=-2 8. Then,commentoutoneofthelinesandchange-2to0intheuncommentedline: #Keepsnd-usb-audiofrombeingloadedasfirstsoundcard #optionssnd-usb-audioindex=-2 optionssnd-usb-audioindex=0 9. Savetheopenfile(bypressingCtrl+O)andthenenterandexitnano(bypressing Ctrl+X). 10. RebootyourBBBwiththisline: $sudoreboot 11. VerifythattheHDMIaudioisnolongerpresentandthatonlytheUSBdongle appearsbypastingthiscommand: $aplay–l^s ****ListofPLAYBACKHardwareDevices**** card0:Device[USBPnPSoundDevice],device0:USBAudio[USBAudio] Subdevices:1/1 Subdevice#0:subdevice#0 12. ConfirmthatitloadedproperlyandisavailabletoALSAwiththiscommand: $cat/proc/asound/cards 0[Device]:USB-Audio-USBPnPSoundDevice C-MediaElectronicsInc.USBPnPSoundDeviceatusb-musbhdrc.1.auto-1.5,full 13. Openupalsamixersothatwecantweakthevolumesettings.Youshouldseeyour sounddongleasthedefaultdeviceintheupper-leftcorneroftheGUI: $alsamixer ChoosetheSpeakeroptionandusetheuparrowtoincreasethevolume: TheAlsamixerwindow 14. ClosethewindowwiththeEsckey. 15. Doasimpletesttocheckaudiooutputwiththefollowingcommand: $aplay/usr/share/sounds/alsa/Front_Center.wav-Dsysdefault:CARD=0 YoushouldheartheniceladysayinEnglish“Front.Center.” Whew!NotexactlyPlugandPlay,butthat’sopensourceforyou…. PartII:InstallingTTS Let’smovealongtomakingtheBBBspeakusingthetext-to-speech(TTS)engine,SVOX Pico.AlthoughthereareotherTTSoptionsavailable,suchasE-Speak,Festival,and GoogleVoice(referencedattheendofthisrecipe),Pico’squalityisbetterthanmostand doesnotrequireacloudconnection: 1. AsitisnotavailableintheDebianreposforARMdevices,weneedtoinstallSVOX Picofromsource.First,however,weneedtoensurethatwehavealldependencies withthesecommands: $sudoapt-getupdate $sudoapt-getinstallautomakelibtoollibpopt-dev 2. Now,wecaninstallthesourcefilesusingthesecommands.Itisnottoolengthyan install;ittakesperhapsaroundfiveminutestocomplete: $gitclone-bupstream+patchesgit://git.debian.org/collabmaint/svox.gitsvox-pico $cdsvox-pico $cdpico $automake $sudoautomake $./autogen.sh $./configure $sudomakeall $sudomakeinstall $sudoldconfig 3. Runasampletexttospeechtestusingtwodifferentaudioplaybacktools,mplayer, whichwejustinstalled,oraplay,whichisalreadyonoursystem: $pico2wave-wtest.wav"ThisisGroundControl"|mplayer-ao alsa:device=hw=0test.wav Takenoteofthevarioussettingsandoptionsneededtorunthepackageproperly. Pico2waveuseswavfiles,sowewillfirstusethe-woptionandthenthefilename thatwewillcreate.Thiswillbefollowedbytheactualtextthatwillberecordedand spoken.Thelastoptionsarethosetochooseaplaybacktool(inthiscase,mplayer), settherightdevice,andthencallthefilenamejustrecorded. Alternatively,wecanuseanotheraudiopackage:aplay.Althoughitisnotasfull featuredasmplay,itiseasiertouseasitrequiresfewersettings.Runthefollowing commandforthis: $pico2wave-wtest.wav"ThisisGroundControl"&&aplaytest.wav Regardlessoftheplayeryouuse,youshouldgetafemalespeakersayingThisis GroundControlintheEnglishlanguageoutofyourspeaker.Youcanchangethe output,ofcourse,includingthespeaker’slanguage,aslongasitisEnglish(UKor US),German,Italian,French,orSpanish. PartIII:PythoncodingtocalculatetheISS’scurrentdistancefromyourlocation Next,wewillusesomePythoncodetotracktheInternationalSpaceStation. 1. IfyoudidtheearlierrecipeinthisbookwithGPredicttotracktheISS,youwould alreadyhavetherepodownloaded.Ifnot,getitfromourGitHubrepoandthen browsethedirectoryasfollows: $gitclonehttps://github.com/HudsonWerks/space-satellite.git $cdspace-satellite 2. Let’stakealookatwhatthecodedoes.Youcanopenitupinananoeditorwindow byrunningthiscommand: $sudonanoISS_current_distance.py Alternatively,youcancopyandpastethecodeintoanewCloud9file. Note Forsimplicity’ssake,wewilluseadifferentsetofcodetotracktheISSthanwedid anearlierrecipeinthischapter.Here,wedonotwanttorunanX-sessionasinthe previousexample;instead,wewanttofocusonanalternativeuserinterface. However,agoodexercisewouldbetocombinethetwopiecesofcodeintooneso thatyoucanexploitbothTTSandagraphicalrenderingoftheISSlocationinthe samescript. Thecodeisheavilycommentedandpareddowntoonlyoutputthecurrentdistance fromthelatitudeandlongitudecoordinatesyousetandstoponcethetaskis completed..Infact,beforemovingon,youmustinputyourhomelatitudeand longitudecoordinatesinthedesignatedcodeblocksinorderforthescripttorun: home_lat=HOME_LATITUDE home_long=HOME_LONGITUDE 3. Afterinputtingyourcoordinates,savethemodifiedcodethenrunit: $sudopythonISS_current_distance.py Youshouldseeamultidecimalnumbershowingthecurrentkilometerdistancefrom yourcoordinates(yournumberwillvary,naturally): 3631.37279398 Theoutputisalittleunderwhelming,isn’tit?However,thisisbydesign;itdoesnotkeep updatingthenumberaswerunthescriptaccordingtospecifiedintervals,andwewantthe TTSenginetocaptureasnapshotinrealtimeoftheISS’slocationrelativetowhereyou are. PartIV:Creatingabashscript Tocreateamoreinterestingexperience,wewillhaveabashscriptrunthePythoncode, stampthetime,andtellusallaboutitviatheTTSengine: 1. Openupananoeditorwindowandcreateanewfile,asfollows: $sudonanotimeTTS-ISS.sh 2. Copyandpastethefollowingbashcodeintheopenwindow: #!/bin/bash #CreateavariablethatwillrunthePythonscript ISS=$(sudopython/home/debian/ISS-current-distance.py) #CreateavariablethatwillgrabthecurrentUTCtime,combineit withtheoutputfromthePythonscript,andincludethetextthatwe wanttheTTSenginetospeak NOW=$(date+"GroundControltimeis%Mminutespast%l%pUTCwith currentdistancetotheInternationalSpaceStation$ISSmiles") echo$NOW #RuntheTTSagainstthevariablewecreated,andthenplayitback pico2wave-wGroundControlTime-ISS.wav"$NOW" aplayGroundControlTime-ISS.wav Thecommentsareprettyself-explanatory;twovariablesarecreated:onetorunthe Pythonfileandtheothertodoacurrenttimestamp.Afterthis,combinethevariables togetherintoaTTSaudiofilethatisplayedback. Note Becarefulnottotruncatecodethatyoucopyandpasteeitherinoroutofanano window. 3. Makethefileexecutablewiththefollowingcommand: $sudochmod+xtimeTTS-ISS.sh PartV:Settingupacronjob Wewanttoautomatetheuseofthebashandpythonscriptssothatwecangetcontinuous readingsandfeedbackwithouthavingtomanuallystartthem: 1. Setupacronjobsothatthescriptwillrunonaschedule.Wehavenotdonethisfor severalchapters,sohereiswhatwewilldo: $sudocrontab-e 2. Copyandpastethefollowinglineatthebottomoftheopenwindow: */30****sudobash/home/debian/timeTTS-ISS.sh Thiswillrunourscriptat30-minuteintervals.Change30to1inordertotestitright away. We’vedoneit!AtalkingBeagleBoneBlackthatcapturesdynamicallygeneratedtracking dataandtellsuswhentheInternationalSpaceStationgetswithinstrikingdistance! There’smore… TexttoSpeech TheTTSoptionsonRpi,mostofwhichcanbeportedtotheBBB,canbefoundat http://elinux.org/RPi_Text_to_Speech_(Speech_Synthesis). E-Speak—Forinstallandsetupinstructions,referto http://hudsonwerks.com/beaglebone-black-recipes/voice-recognition-tts/. Festival—Thisisaquickandeasyoption,commonlyusedonRpi,withvarious tutorialsavailable. GoogleVoice—Thisisagreatreferenceforhigherqualityvoicesandvariety. However,theengineiscloud-based,soyouneedcontinuousinternetaccesstouseit. Additionally,Googlewilloftenthrottleusagefromscriptsbypingingtheservice,so youmayencounterdifficultiesusingit. Voicerecognition Theotherlegofavoiceuserinterfaceisvoicerecognition,whichisbeyondthescopeof thisbook.However,severaltutorialsareoutthereforboththeBBBandtheRPithatcan takeyoudownthepathofvoice-actuateddevicecontrol. TakealookattheJasperprojectthroughthefollowinglinks: http://blog.oscarliang.net/raspberry-pi-voice-recognition-works-like-siri/ http://jasperproject.github.io/documentation/installation/ https://teslafly.wordpress.com/2014/09/22/installing-jasper-on-the-beaglebone-black/ BloggerandtechnologistSteveHicksonhasalsomadegreatstridesingettingvoice recognitiononboardtheRPiathttp://stevenhickson.blogspot.com/. Otherspace-relatedProjects AvarietyofotherprojectsusingtheBeagleBoneBlackforspace-relatedpurposesare underway.Hereareafew: NASA’siceroversandtheBeagleBoneBlack:NASA’sJetPropulsionLabisusing theBBBinanearlyprototypeforaroverthatcouldbeusedonJupiter’sicymoon, Europa.BeingtestedinicyconditionsinAlaska,theroveractuallycrawlsonthe undersideoftheiceasifit’sontheground(https://youtu.be/sY5WQG3-3mo).Here isaclose-upofBeagleBoneBlackinsidetheicerover: Credit:NASA/JPL. Here,youcanseeaniceroverabouttodescendunderneaththeice. Credit:NASA/JPL. HereistheBBB-poweredrovercrawlingundertheice. Credit:NASA/JPL. BeagleSat:ThisisanexcellentGoogleSummerofCode(GSOC)projectdeveloped byNikoVisnjic.Theobjectiveofthiswork-in-progressistosendaBBB-driven sensorpayloadintospaceaboardaCubeSat,thesmallformfactorsatellitepayload specification(http://nvisnjic.com/beaglesat/).Codefortheprojectisalsoavailableon Githubathttps://github.com/nvisnjic/BeagleSat. NASA’sCubeQuestchallenge:Formoreinformation,referto http://www.nasa.gov/cubequest/details/. Index A AdafruitI/O URL/Seealso airplanetracking RTL-SDRused/AirplanetrackingwithRTL-SDR,Howtodoit… alternativescript writing,Pythonused/WritinganalternativescriptwithPython AMSAT URL/There’smore… Antenna URL/Gettingready antenna URL/Gettingready application debuggingremotely,fromEclipse/DebuganapplicationremotelyfromEclipse andGDBserver debuggingremotely,fromGDBserver/Debuganapplicationremotelyfrom EclipseandGDBserver apt-get used,forinstallingpackages/Packagemanagement–Installingpackagesusing apt-get,Seealso autotoolsarcana URL/Seealso autotoolstoolset URL/Seealso B BBB URL/Seealso Beacon URL/There’smore… Beacons/Location-basedrecipes–BluetoothLEandBeacons smartphone,settingup/Howtodoit… simpleIoTtestenvironment,settingup/Howtodoit… BBB,settingup/Howtodoit… BeagleBoneBlack audio,bringingon/Introduction BeagleboneBlack(BBB) about/Firstbootup,Howtodoit… bootup/Firstbootup,Howtodoit…,Howtodoit… prerequisites/Gettingready powerrequisites/Powerrequirements–basicguidelines display/Display controlling,SSHused/UsingSSHtocontrolyourBBB,Howtodoit… controlling,VirtualNetworkComputing(VNC)used/UsingVNCtocontrol yourBBB,Howtodoit…,There’smore… BeagleBoneBlackSystemReferenceManual URL/Headerpinsandpinmuxing BeagleSat URL/There’smore… BluetoothClassic versusBTLEdiscussion,URL/There’smore… installationtroubleshooting,URL/There’smore… bluetoothdongles URL/Gettingready BluetoothLowEnergy(BLE) about/Location-basedrecipes–BluetoothLEandBeacons classicBluetooth/Location-basedrecipes–BluetoothLEandBeacons keyelements/Location-basedrecipes–BluetoothLEandBeacons BoneScript about/IntroductiontoBoneScript URL/Seealso BoneScriptLibrary URL/Introduction boottime optimizing/Optimizeboottime BTLEdocumentation URL/There’smore… Bubbleapp URL/There’smore… buttonpress about/Pull-up,pull-down,andfloating,Howtodoit… buttons using/Usingbuttons–buttonpressfunction C C-codeapplication debuggingfromcommandline,GDBused/DebugasimpleC-codeapplication fromthecommandlineusingGDB,Howtodoit…,Seealso capes about/Connectinganon-HDMILCDorcape Cloud9IDE using/UsingtheCloud9IDE,Howtodoit… commandlineinterface(CLI)/Gettingready pointers/Gettingready commandmemento URL/Seealso commands URL/Seealso forsystemdservices/Basiccommandsforsystemdservices,Howtodoit… commandshell textfile,editingfrom/Editatextfilefromthecommandshell,Howtodoit…, Seealso compatibleconverters URL/Connectinganon-HDMILCDorcape compileandinstall about/Compileandinstall documentationstandards/Compileandinstall BeagleBoneBlack,compilingon/Compileandinstall Git,fromsource/CompileandinstallGitfromsource connectivity about/Connectivity ethernet/Connectivity–Ethernet,Howtodoit… Wi-Fi/Connectivity–Wi-Fi,Gettingready,Howtodoit…,There’smore… content/datacommands,modifying newdirectory,creating/Modifycontent/datacommands–makeanew directory–mkdir file,removing/Modifycontent/datacommands–removeafileordirectory– rm,Howtodoit… directory,removing/Modifycontent/datacommands–removeafileor directory–rm,Howtodoit… files,downloading/Modifycontent/datacommands–downloadfiles–wget, There’smore… tarfile,opening/Modifycontent/datacommands–openatarfile–tar [options],Howtodoit… files,cleaningup/Modifycontent/datacommands–cleanupfiles–autoclean packagepurge/Modifycontent/datacommands–purgeapackage–apt-get purge,apt-getremove—purge,Howtodoit… system,shuttingdown/Modifycontent/datacommands–shutdownthesystem –[options],Seealso conventions/Gettingready currentOSkernel updating/UpdatingyourcurrentOSkernel,Seealso customkernel installing/Installingandbuildingacustomkernel,Howtodoit… D data using,withThingSpeak/UsingsensorsanddatawithThingSpeak,Howtodo it… DCmotors about/DCmotors,Gettingready,Howtodoit…,Howitworks… requisites/Gettingready Debian URL/Howtodoit… debugging about/Debugging,Seealso deviceandsysteminsight directorycontent,displaying/Deviceandsysteminsight–showswhat’sinside adirectory–ls,Howtodoit… connectedUSBdevices,finding/Deviceandsysteminsight–findoutwhat USBdevicesareconnected–lsusb connecteddevices,finding/Deviceandsysteminsight–getinformationabout connecteddevices–cat/proc/bus/input/devices,There’smore… Linuxversion,getting/Deviceandsysteminsight–getyourversionofLinux, Howtodoit… runningprocesses,finding/Deviceandsysteminsight–findoutrunning processes–ps,Howtodoit… resourcesusedbyrunningprocesses,finding/Deviceandsysteminsight–find outtheresourcesusedbyrunningprocesses–topandhtop,Howtodoit… processes,killing/Deviceandsysteminsight–quittingprocesses–kill,Howto doit… messagereports/Deviceandsysteminsight–messagereports–dmesg,Howto doit… diskspace,showing/Deviceandsysteminsight–showsdiskspace–df-h network,exploring/Deviceandsysteminsight–explorenetwork–Ifconfig, Howtodoit… DeviceTree about/DeviceTreeanditsroots benefits/DeviceTreeanditsroots basicbuild/DeviceTree/basicbuild,Howtodoit… overlay,addingtoruncustomcape/DeviceTree/advanced–addingDT overlaytorunacustomcape,Gettingready,Howtodoit…,Seealso DeviceTreeBlob(DTB)/DeviceTreeanditsroots DiamondAntenna URL/Gettingready DigitalMusicalInstruments(DMIs)/Seealso DigitaltoAnalogConverter(DAC) URL/Wiringupaminiampandspeakers Docker URL/Seealso dongles URL/Seealso Dropbox URL/Gettingready Dweet.io/Freeboard URL/Seealso E E-Speak URL/There’smore… Eclipse application,debuggingremotely/DebuganapplicationremotelyfromEclipse andGDBserver,Howtodoit… electronics about/Theessentialsofelectronics EricStevenRaymond(ESR)/Seealso Estimoteteardown URL/There’smore… EvothingsStudio URL/Howtodoit… externalLEDs controlling/ControllingexternalLEDs,Howtodoit… G GDB usedfordebuggingC-codeapplication,fromcommandline,/Debugasimple C-codeapplicationfromthecommandlineusingGDB,Howtodoit…,Seealso GeneralPurposeIn/Out(GPIO) about/IntroductiontoBoneScript Git compileandinstall,fromsource/Howtodoit… GNU/Linuxcommands commandshell/EssentialGNU/Linuxcommands–thecommandshell,Howto doit…,Howitworks… typicalcommands/EssentialGNU/Linuxcommands–typicalcommands, Gettingready GoogleSummerofCode(GSOC)/There’smore… GPredict used,forsatellitetracking/SatellitetrackingusingGPredictandRTL-SDR, Howtodoit… about/SatellitetrackingusingGPredictandRTL-SDR GPredictmanual URL/Howtodoit… GPS hookingup/Location-basedrecipes–hookingupGPS,Howtodoit… toolset,installing/Howtodoit… URL/There’smore… GPScoordinates URL/Howtodoit… GPSD troubleshooting,URL/There’smore… GPSPCB URL/Gettingready groundstation about/SatellitetrackingusingGPredictandRTL-SDR H HDMI troubleshooting,URL/There’smore… HDMILCD connecting/ConnectinganHDMILCD,Howtodoit… URL/Howtodoit… headerpins about/Headerpinsandpinmuxing high-qualityaudioplatform creating,Volumioused/Creatingahigh-qualityaudioplatformwithVolumio, Gettingready,Howtodoit…,There’smore…,Seealso I I2C about/Wiringupaminiampandspeakers I2Cbuses I2C0/Wiringupaminiampandspeakers I2C1/Wiringupaminiampandspeakers I2C2/Wiringupaminiampandspeakers iBeacons/Location-basedrecipes–BluetoothLEandBeacons IfThisThenThat(IFTTT)webservice URL/Gettingready about/Gettingready IFTTTSpaceChannel URL/Howtodoit… initialstate URL/Seealso IntegratedInterchipSound(I2S)bus/Wiringupaminiampandspeakers InternationalSpaceStation(ISS)/Howtodoit…,GrabbingtheInternationalSpace Stationflyoverdataandvisualizingit InternetofThings(IoT) about/Introduction ISSsflyoverdata grabbing/GrabbingtheInternationalSpaceStationflyoverdataandvisualizing it,Howtodoit… URL/Howtodoit… RTL-SDR,usedfortracking/TrackingusingRTL-SDR ISStracking URL/There’smore… about/Addingotherinterfaces–ISStrackingandtexttospeech,Howtodo it… TTS,installing/Howtodoit… bashscript,creating/Howtodoit… cronjob,settingup/Howtodoit… ITPsolderinglesson URL/Howtodoit… J Jasperproject URL/There’smore… Java toNode.js,URL/There’smore… Johnny-Five Node.js,usingwith/UsingNode.jswithJohnny-Five,Howtodoit…,There’s more… URL/There’smore… K kernel building,basics/Kernelbuildingbasics,Seealso applicationbinaryinterface/Kernelapplicationbinaryinterface,Howit works… interactionswith/Interactionswiththekernel–sysfsentriesandcontrollingthe GPIOs,Howtodoit… modifying,RT-PREEMPTused/ModifyingthekernelusingRT-PREEMPT, Howtodoit…,ModifyingthekernelusingXenomai kernelimage latestkernelimage,installing/Installingthelatestkernelimage,Howtodoit… L LCDcapeoptions URL/There’smore… LEDs controlling,Pythonscriptrunningfor/Howtodoit…,There’smore… references/There’smore… Linphone used,forcreatingvideochatclientprototype/Makingavideochatclient prototypeusingLinphone,PartI–compilingandinstallingaLinphonebinary fromtherepository binary,compilingfromrepository/PartI–compilingandinstallingaLinphone binaryfromtherepository binary,installingfromrepository/PartI–compilingandinstallingaLinphone binaryfromtherepository compiling,fromsource/PartII–compilingandinstallingLinphonefrom source,Howtodoit… installing,fromsource/PartII–compilingandinstallingLinphonefrom source,Howtodoit… Linux URL/Seealso location-basedrecipes about/Location-basedrecipes–hookingupGPS GPS,hookingup/Location-basedrecipes–hookingupGPS BluetoothLE/Location-basedrecipes–BluetoothLEandBeacons beacons/Location-basedrecipes–BluetoothLEandBeacons lowEarthorbit(LEO) about/SatellitetrackingusingGPredictandRTL-SDR /SatellitetrackingusingGPredictandRTL-SDR LXQt/OSimageflashing–internaldriveboot M M4Afilesupport URL/Seealso Makeuseof URL/Seealso microUSBdonglemodels/Gettingready MiniAmp wiringup/Wiringupaminiampandspeakers,Gettingready,Howtodoit… miniLCDcape testing/TestingaminiLCDcape,Howtodoit… module newmodule,addingtoNode.js/AddinganewmoduletoNode.js,Howtodo it…,Seealso motors using/Usingmotors MusicPlayerDaemon(MPD)/Creatingahigh-qualityaudioplatformwithVolumio N NASA’sCubeQuestchallenge URL/There’smore… NMapsecurityscanner URL/There’smore… Node.js recipes/Node.jsbasicrecipes URL/There’smore… using,withJohnny-Five/UsingNode.jswithJohnny-Five,Howtodoit…, There’smore… nodemailer URL/Seealso nodemodules URL/There’smore… Nodered.js URL/Seealso non-HDMILCD connecting/Connectinganon-HDMILCDorcape,Howtodoit… O Ohm’slawcalculatortool URL/Theessentialsofelectronics OLEDPCB URL/Gettingready OSimageflashing internaldriveboot/OSimageflashing–internaldriveboot,Howtodoit… partition,expanding/Expandyourpartition codeimage,backinguptofile/Backingupacodeimagetoafile SDcardboot/OSimageflashing–theSDcardboot,Howtodoit… P packagemanagement about/Packagemanagement–Installingpackagesusingapt-get packages installing,apt-getused/Packagemanagement–Installingpackagesusingaptget,Howtodoit…,Seealso updating/Gettingready upgrading/Gettingready PCBamp URL/Howtodoit… pinlayouts sources/There’smore… references/There’smore… pinmuxing about/Headerpinsandpinmuxing process/Theprocessofpinmuxing playlist(PLS)files/Creatingahigh-qualityaudioplatformwithVolumio Programmablereal-timeunits(PRU) about/Programmablereal-timeunits–anintroduction,Howtodoit… test,withassembler/AsimplePRUtestwithanassembler,Gettingready,How todoit… ultrasonicrangesensor,running/Runninganultrasonicrangesensorwiththe PRUs,Howtodoit… Python,usingwith/UsingPythonwiththePRUs,Howtodoit…,Seealso projects video,using/Usingvideosanddisplaysinprojects,Gettingready,Howtodo it… displays,using/Usingvideosanddisplaysinprojects,Gettingready,Howtodo it… miniOLED,hookingup/Usingvideosanddisplaysinprojects,Gettingready PRUCAPE/Seealso Python basicrecipes/Pythonbasicrecipes libraries,adding/Addinglibraries,Howtodoit… used,forwritingalternativescript/WritinganalternativescriptwithPython using,withPRUs/UsingPythonwiththePRUs,Howtodoit…,Seealso Pythonscript running,tocontrolLEDs/RunningaPythonscripttocontroltheLEDs,Howto doit…,There’smore… R Resin.io URL/Seealso RT-PREEMPT used,formodifyingkernel/ModifyingthekernelusingXenomai,Howtodo it…,There’smore… RTL-SDR used,fortracking/TrackingusingRTL-SDR,Seealso URL/Seealso used,forairplanetracking/AirplanetrackingwithRTL-SDR,Howtodoit… used,forsatellitetracking/SatellitetrackingusingGPredictandRTL-SDR, Howtodoit… S satellitetracker about/SatellitetrackingusingGPredictandRTL-SDR satellitetracking GPredictused/SatellitetrackingusingGPredictandRTL-SDR,Gettingready, Howtodoit… RTL-SDRused/SatellitetrackingusingGPredictandRTL-SDR,Gettingready, Howtodoit…,SatellitetrackingusingtheSatNogsNetworkclient/ground stationandRTL-SDR,Gettingready,Howtodoit… SatNogsNetworkclientused/SatellitetrackingusingtheSatNogsNetwork client/groundstationandRTL-SDR,Howtodoit… groundstationused/SatellitetrackingusingtheSatNogsNetworkclient/ groundstationandRTL-SDR,Gettingready,Howtodoit… SatNogsNetworkclient used,forsatellitetracking/SatellitetrackingusingtheSatNogsNetworkclient/ groundstationandRTL-SDR,Howtodoit… script running,tocheckDTusageonGPIOpins/RunningascripttocheckDTusage onGPIOpins,Howtodoit… sensors using,withThingSpeak/UsingsensorsanddatawithThingSpeak,Howtodo it… SerialPeripheralInterface(SPI) URL/Usingvideosanddisplaysinprojects servomotors about/Servomotors,Howtodoit… shellscripts about/Thebasicshellscript,Howtodoit… Ship.iot URL/Seealso SIPaccount settingup/Howtodoit… SoftwareDefinedRadio(SDR)/TrackingusingRTL-SDR soldering URL/Howtodoit… Sparkfun URL/Gettingready,Gettingready speakers wiringup/Wiringupaminiampandspeakers,Gettingready,Howtodoit… SPIdevpins URL/There’smore… SSH used,forcontrollingBBB/UsingSSHtocontrolyourBBB,Howtodoit… SSH/Remoteaccess about/SSH/Remoteaccess systemdcommands quickreferencecheatsheet,URL/There’smore… systemdservice creating,torunatboottime/Createasystemdservicetorunatboottime,How todoit… systemdservices about/systemdservices,There’smore… systemimages about/Systemimages Systemnavigationalcommand directory,changing/Systemnavigationalcommand–changeyourdirectory– cd,There’smore… currentdirectory,showing/Systemnavigationalcommand–showyourcurrent directory–pwd file,finding/Systemnavigationalcommand–findafile–find,Howtodoit… T testtool about/Installingatesttool,Howtodoit… textfile editing,fromcommandshell/Editatextfilefromthecommandshell,Howto doit…,Seealso texttospeech(TTS) about/Addingotherinterfaces–ISStrackingandtexttospeech,Howtodo it…,There’smore… audioSetupandtesting/Howtodoit… Pythoncode,usedfortrackingInternationalSpaceStation/Howtodoit… bashscript,creating/Howtodoit… cronjob,settingup/Howtodoit… URL/There’smore… ThingSpeak sensors,usingwith/UsingsensorsanddatawithThingSpeak,Howtodoit…, Seealso data,usingwith/UsingsensorsanddatawithThingSpeak,Howtodoit…,See also URL/Howtodoit… ToggleLED about/ToggleLED,Seealso two-lineelement(TLE)files/Howtodoit… URL/There’smore… U Ubidots about/Seealso URL/Seealso ultrasonicrangesensor running,withPRUs/RunninganultrasonicrangesensorwiththePRUs,How todoit… Universalasynchronousreceiver/transmitter(UART)/Location-basedrecipes– hookingupGPS universalcapeoverlay about/Universalcapeoverlay,Howtodoit… UniversalUniqueIdentified(UUID)/Location-basedrecipes–BluetoothLEand Beacons V 5Vpower URL/Gettingready videochatclientprototype creating,Linphoneused/MakingavideochatclientprototypeusingLinphone, PartI–compilingandinstallingaLinphonebinaryfromtherepository,Howto doit… VirtualNetworkComputing(VNC) used,forcontrollingBBB/UsingVNCtocontrolyourBBB,Howtodoit…, There’smore… Viewer,URL/Gettingready… voicerecognition/There’smore… Volumio used,forcreatinghigh-qualityaudioplatform/Creatingahigh-qualityaudio platformwithVolumio,Howtodoit…,There’smore…,Seealso URL/Creatingahigh-qualityaudioplatformwithVolumio,Gettingready,See also running,prerequisites/Gettingready W wirelessdigitalpictureframe building/Makingthingssmarter–buildingawirelessdigitalpictureframe, Howtodoit… IfThisThenThat(IFTTT)webservice,using/Gettingready smartphone,settingup/Howtodoit… Dropboxscript,settinguponBBB/Howtodoit… Dropboxscript,testingonBBB/Howtodoit… desktopclient/Howtodoit… BBB/Howtodoit… script,testing/Howtodoit… script,running/Howtodoit…