TableofContents
AndroidfortheBeagleBoneBlack
Credits
AbouttheAuthors
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Errata
Piracy
Questions
1.IntroductiontoAndroidandtheBeagleBoneBlack
LookingbackonAndroidandBeagleBoneBlackdevelopment
Shoppingforthehardwareessentials
TheFTDIcable
Powersupply
Breadboardandthemountingplate
MicroSDcards
Learningaboutthehardwareyou’llinterfacewith
General-purposecomponents
TheAdaFruitmemorybreakoutboard
www.it-ebooks.info
TheAdaFruitsensorbreakoutboard
Preparingthebreakoutboards
InstallingAndroidontheBeagleBoneBlack
DownloadingapremadeAndroidimage
CreatingyourAndroidmicroSDcardusingWindows
CreatingyourAndroidmicroSDcardusingLinux
Summary
2.InterfacingwithAndroid
UnderstandingtheAndroidHAL
Androidmanagers
TheHALdevelopmentworkflow
WorkingwithPacktHAL
InstallingPacktHAL
PreparingPacktHALunderLinux
PreparingPacktHALunderWindows
ThePacktHALdirectorystructure
PreparingAndroidforPacktHAL
PushingPacktHALfilesunderLinux
PushingPacktHALfilesunderWindows
SettinguptheAndroidNDKforPacktHAL
AddingtheheadertotheNDKunderLinux
AddingtheheadertotheNDKunderWindows
MultiplexingtheBBBpins
ThekernelDeviceTreeandcapemgr
Definingacape
Summary
3.HandlingInputsandOutputswithGPIOs
UnderstandingGPIOs
NutsandboltsofGPIO
GPIOaccessmethodsunderAndroid
ProsandconsofthefileI/Omethod
www.it-ebooks.info
Prosandconsofthememory-mappingmethod
PreparingAndroidforGPIOuse
BuildingaGPIO-interfacingcircuit
Constructingthecircuit
Checkingyourwiring
IncludingPacktHALwithinyourapps
UnderstandingtheJavaNativeInterface
CreatinganewappprojectthatusesPacktHAL
BuildingPacktHALunderWindows
BuildingPacktHALunderLinux
ExploringtheGPIOexampleapp
InstallingtheappandsourceunderWindows
InstallingtheappandsourceunderLinux
Theapp’suserinterface
CallingthePacktHALfunctions
UsingthePacktHALGPIOfunctions
Summary
4.StoringandRetrievingDatawithI2C
UnderstandingI2C
DevicesthatuseI2C
MultiplexingforI2ContheBBB
ConnectingtoI2CviatheP9header
MultiplexingforI2C
RepresentingI2CdevicesintheLinuxkernel
PreparingAndroidforFRAMuse
BuildinganI2C-interfacingcircuit
ConnectingtheFRAM
CheckingtheFRAMconnectionwithI2Ctools
ExploringtheI2CFRAMexampleapp
Theapp’suserinterface
CallingthePacktHALFRAMfunctions
www.it-ebooks.info
UnderstandingtheAsyncTaskclass
LearningthedetailsoftheHardwareTaskclass
Summary
5.InterfacingwithHigh-speedSensorsUsingSPI
UnderstandingSPI
MultiplexingforSPIontheBBB
RepresentingSPIdevicesintheLinuxkernel
PreparingAndroidforSPIsensoruse
BuildinganSPIinterfacecircuit
Connectingthesensor
ExploringtheSPIsensorexampleapp
Theapp’suserinterface
CallingthePacktHALsensorfunctions
UsingtheHardwareTaskclass
Summary
6.CreatingaCompleteInterfacingSolution
Buildingthecompleteinterfacecircuit
Exploringthecompleteexampleapp
Theapp’suserinterface
Understandinghardwarepollinginanapp
UsingAsyncTaskwithlong-livedthreads
UsingtheHardwareTaskclass
Summary
7.WheretoGofromHere
IntegratingyoursolutionwithAndroid
CreatingacustomkernelandDeviceTree
Addinghardwarecommunicationintothekernel
Integratingintoexistingmanagers
Creatingnewmanagersforcustomhardware
Combiningyourprojectwithotherhardware
Constructingyourownprototypecapes
www.it-ebooks.info
CommercialcapesthatinterfacewithAndroid
ExploringtheBBB’sotherinterfaces
Programmablereal-timeunits
Serialcommunications
Controllerareanetwork
Theanalog-to-digitalconverter
Pulsewidthmodulation
Summary
Index
www.it-ebooks.info
AndroidfortheBeagleBoneBlackCopyright©2015PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthors,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:February2015
Productionreference:1130215
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78439-216-1
www.packtpub.com
www.it-ebooks.info
CreditsAuthors
AndrewHenderson
AravindPrakash
Reviewers
NathanBurles
GuyCarpenter
AnujDeshpande
CommissioningEditor
AmarabhaBanerjee
AcquisitionEditor
GregWild
ContentDevelopmentEditor
NeetuAnnMathew
TechnicalEditor
TanviBhatt
CopyEditors
DeepaNambiar
VikrantPhadke
ProjectCoordinator
MaryAlex
Proofreaders
SimranBhogal
BernadetteWatkins
Indexer
HemanginiBari
Graphics
SheetalAute
ProductionCoordinator
ManuJoseph
www.it-ebooks.info
AbouttheAuthorsAndrewHendersonhasover15yearsofexperiencedevelopingsoftwarefortheLinuxdesktopandembeddedLinuxandAndroidsystems.HeiscurrentlyaPhDcandidateatSyracuseUniversity,withresearchinterestsintheareasofsystemsecurityanddynamicanalysis.HemaintainsmultipleopensourceprojectsfortheBeagleBoardandBeagleBoneplatforms.
IwanttothankCheryl,Olivia,andmyfatherforalloftheirencouragementandsupportduringthetimethatIspentresearchingandwritingthematerialforthisbook.IwouldalsoliketothankDr.HengYin,Dr.WenliangDu,andDr.EhatErcanliofSyracuseUniversityforlendingtheirknowledgeandguidancetomyAndroidOSandBeagleBone/BeagleBoardresearch.
AravindPrakashisaPhDcandidateatSyracuseUniversity.Hisinterestslieinsystemandmobilesecurity,withemphasisonprogramanalysis.Hehaspublishedinmultipletop-tiercomputer-securityconferences.HebringswithhimoveradecadeofprogrammingexperiencefromcompaniessuchasMicrosoft,McAfee,andFireEye.
www.it-ebooks.info
AbouttheReviewersNathanBurlesisapost-doctoralresearcherwithaPhDincomputerscience.HeiscurrentlyworkingfortheUniversityofYork,onsubjectsasdiverseasartificialneuralnetworksanddynamic,adaptive,andautomatedsoftwareengineering.
Inhisfreetime,heenjoystinkeringwithembeddedsystemsandelectronics,rangingfromfullsystemssuchastheRaspberryPiandBeagleBoneBlacktosimplemicrocontrollerssuchastheArduino—addingcircuitrytocommunicateusing433MHzRFandinfrared.
Nathanblogsabouthisprojectsaswellastopicsincludingwebsitedevelopment,Android,anddancingathttp://www.nburles.co.uk.
GuyCarpenterisasoftwaredeveloperandveteranhacker.HehascontributedcodetotheBeagleBone,RaspberryPi,Arduino,andChumbyHackersBoardcommunities.HeownsClearwaterSoftwareinBrisbane,Australia.
AnujDeshpandeadorestheBeagleboneBlackandallthingsembeddedwithLinux.Heisanactivepartofthelocalhackerspace,Doo,inPune,andregularlyhostsmeet-upsonavarietyoftopics.
SomeoftheprojectsthathehasbeenapartofareUserspaceArduino,PixHawkFire,andTah.HewasaninternatBeagleboard.org,OneirixLabs,aswellas3DRoboticsforabriefperiodoftime.Anujcompletedhisbachelor’sdegreeincomputersciencefromPICT,Pune.
www.it-ebooks.info
Supportfiles,eBooks,discountoffers,andmoreForsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<[email protected]>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.
https://www2.packtpub.com/books/subscription/packtlib
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigitalbooklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.
www.it-ebooks.info
Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser
www.it-ebooks.info
FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.
www.it-ebooks.info
PrefaceThebroadavailabilityofAndroid-baseddeviceshasgeneratedalargeamountofinterestindevelopingsoftwareapplications,orapps,thattargetAndroid.Luckily,apowerfulandlow-costhardwareplatformisavailablethatallowsyoutoquicklyandeasilytestyourappsonrealhardware:theBeagleBoneBlack.Withafocusonsmallsizeandawidevarietyofexpansionandinterfacingopportunities,theBeagleBoneBlackprovidesalotofprocessingpowerataverylowprice.Italsoprovidesanopportunitytoappdevelopersthatoncebelongedonlytothosethatwereexperthardwarehackersorownersofexpensivehardwaredevelopmentkits:thechancetowriteAndroidappsthatinteractwithcustomhardwarecircuits.
Whetheryouarebrandnewtohardwareinterfacingoraseasonedexpert,AndroidfortheBeagleBoneBlackprovidesyouwiththetoolsthatyouneedtobegincreatingAndroidappsthatcommunicatedirectlywithyourcustomhardware.Fromtheverybeginning,thisbookwillhelpyouunderstandAndroid’suniqueapproachtohardwareinterfacing.YouwillinstallandcustomizeAndroid,buildcircuitsthatinterfacewithyourBeagleBoneBlackplatform,andbuildnativecodeandAndroidappsthatusethathardwaretocommunicatewiththeoutsideworld.Bysequentiallyworkingthroughtheexamplesineachchapter,youwilllearnhowtocreatemultithreadedappsthatarecapableofinterfacingwithmultiplehardwarecomponentssimultaneously.
Onceyouhaveexploredthevarietyofexamplecircuitsandappsinthisbook,youwillbewellonyourwaytowardbecominganAndroidhardwareinterfacingpro!
www.it-ebooks.info
WhatthisbookcoversChapter1,IntroductiontoAndroidandtheBeagleBoneBlack,walksyouthroughtheprocessofinstallingtheAndroidOStoyourBeagleBoneBlackboard.Italsoprovidesyouwithalistofhardwarecomponentsthatyouwillneedtoperformtheactivitiesthroughoutthisbook.
Chapter2,InterfacingwithAndroid,introducesyoutoseveralaspectsoftheBeagleBoneBlack’shardwareandAndroid’sHardwareAbstractionLayer.ItdescribeshowtomakeafewmodificationstobothyourdevelopmentenvironmentandAndroidinstalledonyourBeagleBoneBlacktoallowAndroidappstoaccessthevarioushardwarefeaturesoftheBeagleBoneBlack.
Chapter3,HandlingInputsandOutputswithGPIOs,guidesyouthroughbuildingyourveryfirsthardwareinterfacingcircuitandexplainsthedetailsofabasicAndroidappthatcancommunicatewithit.ThisisyourfirststeptowardbuildingmuchmorecomplexappsthatinteractwiththeworldoutsideyourBeagleBoneBlack.
Chapter4,StoringandRetrievingDatawithI2C,expandsonthebasicsfromChapter3,HandlingInputsandOutputswithGPIOs,andexplainshowasynchronousbackgroundthreadswithinyourappsareusedtocommunicatewithhardware.ItguidesyouthroughbuildingacircuitthatinterfacesanonvolatilememorychiptotheBeagleBoneBlackandtheimplementationdetailsofanappthatinteractswiththechip.
Chapter5,InterfacingwithHigh-speedSensorsUsingSPI,explorescreatingappsthatperformhigh-speedinterfacingusingatemperatureandpressuresensorinterfacedtotheBeagleBoneBlack.
Chapter6,CreatingaCompleteInterfacingSolution,combinesthelessonslearnedaboutGPIO,I2C,andSPIinterfacingfromthepreviouschapterstocreateasingle,complexhardwareandsoftwaresolutionthatusesallthreeinterfacestoreacttohardwareeventsthatoriginatefromtheoutsideworld.
Chapter7,WheretoGofromHere,describesafewmoreofthehardwareinterfacesavailableontheBeagleBoneBlack,explainshowtocreatemorepermanentAndroidhardware/softwaresolutions,andgivesyouafewideasforfutureprojectstoexplore.
www.it-ebooks.info
WhatyouneedforthisbookWehaveprovidedinstructionsinthisbookassumingthatyouareusingeitheraWindows-orLinux-basedcomputer.IfyouarealreadyanAndroidappdeveloper,youprobablyhaveallofthesoftwareapplicationsthatyouneedalreadyinstalled.WeexpectyoutohaveboththeEclipseADTandAndroidNDKalreadyinstalled,thoughweprovidelinkstodownloadthesetoolsatthestartofChapter2,InterfacingwithAndroid,intheeventthatyoudonotalreadyhavethem.Chapter1,IntroductiontoAndroidandtheBeagleBoneBlack,providesalistofthevarioushardwarecomponentsandequipmentthatyouwillneedtoimplementtheexampleinterfacingcircuitsusedthroughoutthebook.
www.it-ebooks.info
WhothisbookisforIfyouareanAndroidappdeveloperwhowantstobeginexperimentingwiththehardwarecapabilitiesoftheBeagleBoneBlackplatform,thenthisbookisidealforyou.Havingfamiliaritywithbasicelectronicsprinciplesishelpful,andthereaderisexpectedtohavebasicknowledgeindevelopingAndroidappswiththeEclipseADTandAndroidSDK,butnopriorhardwareexperienceisrequired.
www.it-ebooks.info
ConventionsInthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Thisavoidshavingtoincludeaspecialmoduleandanoverlaythatloadscommandsinyourinit.{ro.hardware}.rcfile.”
Ablockofcodeissetasfollows:
externintopenFRAM(constunsignedintbus,constunsignedintaddress);
externintreadFRAM(constunsignedintoffset,constunsignedint
bufferSize,constchar*buffer);
externintwriteFRAM(constunsignedintoffset,constunsignedint
constchar*buffer);
externvoidcloseFRAM(void);
Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,therelevantlinesoritemsaresetinbold:
publicvoidonClickSaveButton(Viewview){
hwTask=newHardwareTask();
hwTask.saveToFRAM(this);
}
publicvoidonClickLoadButton(Viewview){
hwTask=newHardwareTask();
hwTask.loadFromFRAM(this);
}
Anycommand-lineinputoroutputiswrittenasfollows:
root@beagleboneblack:/#i2cdetect-y-r2
Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,forexample,inmenusordialogboxes,appearinthetextlikethis:“IftheuserclicksontheSamplebuttononcemore,anotherHardwareTaskinstanceisinstantiated.”
NoteWarningsorimportantnotesappearinaboxlikethis.
TipTipsandtricksappearlikethis.
www.it-ebooks.info
ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.
Tosendusgeneralfeedback,simplye-mail<[email protected]>,andmentionthebook’stitleinthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.
www.it-ebooks.info
CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.
www.it-ebooks.info
DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.comforallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
www.it-ebooks.info
ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyoucouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata,selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsiteoraddedtoanylistofexistingerrataundertheErratasectionofthattitle.
Toviewthepreviouslysubmittederrata,gotohttps://www.packtpub.com/books/content/supportandenterthenameofthebookinthesearchfield.TherequiredinformationwillappearundertheErratasection.
www.it-ebooks.info
PiracyPiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.
www.it-ebooks.info
QuestionsIfyouhaveaproblemwithanyaspectofthisbook,youcancontactusat<[email protected]>,andwewilldoourbesttoaddresstheproblem.
www.it-ebooks.info
Chapter1.IntroductiontoAndroidandtheBeagleBoneBlackInthisbook,you’lllearnhowtoinstallAndroidtoamicroSDcardforusewiththeBeagleBoneBlackandcreateAndroidappsthatinterfacewithexternalhardwarethatisconnectedtotheBeagleBoneBlack.Youwilldevelopsoftwarethatreceivesinputfromtheoutsideworldviabuttonsandsensors,storesandretrievesdatafromexternalmemorychips,andlightsexternalLEDs.Betteryet,you’lllearnhowtodothisinaflexiblewaythatcanbeeasilyintegratedintoyourapps.
AsyouexploretheworldofinterfacinghardwarewithAndroid,youwilldiscoverthatitencompassesmanydifferentareasofexpertise.UnderstandingelectroniccircuitsandknowinghowtointerfacethemwiththeBeagleBoneBlack,understandingtheLinuxkernel,anddevelopingAndroidappsareafewsuchareas.Luckily,youdon’thavetobeanexpertintheseareastolearnthebasicsofinterfacinghardwarewithAndroid.Wehavedoneourbesttoguideyouthroughtheexamplesinthisbookwithoutrequiringyoutohaveanin-depthknowledgeoftheLinuxkernelorelectronicstheory.
Inthischapter,wewillcoverthefollowingtopics:
LookingbackonAndroidandBeagleBoneBlackdevelopmentShoppingforthehardwareessentialsLearningaboutthehardwareyou’llinterfacewithInstallingAndroidontheBeagleBoneBlack
www.it-ebooks.info
LookingbackonAndroidandBeagleBoneBlackdevelopmentTheAndroidoperatingsystemhasbeentakingtheworldbystorm.Eversinceitsintroductiontotheworldinabetareleasein2007,ithasgrowntobecomethedominantmobilephoneOS.Asidefrommobilephones,ithasalsobeenusedfortablets(suchastheBarnes&NobleNookeReaderandtheTescoHudltablet)andavarietyofotherembeddedmultimediadevices.TheOShasaddednewfeaturesandevolvedovertheyears,butitstillhasthesameprimarydesignprinciplesasitdidwhenitwasfirstconceived.ItprovidesalightweightOSwithatouchscreeninterfacethatgivesquickandeasyaccesstomultimediaapplicationswhileusingminimalresources.
Asidefromitsgeneralpopularity,AndroidhasanumberofadvantagesthatmakeitanexcellentOSforyourprojects.ThesourcecodeofAndroidisopensourceandfreelyavailablefromhttp://source.android.com.Itisfreeforyoutouseinanyproductsthatyoucreate.AndroidusesthepopularLinuxkernel,soanyexpertisethatyoualreadyhavewithLinuxwillaidyouinyourAndroiddevelopment.Thereisawell-documentedinterfacingAPIthatmakesdevelopingforAndroidsimpleandstraightforward.
ThebroadavailabilityofAndroid-baseddeviceshasgeneratedalargeamountofinterestindevelopingsoftwareapplications,orapps,thattargetAndroid.IthasbecomeeasiertodevelopAndroidapps.EclipseAndroidDevelopmentTools(ADT)allowsappdeveloperstoprototypesoftwareandthenexecutethatsoftwarewithinanemulatedAndroiddeviceenvironment.However,theemulateddevicediffersfromrealhardwareinsubtle(andsometimesdramatic)waysintermsofspeedandappearance.Luckily,apowerfulandlow-costhardwareplatformisavailablethatallowsyoutoquicklyandeasilytestyourappsonrealhardware:theBeagleBoneBlack.
TheBeagleBoneBlack(BBB)hardwareplatform,producedbyCircuitCofortheBeagleBoard.orgnonprofitorganization,isanewcomertotheopensourcehardwarescene.Firstproducedin2013,thislow-cost,ARM-basedsingleboardcomputerisanimprovementovertheoriginalBeagleBoneplatform.TheBBBisanimprovementovertheoriginalBeagleBoneboardthatoffersincreasedprocessingpower,built-inHDMIvideo,andeithera2or4GB(dependingupontheBBB’srevision)on-boardeMMCmemory.Withafocusonsmallsizeandawidevarietyofexpansionandinterfacingopportunities,theBBBprovidesalotofprocessingpowerataverylowprice.ThefollowingimageshowsatypicalBBB:
www.it-ebooks.info
TheBeagleBoneBlack(Source:www.beagleboard.org)
AndroidrunsontheinexpensiveBBB,whichmakesitanexcellenthardwareplatformtousetoexploreAndroidanddevelopyourowncustomAndroidprojects,forexample,ifyouhadanideaforanAndroidkioskdevice,ahand-heldgamingconsole,orsomeothermultimediadevice.ThecombinationofAndroidandtheBBBwillallowyoutoprototypesuchdevicesquicklyandcheaply.
NowthatwehavetakenaquicklookattheBBBandAndroid,let’stakealookatthehardwarethatyouwillneedtomakethemostoutofbothofthem.
www.it-ebooks.info
ShoppingforthehardwareessentialsWhenyoupurchaseyourBBB,youwillonlyreceivetheboardandaUSBcabletopowerandcommunicatewithit.Beforeyoubeginanyserioussoftwaredevelopmentforhardware-interfacingprojectswiththeBBB,thereareafewadditionalpiecesofhardwarethatyouwillneed.Inouropinion,thebestplacetopurchasetheseitemsisAdaFruit(www.adafruit.com).Almosteverythinghereisavailablefromthissinglesource,andtheircustomerserviceisverygood.Infact,manyoftheitemslistedhereareavailableasaBeagleBoneBlackstarterkitfromAdaFruit(productID703).Thestarterkitdoesnotcontaina3.3VFutureTechnologyDevicesInternational(FTDI)cable,butitdoesincludetheBeagleBoneBlackitself.
ContentsoftheBeagleBoneBlackstarterkitfromAdaFruit(source:www.adafruit.com)
www.it-ebooks.info
TheFTDIcableA3.3voltFTDIcable(productID70)allowsyoutoviewalloftheserialdebugoutputoftheBBB.Ifyouareperforminganyseriousdevelopment,youmusthaveoneofthesecables.ThecableisnecessaryifyouwishtoobservethebootprocessoftheBBB(bothbootloaderandkerneloutputasthesystemisinitialized),anditalsoprovidesaconsoleshellintoLinuxandAndroid.Thisshellhelpsyoutotroubleshootbootproblems,asyouwillalwayshaveamethodofinteractingwiththesystemwhenanetworkconnectionisunavailable,orwhennocommunicationservicesareupandrunning.
www.it-ebooks.info
PowersupplyWhiletheBBBcanbepoweredviatheUSBcable,thismethodsuppliesbarelyenoughpowertoruntheBBB.Ifyouareusingexternalcapes,orareotherwiseattachingexternalcircuitsthatdrawpowerfromthe5voltpinsoftheBBB,youmustuseanexternalpowersupply.BeagleBoard.orgspecifiesthatthepowersupplymustbea2amp,5voltDCpowersupplywitha2.1mmbarrelconnectorthatiscenterpositive.AdaFruitsellsapowersupplythatconformstotheBBB’srequirements(productID276).
www.it-ebooks.info
BreadboardandthemountingplateExperimentingwithelectronicsbecomesmuchsimplerifyouareabletoeasilyandquicklyconstructcircuitswithouttheworryofsoldering.Becauseofthis,werecommendthatyouinvestinabreadboardandsomebreadboardingjumperwires(productID153).Yourbreadboarddoesn’thavetobeanythingbigorfancy,butyoushoulduseatleastastandardhalf-sizebreadboard(productID64)fortheprojectsgiveninthisbook.
AdaFruitProtoPlate(productID702)isanadditionalitemthatwerecommendthatyoupurchase.ProtoPlateisaplasticplatethatboththeBBBandahalf-sizebreadboardmountonto.ThishelpsyouavoidaccidentallystretchingordisconnectingthewiresthatconnectelectroniccircuitstotheBBB.UsingProtoPlatemakesrelocatingyourBBBandbreadboardsimpleandpainless.
www.it-ebooks.info
MicroSDcardsIfyoudomuchworkwiththeBBB,you’llalwayswanttohaveafewextramicroSDcardsaround!Androidwillfitontoan8GBmicroSDcardwithplentyoffreespaceavailabletoholdyourownapps.YoucanwriteanAndroidimagetoalargermicroSDcard,butmostpremadeAndroidsystemimageswillonlyconsumethefirst4–8GBofspaceonthecard.AsmostlaptopsanddesktopPCsdon’tdirectlyacceptmicroSDcards,youshouldownatleastonemicroSD-to-SDcardadapter.Luckily,oneoftheseadaptersistypicallypackagedwitheachmicroSDcardthatyoubuy.
www.it-ebooks.info
Learningaboutthehardwareyou’llinterfacewithThebestwaytolearnaboutinterfacingAndroidsoftwarewithhardwareistolearnwhilehavingrealhardwarecomponentsconnectedtoyourBBB.Thisway,yoursoftwarewilltalktoactualhardwareandyoucandirectlyobservehowyourappsrespondtophysicalinteractionwithyoursystem.Wehaveselectedavarietyofelectroniccomponentsthatwillbeusedthroughoutthebooktodemonstratevariousaspectsofhardwareinterfacing.Youarewelcometouseasmanyorasfewofthesecomponentsasyourinterestsandbudgetpermit.Itcanbeexpensivetopurchaseallofthesecomponentsatonce,butmakesuretobuyallofthecomponentsnecessaryforeachchapterifyouareinterestedinimplementingtheexamplesinthatchapter.
www.it-ebooks.info
General-purposecomponentsInChapter3,HandlingInputsandOutputswithGPIOs,andChapter6,CreatingaCompleteInterfacingSolution,youwilluseavarietyofelectroniccomponentssuchaspushbuttons,LEDs,andresistorstointerfacewiththeBBB.Manyoftheseitemscanbepurchasedfromanyelectronicssupplier,suchasDigiKey(www.digikey.com),MouserElectronics(www.mouser.com),andSparkFun(www.sparkfun.com).BothDigikeyandMouseroffersomanyvariantsofeachavailablecomponentthatitcanbedifficultforaninexperiencedhardwarehackertopicktherightcomponentstobuy.Becauseofthis,wewillrecommendafewproductsfromSparkFunthatwillgiveyousuitablecomponentsneededtocompletetheexercisesinthisbook.Youarewelcometoselectyourcomponentsfromanothersupplierifusingadifferentoneismoreconvenientforyou.
Ourexamplesrequireonlythreecomponents:aresistor,apushbuttonswitch,andanLED.Wesuggestpurchasinga1Kohm,1/6(or1/4)wattresistor(part#COM-08980),a12mmpushbuttonswitch(part#COM-09190),andanysmallLED(3–10mminsize)thatcanbetriggeredbyaround3voltorless(part#COM-12903isagoodassortmentof5mmLEDs).
www.it-ebooks.info
TheAdaFruitmemorybreakoutboardInChapter4,StoringandRetrievingDatawithI2C,andChapter6,CreatingaCompleteInterfacingSolution,youwillinterfacewitha32KBFerroelectricRandomAccessMemory(FRAM),whichisanonvolatilememoryIC,tostoreandretrievedata.WehaveselectedAdaFruitBreakoutBoard(productID1895)thatcontainsthisIC.ThebreakoutboardalreadycontainsallofthenecessarycomponentstointerfacetheICtotheBBB,soyouneednotworryaboutmanyofthelow-leveldetailsinvolvedincreatingaclean,noise-freeconnectionbetweeneachICandtheBBB.
TheFRAMBreakoutBoardwithitsheaderstrip(source:www.adafruit.com)
www.it-ebooks.info
TheAdaFruitsensorbreakoutboardInChapter5,InterfacingwithHigh-speedSensorsUsingSPI,andChapter6,CreatingaCompleteInterfacingSolution,youwillinterfacewithasensorICtoreceiveenvironmentaldata.WehaveselectedanAdaFruitbreakoutboard(productID1900)thatcontainstheseICs.ThesebreakoutboardsalreadycontainallofthenecessarycomponentstointerfacetheICstotheBBB,soyouneednotworryaboutmanyofthelow-leveldetailsinvolvedincreatingaclean,noise-freeconnectionbetweeneachICandtheBBB.
www.it-ebooks.info
PreparingthebreakoutboardsEachbreakoutboardcomeswithaheaderstrip.Thisheaderstripmustbesolderedintoeachbreakoutboardsothattheycanbeeasilyconnectedtothebreadboard.Thisistheonlysolderingthatisrequiredtocompletetheexercisesinthisbook.Ifyouareunfamiliarwithsoldering,therearenumeroustutorialsonlinethatexplaintechniquesforeffectivesoldering.Ifyoufeeluncomfortablesolderingtheheaderstrips,askafriend,instructor,orcolleaguetoassistyouwiththeprocess.
NoteAfewonlinesolderingtutorialsthatwesuggestthatyoucheckoutare:
https://www.youtube.com/watch?v=BLfXXRfRIzYhttps://learn.sparkfun.com/tutorials/how-to-solder–through-hole-soldering
www.it-ebooks.info
InstallingAndroidontheBeagleBoneBlackTheAndroidOSisacomplexpieceofsoftwarethatisconstructedoutofmanycomponentsbuiltfromaverylargecodebase.Itcanbeadifficultandtime-consumingtasktobuildAndroidfromsource,soyouwillbeusingapremadeAndroidimagefromtheBBBAndroidproject(www.bbbandroid.org)throughoutthisbook.
BBBAndroidisaportofAndroidOpenSourceProject(AOSP)KitKatAndroidtotheBBB.ThereareafewdifferentdistributionsofAndroidavailablefortheBBB,butweselectedBBBAndroidbecauseitusesthe3.8Linuxkernel.ThiskernelincludestheCapeManager(capemgr)functionalityaswellasafewothertoolsthatwillassistyouininterfacinghardwaretoAndroidapps.OtherflavorsofAndroidontheBBBusethe3.2Linuxkernel,whichismucholderandlackscapemgrsupport.Chapter2,InterfacingwithAndroid,discussesthecapemgrfunctionalityinmoredetail.The3.8kernelisagoodbalancebetweenenablingthenewerfeaturesfortheBBBwhileavoidinganypotentiallyunstable,cutting-edgefeatures.
TheBBBcanbootitsOSinafewdifferentways:
OnboardeMMC:TheOSresideswithintheonboardeMMCstorage.TheAngstromorDebianOSthatcomesinstalledonyourBBBbootsfromtheeMMCoutofthebox.MicroSDcard:TheOSresidesonamicroSDcardthatisinsertedintotheBBB.IfabootloaderisinstalledonthemicroSDcard,thebootloaderinstalledontheonboardeMMCnoticesthepresenceofthemicroSDandwillbootfromthatinstead.Inaddition,bootingfromthemicroSDcardisforcedwhentheuserbootbuttonishelddownduringBBBpowerup.Overthenetwork:ThebootloaderiscapableofdownloadingakerneloverthenetworkviaTFTP.TheOScanactuallybedownloadedatboottimethoughthisisusuallyonlydoneduringcommercialproductdevelopment.Thisisanadvancedfeaturethatisoutsidethescopeofthisbook.
TheBBBAndroidimageisdesignedtobewrittentoandbootedfromamicroSDcard.AstheimagecreatesafullybootablesystemonthemicroSDcard,youwillnothavetoholdtheBBB’suserbootbuttonduringpowerontobootintoAndroid.SimplyinsertthemicroSDcardintotheBBBandyou’llbootintoAndroidautomatically.
UsingamicroSDcard-basedOSisadvantageousforusbecauseyoucaneasilymountthecardonaLinuxPCtomodifytheAndroidfilesystemasyouseefit.IftheOSisinstalledintheeMMC,itcanbehardtoaccesstheOStochangearbitraryfilesinthefilesystem.ThesystemmustberunningtoaccesstheeMMCcontents,somakingachangethatcorruptsthesystemormakesitunbootablemakesaccessingtheeMMCtofixtheproblemdifficult.
www.it-ebooks.info
DownloadingapremadeAndroidimageThemainpageoftheBBBAndroidwebsiteprovidesadownloadlinkforthemostrecentpremadeimage.Likeanyopensourceproject,detailsabouttheversionnumberandsizeofeachimagearelikelytochangeovertimeasbugsarefoundandchangesaremade.However,thelatestandgreatestwillbeavailableviathewebsite.
BBBAndroid’simagesarecompressedusingthexzcompressorutilitytosavetimewhendownloading,sotheimagemustbedecompressedpriortowritingittoamicroSDcard.ThetoolsusedtodecompressandwritetheimagewillvarydependingupontheOSthatyouareusing.WhilethecompressedimagemightonlybeafewhundredMBinsize,theuncompressedimagewillbe8GB.
NotePriortobeginningthedecompressionoftheimage,makesurethatyouhaveenoughharddrivespacetoholdtheuncompressedimage.
www.it-ebooks.info
CreatingyourAndroidmicroSDcardusingWindowsUnderWindows-basedOSes,thecompressedimagecanbeuncompressedusingtoolssuchas7-ZiporWinRARandthenwrittentothemicroSDcardusingthetoolWin32DiskImager.Allofthesetoolsarefreelyavailablefordownload.ToprepareanAndroidmicroSDcard,followthesesteps:
1. Forthisexample,you’llusetheWinRARapplication.DownloadWinRARfromwww.rarlab.comandinstallit.WinRARwillintegratewiththeWindowsExplorershelloftheWindowsdesktop.
2. DownloadandinstalltheWin32DiskImagerapplication.Itisavailablefromtheproject’sSourceForgepageathttp://sourceforge.net/projects/win32diskimager.
3. Right-clickontheBBBAndroidimagethatyoudownloadedandselecttheExtracthereoptionontheExplorershellcontextmenu.Anuncompressedversionoftheimage(8GBinsize)willbewrittentothesamelocationasthecompressedimage.Thedecompressionprocessmighttakeseveralminutes.
Decompressthexz-compressedimagewithWinRAR
4. Insertan8+GBmicroSDcardintothesystem.ThecardwillbedetectedbyWindowsashavingavalidfilesystemonitifitcamepreformatted(mostcardsaresoldpreformattedforyourconvenience).Irrespectiveofwhetherthecardisformattedornot,adriveletterisassignedtoitbyWindows.
5. BrowsetoThisPCandexaminethedevicesshownunderDevicesanddrives.Thecardshouldbeshown.Makeanoteofthedriveletterassignedtothecard.
ThemicroSDcardwillbeshownwithadriveletterunderWindows(driveEintheimage)
www.it-ebooks.info
6. LaunchWin32DiskImager.Enterthefilenameandpathtotheuncompressedimageinthetextfield,orclickonthefoldericontonavigatetothefile’slocation.ChangetheDevicedrop-downboxtothedriveletterofthemicroSDcardthatyouidentifiedinstep4.
Win32DiskImagerwiththeimagefilespecified(notethatthedrivelettermatchesthatofthemicroSDcard)
7. Writingtheimagewilltakeseveralminutes.Oncethewritehascompleted,removethemicroSDcardfromyourcomputerandinsertitintoyourBBB.
8. PowerontheBBBandAndroidwillbegintoboot.Onthefirstboot,itwilltakeseveralminutesforthetop-levelUIscreentoappear.Onsubsequentboots,itwilltakeonly30to60secondstoreachthetop-levelUIscreen.
Congratulations!YourBBBisnowrunningtheAndroidOS.
www.it-ebooks.info
CreatingyourAndroidmicroSDcardusingLinuxUnderLinux,thecompressedAndroidimagecanbeuncompressedusingthexzcommandandwrittentothemicroSDcardusingtheddcommand.ToprepareanAndroidmicroSDcard,followthesesteps:
1. Makesurethatyouhavexzinstalled.Forsystemsusingapt-get,tryinstallingthexz-utilspackage:
$sudoapt-getinstallxz-utils
2. Decompresstheimageusingxz.Substitutethenameofyourimagefile(withthe.xzfileextension),asshowninthefollowingcommand:
$xz--decompress[IMAGEFILENAME]
3. Onceuncompressed,theimagewillloseits.xzfileextensionandhaveasizeof8GB.InsertyourmicroSDcardintothecomputer.Adeviceinthe/devdirectorywillbeassignedtoyourcard.Todeterminewhichdeviceitis,usefdisk:
$sudofdisk–l
4. Thefdiskutilitywilldisplayallstoragedevicescurrentlyconnectedtoyourcomputer.OneofthedeviceswillreportasbeingthesamesizeasthemicroSDcard.Forexample,ifyouinsertan8GBmicroSDcard,youwillseesomethingsimilartothis:
Disk/dev/sdb:8018MB,8018460672bytes
Theexactstoragecapacityofthecardvariesslightlybetweenmanufacturers,butthesizeisapproximately8GB.Thedeviceassignedtothiscardis/dev/sdb.Otherdeviceslistedbyfdiskwillbesecondarystoragedevices(suchasyourharddrive).Beforeproceedinganyfurther,makecertainthatyouhaveidentifiedtheproperdevicefilethatbelongstoyourmicroSDcard.Ifyouselectthewrongdevice,youwilldestroythefilesystemonthatdevice!
5. WritetheimagetothemicroSDcardusingdd.Assumingthatthedeviceyouidentifiedinstep5is/dev/sdb,usethefollowingcommandtoperformthewrite:
$sudoddif=[NAMEOFIMAGE]of=/dev/sdbbs=4M
6. Writingtheimagewilltakeseveralminutes.Oncethewritehascompleted,removethemicroSDcardfromyourcomputerandinsertitintoyourBBB.
PowerontheBBBandAndroidwillbegintoboot.Onthefirstboot,itwilltakeseveralminutesforthetop-levelUIscreentoappear.Onsubsequentboots,itwilltakeonly30to60secondstoreachthetop-levelUIscreen.
Congratulations!YourBBBisnowrunningtheAndroidOS.
www.it-ebooks.info
SummaryInthischapter,youlearnedaboutthehardwarethatyou’llneedtodevelopsoftwarefortheBeagleBoneBlack,theelectronicscomponentsanddevicesthatyouwillneedfortheexercisesinthisbook,andhowtoinstallanAndroiddistributionontoamicroSDcardforuseontheBBB.Inthenextchapter,youwilllearnhowAndroidinteractswithhardwareatthesoftwarelevelandhowtheBBBcanbeconfiguredtointerfacewiththehardwarecomponentsthatyouwillbeusinginthisbook.
www.it-ebooks.info
Chapter2.InterfacingwithAndroidInthelastchapter,youinstalledAndroidonyourBBB.Youalsogatheredallofthehardwareandcomponentsthatyouwillneedtotryouttheexercisesinthisbook.NowthatyouhaveaworkingAndroidsystemandthehardwareneededtoexploreit,itistimetodiveintoAndroidandfindouthowtoprepareittointerfacewithcustomhardware.
MostpeoplewouldnotconsiderAndroidandLinuxtobeverysimilar,butthetwohavemoreincommonthanyoumightrealize.UnderneaththepolishedUIsandawidevarietyofapps,AndroidissecretlyLinux.Android’sfilesystemlayoutandservicesarequitedifferentfromthoseofatypicalLinuxsystem,sotherearecertainlymanydifferencesbetweenthetwointermsofuserspace(whereappsandotherprocessesexecute).Intermsofkernelspace(wheredevicedriversexecuteandresourcesareallocatedtoeachrunningprocess),theyarealmostidenticalinfunctionality.UnderstandinghowtheBBBinteractswithLinuxkerneldriversisthekeytocreatingAndroidappsthatcandothesame.
Inthischapter,wewilltellyouaboutAndroid’shardwareabstractionlayer,orHAL.WewillalsointroduceyoutoPacktHAL,aspeciallibrarythatyoucanincludewithinyourappstointerfacewithhardwareontheBBB.WeassumethatyoualreadyhaveEclipseAndroidDeveloperTools(ADT)withtheAndroidSDK,theAndroidNativeDevelopmentKit(NDK),andtheAndroidDebugBridge(ADB)toolsinstalledandworkingonyoursystem.
Inthischapter,wewillcoverthefollowingtopics:
UnderstandingtheAndroidHALInstallingPacktHALSettinguptheAndroidNDKforPacktHALMultiplexingtheBBBpins
TipAreyoumissingafewtools?
IfyoudonotyethavetheEclipseADTorAndroidNDKtoolsinstalledonyoursystem,youcanfindinstallationinstructionsanddownloadlinksattheselocations:
EclipseADT:http://developer.android.com/sdkAndroidNDK:http://developer.android.com/tools/sdk/ndk
HowtoinstallADBisdiscussedlaterinthischapter.ThischapterassumesthatyouhaveinstalledtheEclipseADTtothec:\adt-bundledirectoryifyouareusingWindows(wemakenoassumptionsforLinux)andthatyouhaveinstalledtheAndroidNDKtothec:\android-ndkdirectory(Windows)orandroid-ndkinyourhomedirectory(Linux).Ifyouhaveinstalledthesetoolstoadifferentlocation,youwillhavetomakeafewsimpleadjustmentstoafewinstructionslaterinthischapter.
www.it-ebooks.info
UnderstandingtheAndroidHALAnAndroidkernelcontainsafewadditionalfeaturesthataren’tfoundinatypicalLinuxkernel,suchasBinderIPCandthelow-memorykiller,butotherwiseitisstillLinux.ThisprovidesyouwithoneverybigadvantagewheninterfacinghardwarewithAndroid,thatis,ifaLinuxdriveralreadyexistsinthekernelusedforanAndroidsystem,thenyoualreadyhaveanAndroiddriverforthatdevice.
AndroidappsmustinteractwiththehardwareofanAndroiddevicebygeneratingvideoandaudiodata,receivingbuttonandtouchscreeninputevents,andreceivingsensoreventsfromcameras,accelerometers,andotherdevicesthatgatherinformationfromtheoutsideworld.LeveragingexistingLinuxdriversforthesedevicesmakesAndroidsupportmucheasier.UnlikeatraditionalLinuxdistribution,whichgrantsapplicationspermissiontodirectlyaccessmanydifferentdevicefiles(bydirectlyopeningfilesinthe/devfilesystem),Androiddramaticallylimitstheabilityofprocessestodirectlyaccesshardware.
ConsiderthenumberofdifferentAndroidappsthatusetheaudiofunctionalityofthedevicetoplaysoundsorrecordaudiodata.UnderneathAndroid,theLinuxkernelprovidesthisaudiofunctionalityviaanAdvancedLinuxSoundArchitecture(ALSA)audiodriver.Inmostcases,onlyoneprocessatatimecanopenandcontroltheALSAdriverresource.Ifindividualappswereinchargeoftaking,using,andreleasingtheALSAdriver,itwouldbecomeahugemesstocoordinateaudioresourceusageamongallofthevariousapps.Onemisbehavingappcaneasilytakecontrolofaudioresourcesandblockallotherappsfromusingthem!Buthowcantheallocationandcontroloftheseresourcesbehandled?Tosolvethisproblem,Androidusesmanagers.
www.it-ebooks.info
AndroidmanagersManagersarethecomponentsofthesystemthatcontrolhardwaredevicesonbehalfofallapps.Everyapprequiressomesetofresources(suchasaudio,GPS,andnetworkaccess)toperformitsjob.Managersareinchargeofallocatingandinterfacingwitheachoftheseresourcesanddeterminingwhetheranapphaspermissiontousethatresource.
Havingmanagersdealwiththeselow-leveldetailsmakeslifemucheasier.Androidcanbeinstalledonawidevarietyofhardwareplatformsthatvarywildlyintermsofphysicalsizeandinput/outputcapabilities,andappdeveloperscan’tbeexpectedtohaveintimateknowledgeofeachandeveryplatformthattheirappcanbeinstalledon.
Tousearesource,anappmustcreateareferencetothepropermanagerviathegetSystemService()methodoftheandroid.content.Contextclass:
//Createareferencetothesystem"location"manager
LocationManagerlocationManager=(LocationManager)
mContext.getSystemService(LOCATION_SERVICE);
Then,makeinformationandcontrolrequestsviathismanagerreference:
//QuerythelocationmanagertodetermineifGPSisenabled
isGPSEnabled=locationManager.
isProviderEnabled(LocationManager.GPS_PROVIDER);
AppsinteractwithmanagersthroughtheJavaAndroidAPI.WhilemanagersrespondtotheseJavamethods,theymusteventuallyusetheJavanativeinterface(JNI)tocallthenativecodethatdirectlyinteractswiththehardware.Thisiswherethetruecontrolofthehardwaretakesplace.ThebridgebetweentheAndroidAPIandcallstothenativecodethatcontrolthehardwareisknownasthehardwareabstractionlayer(HAL).
ThevariouspiecesoftheHALaretypicallywritteninC/C++,andeachdevice’svendorisresponsibleforimplementingthem.IfsomepiecesoftheHALaremissing,servicesandappswon’tbeabletofullyutilizeallaspectsofthehardwareplatform.VariousAndroidservicesusetheHALtocommunicatewiththehardware,andappsuseIPCtocommunicatewiththeseservicesandgainaccesstothehardware.Theservicesinteractwiththehardwareonanapp’sbehalf(assumingthattheapphastheproperAndroidpermissionstoaccessthatparticularhardwareresource).
www.it-ebooks.info
TheHALdevelopmentworkflowTypically,creatingacompleteHALfollowsthesesteps:
1. IdentifyordevelopaLinuxkerneldevicedrivertocontrolthehardware.2. CreateakernelDeviceTreeoverlaythatinstantiatesandconfiguresthedriver.3. Developauserspacelibrarytointerfacewiththekerneldevicedriver.4. DevelopJNIbindingstotheuserspacelibrary.5. DevelopanAndroidmanagerusingtheJNIbindingstointerfacewiththehardware.
Sometimes,itisn’tacleardecisionastowhereaparticularpieceofcustomhardwareshouldbeproperlyintegratedintotheHALandwhichmanagershouldbeinchargeofaccessingthehardware.WhatAndroidpermissionscontrolaccesstothehardware?WilltheAPIhavetobeextendedtooffernewtypesofpermissions?Willacustomservicehavetobecreated?
ImplementingeveryaspectofaproperHALforapieceofcustomhardwareisabitofanoverkillforhobbyists,students,andotherdevelopersinterestedinsimpleexperimentationwithhardwareinterfacing.WhileacommercialAndroidsystemmustaddressallofthesestepstodevelopaproperHAL,wetakeafarmoredirectapproachtohardwareaccessinthisbook.
AsourfocusisonshowinghowyoucaninterfaceAndroidappswithhardware,weskipsteps1through4byprovidingyouwithPacktHAL,anativelibrarythatimplementsaverysimpleHAL.PacktHALwilleaseyouintothedauntingtaskofinterfacingwithhardwareontheBBB,anditprovidesasetoffunctionsthatarecapableofinterfacingwiththehardwareusedintheexamplesthroughoutthisbook.Strictlyspeaking,yourappswillactasthemanagerinchargeofeachhardwareresource.
www.it-ebooks.info
WorkingwithPacktHALAppscommunicatewiththenativecallsofPacktHALusingJNI.PacktHALdemonstrateshowtoperformuserspaceinterfacingwithhardwareviathreedifferentinterfacingmethods:GPIO,SPI,andI2C.UsingPacktHAL,youhavedirectaccesstohardwaredevices.Chapters3throughChapter6provideexamplesofhowthisinterfacingworksandhowyoucanuseitwithinyourownAndroidappcode.EachchapterwillexaminethevariouspiecesofPacktHALusedintheappexamplesofthatchapter.
TipHowdoesPacktHALactuallytalktohardware?
Generally,anymethodthatallowsyoutointerfacewithhardwareunderLinuxcanalsobeusedbytheHALforinterfacing.Reading,writing,andmakingioctl()callstofilesinthe/devfilesystemwillwork,asdoesusingmmap()toprovideaccesstomemory-mappedcontrolregisters.PacktHALusesallofthesetechniquestointerfacewiththehardwarethatyouconnecttoyourBBB.
UsingPacktHALisnowherenearassecureasaproperHALimplementationbecausewemustchangethepermissionsonthehardware’suserspaceinterfacessuchthatanyappcanaccessthehardwaredirectly.Thiscanpotentiallymakeyoursystemvulnerabletomaliciousapps,sosuchanapproachshouldneverbeusedinaproductiondevice.Usersthatroot(gainsuperuseraccessto)commercialAndroidphonesandtabletsoftendosotolessenthestrictpermissionsonthesedevicesbydefault.Thisallowsthemtoinstallandenablecustomfeatures,anditprovidesmoreflexibilityandcustomizationfortheirdevices.
AsyouareusingtheBBBasanAndroid-prototypingdevice,suchanapproachistheeasiestwayforyoutointeractwiththehardware.Thisisasteppingstonetowardsdevelopingyourowncustommanagersandservicesthatspeaktoyourhardwareonbehalfofapps.Ideally,onacommercialdevice,onlyanAndroidmanagerwillhavethenecessarypermissionstodirectlyinterfacewiththehardware.
TipOnceyoubecomecomfortablewithusingPacktHALinyourapps,youcanthenexaminePacktHAL’ssourcecodetobetterunderstandhownativecodeinterfaceswiththeLinuxkernel.Eventually,youmightfindyourselfintegratingPacktHALintoyourowncustommanagers.Youmightevenfindyourselfdevelopingcustomcodefortheactualkernel!
www.it-ebooks.info
InstallingPacktHALAllofthevariouspiecesofPacktHALarelocatedinthePacktHAL.tgzfile,whichisavailablefordownloadfromPackt’swebsite(http://www.packtpub.com/support).ThisisacompressedtarfilethatcontainsallofthesourcecodeandconfigurationfilesrequiredtomodifyBBBAndroidtousePacktHALandincludePacktHALsupportinyourapps.
www.it-ebooks.info
PreparingPacktHALunderLinuxOnceyouhavedownloadedthePacktHAL.tgzfile,youmustdecompressanduntarit.WewillassumethatyouhavecopiedPacktHAL.tgztoyourhomedirectoryafterdownloadingitandwilldecompressitfromthere.Wewillrefertoyourhomedirectoryas$HOME.
UsetheLinuxtarcommandtodecompressanduntarthefile:
$cd$HOME
$tar–xvfPacktHAL.tgz
AdirectorynamedPacktHALnowexistsinyour$HOMEdirectory.AllofthePacktHALfilesarelocatedinthisdirectory.
www.it-ebooks.info
PreparingPacktHALunderWindowsOnceyouhavedownloadedthePacktHAL.tgzfile,decompressanduntarit.WewillassumethatyouhavecopiedPacktHAL.tgztotherootdirectoryoftheC:driveafterdownloadingitandwilluseWinRARtodecompressitfromthere.
TipWhereshouldIunpackPacktHAL.tgz?
YoucandecompressanduntarPacktHAL.tgzonthedesktoporwhereverelseyouwish,butyouwillbeperformingsomecommand-linecommandstocopyfilesaroundlater.ItismuchsimplertoperformtheseoperationsifPacktHAL.tgzisdecompressedanduntarredintherootdirectoryoftheC:drive,sowewillassumethatyouareperformingtheseoperationsfromthere.
PerformthefollowingstepstoextractthePacktHAL.tgzfile:
1. OpenafileexplorerwindowandnavigatetotherootoftheC:drive.2. Right-clickonthePacktHAL.tgzfileinfileexplorerandselectExtractHere.
AdirectorynamedC:\PacktHALnowexists.AllofthePacktHALfilesarelocatedinthisdirectory.
www.it-ebooks.info
ThePacktHALdirectorystructureThePacktHALdirectoryhasthefollowingstructure:
PacktHAL/
|
+----cape/
||
|+----BB-PACKTPUB-00A0.dts
|+----build_cape.sh
|
+----jni/
||
|+----(Various.cand.hfiles)
|+----(Various.mkfiles)
|
+----prebuilt/
||
|+----BB-PACTPUB-00A0.dtbo
|+----init.genericam33xx(flatteneddevicetr.rc
|+----spi
||
|+----spidev.h
|
+----README.txt
ThecapesubdirectorycontainsthesourcecodeandbuildscriptforbuildingaDeviceTreeoverlaythatenablesallofthehardwarefeaturesthatPacktHALneeds.YouwilllearnmoreaboutDeviceTreeoverlayslaterinthischapter.ThejnisubdirectorycontainsthesourcecodefilesthatimplementPacktHAL.ThesesourcefileswillbeaddedtoyourprojectsinlaterchapterstobuildPacktHALsupportintoyourapps.TheprebuiltdirectorycontainsafewpremadefilesthatmustbeaddedtoyourBBBAndroidimageandAndroidNDKtobuildandusePacktHAL.Youwillinstallthefilesintheprebuiltdirectorytotheirrequiredlocationsinthenextfewsections.
www.it-ebooks.info
PreparingAndroidforPacktHALBeforeusingPacktHALwithanyapps,youhavetoprepareyourBBBAndroidinstallation.Bydefault,Androidisveryrestrictiveonthepermissionsthatitassignstohardwaredevices.TousePacktHAL,youmustlessenthepermissionrestrictionsandconfigureAndroidforthehardwarethatyouwillinterfacewith.TheseactionsrequirecopyingsomeprebuiltfilesintoyourAndroidsystemtomakeafewconfigurationchangesthatrelaxvariousAndroidpermissionsandconfigurethehardwareproperlyforPacktHAL’suse.
YouwillusetheADBtooltopush(push)thenecessaryfilesovertoyourrunningBBBsystem.Priortopushingthefiles,bootAndroidontheBBBandconnecttheBBBtoyourPCusingtheUSBcablethatcamewithyourBBB.Onceyouhavereachedthispoint,continuewiththeinstructions.
www.it-ebooks.info
PushingPacktHALfilesunderLinuxThefollowingstepsareusedinordertopublishPacktHALfilesunderLinux:
1. Beforeyougetstarted,makesurethatADBcanseeyourBBBbyusingtheadbdevicescommand.TheBBBwillreportashavingaserialnumberofBBBAndroid.Executethefollowingcommand:
$adbdevices
Listofdevicesattached
BBBAndroiddevice
2. Ifyouaremissingtheadbcommand,installtheandroid-tools-adbpackageviaapt-get:
$sudoapt-getinstallandroid-tools-adb
TipWhycan’tLinuxfindmyBBB?
IfadbisinstalledonyoursystemandyouareunabletoseetheBBB,youmightneedtoaddaudevruletoyoursystemandperformsomeadditionaltroubleshooting.Googleprovidesdirectionsforaddingthisruleandsometroubleshootingstepsifyourunintoanydifficulty,andthiscanbefoundathttp://developer.android.com/tools/device.html.
BBBAndroidreportstheUSBdeviceIDofitsADBinterfaceas18D1:4E23,whichisthedeviceIDofaGoogleNexusS,sotheUSBvendorIDfortheBBBis18D1(thedeviceIDforGoogledevices).
3. OnceyouhaveverifiedthatadbcanseetheBBB,changeintothePacktHALdirectory,shellintoAndroidviaadb,andremounttheread-onlyrootfsfilesystemasread-write:
$cd$HOME/PacktHAL/prebuilt
$adbshell
root@beagleboneblack:/#mountrootfsrootfs/rw
root@beagleboneblack:/#exit
4. Now,pushthenecessaryfilesintoAndroid’srootfsfilesystem:
$adbpushBB-PACKTPUB-00A0.dtbo/system/vendor/firmware
$adbpushinit.genericam33xx\(flatteneddevicetr.rc/
$adbchmod750/init.genericam33xx\(flatteneddevicetr.rc
5. Finally,shellintoAndroid’srootfsfilesystemtosyncitandremountitasread-only:
$adbshell
root@beagleboneblack:/#sync
root@beagleboneblack:/#mountrootfsrootfs/roremount
root@beagleboneblack:/#exit
6. YouhavenowpreparedyourBBBAndroidimageforPacktHALunderLinux.
www.it-ebooks.info
RemovethepowersupplycableandUSBcablefromyourBBBtoshutitdown.7. Then,poweruptheBBBtoverifythatAndroidbootsproperlywiththemodifications
thatyouhavejustmade.
www.it-ebooks.info
PushingPacktHALfilesunderWindowsYoumustlocatewhereyouradb.exefileislocated.ItispartoftheplatformtoolsintheAndroidSDK.Inthefollowinginstructions,weareassumingthatyouinstalledtheEclipseADTinthec:\adt-bundledirectory,makingthefullpathtoadbtobec:\adt-bundle\sdk\platform-tools\adb.exe.
ThefollowingstepsareusedinordertopublishPacktHALfilesunderWindows:
1. Beforeyougetstarted,makesurethatadbcanseeyourBBBbyusingtheadbdevicescommand.TheBBBwillreportashavingaserialnumberofBBBAndroid:
$adbdevices
Listofdevicesattached
BBBAndroiddevice
TipWhycan’tWindowsfindmyBBB?
ItcanbenotoriouslydifficulttogetadbtoseeAndroiddevicesunderWindows.ThisisbecauseeachhardwaremanufacturerthatcreatesanAndroiddeviceprovidesitsownWindowsADBdevicedriverthatWindowsusestotalktothatdevice.BBBAndroidreportstheUSBdeviceIDofitsADBinterfaceas18D1:4E23,whichisthedeviceIDofaGoogleNexusS.Thisdeviceisoneofthe(many)USBdevicesthataresupportedbyKoushikDutta’sexcellentUniversalADBdriverforWindows.Ifadbcan’tfindyourBBB,installtheUniversalADBdriverandthentryagain.Youcandownloadthedriverfromhttp://www.koushikdutta.com/post/universal-adb-driver.
2. Onceyouhaveverifiedthis,adbcanseetheBBB,shellintoAndroidviaadb,andremounttheread-onlyrootfsfilesystemasread-write:
$adbshell
root@beagleboneblack:/#mountrootfsrootfs/rw
root@beagleboneblack:/#exit
3. Now,pushthenecessaryfilesintoAndroid’srootfsfilesystem:
$adbpushc:\PacktHAL\prebuilt\BB-PACKTPUB-00A0.dtbo
/system/vendor/firmware
$adbpushc:\PacktHAL\prebuilt\init.genericam33xx(flatteneddevicetr.rc
/
$adbchmod750/init.genericam33xx\flatteneddevicetr.rc
4. Finally,shellintoAndroid’srootfsfilesystemtosyncitandremountitasread-only:
$adbshell
root@beagleboneblack:/#sync
root@beagleboneblack:/#mountrootfsrootfs/roremount
root@beagleboneblack:/#exit
5. YouhavenowpreparedyourBBBAndroidimageforPacktHALunderWindows.
www.it-ebooks.info
RemovethepowersupplycableandUSBcablefromyourBBBtoshutitdown.Then,poweruptheBBBtoverifythatAndroidbootsproperlywiththemodificationsthatyouhavejustmade.
TipWhyisitthattheinit.genericam33xx(flatteneddevicetr.rcfileisnamedsooddly?
Androiddeviceshaveasetofread-onlypropertiesthatdescribethehardwareandsoftwareofthesystemtoappsandmanagers.Oneofthesepropertiesisro.hardware,whichdescribesthehardwarethatthekernelisconfiguredfor.Device-specific.rcfilesinAndroidhavetheinit.{ro.hardware}.*rcform.
IntheLinuxkernelsource,thearch/arm/mach-omap2/board-generic.cfileusesaDT_MACHINE_START()macrotospecifythenameoftheBBBplatformasGenericAM33XX(FlattenedDeviceTree).Thistextstringisconvertedtolowercase,spacesareremoved,andthestringistruncatedtoproducethefinalstringthatisstoredinthero.hardwareproperty.
www.it-ebooks.info
SettinguptheAndroidNDKforPacktHALUnfortunately,theAndroidNativeDevelopmentKit(NDK)ismissingakernelheaderfilethatisneededtobuildPacktHAL.ThemissingheaderdescribestheinterfacebetweenuserspaceappsandthegenericSPIdriver(spidev,whichyouwilluseinChapter5,InterfacingwithHigh-speedSensorsUsingSPI).ItisnotthefaultoftheNDKthatthisheaderfileismissing,asusuallyappswillneverneeddirectaccesstothespidevdriver.
Asyouareusinganapptotalkdirectlytalktothehardware,youwillneedtocopythismissingheaderintoyourNDKinstallation.
TipForyourconvenience,wehaveincludedacopyofthisheaderfileinthePacktHALsourcetarball.YouonlyneedtocopythefileintoyourNDKinstallationpriortobuildingPacktHAL.
BBBAndroidis4.4.4KitKat,andAPIlevel19isthehighestlevelsupportedbythisversion.YouwillbebuildingalloftheexamplesinthisbookforAPIlevel19.EachAPIlevelhasadifferentsetofheadersintheNDK,soyoumustaddthemissingheaderstotheinclude/linuxdirectoryforAPIlevel19.IfyoudecidetobuildappsatlowerAPIlevels,youcanrepeatthefollowingstepstoaddtheadditionalheaderfiletoanyoftheotherAPIlevelsthatyouwishto.
www.it-ebooks.info
AddingtheheadertotheNDKunderLinuxIfyouaregoingtobebuildingappsusingEclipseADTunderLinux,youwillneedtohavetheAndroidNDKinstalledonyourLinuxsystem.Fortheseinstructions,wewillassumethatyouhavealreadyinstalledtheNDKtotheandroid-ndkfolderinyour$HOMEdirectory.Asyouhavealreadydownloaded,decompressed,anduntarredthePacktHAL.tgzfiletoyour$HOMEdirectoryearlierinthischapter,wewillassumethatthePacktHALdirectorythatyoucreatedisstillthere:
$cd$HOME/android-ndk/platforms/android-19/arch-arm/usr/include/linux
$cp-rf$HOME/PacktHAL/prebuilt/spi
ThiswillcopythecontentsofthespiheaderfiledirectoryintoyourNDKheaderfiles.YourLinuxNDKinstallationnowhastheextraheaderfilethatitneedstobuildPacktHAL.
www.it-ebooks.info
AddingtheheadertotheNDKunderWindowsIfyouaregoingtobebuildingappsusingEclipseADTunderWindows,youwillneedtohavetheAndroidNDKinstalledonyourWindowssystem.Fortheseinstructions,wewillassumethatyouhaveinstalledtheNDKtothec:\android-ndkfolder.Asyouhavealreadydownloaded,decompressed,anduntarredthePacktHAL.tgzfiletoyourc:\directoryearlierinthischapter,wewillassumethatthePacktHALdirectorythatyoucreatedisstillthere:
1. Openafileexplorerwindowandnavigatetothec:\android-ndk\platforms\android-19\arch-arm\usr\include\linuxpath.
2. Openasecondfileexplorerwindowandnavigatetothec:\PacktHAL\prebuiltpath.Right-clickonthespidirectoryandselectCopyfromthecontextmenu.
3. ChangetotheAndroidNDKwindow,right-clickanywherewithinthewhitespaceofthefilelistinthewindow,andselectPastefromthecontextmenu.
ThiswillcopythecontentsofthespiheaderfiledirectoryintoyourNDKheaderfiles.YourWindowsNDKinstallationnowhastheextraheaderfilethatitneedstobuildPacktHAL.
www.it-ebooks.info
MultiplexingtheBBBpinsAsaccessinghardwareresourcesfollowsthesameprocessunderAndroidasitdoesunderLinux,itisimportanttounderstandhowtheLinuxkernelconfiguresdevicedriversandallocatesthemtoparticularpiecesofhardware.ItisalsonecessarytounderstandhowthesekerneldriversprovideuserspaceinterfacesthatPacktHALcaninteractwith.
TheBBB’sAM3359processoroffersawidevarietyofsignalsonitshundredsofpins.Thesesignalsincludemanydifferent,specializedinterfacebusesandsensorinputs.Therearefartoomanypotentialsignalsforthenumberofpinsavailabletosupplythesesignalstotheoutsideworld.Toselectwhichsignalsareavailableonthepins,thepinsaremultiplexed,ormuxed,tospecificsignals.
Severaloftheprocessor’spinsarewiredtotheconnectionsoftheBBB’sP8andP9headers.ThemuxingoftheseparticularpinsisofgreatinteresttoBBBusers,asthemuxingdetermineswhichprocessorsignalsandfeaturesareeasilyaccessibletotheuserforhardwareinterfacing.Thereare46pinsoneachoftheBBB’stwoheaders,givingyouatotalof92pinstointerfacewith.Unfortunately,61ofthesepinsareinusebydefault,meaningthatonly31pinscanbechangedaroundforyourprojectswithoutyouhavingtodisableoneormorestandardfeaturesoftheBBBtomakemorepinsavailable.
TheP8andP9expansionheadersoftheBeagleBoneBlack
Somepinsontheheadersarepermanentlyassigned,suchasthepinsthatprovideaccesstovoltage(1.8,3.3,and5VDCareavailable)andgroundsignals.Theotherpinsthough,canbemuxedtomeettheneedsofyourproject.PropermuxingalloftheP8/P9pinsto
www.it-ebooks.info
providealloftheresourcesthatyourequirecansometimesbetricky,particularlyifyouareonlybeginningtolearnaboutthehardwareinterfacingaspectsoftheBBB.Luckily,wehavealreadydeterminedapinmuxconfigurationforyouthatwillprovidePacktHALwithallofthehardwareresourcesthatitneedstorunalloftheexercisesinthisbook.
DefaultpinsinuseontheBeagleBoneBlack
www.it-ebooks.info
ThekernelDeviceTreeandcapemgrThepinsoftheBBBmustbemuxedinaspecificwaytospeakwithcustomhardware,butwhereandhowisthisactuallydone?Theansweris“thekernel’sDeviceTree.”TheDeviceTreeisahierarchicaldatastructureinsidethekernelthatdescribeswhathardwareispresent,whichresourcesareusedbythathardware,andwhichkerneldriversshouldbeusedtotalktoeachhardwaredevice.Itdescribesdifferentfacetsofthehardware,suchaspinmuxingsettings,clockspeeds,andparametersthatarepassedtokerneldevicedrivers.
Itwouldbeanannoyinghassleiftheuserwasrequiredtoinstallanewkerneleverytimethehardwarechanged.ForahardwareplatformliketheBBB,theusercanchangethehardwareconnectedtotheBBBbetweenpowercycles!ItwouldbeveryusefultobeabletodynamicallychangetheDeviceTreetoaddorremovehardwareonthefly.TheBBB’sLinux3.8kernelhasaspecialsubsystem,calledthecapemanager(capemgr)thatallowsyoutodojustthat.
ThecapemgrdynamicallyaddsandremovespiecesoroverlaysoftheDeviceTree.Itprovidesthreeimportantservices:
ItrecognizesanycapehardwarethatisconnectedtotheBBBItloadstheappropriateDeviceTreeoverlaytoenableandconfigureeachrecognizedcapeItallowsarbitraryDeviceTreeoverlaystobeloadeddynamicallyfromuserspacetoconfigureanyhardwarethatisnotautomaticallydiscovered
www.it-ebooks.info
DefiningacapeAcapeisanyhardwareadd-onthatconnectstotheBBB’sP8/P9connectors(similartohowshieldboardsconnecttoanArduino)andcontainsanelectricallyerasableprogrammableread-onlymemory(EEPROM)chipthatreportsthecape’sidentitytothekernel’scapebus.ThecapemgrinthekernelcanthendynamicallyenabletheappropriateDeviceTreeoverlayforthatparticularcape.Thisiswhatallowsyoutoconnectavarietyofdifferent,commerciallyavailablecapeboardstotheBBB,andtheyalljustautomaticallyworkwithoutyouhavingtochangeasingleconfigurationfile.
AmuchlooserdefinitionofacapeisanyexternalcircuitrythatinterfacesviatheP8/P9connectors.WithoutincludinganEEPROMthattellsthecapemgr“IamacapeandmynameisXYZ”,thecapemgrwon’tautomaticallylocateandloadtheproperDeviceTreeoverlayforthecape.Thisisthecaseforalloftheexamplesinthisbook.YoucanstillconsiderthehardwarethatyouconnecttotheBBBtobeacapethatAndroidisinterfacingwith,buttheDeviceTreeoverlaymustbeloadedmanuallyfromuserspace.
Earlierinthischapter,youusedadbtopushafilenamedBB-PACKTPUB-00A0.dtbotoyourAndroidimage.ThisfileistheDeviceTreeoverlaythatconfigurestheBBBforthehardwarethatyouwilluseintheexercisesthroughoutthisbook.Thecustominit.genericam33xx(flatteneddevicetr.rcfilethatyoualsopushedovertotheAndroidimagemanuallyloadsthisoverlayforyouduringAndroid’sbootprocess.
IntheLinuxfilesystem,customoverlaysareplacedintothe/lib/firmwaredirectory.UnderAndroid,however,thereisno/libdirectoryinrootfs,sooverlaysareinsteadplacedintothe/system/vendor/firmwaredirectory.Thisisalsothelocationwherefirmware(.fwfiles)builtduringkernelcompilationisinstalled.WhenusingyourownDeviceTreeoverlaysforyourfutureprojects,remembertoplacethemintothe/system/vendor/firmwaredirectorysothatthecapemgrcanfindthem.
TipWherecanIlearnmoreaboutmultiplexingtheBBB’spins,theDeviceTree,andcreatingcustomoverlays?
LearninghowtoselectthebestpinmuxingforcustomprojectsandcreatingtheappropriateDeviceTreeoverlaysareoutsidethescopeofthisbook,buttherearemanyexcellentresourcesavailablethatcanintroduceyoutotheprocess.Hereareafewgreatresourceswerecommendthatyoureadtolearnmore:
TheBeagleBoneBlackSystemreferencemanual:http://www.adafruit.com/datasheets/BBB_SRM.pdfDerekMolloy’swebsite:http://derekmolloy.ie/category/embedded-systems/beaglebone/AdaFruit’sDeviceTreeOverlaytutorial:https://learn.adafruit.com/introduction-to-the-beaglebone-black-device-tree
www.it-ebooks.info
SummaryInthischapter,weexplainedhowAndroidusesaHALtoallowAndroidmanagerstoprovidehardwareaccesstoapps.WeintroducedyoutoPacktHALthatcanbeusedtointerfacewithalloftheexamplesthroughoutthisbook.YouconfiguredyourBBBAndroidimagetousePacktHAL,andyoumodifiedyourNDKinstallationtobuildPacktHALintoyourapps.
WealsoshowedwhichpinsoftheBBB’sP8/P9headerscanbemultiplexed,whattheDeviceTreeisandhowitisusedtomultiplexpins,andhowthecapemgrloadsDeviceTreeoverlaystodynamicallymuxtheBBB’spins.
Inthenextchapter,you’llputPacktHALtoworkandbuildyourfirsthardware-interfacingappusingGPIOs.
www.it-ebooks.info
Chapter3.HandlingInputsandOutputswithGPIOsInthelastchapter,youpreparedyourdevelopmentPCandBBBAndroidsystemforthedevelopmentofhardware-interfacingAndroidapps.Nowthatyourdevelopmentenvironmentissetupandreadytogo,youwillbeginexploringyourveryfirstappthatiscapableofdirectcommunicationwithhardwareconnectedtotheBBB.
General-PurposeInput/Output(GPIO)isoneofthemostbasicinterfacesindigitalelectronics.Intheexampleswithinthischapter,youwillbeworkingwithGPIOstoreceivedigitalinputsignalsfromtheoutsideworldandsenddigitaloutputsignalsbackinresponse.Whilethisisasmallstart,itisthefirststepindevelopingandunderstandinghardware-interfacingappsthataremuchmorecomplex.GPIOscanbeusedtoimplementcomplexandpowerfulinterfacinglogic.WewilldiscussboththehardwareandsoftwaresidesofGPIOinterfacingandexplainhowcallingJavamethodsinAndroidappscaninterfacewithlow-levelhardware-interfacingcode.
Inthischapter,wewillcoverthefollowingtopics:
UnderstandingGPIOsBuildingaGPIOinterfacecircuitIncludingPacktHALwithinyourappsExploringtheGPIOexampleapp
www.it-ebooks.info
UnderstandingGPIOsAtitsmostbasiclevel,communicationbetweentwopiecesofhardwarerequiresthetransmissionofdatabackandforthbetweenthem.Incomputersystems,thisdataisrepresentedasvoltagelevelssentoverawirethatconnectsthedevicestogether.Thepatternsandlevelsofvoltagebackandforthformacommunicationprotocolthatthedevicesusetotransmitdatabetweeneachother.
GPIOisthemostbasicinterfacingoptionofferedbymicrocontrollersandmicroprocessors.SomepinsoftheBBB’sprocessorareallocatedasGPIOsthatactasaninput(monitoringvoltageonthewiretoreceivedata)oranoutput(placingaparticularvoltageonthewiretosenddata).TheBBBhasdozensofavailableGPIOpins,whichmakesGPIOaflexibleandsimplewayforAndroidappstointeractwiththeoutsideworldwithoutrequiringfancydevicedriversorextrainterfacinghardware.
www.it-ebooks.info
NutsandboltsofGPIODigitallogicoperatesontheconceptthattherearetwodiscretevoltagelevelsthatrepresentanon/highstateandanoff/lowstate.Bytogglingbetweenthesetwostates,binarybitsofdataaretransmittedbetweendevices.TheBBBusesthevoltageof3.3Vforitshighlevelandavoltageof0V(connectedtoaground)forthelowlevel.Thisvoltageschemeisknownasa3.3Vlogiclevel,anditiscommonlyusedforsingle-boardcomputerssuchastheBeagleBoardandRaspberryPi.Manymicrocontrollers(manyArduinos,forexample)usea5Vlogiclevelinstead.
TipNeverapplymorethan3.3VtoanyBBBpin!
Applyinggreaterthan3.3VtoaBBBGPIOcanfrytheBBB’sprocessor,soalwaysmakesurethatyouonlyworkwithamaximumof3.3VwhendesigningtheGPIOinterfacecircuitryfortheBBB.PinsP9.3/4supply3.3V,andpinsP9.5/6supply5V.Itisverysimpletoaccidentallyconnectabreadboardwiretothepinssupplying5Vwhenyouintendedtousethe3.3Vpins.Tohelpavoidthismistake,trycoveringtheP9.5/6pinswithapieceoftape.Thispreventsyoufromaccidentallyinsertingabreadboardwireintothesepins.
TheBBB’sprocessorhasfourbanksofGPIOs,with32individualGPIOsineachbank.Withonly92pinsavailableontheP8/9connectors,itisnotpossibletogiveeveryGPIOaccesstotheoutsideworld.Infact,theBBB’sSystemReferenceManualshowsthatitisonlypossibletomuxabout65uniqueGPIOstoP8/P9atthesametime,evenifeveryotherfeaturebeingmuxedtoP8/9wasdisabled.ThereareafewotherGPIOsthatareusedinternallyfortaskssuchaslightingandblinkingtheBBB’sLEDs,butyoushouldconsideryourselfrestrictedtoonlyusingtheGPIOsthatareaccessibleviaP8/P9andthatdonotconflictwithanyofthestandardBBBfeatures.
www.it-ebooks.info
GPIOaccessmethodsunderAndroidTherearetwobasicapproachestointeractingwithGPIOsontheBBB:fileI/Oandmemory-mapping.WiththefileI/O,youpassGPIOrequeststhroughakerneldriverbyreadingandwritingtoGPIOfilesinthefilesystem.Withmemory-mapping,youmaptheGPIOcontrolresistorsintomemoryandthenreadandwritethesemappedmemorylocationstodirectlymanipulatethecontrolresistors.AsbothofthesemethodsaremadepossiblebytheLinuxkernel,theywillbothworkjustaswellunderAndroidastheydounderLinux.
ProsandconsofthefileI/OmethodThefileI/Omethodcanbeperformedbyanyprocessthathastheproperpermissionstoread/writetheGPIOdevicefiles.However,likeanyfileI/Ooperation,thiscanbequiteslow.
Prosandconsofthememory-mappingmethodThememory-mappingmethodallowsyoutodirectlyaccesstheresistorsthatcontroltheGPIOs.Memory-mappingisveryfast(about1000timesfasterthanfileI/O!),butonlyprocesseswithrootpermissionscanuseit.
Asyourappsareunabletoexecutewithrootpermissionswithoutsomeseriouspermissionchanges,youwillbeunabletousememory-mappingtoaccessGPIOs.ThiseffectivelyrestrictsyoutoonlyusingfileI/Oforyourapps.
NotePacktHALimplementsbothmemory-mappingandfileI/OforGPIOaccess.Ifyouareinterestedinthelow-leveldetailsofhowbothoftheseapproacheswork,examinethejni/gpio.cfileinPacktHAL.tgz.
www.it-ebooks.info
PreparingAndroidforGPIOuseInChapter2,InterfacingwithAndroid,youusedadbtopushtwoprebuiltfilesfromPacktHALtoyourAndroidsystem.Thesetwofiles,BB-PACKTPUB-00A0.dtboandinit.{ro.hardware}.rc,configureyourAndroidsystemtoenablespecificGPIOsandallowyourappstoaccessthem.
NoteRememberthatwhenwetalkabouttheinit.{ro.hardware}.rcfile,wearereferringtotheinit.genericam33xx(flatteneddevice.trfileintherootdirectoryoftheAndroidfilesystem.
TheBB-PACKTPUB-00A0.dtbofileisaDeviceTreeoverlaythatmuxestheBBBtosupportalloftheexamplesinthisbook.AsfarasGPIOsareconcerned,thisoverlaymuxestheP9.11andP9.13pinsintoGPIOs.InthePacktHAL.tgzfile,thesourcecodefortheoverlayislocatedinthecape/BB-PACKTPUB-00A0.dtsfile.ThecoderesponsibleformuxingthetwoGPIOsislocatedinthebb_gpio_pinsnodewithinfragment@0:
/*AllGPIOpinsarePULLUP,MODE7*/
bb_gpio_pins:pinmux_bb_gpio_pins{
pinctrl-single,pins=<
0x0700x17/*P9.11,gpio0_30,OUTPUT*/
0x0740x37/*P9.13,gpio0_31,INPUT*/
>;
};
Thedetailsofthehexvaluesusedinthebb_gpio_pinsnodearebeyondthescopeofthisbook.However,thegeneralideaisthattheyspecifywhichpinisofinterest,whichmodethepinshouldbemuxedto,afewdetailsaboutpull-up/pull-downresistors,whetheritisaninputoranoutputpin,andwhetheranyskewingadjustmentsshouldbemadetothesignal.
NoteThedetailsofwhatskewisandhowtoadjustforitarebeyondthescopeofthisbook.Ifyouwouldliketolearnmoreaboutskewing,wesuggesttheWikipediapageonthesubjectasagoodstartingpoint(http://en.wikipedia.org/wiki/Clock_skew).
Atboot,thisoverlayisloadedbytheinit.{ro.hardware}.rcfile.ThekernelthenknowswhichpinsaretreatedasGPIOs.Afterloadingtheoverlay,theinit.{ro.hardware}.rcfilethenexecutesafewcommandsthatexplicitly“unlock”theseGPIOfilesforusebyappsbyexportingthem.ExportingaGPIOpincreatesaseriesoffilesinthe/sysfilesystemthatcanbereadandwrittentointeractwiththatGPIOpin.
ByexportingaGPIOpinandthenchangingthepermissionsoftheproperfilesinthe/sysfilesystemviachmod,anyprocesscanreadfromorwritetoGPIOs.Thisisexactlywhatthecommandsintheinit.{ro.hardware}.rcfiledotoallowAndroidappstointerfacewithGPIOs.Thefollowingportionoftheinit.{ro.hardware}.rcfileperformsthe
www.it-ebooks.info
exportandchmodoperations:
#ExportGPIOs30and31(P9.11andP9.13)
write/sys/class/gpio/export30
write/sys/class/gpio/export31
#MakeGPIO30anoutput
write/sys/class/gpio/gpio30/directionout
#MakeGPIOs30and31writeablefromtheFS
chmod777/sys/class/gpio/gpio30/value
chmod777/sys/class/gpio/gpio31/value
EachGPIOhasaspecificintegeridentifierthatisdeterminedbythebanktheGPIObelongstoanditspositionwithinthatbank.Inourcase,theGPIOmuxedtoP9.11isthe30thGPIOinbank0,andP9.13isthe31stGPIOinbank0.Thismakestheirintegeridentifiers30and31,respectively.
NoteTheGPIOpins30and31areonlyavailableviathe/sysfilesystembecausetheywereexplicitlyexportedviathewritecommandsintheinit.{ro.hardware}.rcfile.OtherGPIOpinswillnotbeavailableviathefilesystemunlesstheyarealsoexplicitlyexportedinthesamefashion.
ThisisaveryinsecurewayofallowingGPIOaccessbecauseitopensuptheGPIOsforusebyprocessesthatwemightnotwanttohavedirectaccesstothem.Forexperimentationandprototyping,thisisnotaproblem.However,youcertainlyshouldnotdothisinacommercialsystem.Unlessyoudevelopaproper,privilegedAndroidmanagertohandletheGPIOresources,youmustallowallprocessestoaccesstheGPIOfilesunlessyoutailorthepermissionstoonlybeusablebyappsbelongingtoaspecificuserorgroup.Aseachappisassigneditsownuser,youwouldhavetochowntheGPIOstotheproperuserandgroupafteryouinstalltheapp’s.apkfileontothesystem.
www.it-ebooks.info
BuildingaGPIO-interfacingcircuitBeforeyoubegindevelopingsoftwarethatcommunicatesusingGPIOs,youmustfirstconstructahardwarecircuitfortheGPIOstointerfacewith.Forthischapter,youwillbuildasimplecircuitthatconsistsofa1kohmresistor,anLED,andapushbuttonswitch.PartnumbersandsuppliersforthesecomponentswerelistedinChapter1,IntroductiontoAndroidandtheBeagleBoneBlack.Beforegettingstarted,besurethatyouhavealloftheproperpartsandremoveallpowersourcesfromyourBBB(unplugthepowersupplyandUSBcables)priortoconnectinganythingtotheBBB’sP8/P9connector.
TipDon’tdisassembleyourcircuit!
TheGPIOcircuitinthischapterispartofamuchlargercircuitusedinChapter6,CreatingaCompleteInterfacingSolution.Ifyoubuildthecircuitasitispositionedinthefollowingdiagram(towardsthetopofthebreadboard),youcansimplyleavetheGPIOcomponentsandwiresinplaceasyoubuildtheremainingcircuitsinthisbook.Thisway,itwillalreadybeconstructedandworkingwhenyoureachChapter6.
www.it-ebooks.info
ConstructingthecircuitThecircuitthatyouwillbuildinterfaceswiththefollowingfourBBB’spins:
P9.1(ground)P9.3(3.3V)P9.11(GPIO)P9.13(GPIO)
TheP9.11pinisconfiguredasanoutputGPIO,anditdrivestheLED.TheP9.13pinisconfiguredasaninputGPIO,anditsetsitsstatedependingupontheinputvoltagethatisappliedtoit.BothGPIOpinsareconfiguredbytheBB-PACKTPUB-00A0.dtbooverlaytouseaninternalpull-upresistor.Ifyouarenotfamiliarwithwhatapull-upresistoris,don’tworry.Forthepurposesoftheseexamples,itsimplymeansthatthelogicleveloftheGPIOswillnot“float”betweenonandoffifnothingisattachedtotheGPIOpins.Instead,thelogiclevelwillbe“pulled-up”totheonstate.
NoteInterestedinlearningmoreaboutwhatapull-upresistorisandhowitworks?Wesuggestthatyoucheckoutthisonlinetutorialonpull-upandpull-downresistors,availableathttp://www.resistorguide.com/pull-up-resistor_pull-down-resistor.
Breadboardstypicallyhavetwoverticalbusesoneithersidethatrunalmosttheentirelengthofthebreadboard.Thesebusesareusedtoprovideconvenientaccesstopowerandgroundsignalsforanycomponentsinsertedintothebreadboard.
www.it-ebooks.info
ThecompleteGPIO-interfacingcircuit
Nowwecanstartconstructingourcircuit:
1. ConnecttheBBB’sground(P9.1)and3.3V(P9.3)signalstothetwoverticalbusesonthebreadboard.Thegroundbusistheverticalbustowardsthecenterofthebreadboard.The3.3Vbusistheverticalbustowardstheedgeofthebreadboard.
2. Next,connecttheanode,orthepositivelead,oftheLEDtoP9.11.LEDshaveapolarity,socurrentwillonlyflowthroughtheminonedirection.Currentflowsfromthelongerlead(theanode)oftheLEDtotheshorterlead(thecathode).
3. IftheLED’sleadshavebeencuttothesamelengthandyouareunabletotellwhichleadiswhich,feelaroundtheedgeoftheLED’splasticcasing.Theedgeofthecasingisflatonthecathodesideandroundedontheanodeside.AslongasthecathodeisconnectedtothegroundandtheanodeisconnectedtotheGPIOpin,theLEDwillworkproperly.
4. YoumustlimitthecurrentdrawnbytheLEDtoensurethatyoudonotdamagetheGPIOpin,soplacea1KohmresistorbetweentheLED’scathodeleadandthegroundsignal.ResistorsdonothaveapolaritylikeLEDsdo,sothedirectionthatyouconnectittothebreadboardwillnotmatter.
NoteIfyouwishtolearnmoreaboutusingacurrent-limitingresistorwithanLED,suchasselectingtherightresistorforthetask,wesuggestthatyoureadthetutorialfrom
www.it-ebooks.info
SparkFun,availableathttps://www.sparkfun.com/tutorials/219.
5. NowthattheLEDandresistorhavebeenconnectedtotheBBB,youmustconnectthepushbuttonswitch.Differentswitcheshavedifferentnumbersofleads,buttheswitchthatwesuggestedforyourusehasatotaloffourleads.Theseleadsformtwopairsoftwoleadseach.Thetwoleadsineachpairarealwayselectricallyconnectedtoeachother,butonepairwillonlybeelectricallyconnectedtotheotherpairwhenthebuttonisbeingpressed.Twosidesoftheswitcharesmooth,andtheothertwosideshavetwoprotrudingleadsoneachside.Thetwoprotrudingleadsonasinglesideoftheswitchbelongtodifferentpairsofleads.PickonesideoftheswitchwithtwoleadsonitandconnectoneleadtoP9.13andtheotherleadtothebreadboard’sgroundbus.
Yourcircuitisnowcomplete.Double-checkyourwiringagainstthediagramofthecompleteGPIO-interfacingcircuittoensurethateverythingisconnectedproperly.
www.it-ebooks.info
CheckingyourwiringOnceyouhavecompletedthewiringoftheGPIOcircuit,youshouldtestittoensurethatitworksproperly.Luckily,youcandothiseasilybyshellingintotheBBBandworkingwiththeexportedGPIOpinfiles.WewillassumethatyouareusingadbtoshellintotheAndroidsystem,butusingtheFTDItoaccesstheconsoleshellwillworkinexactlythesameway.
TipHowdoIusetheFTDIcable?
IfyouhaveneverusedanFTDIcabletocommunicatewithyourBBB,thereisapageonthewww.elinux.orgwiki(maintainedbytheBeagleBoard.orgstaff)thatcanhelpyougetstarted,whichishttp://elinux.org/Beagleboard:Terminal_Shells.
Inthisbook,wewillonlybeusingtheUSBcableandADBshelltoaccesstheBBB.However,learninghowtousetheFTDItomonitorandtroubleshootyourBBBcanreallycomeinhandy.
ConnectpowertoyourBBBandthenusetheUSBcabletoconnecttheBBBtoyourdevelopmentsystem.AftershellingintotheBBB,begintestingyourGPIOcircuitusingthefollowingsteps:
1. ChangeintothedirectoryfortheGPIOpinmuxedtoP9.11(GPIOpin30):
root@beagleboneblack:/#cd/sys/class/gpio/gpio30
2. UsetheechocommandtoturntheLEDonbyforcingthestateofthisGPIOto1:
root@beagleboneblack:/#echo1>value
3. TheLEDwillnowbeturnedon.UsetheechocommandtoturntheLEDoffbyforcingthestateofthisGPIOto0:
root@beagleboneblack:/#echo0>value
4. TheLEDwillnowbeturnedoff.ChangeintothedirectoryfortheGPIOpinmuxedtoP9.13(theGPIOpin31):
root@beagleboneblack:/#cd/sys/class/gpio/gpio31
5. Usethecatcommandtocheckthecurrentstateofthepushbuttonswitch.Whenexecutingthiscommand,makesurethatyouarenotpushingthebutton:
root@beagleboneBlack:/#catvalue
1
6. Now,executethefollowingcatcommandwhileholdingdownthebutton.Youshouldtypetheentirecommand,pressthebutton,andthenhittheEnterkeytoenterthecommandwhilestillholdingthebuttondown:
root@beagleboneblack:/#catvalue
www.it-ebooks.info
0
NoteThepushbuttonvalueslookreversedbecauseofhowthecircuitiswired.Thepull-upresistoronP9.13willpullthevalueoftheGPIOto1whenthebuttonisnotpressed.Whenthebuttonispressed,theP9.13pinbecomesconnectedtothegroundsignalandchangestheGPIOto0.
IfyousawtheLEDturnonandoffandthecorrectvalueswerereturnedwhentheswitchwaspressedandreleased,youhavecorrectlywiredthecircuit.IftheLEDdidnotlightup,makesurethatyouhavenotaccidentallyswappedtheanodeandcathodeleadsoftheLED.Iftheswitchalwaysreturnsavalueof0,makesurethatyouhaveconnectedthecorrectpairofleadsontheswitchtothegroundsignalbusandP9.13.
www.it-ebooks.info
IncludingPacktHALwithinyourappsBeforedivingintousingPacktHALtointerfacewithGPIOs,youmustunderstandhowtoincludePacktHALsupportinyourapps.WewillwalkyouthroughtheprocessofaddingthePacktHALcodeintoyourappandthenbuildingit.PacktHALwillbepackagedwithyourappinthe.apkappasasharedlibrary.Thesourcecodeforthelibraryexistswithintheapp’sprojectdirectory,butitisbuiltseparatelyfromtheJavacodeoftheapp.YoumustmanuallybuildthePacktHALsharedlibrarybeforeyourappcanincludeitwithinthe.apkappanduseit.
NoteWeincludeaprebuiltversionofthePacktHALlibraryineachoftheexampleappprojectsincludedwiththisbook,soyoucanjumpintobuildingandrunningtheexampleappsrightawaywithoutworryingaboutthedetailsofbuildingPacktHAL.OnceyoubegincreatingyourowncustomappsandmodifyingPacktHALforyourownhardwareprojects,youwillneedtounderstandhowtobuildPacktHALfromsource.
www.it-ebooks.info
UnderstandingtheJavaNativeInterfaceAndroidappsarewritteninJava,butthefunctionsinPacktHALarewritteninCnativecode.Nativecodeisthecodethatiscompiledintoanativebinary,suchasasharedlibraryorexecutable,andthenexecuteddirectlybytheAndroidOS.NativecodeisbuiltusingthecompilertoolchainsuppliedwithintheAndroidNDK.Nativebinariesarenotasportableasthe“buildonce,runanywhere”bytecodeofAndroidapps,buttheycanbeusedforlow-levelinterfacinginwaysthatJavacodecannot.UnlikeJavabytecode,whichisexecutableonanyplatformthathasapropervirtualmachine,nativecodeiscompiledforonespecifichardwarearchitecture(suchasARM,x86,orPowerPC)andcanbeexecutedonlyonthatarchitecture.
Functionsimplementedinnativecodearecalledfromanapp’sJavacodeviatheJavaNativeInterface(JNI).JNIisapopularinterfacingmechanismthatJavaapplicationsusetointeractwithnativeC/C++code.Amongotherfeatures,JNIisusedtotranslateJavadatatypesintoCdatatypesandviceversa.
Forexample,considertheJavaStringtype.WhileJavahasaStringimplementation,thereisnoequivalenttypeinC.ThestringmustbesuitablyconvertedtoacompatibletypebeforeitcanbeusedbytheCcode.EachJavatypeisrepresentedinCbyaseriesofequivalenttypes,suchasjint,jstring,andjboolean,whicharedefinedinthestandardjni.hheaderfilethatissuppliedbytheAndroidNDK.
www.it-ebooks.info
CreatinganewappprojectthatusesPacktHALThefollowingstepsdemonstratehowyoucancreateanewcustomappthatincludesPacktHAL:
1. LaunchtheEclipseADTandselectthemenuoptionFile,thenNew,thenAndroidApplicationProject.
2. IntheNewAndroidApplicationdialog,entermyappintotheApplicationNamefield.ThiswillautomaticallypopulatetheProjectNameandApplicationNamefields.ChangetheMinimumRequiredSDK,TargetSDK,andCompileWithfieldstoAPI19:Android4.4.Thethemefieldcanbeleftaloneorchangedtowhicheverthemeyouwouldlikeforyourapp.Whenfinished,clickontheNextbutton.
TheNewAndroidApplicationscreen
3. Proceedthroughthesuccessivedialogscreens,retainingthedefaultsettingsforeachscreen,untilyouclickontheFinishbuttononthefinalscreen.
ThenameofthedefaultactivitycreatedforyournewappisMainActivity.Aftercreatingthenewproject,thefolderstructureofyournewmyappprojectwillresideinthemyapp($PROJECT)directoryandhaveadirectorystructuresimilartothefollowing:
www.it-ebooks.info
myapp
|
+----.settings/
+----assets/
+----bin/
+----gen/
+----libs/
+----res/
+----src/
+----...
Aftercreatingtheappforthefirsttime,severalnewfolderswillbecreatedtoholdthevariousintermediaryfilescreatedduringthebuildprocess.Onceyouhavecreatedyourapp,youmustaddthePacktHALcodetoitandcompileit.
BuildingPacktHALunderWindowsPacktHALmustbebuiltintoalibraryandincludedwithinyourapp’sprojectcodebasetobeusedbyyourapp.AssumingthatyoudecompressedanduntarredthePacktHAL.tgzfileinc:\,youcancopythePacktHALcodeintoyourapp’sprojectdirectory($PROJECT)usingthefollowingprocess:
1. Openafileexplorerwindowandbrowsetothe$PROJECTdirectory.2. Openasecondfileexplorerwindowandbrowsetoc:\PacktHAL.3. Right-clickonthejnidirectoryinthec:\PacktHALdirectoryandselectCopyfrom
thecontextmenu.4. Right-clickanywhereconvenientonwhitespacewithinthe$PROJECTdirectory
windowandthenselectPastefromthecontextmenu.
Nowthatthejni\directoryexistsinyour$PROJECTdirectory,youcanbuildPacktHALusingtheAndroidNDK.AssumingthatyouinstalledtheAndroidNDKinc:\android-ndk,youcanbuildPacktHALusingthefollowingprocess:
1. Launchcmd.exeforacommandpromptwindow.Usingthecommandprompt,changeintothe$PROJECTdirectory:
c:\>cd$PROJECT\jni
2. BuildthePacktHALlibraryusingtheAndroidNDK:
c:\$PROJECT\jni>c:\android-ndk\ndk-build
[armeabi]Compilethumb:packtHAL<=jni_wrapper.c
[armeabi]Compilethumb:packtHAL<=gpio.c
[armeabi]Compilethumb:packtHAL<=fram.c
[armeabi]Compilethumb:packtHAL<=bmp183.c
[armeabi]SharedLibrary:libpacktHAL.so
[armeabi]Install:libpacktHAL.so=>
libs/armeabi/libpacktHAL.so
ThePacktHALlibraryisnowbuiltandpresentinyourprojectasthefile$PROJECT\libs\armeabi\libpacktHAL.so.
www.it-ebooks.info
BuildingPacktHALunderLinuxPacktHALmustbebuiltintoalibraryandincludedwithinyourapp’sprojectcodebasetobeusedbyyourapp.AssumingthatyoudecompressedanduntarredthePacktHAL.tgzfileinyour$HOMEdirectory,youcancopythePacktHALcodeintoyourapp’sprojectdirectory($PROJECT)usingthefollowingcommands:
$cd$PROJECT
$cp–rf$HOME/PacktHAL/jni.
Nowthatthejnidirectoryexistsinyour$PROJECTdirectory,youcanbuildPacktHALusingtheAndroidNDK.AssumingthatyouinstalledtheAndroidNDKin$HOME/android-ndk,youcanbuildPacktHALusingthefollowingprocess:
1. Changeintothe$PROJECT/jnidirectory:
$cd$PROJECT/jni
2. BuildthePacktHALlibraryusingtheAndroidNDK:
$./$HOME/android-ndk/ndk-build
[armeabi]Compilethumb:packtHAL<=jni_wrapper.c
[armeabi]Compilethumb:packtHAL<=gpio.c
[armeabi]Compilethumb:packtHAL<=fram.c
[armeabi]Compilethumb:packtHAL<=bmp183.c
[armeabi]SharedLibrary:libpacktHAL.so
[armeabi]Install:libpacktHAL.so=>
libs/armeabi/libpacktHAL.so
ThePacktHALlibraryisnowbuiltandpresentinyourprojectasthe$PROJECT/libs/armeabi/libpacktHAL.sofile.
www.it-ebooks.info
ExploringtheGPIOexampleappInthissection,youwillexaminetheexampleAndroidappthatperformsGPIOinterfacingonBBB.ThepurposeofthisapplicationistodemonstratehowtousePacktHALtoperformGPIOreadandwriteprocessesfromwithinanactualapp.PacktHALprovidesasetofinterfacingfunctionsthatyouwillusetoworkwithGPIOsfromwithinyourAndroidapps.ThesefunctionsallowyoutoreadthevaluesofinputGPIOsandsetthevaluesofoutputGPIOs.Thelow-leveldetailsofthehardwareinterfacingareimplementedinPacktHAL,soyoucanquicklyandeasilygetyourappsinteractingwithGPIOs.
BeforediggingthroughtheGPIOapp’scode,youmustinstallthecodetoyourdevelopmentsystemandinstalltheapptoyourAndroidsystem.Thesourcecodefortheapp,aswellasaprecompiled.apkpackage,arelocatedinthechapter3.tgzfile,whichisavailablefordownloadfromthebook’swebsite.
www.it-ebooks.info
InstallingtheappandsourceunderWindowsOnceyouhavedownloadedthechapter3.tgzfile,youmustdecompressanduntarit.Wewillassumethatyouhavecopiedchapter3.tgztotherootdirectoryofc:\afterdownloadingitandwilldecompressitfromthere.Wewillrefertoyourworkspacedirectoryas$WORKSPACE.
Wewillassumethatyouradb.exebinaryisinyourcurrentpath.Ifitisnot,calladbbyusingthefullpathtotheadb.exebinary:
1. Openafileexplorerwindowandnavigatetothedirectory.2. Right-clickonthechapter3.tgzfileinfileexplorerandselectExtractHere.
Adirectorynamedc:\gpionowexists,anditcontainsallofthefilesfortheGPIOexampleapp.YoumustimportthisprojectintoyourEclipseADTworkspace:
1. LaunchEclipseADT.2. OpentheFilemenuandselectImport.3. OntheImportdialog,expandtheAndroidfolderandhighlightExistingAndroid
CodeIntoWorkspace.TheNextbuttonatthebottomofthedialogwillbecomeactive.Clickonittocontinue.
4. OntheImportProjectsdialog,typec:\gpiointheRootDirectorytextfield.Then,clickontheRefreshbutton.Thegpioprojectwillappearonthelistofprojectstoimport.
5. ClickontheSelectAllbutton,thenselectthecheckboxforCopyprojectsintoworkspace.
6. ClickontheFinishbuttontoimportthegpioappprojectintoyourworkspaceandcopythec:\gpiodirectoryintoyour$WORKSPACEdirectory.
AlloftheprojectfilesfortheGPIOapparenowlocatedinthatgpiodirectory.Aprebuilt.apkpackagefortheappisprovidedinthe$WORKSPACE\gpio\bindirectory.Youcaninstallthis.apkpackagedirectlytoyourAndroidsystemusingadb:
1. Launchcmd.exeforacommandpromptwindow.Usingthecommandprompt,changeintothe$WORKSPACE\gpio\bindirectory:
c:\>cd$WORKSPACE\gpio\bin
2. VerifythatadbcanseeyourBBBusingtheadbdevicescommand:
c:\$WORKSPACE\gpio\bin>adbdevices
Listofdevicesattached
BBBAndroiddevice
3. Installgpio.apktoyourAndroidsystemviatheinstallcommandinadb:
c:\$WORKSPACE\gpio\bin>adbinstall-dgpio.apk
4. Ifyouhavealreadyinstalledthegpio.apkapponceandarenowreceivingthefailure
www.it-ebooks.info
messageofINSTALL_FAILED_ALREADY_EXISTS,useadbtoreinstallgpio.apk:
c:\$WORKSPACE\gpio\bin>adbinstall-d-rgpio.apk
Thegpio.apkappisnowinstalledonyourAndroidsystem,andtheapp’ssourceisnowinstalledinyourEclipseADTworkspace.
www.it-ebooks.info
InstallingtheappandsourceunderLinuxOnceyouhavedownloadedthechapter3.tgzfile,youmustdecompressanduntarit.Wewillassumethatyouhavecopiedchapter3.tgztoyour$HOMEdirectoryafterdownloadingitandwilldecompressitfromthere.Wewillrefertoyourworkspacedirectoryas$WORKSPACE.
UsetheLinuxtarcommandtodecompressanduntarthechapter3.tgzfile:
$cd$HOME
$tar–xvfchapter3.tgz
Adirectorynamedgpionowexistsinyour$HOMEdirectory,anditcontainsallofthefilesforthegpioexampleapp.YoumustimportthisprojectintoyourEclipseADTworkspaceasfollows:
1. LaunchEclipseADT.2. OpentheFilemenuandselectImport.3. OntheImportdialog,expandtheAndroidfolderandhighlightExistingAndroid
CodeIntoWorkspace.TheNextbuttonatthebottomofthedialogwillbecomeactive.Clickonittocontinue.
4. OntheImportProjectsdialog,type$HOME/gpio(substitutinginthefullpathfor$HOME)intheRootDirectorytextfield.Then,clickontheRefreshbutton.Thegpioprojectwillappearonthelistofprojectstoimport.
5. ClickontheSelectAllbutton,thenselectthecheckboxforCopyprojectsintoworkspace.
6. ClickontheFinishbuttontoimportthegpioappprojectintoyourworkspaceandcopythe$HOME/gpiodirectoryintoyour$WORKSPACEdirectory.
Alloftheprojectfilesfortheapparenowlocatedinthe$WORKSPACE/gpiodirectory.Aprebuilt.apkpackageforthegpioprojectisprovidedinthegpio/bindirectory.Youcaninstallthis.apkpackagedirectlytoyourAndroidsystemusingadb:
1. Changeintothebindirectoryofthegpioproject:
$cd$WORKSPACE/gpio/bin
2. VerifythatadbcanseeyourBBBusingtheadbdevicescommand:
$adbdevices
Listofdevicesattached
BBBAndroiddevice
3. Installgpio.apktoyourAndroidsystemviatheinstallcommandinadb:
$adbinstall-dgpio.apk
4. Ifyouhavealreadyinstalledthegpio.apkapponceandarenowreceivingthefailuremessageofINSTALL_FAILED_ALREADY_EXISTS,useadbtoreinstallgpio.apk:
$adbinstall-d-rgpio.apk
www.it-ebooks.info
Thegpio.apkappisnowinstalledonyourAndroidsystem,andtheapp’ssourceisnowinstalledinyourEclipseADTworkspace.
www.it-ebooks.info
Theapp’suserinterfaceLaunchthegpioappontheAndroidsystemtoseetheapp’s(UI).Ifyouareusingatouchscreencape,youcansimplytouchthegpioappicononthescreentolaunchtheappandinteractwithitsUI.IfyouareusingtheHDMIforvideo,connectaUSBmousetotheBBB’sUSBportandusethemousetoclickonthegpioappicontolaunchtheapp.
TheappusesaverysimpleUItointeractwiththeGPIOs.Asitissosimple,theonlyactivitythattheapphasisdefaultMainActivity.TheUIconsistsofonlythreebuttonsandtextview.
TheGPIOsampleappscreen
ThePollButtonStatebuttonchecksthecurrentstateofthepushbuttonswitchandupdatesthevalueoftheButtonStatetextviewtoreportthatstate.TheswitchstatewillbereportedasUNKNOWNuntilthePollButtonStatebuttonispressedforthefirsttime.TheTurnlightonbuttonwillturnontheLEDifitisnotalreadyon,andtheTurnlightoffbuttonwillturntheLEDoff.
ThetextviewhasanIDassociatedwithitinres/layout/activity_main.xmlsothattheappcanupdatethetextview’svalueprogrammatically:
<TextView
…
android:text="@string/button_state"
android:id="@+id/button_state"/>
EachofthethreebuttonshaveanonClick()handlerdefined:
<Button
…
android:text="@string/button_poll"
android:onClick="onClickButtonPollStatus"/>
<Button
…
android:text="@string/button_lighton"
android:onClick="onClickButtonLightOn"/>
<Button
…
android:text="@string/button_lightoff"
android:onClick="onClickButtonLightOff"/>
www.it-ebooks.info
EachonClick()handlerwilltriggeroneofthePacktHALGPIOfunctionstoreadthestateofaGPIOorwriteanewstatetoaGPIO.
NoteIfyouneedarefresheronthefinedetailsofthevariousAndroidUIelements,thereareseveralresourcesavailableonlinethatcanhelpyou.WerecommendthatyoustartwiththeofficialAndroidDeveloperwebsiteathttp://developer.android.com/guide/topics/ui/index.html.
www.it-ebooks.info
CallingthePacktHALfunctionsTheGPIOinterfacefunctionalityinPacktHALisimplementedinfourCfunctions:
openGPIO()
readGPIO()
writeGPIO()
closeGPIO()
Theprototypesforthesefunctionsarelocatedinthejni/PacktHAL.hheaderfilewithintheapp’sproject:
externintopenGPIO(constintuseMmap);
externintreadGPIO(constunsignedintheader,constunsignedintpin);
externintwriteGPIO(constunsignedintheader,
constunsignedintpin,constunsignedintvalue);
externvoidcloseGPIO(void);
Ideally,youwouldloadthePacktHALsharedlibraryintoyourappandthensimplycallthelibraryfunctionsdirectlytocontroltheGPIOs.TheexampleappactuallydoesloadthePacktHALlibraryviaaSystem.loadLibrary()call,butthenthingsbecomelessstraightforwardbecausetheseCfunctionscannotbecalleddirectly.YoumustspecifyJavamethodsthat,whencalled,actuallycalltheCfunctions.
TheMainActivityclassspecifiesfourmethodswiththenativekeywordtocallthePacktHALCfunctionsinMainActivity.java:
publicclassMainActivityextendsActivity{
privatenativebooleanopenGPIO();
privatenativevoidcloseGPIO();
privatenativebooleanreadGPIO(intheader,intpin);
privatenativevoidwriteGPIO(intheader,intpin,intval);
static{
System.loadLibrary("packtHAL");
}
…
}
ThesefourJavamethodsspecifiedinMainActivityarenotactuallyadirectmappingtotheCfunctionsofthesamenameinPacktHAL.NoticethattheGPIOmethodsinMainActivityareallprivatenativewithinthescopeoftheclass.AnymethoddefinedwiththenativekeywordwillattempttocallanativeJNIwrapperfunctionwhenitisinvoked.However,thenamingoftheinvokedJNIwrapperfunctionfollowssomeveryspecificrulesthatrepresentthescopeofitsJava-sidemethod.ThefollowingfigureshowshowtheseJNIwrapperfunctionsfinallycalltheGPIO-interfacingfunctionsinsideofPacktHAL:
www.it-ebooks.info
TheMainActivitymethodsandthePacktHALGPIO-interfacingfunctionsthattheycall
EachnativemethodintheMainActivityclasswiththenamename()willuseJNItocallaJNIwrapperfunctionwiththenameJava_com_packt_gpio_MainActivity_name().Thenameofthiswrapperfunctionisdeterminedbyreplacingeach.inthefullyqualifiednameoftheappwithanunderscore.TheJava_prefixofthefunctionnametellsAndroidthatthefunctionisbeingcalledviaamethodinaJavaclass.ThereareafewexceptionstothisJNInamingconvention,butthisgeneralrulewillgetyouthroughmostcases.
TipDoIneedtoknowallaboutJNItomakemyownAndroidinterfacingprojects?
Notreally.UsingJNIcanbequiteconfusing,andmany,manybooksandtutorialshavebeendedicatedtodescribingitingreatdetail.Fornow,don’tworryaboutnotknowingeverythingthatthereistoknowaboutJNI.WhenyouhavespentsometimeexperimentingwithhardwareinterfacingunderAndroid,youcanrevisitthistopicandlearnmoreofthefinedetailsofhowJNIworks.Inthisbook,wewillfocusonshowingyoujustenoughinformationaboutJNItogetyoustarted.
Asanexample,ourJavaopenGPIO()methodintheMainActivityclassforthecom.packtpub.gpioexampleappusesJNItocallthewrapperCfunctionJava_com_packtpub_gpio_MainActivity_openGPIO().Thisisalittleconfusing,butstillverymanageable.PacktHALimplementstheseJNIwrapperCfunctionsinthejni/packt_native_gpio.cfile.Lookingatthissourcefile,youcanseewheretheJava_com_packtpub_gpio_MainActivity_openGPIO()functioninPacktHALcallstheopenGPIO()CfunctioninPacktHAL:
jbooleanJava_com_packt_gpio_MainActivity_openGPIO(JNIEnv*env,
jobjectthis)
{
jbooleanret=JNI_TRUE;
if(openGPIO(0)==0){
__android_log_print(ANDROID_LOG_DEBUG,PACKT_NATIVE_TAG,
www.it-ebooks.info
"GPIOOpened.");
}else{
__android_log_print(ANDROID_LOG_ERROR,PACKT_NATIVE_TAG,
"openGPIO()failed!");
ret=JNI_FALSE;
}
returnret;
}
WhynotjustdoawaywiththeseparateopenGPIO()CfunctionandplaceallofthehardwareinterfacecodeinsideJava_com_packt_gpio_MainActivity_openGPIO()?FunctionssuchasopenGPIO()inPacktHALwillusuallynotchangeonceyouhavethemworkingproperly,andyoucanusethesesamefunctionsunderbothLinuxandAndroid.WrapperfunctionssuchasJava_com_packt_gpio_MainActivity_openGPIO()willchangetheirnameandimplementationdetailsbaseduponhowandwheretheyareinvokedfromanapp’sJavacode.Itisbettertoisolatefunctionalitythatwillnotchangeinitsownfunction.ThisavoidsyouraccidentallybreakingsomethingwhencustomizingorrenamingthefunctionsinvokedviaJNI.
NoteJustrememberthataJavamethodinyourapp,suchasopenGPIO()intheMainActivityclass,makesaJNIcalltoinvokeaPacktHALCfunctionwithalong,manglednamelikeJava_com_packt_gpio_MainActivity_openGPIO().TheJNIwrapperfunctionwillthencalloneofthePacktHALCfunctions,forexample,openGPIO(),thatactuallycontrolsthehardware.Fromtheappdeveloper’spointofview,onceyousortouttheJNIwrapperfunctiondetails,itisalmostlikecallingtheCfunctionthatcontrolsthehardwaredirectlyfromtheJavaappcode!
www.it-ebooks.info
UsingthePacktHALGPIOfunctionsNowthatyouhaveseenhowthePacktHALGPIOfunctionsarecalledfromJava,youwillseewhateachofthesefunctionsdoesandhowyoucanusethem.
TheopenGPIO()functioninitializesyourapp’saccesstoGPIOs.ThisfunctionoffersyoutwodifferentmethodsforGPIOinterfacing,ofwhichyouselectonemethodusingopenGPIO()function’suseMmapparameter.ThetwomethodsarefileI/O(bysettinguseMmapto0)andmemory-mapping(bysettinguseMmaptoanynon-zeronumber).Tochangefromoneinterfacingmethodtotheother,youmustcallcloseGPIO()toshutdowntheGPIOportionofPacktHALandthencallopenGPIO()againwithadifferentvalueforuseMmap.
Processesmustrunasroottousememory-mappingtodirectlyaccesstheGPIOcontrolresistors.Asappscannotrunasroot,theJNIwrapperfunctionalwayspasses0astheuseMmapargumenttoopenGPIO()toforcetheuseoffileI/OtointeractwithGPIOs.TheopenGPIO()methodintheMainActivityclassdoesnotacceptanyargumentsbecauseofthis.
TheexampleappcallstheopenGPIO()methodfromtheonCreate()methodoftheMainActivityclass:
protectedvoidonCreate(BundlesavedInstanceState){
...//Existingstatements
TextViewtv=(TextView)findViewById(R.id.button_state);
tv.setText("ButtonState:UNKNOWN");
if(openGPIO()==false){
Log.e("com.packt","UnabletoopenGPIO.");
finish();
}
}
ThecomplementarycalltothecloseGPIO()methodismadebytheonDestroy()methodoftheMainActivityclass:
protectedvoidonDestroy(){
closeGPIO();
}
ThereadGPIO()methodreadsthestateofaparticularinputGPIO.BoththePacktHALreadGPIO()functionandthereadGPIO()methodinMainActivitytakethesametwoparameters.ThefirstparameterisaconnectornumberontheBBB(8or9),andthesecondparameterisapinlocationonthatconnector(1through42).ThereadGPIO()methodiscalledfromwithintheonClick()handlerofthePollStatusbutton:
publicvoidonClickPollStatus(Viewview){
Stringstatus=readGPIO(9,13)==true?"ON":"OFF";
TextViewtv=(TextView)findViewById(R.id.button_state);
tv.setText("ButtonState:"+status);
}
www.it-ebooks.info
InonClickPollStatus(),thereadGPIO()methodcallisreadingthestateoftheGPIOpinP9.13.ThisistheGPIOpinthatyouconnectedtothepushbuttonswitch.IftheswitchispressedwhenthereadGPIO()methodiscalled,trueisreturned.Otherwise,falseisreturned.
ThewriteGPIO()methodisusedtosetthestateofanoutputGPIO.BoththePacktHALwriteGPIO()functionandthewriteGPIO()methodinMainActivitytakethreeparameters.ThefirstparameteristheconnectornumberontheBBB(8or9),thesecondparameterisapinlocationonthatconnector(1through42),andthethirdparameteristhevaluetoset(0or1).ThewriteGPIO()methodiscalledfromwithintheonClickhandlersoftheLightOnandLightOffbuttons:
publicvoidonClickButtonLightOn(Viewview){
writeGPIO(9,11,1);
}
publicvoidonClickButtonLightOff(Viewview){
writeGPIO(9,11,0);
}
InbothoftheseonClick()handlers,theGPIObeingsetisP9.11.ThisistheGPIOpinthatyouconnectedtotheLED.TheonClickButtonLightOn()methodsetstheGPIOto1,turningtheLEDon.Likewise,theonClickButtonLightOff()methodsetstheGPIOto0,turningtheLEDoff.
TipAreyoureadyforachallenge?
Nowthatyouhaveseenallofthepiecesofthegpioapp,whynotchangeittoaddnewfunctionality?Forachallenge,trychangingtheapptouseonlyasinglebuttonthattogglesthestateoftheLED.IftheLEDiscurrentlyoff,pressingthebuttonwillturnitonandviceversa.Wehaveprovidedonepossibleimplementationofthisinthechapter3_challenge.tgzfile,whichisavailablefordownloadfromthebook’swebsite.
www.it-ebooks.info
SummaryInthischapter,weintroducedyoutoGPIOsandhowtheywork.YouconstructedacircuitthatusesGPIOsforbothinputandoutput,andthenyoudidsomebasictestingonthecircuittoensurethatthecircuitwasconstructedproperlyandthatthekernelisabletointeractwiththecircuitviathefilesystem.YoualsolearnedabouttheportionsofthePacktHALinit.{ro.hardware}.rcfileandBB-PACKTPUB-00A0.dtboDeviceTreeoverlaythatareresponsibleforconfiguringGPIOsandmakingthemavailableforyourapp’suse.
WeshowedyouhowtoaddPacktHALintoanewlycreatedappprojectandhowtobuildPacktHALusingtheAndroidNDK.Then,youlearnedhowJNIintegratesPacktHALintoyourJavaappviaJNIwrapperfunctionsandexploredhoweachGPIOfunctionofPacktHALiscalledandusedfromwithinanapp.
Inthenextchapter,youwilllearnhowtointegrateI2Cbusdevicesintoyourappsandbegininteractingwithhardwarethatismuchmoresophisticatedthanthebasicon/offlogicofGPIOs.
www.it-ebooks.info
Chapter4.StoringandRetrievingDatawithI2CInthelastchapter,youusedGPIOstoexchangesimpledigitaldatawiththeoutsideworld.However,whataboutinterfacingwithmoreadvanceddevicesthatrequirecomplexsequencesofbitsorbytesforcommunication?
OneofthemostpopularinterfacingbusesinusetodaywithinembeddedsystemsistheInter-IntegratedCircuitserialbus(commonlyabbreviatedasIIC,I2C,orI2C).Inthischapter,youwilllearnhowtowriteanappthatusestheBBB’sI2CinterfacetostoredatatoandretrievedatafromaFRAMchip.Wewillcoverthefollowingtopics:
UnderstandingI2CMultiplexingforI2ContheBBBRepresentingI2CdevicesintheLinuxkernelBuildinganI2CinterfacecircuitExploringtheI2CFRAMexampleapp
www.it-ebooks.info
UnderstandingI2COriginallydevelopedbyPhilipsSemiconductorin1982asabusforcommunicatingwiththeICs,theI2Cprotocolhasbecomeageneral-usebusthatissupportedbyawidevarietyofICmanufacturers.I2Cisamultimasterandmultislavebus,thoughthemostcommonconfigurationisthatofasinglemasterdeviceandoneormoreslavedevicesonasinglebus.AnI2Cmasterdevicesetsthepaceforthebusbygeneratingaclocksignal,anditinitiatescommunicationwiththeslavedevices.Slavedevicesreceivethemaster’sclocksignalandrespondtothemaster’squeries.
OnlyfourwiresarerequiredtocommunicateviaI2C:
Oneclocksignal(SCL)Onedatasignal(SDA)ApositivesupplyvoltageAground
Requiringonlytwopins(fortheSCLandSDAsignals)tocommunicatewithanumberofslavedevicesmakesI2Canenticinginterfacingoption.Oneofthedifficultiesinhardwareinterfacingiseffectivelyallocatingalimitednumberofprocessorpinstobesthandlecommunicatingwithalargenumberofdifferentdevicessimultaneously.Byonlyrequiringtwoprocessorpinstocommunicatewithavarietyofdevices,I2Cfreesuppinsthatcannowbeallocatedtoothertasks.
AnexampleoftheI2Cbuswithasinglemasterdeviceandthreeslavedevices
www.it-ebooks.info
DevicesthatuseI2CDuetotheflexibilityandwideusageoftheI2Cbus,therearemanydevicesthatuseitforcommunication.Differentvarietiesofstoragedevices,suchasEEPROMandFRAMICs,arecommonlyinterfacedviaI2C.Forexample,theEEPROMspresentonBBBcapesareallaccessedbytheBBB’sprocessorviaI2C.Sensorsfortemperature,pressure,andhumidity,accelerometers,LCDcontrollers,andsteppermotorcontrollersareallexamplesofdevicesthatareavailablethroughtheI2Cbus.
www.it-ebooks.info
MultiplexingforI2ContheBBBTheAM335XprocessoroftheBBBprovidesthreeI2Cbuses:
I2C0I2C1I2C2
TheBBBexposestheI2C1andI2C2busesviaitsP9header,buttheI2C0busisnoteasilyaccessible.I2C0currentlyprovidesthecommunicationchannelbetweentheBBB’sprocessorandtheHDMIframerchipofthebuilt-inHDMIcape,soitshouldbeconsideredunavailableforyouruse(unlessyouwouldliketovoidyourwarrantybysolderingwiresdirectlytothetracesandchippinsontheBBB).
TheI2C1busisavailableforyourgeneraluseandisoftenthegotobusforI2Cinterfacing.IfI2C1isatitsmaximumcapacityorunavailable,theI2C2busisalsoavailableforyouruse.
www.it-ebooks.info
ConnectingtoI2CviatheP9headerBydefault,I2C1isnotmuxedtoanypinsandI2C2isavailableviatheP9.19andP9.20pins.I2C2providesI2CcommunicationbetweentheidentificationEEPROMspresentonexternalcapeboardsandthekernel’scapemgr.YoucanmuxI2C2tootherpins,orevendisableitentirely,butifyoudoso,thecapemgrwillnolongerbeabletoautomaticallydetectthepresenceofcapeboardsthatareattachedtotheBBB.Generallyspeaking,youprobablydonotwanttodothis.
ThefollowingfigureshowseachofthepotentialpinsontheP9headerwhereI2Csignalscanbemuxed:
LocationsoftheI2CbusesontheP9headerwithdifferentpinmuxmodes
www.it-ebooks.info
MultiplexingforI2CWhendecidinghowyouwouldlikeyourpinstobemuxedwhenusingI2Cinyourprojects,keepthefollowingitemsinmind:
AvoidmuxinganysingleI2Csignaltomorethanonepin.Doingsowastesoneofyourpinsfornogoodreason.AvoidmuxingI2C2awayfromitsdefaultlocation,asthispreventsthecapemgrfromautomaticallydetectingcapeboardsconnectedtotheBBB.YoucanusethedefaultI2C2busforyourownprojects,butnotethatitisclockedat100KHzandtheaddresses0x54through0x57arereservedforcapeEEPROMs.MuxingtheI2C1channeltoP9.17andP9.18conflictswiththeSPI0channel,soyougenerallywouldn’twanttousethisconfigurationifyoualsowishtouseSPI.
www.it-ebooks.info
RepresentingI2CdevicesintheLinuxkernelI2Cbusesanddevicesareexposedinuserspaceasfilesinthe/devfilesystem.I2Cbusesareexposedasthe/dev/i2c-Xfile,whereXisthelogicalnumberoftheI2Cchannel.WhilethehardwaresignalsfortheI2Cbusareclearlynumberedas0,1,and2,thelogicalchannelnumberswon’tnecessarilybethesameastheirhardwarecounterparts.
LogicalchannelnumbersareassignedintheorderthattheI2CchannelsareinitializedintheDeviceTree.Forexample,theI2C2channelisusuallythesecondI2Cchannelinitializedbythekernel.Therefore,eventhoughitisphysicalI2Cchannel2,itwillbelogicalI2Cchannel1andaccessibleasthe/dev/i2c-1file.
UnderneathallofthelayersofAndroidAPIsandservices,Androidultimatelyinteractswithdevicedriversinthekernelbyopeningfilesinthe/devand/sysfilesystemsandthenreading,writing,orperformingioctl()callsonthosefiles.WhileitispossibletointeractwithanyI2Cdeviceusingonlytheioctl()callsonthe/dev/i2c-XfilestodirectlycontroltheI2Cbus,thisapproachiscomplicatedandgenerallyshouldbeavoided.Instead,youshouldtrytouseakerneldriverthatcommunicateswithyourdeviceontheI2Cbusforyou.Youcanthenmakeioctl()callsonthefileexposedbythatkerneldrivertoeasilycontrolyourdevice.
www.it-ebooks.info
PreparingAndroidforFRAMuseInChapter2,InterfacingwithAndroid,youusedadbtopushtwoprebuiltfilestoyourAndroidsystem.Thesetwofiles,BB-PACKTPUB-00A0.dtboandinit.{ro.hardware}.rc,configureyourAndroidsystemtoenableakerneldevicedriverthathandlesFRAMinterfacing,muxthepinstoenabletheI2C1bus,andallowyourappstoaccessit.
AsfarasI2Cisconcerned,theBB-PACKTPUB-00A0.dtbooverlaymuxestheP9.24andP9.26pinsintotheI2CSCLandSDAsignals.InthePacktHAL.tgzfile,thesourcecodefortheoverlayislocatedinthecape/BB-PACKTPUB-00A0.dtsfile.Thecoderesponsibleformuxingthesetwopinsislocatedinthebb_i2c1a1_pinsnodewithinfragment@0:
/*AllI2C1pinsareSLEWCTRL_SLOW,INPUT_PULLUP,MODE3*/
bb_i2c1a1_pins:pinmux_bb_i2c1a1_pins{
pinctrl-single,pins=<
0x1800x73/*P9.26,i2c1_sda*/
0x1840x73/*P9.24,i2c1_scl*/
>;
};
Whilethissetsupthemuxing,itdoesn’tassignandconfigureadevicedrivertothesepins.Thefragment@1nodeperformsthiskerneldriverallocation:
fragment@1{
target=<&i2c1>;
__overlay__{
status="okay";
pinctrl-names="default";
pinctrl-0=<&bb_i2c1a1_pins>;
clock-frequency=<400000>;
#address-cells=<1>;
#size-cells=<0>;
/*ThisiswherewespecifyeachI2Cdeviceonthisbus*/
adafruit_fram:adafruit_fram0@50{
/*Kerneldriverforthisdevice*/
compatible="at,24c256";
/*I2Cbusaddress*/
reg=<0x50>;
};
};
};
Withoutgoingintotoomuchdetail,therearefoursettingsinfragment@1thatareofinteresttoyou:
Thefirstsettingispinctrl-0,whichtiesthisnodeoftheDeviceTreetothepinsmuxedinthebb_i2c1a1_pinsnodeThesecondsettingisclock-frequency,whichsetstheI2Cbusspeedto400KHzThethirdsettingiscompatible,whichspecifiestheparticularkerneldriver(the24c256driverforEEPROM-likedevices)thatwillhandleourhardwaredeviceThelastsettingisreg,whichspecifiestheaddressontheI2Cbuswherethisdevice
www.it-ebooks.info
BuildinganI2C-interfacingcircuitNowthatyouhaveanunderstandingofwhereI2CdevicesareconnectedtotheBBBandhowtheLinuxkernelpresentsaninterfacetothosedevices,itistimetoconnectanI2CdevicetotheBBB.
AswementionedinChapter1,IntroductiontoAndroidandtheBeagleBoneBlack,youwillbeinterfacingwithaFRAMchipinthischapter.Specifically,itisaFujitsuSemiconductorMB85RC256VFRAMchip.This8-pinchipprovides32KBofnonvolatilestorage.Thisparticularchipisonlyavailableinasmalloutlinepackage(SOP),whichisasurfacemountchipthatcanbedifficulttoworkwithwhenbuildingprototypecircuits.Luckilyforus,theAdaFruitbreakoutboardfortheFRAMalreadyhasthechipmounted,whichmakesprototypingsimpleandeasy.
TipDon’tdisassembleyourcircuit!
TheFRAMcircuitinthischapterispartofamuchlargercircuitusedinChapter6,CreatingaCompleteInterfacingSolution.Ifyoubuildthecircuitaspositionedinthediagram(towardsthebottomofthebreadboard),youcansimplyleavetheFRAMbreakoutboardandwiresinplaceasyoubuildtheremainingcircuitsinthisbook.Thisway,itwillalreadybeconstructedandworkingwhenyoureachChapter6.
www.it-ebooks.info
ConnectingtheFRAMEachI2CdevicemustuseanaddresstoidentifyitselfontheI2Cbus.TheFRAMchipthatweareusingcanbeconfiguredtouseanaddressintherangeof0x50to0x57.ThisisacommonaddressrangeforEEPROMdevices.Theexactaddressissetbyusingtheaddresslines(A0,A1,A2)ofthebreakoutboard.TheFRAMhasabaseaddressof0x50.IftheA0,A1,and/orA2linesareconnectedtoa3.3Vsignal,0x1,0x2,and/or0x4areaddedtotheaddress,respectively.Forthisinterfacingproject,noneoftheaddressinglinesareconnected,whichresultsintheFRAMretainingitsbaseaddressof0x50ontheI2Cbus.
TheFRAMbreakoutboard(theA0,A1,andA2addressinglinesarethethreeright-mostterminalsoftheboard)
NoteTheaddressesofmanyI2Cdevicesareconfigurablebyconnectingtheaddresspinsofthedevicetoeitherthegroundorvoltagesignals.ThisisbecausetherecanbemultiplecopiesofthesamedeviceonasingleI2Cbus.Thecircuitdesignercanassignadifferentaddresstoeachdevicebyrewiringtheaddresspins,ratherthanhavingtobuydifferentpartswithdifferentpre-assignedaddressesthatdonotconflictwitheachother.
ThefollowingfigureshowstheconnectionsbetweentheFRAMbreakoutboardandtheBBB.ThefourmainI2Cbussignals(+3.3V,ground,andI2CSCL/SDA)aremadeusingthepinsoftheP9connector,sowe’veplacedthebreadboardontheP9sideoftheBBB.
www.it-ebooks.info
ThecompleteI2C-interfacingcircuit
Let’sgetstarted:
1. ConnectP9.1(ground)totheverticalgroundbusofthebreadboardandconnectP9.3(3.3V)totheverticalVCCbusofthebreadboard.TheseconnectionsareidenticaltotheonesmadefortheGPIObreadboardcircuitthatyoucreatedinChapter3,HandlingInputsandOutputswithGPIOs.
2. TheI2Csignals,SCLandSDA,areontheP9.24andP9.26pins,respectively.WiretheP9.24pintothepinmarkedSCLonthebreakoutboard,andwiretheP9.26pintothepinmarkedSDAonthebreakoutboard.
3. WirethegroundbustotheGNDpinofthebreakoutboardandwiretheVCCbustotheVCCpinofthebreakoutboard.Leavethewriteprotect(WP)pinandthethreeaddresspins(A0,A1,A2)unconnected.
TheFRAMbreakoutboardisnowelectricallyconnectedtotheBBBandisreadyforyouruse.Double-checkyourwiringagainstthediagramofthecompleteFRAMinterfacingcircuittoensurethateverythingisconnectedproperly.
www.it-ebooks.info
CheckingtheFRAMconnectionwithI2CtoolsTheI2CtoolsareasetofutilitiesthatallowyoutoprobeandinteractwiththeI2Cbus.ThesetoolsworkonsystemsthatuseaLinuxkernel,andtheyareincludedintheBBBAndroidimage.TheutilitiesinteractwiththeI2Cbusbyopeningthe/dev/i2c-Xdevicefilesandmakingioctl()callsonthem.Bydefault,youmusthaverootaccesstousei2c-tools,butBBBAndroidreducesthepermissionsonthe/dev/i2c-Xfilessothatanyprocess(includingi2c-tools)canreadandwriteinformationabouttheI2Cbuses.
Asanexample,let’stryusingthei2cdetectutilityini2c-tools.i2cdetectwillsweepaspecifiedI2CbusandidentifybusaddresseswhereI2Cdevicesarelocated.UsingtheADBshell,youwillprobethei2c-2physicalbus,whichisalsothesecondlogicalbus(/dev/i2c-1):
root@beagleboneblack:/#i2cdetect-y-r1
0123456789abcdef
00:—--—--—--—--—--—----
10:—--—--—--—--—--—--—--—--
20:—--—--—--—--—--—--—--—--
30:—--—--—--—--—--—--—--—--
40:—--—--—--—--—--—--—--—--
50:—--—--UUUUUUUU—--—--—--—--
60:—--—--—--—--—--—--—--—--
70:—--—--—--—--
NoteTheoutputofi2cdetectshowseverydevicedetectedonthecurrentbus.Anyaddressthatisnotinusehasa--identifier.AnyaddressthatisreservedforadevicedriverintheDeviceTree,butdoesnotcurrentlyhaveadevicelocatedatthataddress,hasaUUidentifier.Ifadeviceisdetectedataparticularaddress,thedevice’stwo-digithexadecimaladdresswillappearasanidentifierinthei2cdetectoutput.
Theoutputofi2cdetectshowsthattheDeviceTreehasallocateddriversforfourI2Cdevicesonthei2c-2physicalbus.ThesefourdevicesaretheEEPROMsataddresses0x54-0x57ofthecapemgr.Thedevicesaren’tactuallypresentbecausenocapeboardsareconnectedtotheBBB,soeachaddresshasaUUidentifier.
AftertheFRAMbreakoutboardiselectricallyconnectedtotheBBB,youmustverifythattheFRAMisavisibledeviceontheI2Cbus.Todothis,usei2cdetecttoexaminethedevicespresentonthei2c-1physicalbus(logicalbus2):
root@beagleboneblack:/#i2cdetect-y-r2
0123456789abcdef
00:—--—--—--—--—--—----
10:—--—--—--—--—--—--—--—--
20:—--—--—--—--—--—--—--—--
30:—--—--—--—--—--—--—--—--
40:—--—--—--—--—--—--—--—--
50:50—--—--—--—--—--—--—----
60:—--—--—--—--—--—--—--—--
www.it-ebooks.info
70:—--—--—--—--
TipDouble-checkyourwiring
Ifthei2cdetectoutputshowsaUUatthe0x50addresslocation,youknowthattheI2CbusdoesnotrecognizetheFRAMasbeingattached.Makesurethatyoudon’taccidentallyswaptheSCL(P9.24)andSDA(P9.26)wireswhenconnectingtheFRAMbreakoutboardtotheBBB.
www.it-ebooks.info
ExploringtheI2CFRAMexampleappInthissection,wewillexamineourexampleAndroidappthatinterfaceswiththeFRAMusingI2ConBBB.ThepurposeofthisapplicationistodemonstratehowtousePacktHALtoperformFRAMreadsandwritesfromwithinanactualapp.PacktHALprovidesasetofinterfacingfunctionsthatyouwillusetoworkwiththeFRAMfromwithinyourAndroidapps.ThesefunctionsallowyoutoretrieveblocksofdatafromtheFRAMandwritenewdatatobestoredontheFRAM.Thelow-leveldetailsofthehardwareinterfacingareimplementedinPacktHAL,soyoucanquicklyandeasilygetyourappsinteractingwiththeFRAMbreakoutboard.
BeforediggingthroughtheFRAMapp’scode,youmustinstallthecodetoyourdevelopmentsystemandinstalltheapptoyourAndroidsystem.Thesourcecodefortheappaswellastheprecompiled.apkpackage,arelocatedinthechapter4.tgzfile,whichisavailablefordownloadfromthePacktwebsite.FollowthesameprocesstodownloadandaddtheapptoyourEclipseADTenvironmentthatwasdescribedinChapter3,HandlingInputsandOutputswithGPIOs.
www.it-ebooks.info
Theapp’suserinterfaceLaunchtheframappontheAndroidsystemtoseetheapp’sUI.Ifyouareusingatouchscreencape,youcansimplytouchtheframappicononthescreentolaunchtheappandinteractwithitsUI.IfyouareusingtheHDMIforvideo,connectaUSBmousetotheBBB’sUSBportandusethemousetoclickontheframappicontolaunchtheapp.Asthisappacceptstextinputfromtheuser,youmightfinditconvenienttoconnectaUSBkeyboardtotheBBB.Otherwise,you’llbeabletousetheonscreenAndroidkeyboardtoinputtext.
Thisapp’sUIisabitmorecomplexthanthatoftheGPIOappinthelastchapter,butitisstillfairlysimple.Asitissosimple,theonlyactivitythattheapphasisthedefaultMainActivity.TheUIconsistsoftwotextfields,twobuttons,andtwotextviews.
TheFRAMsampleappscreen
ThetoptextfieldhasthesaveEditTextidentifierintheactivity_main.xmlfile.ThesaveEditTextfieldacceptsupto60charactersthatwillbestoredtotheFRAM.ThetopbuttonwiththeSavelabelhasthesaveButtonidentifier.ThisbuttonhasanonClick()methodcalledonClickSaveButton()thattriggerstheprocessofinterfacingwiththeFRAMtostorethetextcontainedwithinthesaveEditTexttextfield.
ThebottomtextfieldhastheloadEditTextidentifier.ThistextfieldwilldisplayanydatathatisheldintheFRAM.ThebottombuttonwiththeLoadlabelhastheloadButtonidentifier.ThisbuttonhasanonClick()methodcalledonClickLoadButton()thattriggerstheprocessofinterfacingwiththeFRAMtoloadthefirst60bytesofdataandthenupdatingthetextdisplayedintheloadEditTexttextfield.
www.it-ebooks.info
CallingthePacktHALFRAMfunctionsTheFRAMinterfacefunctionalityinPacktHALisimplementedinfourCfunctions:
openFRAM()
readFRAM()
writeFRAM()
closeFRAM()
Theprototypesforthesefunctionsarelocatedinthejni/PacktHAL.hheaderfilewithintheapp’sproject:
externintopenFRAM(constunsignedintbus,constunsignedintaddress);
externintreadFRAM(constunsignedintoffset,constunsignedint
bufferSize,constchar*buffer);
externintwriteFRAM(constunsignedintoffset,constunsignedint
constchar*buffer);
externvoidcloseFRAM(void);
TheopenFRAM()functionopensthefileinthe/devfilesystemthatprovidestheinterfacetothe24c256EEPROMkerneldriver.ItscounterpartfunctioniscloseFRAM(),whichclosesthisfileoncehardwareinterfacingwiththeFRAMisnolongerneeded.ThereadFRAM()functionreadsabufferofdatafromtheFRAM,andthewriteFRAM()functionwritesabufferofdatatotheFRAMforpersistentstorage.Together,thesefourfunctionsprovideallofthenecessaryfunctionalitythatyouneedtointeractwiththeFRAM.
Justlikethegpioappfromthepreviouschapter,theframapploadsthePacktHALsharedlibraryviaaSystem.loadLibrary()calltoaccessthePacktHALFRAMinterfacefunctionsandtheJNIwrapperfunctionsthatcallthem.However,unlikethegpioapp,theMainActivityclassoftheframappdoesnotspecifymethodswiththenativekeywordtocallthePacktHALJNI-wrapperCfunctions.Instead,itleavesthehardwareinterfacingtoanasynchronoustaskclassnamedHardwareTask:
PublicclassMainActivityextendsActivity{
PublicstaticHardwareTaskhwTask;
Static{
System.loadLibrary("packtHAL");
}
www.it-ebooks.info
UnderstandingtheAsyncTaskclassHardwareTaskextendstheAsyncTaskclass,andusingitprovidesamajoradvantageoverthewayhardwareinterfacingisimplementedinthegpioapp.AsyncTasksallowsyoutoperformcomplexandtime-consuminghardware-interfacingtaskswithoutyourappbecomingunresponsivewhilethetasksareexecuted.EachinstanceofanAsyncTaskclasscancreateanewthreadofexecutionwithinAndroid.ThisissimilartohowmultithreadedprogramsfoundonotherOSesspinnewthreadstohandlefileandnetworkI/O,manageUIs,andperformparallelprocessing.
Inthepreviouschapter,thegpioapponlyusedasinglethreadduringitsexecution.ThisthreadisthemainUIthreadthatispartofallAndroidapps.TheUIthreadisdesignedtohandleUIeventsasquicklyaspossible.WhenyouinteractwithaUIelement,thatelement’shandlermethodiscalledbytheUIthread.Forexample,clickingabuttoncausestheUIthreadtoinvokethebutton’sonClick()handler.TheonClick()handlerthenexecutesapieceofcodeandreturnstotheUIthread.
AndroidisconstantlymonitoringtheexecutionoftheUIthread.Ifahandlertakestoolongtofinishitsexecution,AndroidshowsanApplicationNotResponding(ANR)dialogtotheuser.YouneverwantanANRdialogtoappeartotheuser.Itisasignthatyourappisrunninginefficiently(orevennotatall!)byspendingtoomuchtimeinhandlerswithintheUIthread.
TheApplicationNotRespondingdialoginAndroid
ThegpioappinthelastchapterperformedreadsandwritesoftheGPIOstatesveryquicklyfromwithintheUIthread,sotheriskoftriggeringtheANRwasverysmall.InterfacingwiththeFRAMisamuchslowerprocess.WiththeBBB’sI2Cbusclockedatitsmaximumspeedof400KHz,ittakesapproximately25microsecondstoreadorwriteabyteofdatawhenusingtheFRAM.Whilethisisnotamajorconcernforsmallwrites,readingorwritingtheentire32,768bytesoftheFRAMcantakeclosetoafullsecondtoexecute!
MultiplereadsandwritesofthefullFRAMcaneasilytriggertheANRdialog,soitisnecessarytomovethesetime-consumingactivitiesoutoftheUIthread.ByplacingyourhardwareinterfacingintoitsownAsyncTaskclass,youdecoupletheexecutionofthesetime-intensivetasksfromtheexecutionoftheUIthread.ThispreventsyourhardwareinterfacingfrompotentiallytriggeringtheANRdialog.
www.it-ebooks.info
LearningthedetailsoftheHardwareTaskclassTheAsyncTaskbaseclassofHardwareTaskprovidesmanydifferentmethods,whichyoucanfurtherexplorebyreferringtotheAndroidAPIdocumentation.ThefourAsyncTaskmethodsthatareofimmediateinterestforourhardware-interfacingeffortsare:
onPreExecute()
doInBackground()
onPostExecute()
execute()
Ofthesefourmethods,onlythedoInBackground()methodexecuteswithinitsownthread.TheotherthreemethodsallexecutewithinthecontextoftheUIthread.OnlythemethodsthatexecutewithintheUIthreadcontextareabletoupdatescreenUIelements.
ThethreadcontextsinwhichtheHardwareTaskmethodsandthePacktHALfunctionsareexecuted
MuchliketheMainActivityclassofthegpioappinthelastchapter,theHardwareTaskclassprovidesfournativemethodsthatareusedtocallPacktHALJNIfunctionsrelatedtoFRAMhardwareinterfacing:
publicclassHardwareTaskextendsAsyncTask<Void,Void,Boolean>{
privatenativebooleanopenFRAM(intbus,intaddress);
privatenativeStringreadFRAM(intoffset,intbufferSize);
privatenativevoidwriteFRAM(intoffset,intbufferSize,
Stringbuffer);
privatenativebooleancloseFRAM();
TheopenFRAM()methodinitializesyourapp’saccesstoaFRAMlocatedonalogicalI2Cbus(thebusparameter)andataparticularbusaddress(theaddressparameter).Oncethe
www.it-ebooks.info
connectiontoaparticularFRAMisinitializedviaanopenFRAM()call,allreadFRAM()andwriteFRAM()callswillbeappliedtothatFRAMuntilacloseFRAM()callismade.
ThereadFRAM()methodwillretrieveaseriesofbytesfromtheFRAMandreturnitasaJavaString.AtotalofbufferSizebytesareretrievedstartingatanoffsetofoffsetbytesfromthestartoftheFRAM.ThewriteFRAM()methodwillstoreaseriesofbytestotheFRAM.AtotalofbufferSizecharactersfromtheJavastringbufferarestoredintheFRAMstartedatanoffsetofoffsetbytesfromthestartoftheFRAM.
Intheframapp,theonClick()handlersfortheLoadandSavebuttonsintheMainActivityclasseachinstantiateanewHardwareTask.ImmediatelyaftertheinstantiationofHardwareTask,eithertheloadFromFRAM()orsaveToFRAM()methodiscalledtobegininteractingwiththeFRAM:
publicvoidonClickSaveButton(Viewview){
hwTask=newHardwareTask();
hwTask.saveToFRAM(this);
}
publicvoidonClickLoadButton(Viewview){
hwTask=newHardwareTask();
hwTask.loadFromFRAM(this);
}
BoththeloadFromFRAM()andsaveToFRAM()methodsintheHardwareTaskclasscallthebaseAsyncTaskclassexecution()methodtobeginthenewthreadcreationprocess:
publicvoidsaveToFRAM(Activityact){
mCallerActivity=act;
isSave=true;
execute();
}
publicvoidloadFromFRAM(Activityact){
mCallerActivity=act;
isSave=false;
execute();
}
NoteEachAsyncTaskinstancecanonlyhaveitsexecute()methodcalledonce.IfyouneedtorunanAsyncTaskasecondtime,youmustinstantiateanewinstanceofitandcalltheexecute()methodofthenewinstance.ThisiswhyweinstantiateanewinstanceofHardwareTaskintheonClick()handlersoftheLoadandSavebuttons,ratherthaninstantiatingasingleHardwareTaskinstanceandthencallingitsexecute()methodmanytimes.
Theexecute()methodautomaticallycallstheonPreExecute()methodoftheHardwareTaskclass.TheonPreExecute()methodperformsanyinitializationthatmustoccurpriortothestartofthenewthread.Intheframapp,thisrequiresdisablingvariousUIelementsandcallingopenFRAM()toinitializetheconnectiontotheFRAMvia
www.it-ebooks.info
PacktHAL:
protectedvoidonPreExecute(){
//Somesetupgoeshere
...
if(!openFRAM(2,0x50)){
Log.e("HardwareTask","Erroropeninghardware");
isDone=true;
}
//DisabletheButtonsandTextFieldswhiletalkingtothehardware
saveText.setEnabled(false);
saveButton.setEnabled(false);
loadButton.setEnabled(false);
}
TipDisablingyourUIelements
Whenyouareperformingabackgroundoperation,youmightwishtokeepyourapp’suserfromprovidingmoreinputuntiltheoperationiscomplete.DuringaFRAMreadorwrite,wedonotwanttheusertopressanyUIbuttonsorchangethedataheldwithinthesaveTexttextfield.IfyourUIelementsremainenabledallthetime,theusercanlaunchmultipleAsyncTaskinstancessimultaneouslybyrepeatedlyhittingtheUIbuttons.Topreventthis,disableanyUIelementsrequiredtorestrictuserinputuntilthatinputisnecessary.
OncetheonPreExecute()methodfinishes,theAsyncTaskbaseclassspinsanewthreadandexecutesthedoInBackground()methodwithinthatthread.ThelifetimeofthenewthreadisonlyforthedurationofthedoInBackground()method.OncedoInBackground()returns,thenewthreadwillterminate.
AseverythingthattakesplacewithinthedoInBackground()methodisperformedinabackgroundthread,itistheperfectplacetoperformanytime-consumingactivitiesthatwouldtriggeranANRdialogiftheywereexecutedfromwithintheUIthread.ThismeansthattheslowreadFRAM()andwriteFRAM()callsthataccesstheI2CbusandcommunicatewiththeFRAMshouldbemadefromwithindoInBackground():
protectedBooleandoInBackground(Void…params){
...
Log.i("HardwareTask","doInBackground:Interfacingwithhardware");
try{
if(isSave){
writeFRAM(0,saveData.length(),saveData);
}else{
loadData=readFRAM(0,61);
}
}catch(Exceptione){
...
NoteTheloadDataandsaveDatastringvariablesusedinthereadFRAM()andwriteFRAM()
www.it-ebooks.info
callsarebothclassvariablesofHardwareTask.ThesaveDatavariableispopulatedwiththecontentsofthesaveEditTexttextfieldviaasaveEditText.toString()callintheHardwareTaskclass’onPreExecute()method.
TipHowdoIupdatetheUIfromwithinanAsyncTaskthread?
Whiletheframappdoesnotmakeuseoftheminthisexample,theAsyncTaskclassprovidestwospecialmethods,publishProgress()andonPublishProgress(),thatareworthmentioning.TheAsyncTaskthreadusesthesemethodstocommunicatewiththeUIthreadwhiletheAsyncTaskthreadisrunning.ThepublishProgress()methodexecuteswithintheAsyncTaskthreadandtriggerstheexecutionofonPublishProgress()withintheUIthread.Thesemethodsarecommonlyusedtoupdateprogressmeters(hencethenamepublishProgress)orotherUIelementsthatcannotbedirectlyupdatedfromwithintheAsyncTaskthread.YouwillusethepublishProgress()andonPublishProgress()methodsinChapter6,CreatingaCompleteInterfacingSolution.
AfterdoInBackground()hascompleted,theAsyncTaskthreadterminates.ThistriggersthecallingofdoPostExecute()fromtheUIthread.ThedoPostExecute()methodisusedforanypost-threadcleanupandupdatinganyUIelementsthatneedtobemodified.TheframappusesthecloseFRAM()PacktHALfunctiontoclosethecurrentFRAMcontextthatitopenedwithopenFRAM()intheonPreExecute()method.
protectedvoidonPostExecute(Booleanresult){
if(!closeFRAM()){
Log.e("HardwareTask","Errorclosinghardware");
}
...
Theusermustnowbenotifiedthatthetaskhasbeencompleted.IftheLoadbuttonwaspressed,thenthestringdisplayedintheloadTextFieldwidgetisupdatedviatheMainActivityclassupdateLoadedData()method.IftheSavebuttonwaspressed,aToastmessageisdisplayedtonotifytheuserthatthesavewassuccessful.
Log.i("HardwareTask","onPostExecute:Completed.");
if(isSave){
Toasttoast=Toast.makeText(mCallerActivity.getApplicationContext(),
"DatastoredtoFRAM",Toast.LENGTH_SHORT);
toast.show();
}else{
((MainActivity)mCallerActivity).updateLoadedData(loadData);
}
TipGivingToastfeedbacktotheuser
TheToastclassisagreatwaytoprovidequickfeedbacktoyourapp’suser.Itpopsupasmallmessagethatdisappearsafteraconfigurableperiodoftime.Ifyouperformahardware-relatedtaskinthebackgroundandyouwanttonotifytheuserofitscompletion
www.it-ebooks.info
withoutchanginganyUIelements,tryusingaToastmessage!ToastmessagescanonlybetriggeredbymethodsthatareexecutingfromwithintheUIthread.
AnexampleoftheToastmessage
Finally,theonPostExecute()methodwillre-enablealloftheUIelementsthatweredisabledinonPreExecute():
saveText.setEnabled(true);
saveButton.setEnabled(true);
loadButton.setEnabled(true);
TheonPostExecute()methodhasnowfinisheditsexecutionandtheappisbacktopatientlywaitingfortheusertomakethenextframaccessrequestbypressingeithertheLoadorSavebutton.
TipAreyoureadyforachallenge?
Nowthatyouhaveseenallofthepiecesoftheframapp,whynotchangeittoaddnewfunctionality?Forachallenge,tryaddingacounterthatindicatestotheuserhowmanymorecharacterscanbeenteredintothesaveTexttextfieldbeforethe60-characterlimitisreached.Wehaveprovidedonepossibleimplementationofthisinthechapter4_challenge.tgzfile,whichisavailablefordownloadfromthePackt’swebsite.
www.it-ebooks.info
SummaryInthischapter,weintroducedyoutotheI2Cbus.YouconstructedacircuitthatconnectedanI2CFRAMbreakoutboardtotheBBB,andthenyoudidsomebasictestingonthecircuitusingi2cdetectfromi2c-toolstoensurethatthecircuitwasconstructedproperlyandthekernelisabletointeractwiththecircuitviathefilesystem.YoualsolearnedabouttheportionsofthePacktHALinit.{ro.hardware}.rcfileandDeviceTreeoverlaythatareresponsibleforconfiguringandmakingtheI2CbusandI2Cdevicedriversavailableforyourapp’suse.TheframappinthischapterdemonstratedhowtousetheAsyncTaskclasstoperformtime-intensivehardwareinterfacingtaskswithoutstallingtheapp’sUIthreadandtriggeringtheANRdialog.
Inthenextchapter,youwilllearnaboutthehigh-speedserialperipheralinterface(SPI)busanduseittointerfacewithanenvironmentalsensor.
www.it-ebooks.info
Chapter5.InterfacingwithHigh-speedSensorsUsingSPIInthepreviouschapter,youworkedwiththeI2CbustocommunicatewithanFRAMdevicethatrequiresfarmorecomplexcommunicationsthanthatofthesimpleon/offdigitalcommunicationsusedbyGPIOs.I2Cisverypowerfulandflexible,butitcanbequiteslow.
Inthischapter,youwilllearnhowtowriteanAndroidappthatusestheBBB’sSPIcapabilitiestoretrieveenvironmentaldatafromahigh-speedsensor.Wewillcoverthefollowingtopics:
UnderstandingSPIMultiplexingforSPIontheBBBRepresentingSPIdevicesintheLinuxkernelBuildinganSPIinterfacecircuitExploringtheSPIsensorexampleapp
www.it-ebooks.info
UnderstandingSPITheSerialPeripheralInterface(SPI)busisahigh-speed,serialbusoriginallydevelopedbyMotorola.Itspurposeistofacilitatepoint-to-pointcommunicationbetweenasinglemasterdeviceandoneormoreslavedevice.TheSPIbusistypicallyimplementedusingfoursignals:
SCLK
MOSI
MISO
SS/CS
LikeI2C,themasterontheSPIbussetsthepaceofcommunicationbetweenthemasterandtheslavebyproducingaclocksignal.WithSPI,thisclocksignaliscalledtheserialclock(SCLK).UnlikethebidirectionaldatabusofI2C,SPIusesdedicatedoutgoingandincomingdatalinesforeachdevice.UsingdedicatedlinesresultsinSPIbeingabletoachievecommunicationspeedsfarhigherthanthoseofI2C.Themastersendsdatatotheslaveviathemasterout,slavein(MOSI)signal,anditreceivesdatafromtheslaveviathemasterin,slaveout(MISO)signal.Theslaveselect(SS)signal,alsocalledchipselect(CS),tellstheslavedevicewhetheritshouldbeawakeandpayingattentionforanyclocksignalsonSCLKanddatabeingsenttoitviaMOSI.Therearevariantsonthisfour-wireSPIbusscheme,suchasathree-wireschemethatomitstheSS/CSsignal,buttheBBBusesafour-wireschemeforitsSPIbuses.
TheSPImasterandslavedevicesonanSPIbus
TheBBBcanactaseitheranSPImasterorslave,soitdoesnotlabelitsdatainputandoutputsignalsforSPIasMISOorMOSI.Instead,itusesthenamesD0andD1forthesesignals.IftheBBBactsasthemasterontheSPIbus,D0istheMISOsignalandD1istheMOSIsignal.IftheBBBactsastheslaveontheSPIbus,thesearereversed(D1isMISO,D0isMOSI).Forthisbook,theBBBwillalwaysbeactingastheSPImaster.
TipHowdoIrememberwhichBBBSPIsignalisinputandwhichisoutput?
ItcanbeconfusingtorememberwhichsignalisMISOandwhichisMOSIwhentheBBBusesthesignalnamesD0andD1.Onewaytorememberistothinkofthe0inD0asanO
www.it-ebooks.info
(forslaveoutput)andthe1inD1asanI(forslaveinput).IftheBBBistheSPImaster(whichwillalmostalwaysbethecase),thenD1istheslaveinputsignal(MOSI)andD0istheslaveoutputsignal(MISO).
ThemaximumSCLKspeedforSPIontheBBBis48MHz,butspeedsrangingfrom1MHzto16MHzarecommonlyused.Evenatthesereducedclockspeeds,SPIisfarsuperiortothe400KHzclockspeedofI2Cbuseswhenconsideringtheamountofrawdatathatcanbetransmittedeachsecond.OnlyonedevicecantransmitdataonanI2Cbusatanytime,butboththemasterandslavecantransmitdatasimultaneouslyonanSPIbusbecauseeachdevicehasadedicatedtransmissionsignal.
www.it-ebooks.info
MultiplexingforSPIontheBBBTheAM335XprocessoroftheBBBprovidestwoSPIbuses:SPI0andSPI1.BothbusesareaccessibleviatheP9header.Bydefault,noSPIbusesaremuxed.ThefollowingfigureshowseachofthepotentialpinsontheP9headerwhereSPIsignalscanbemuxedindifferentpinmuxmodes:
LocationsoftheSPIbusesontheP9headerwithdifferentpinmuxmodes
WhendecidinghowyouwouldlikeyourpinstobemuxedusingSPIinyourprojects,keepthefollowinginmind:
Whenindoubt,stickwithusingtheSPI0busmuxedtotheP9.17,P9.18,P9.21,andP9.22pins.TheSPI1channelconflictswiththeI2Cbususedbythecapemgr(P9.20)andaudiooutput(P9.28,P9.29,P9.31).BeawarethatmuxingthesepinstouseSPI1candisablesomeotherfunctionalitythatyouaredependinguponforafull-featuredAndroidsystem.
www.it-ebooks.info
Ifyouareusingothercapeboardsinyourprojects,makesurethatthesecapesdon’trequiretheuseoftheSPIbuses.OnlyonedevicecanexistoneachSPIbusunlessyouuseaGPIOpinandextralogiccircuitrytomanuallycontroleachSPIdevice’schipselectsignal.
www.it-ebooks.info
RepresentingSPIdevicesintheLinuxkernelTheLinuxkernelprovidesageneral-purposeSPIdrivernamedspidev.ThespidevdriverisasimpleinterfacethatabstractsmanyofthehousekeepingdetailsinvolvedinSPIcommunications.Thespidevdriverisexposedviathe/devfilesystemasthe/dev/spidevX.Yfile.MultipleversionsofthesespidevfilescanbepresentdependinguponthenumberofSPIbusesconfiguredintheDeviceTree.TheXvalueinthespidevfilenamereferstotheSPIcontrollernumber(1forSPI0and2forSPI1),andtheYvaluereferstotheSPIbusofthatcontroller(0forthefirstbusand1forthesecondbus).Fortheexamplesinthisbook,youwillonlybeusingthefirstSPIbusoftheSPI0controller,so/dev/spidev1.0istheonlyfilewithwhichPacktHALwillinteract.
www.it-ebooks.info
PreparingAndroidforSPIsensoruseInChapter2,InterfacingwithAndroid,youusedadbtopushtwoprebuiltfilestoyourAndroidsystem.Thesetwofiles,BB-PACKTPUB-00A0.dtboandinit.{ro.hardware}.rc,configureyourAndroidsystemtoenablethespidevkerneldevicedriverthathandlesSPIbusinterfacing,muxesthepinstoenabletheSPI0bus,andallowyourappstoaccessthem.
AsfarasSPIisconcerned,theBB-PACKTPUB-00A0.dtbooverlaymuxestheP9.17,P9.18,P9.21,andP9.22pinsintotheSPICS0,D1,D0,andSCLKsignals,respectively.InthePacktHAL.tgzfile,thesourcecodefortheoverlayislocatedinthecape/BB-PACKTPUB-00A0.dtsfile.Thecoderesponsibleformuxingthesetwopinsislocatedinthebb_spi0_pinsnodewithinfragment@0:
/*AllSPI0pinsarePULL,MODE0*/
bb_spi0_pins:pinmux_bb_spi0_pins{
pinctrl-single,pins=<
0x1500x30/*P9.22,spi0_sclk,INPUT*/
0x1540x30/*P9.21,spi0_do,INPUT*/
0x1580x10/*P9.18,spi0_d1,OUTPUT*/
0x15c0x10/*P9.17,spi0_cs0,OUTPUT*/
>;
};
Whilethissetsupthemuxing,itdoesn’tassignandconfigureadevicedrivertothesepins.Thefragment@2nodeperformsthiskerneldriverallocation:
fragment@2{
target=<&spi0>;
__overlay__{
#address-cells=<1>;
#size-cells=<0>;
status="okay";
pinctrl-names="default";
pinctrl-0=<&bb_spi0_pins>;
channel@0{
#address-cells=<1>;
#size-cells=<0>;
/*Kerneldriverforthisdevice*/
compatible="spidev";
reg=<0>;
/*Settingthemaxfrequencyto16MHz*/
spi-max-frequency=<16000000>;
spi-cpha;
};
…
};
};
Withoutdiggingintothefinedetails,therearethreesettingsinfragment@2thatareofinteresttoyou:
www.it-ebooks.info
pinctrl-0
compatible
spi-max-frequency
Thefirstispinctrl-0,whichtiesthisnodeofDeviceTreetothepinsmuxedinthebb_spi0_pinsnode.Thesecondiscompatible,whichspecifiestheparticularkerneldriver,spidev,thatwillhandleourhardwaredevice.Thelastisspi-max-frequency,whichspecifiesthemaximumallowablespeedforthisSPIbus(16MHz).16MHzisthemaximumfrequencyspecifiedforspidevintheDeviceTreeoverlaysprovidedwiththeBBB’skernelsource.
Thecustominit.{ro.hardware}.rcfilethatyoupushedtotheAndroidsystemdoesn’thavetodoanythingspecialforPacktHAL’sSPIinterfacing.Bydefault,BBBAndroiduseschmodtosetthepermissionsofthe/dev/spidev*filesto777(completeaccessforeveryone).Thisisnotasecurepracticesinceanyprocessonthesystemcanpotentiallyopenaspidevdeviceandbeginreadingandwritingtothehardware.Forourpurposes,though,havingthe/dev/spidev*filesaccessibletoeveryprocessisnecessarytoallowourunprivilegedexampleappaccesstotheSPIbus.
www.it-ebooks.info
BuildinganSPIinterfacecircuitNowthatyouhaveanunderstandingofwhereSPIdevicesareconnectedtotheBBBandhowtheLinuxkernelpresentsaninterfacetothesedevices,itistimetoconnectanSPIdevicetotheBBB.
AswementionedinChapter1,IntroductiontoAndroidandtheBeagleBoneBlack,youwillbeinterfacingwithasensorinthischapter.Tobespecific,wewillbeusingaBoschSensortecBMP183digitalpressuresensor.This7-pincomponentprovidespressuredatasamples(in16-to19-bitresolution)andtemperaturedatasamples(in16-bitresolution)forapplicationsusedfornavigation,weatherforecasting,andtomeasurechangesinverticalelevationandsoon.
Thisparticularchipisonlyavailableinalandgridarray(LGA),whichisasurfacemountpackagethatcanbedifficulttoworkwithwhenbuildingprototypecircuits.Luckilyforus,theAdaFruitbreakoutboardforthesensoralreadyhasthechipmounted,whichmakesprototypingsimpleandeasy.
Thesensorbreakoutboard(source:www.adafruit.com)
ThebreakoutboardlabelstheSCLKsignalasSCK,MOSIasSDI(serialdatain),MISOasSDO(serialdataout),andSSasCS(chipselect).Topowertheboard,a+3.3VsignalisconnectedtoVCCandagroundisconnectedtoGND.The3Vosignalofthebreakoutboardprovidesa+3.3Vsignalandisnotusedinourexamples.
www.it-ebooks.info
TipDon’tdisassembleyourcircuit!
ThesensorcircuitinthischapterispartofamuchlargercircuitusedinChapter6,CreatingaCompleteInterfacingSolution.Ifyoubuildthecircuitasitispositionedinthediagram(towardsthemiddleofthebreadboard),youcansimplyleavethesensorbreakoutboardandwiresinplaceasyoubuildtheremainingcircuitsinthisbook.Thisway,itwillalreadybeconstructedandworkingwhenyoureachChapter6.
www.it-ebooks.info
ConnectingthesensorThefollowingfigureshowstheconnectionsbetweenthesensorbreakoutboardandtheBBB.ThesixmainSPIbussignals(+3.3V,ground,andtheSPISCLK,MISO,MOSI,andSS)aremadeusingthepinsoftheP9connector,sowehaveplacedthebreadboardontheP9sideoftheBBB.
Thecompletesensorinterfacingcircuit
Let’sgetstarted:
1. ConnectP9.1(ground)totheverticalgroundbusofthebreadboardandP9.3(3.3V)totheverticalVCCbusofthebreadboard.TheseconnectionsareidenticaltotheonesmadefortheGPIOandI2CbreadboardcircuitsyoucreatedinChapter3,HandlingInputsandOutputswithGPIOsandChapter4,StoringandRetrievingDatawithI2C.
2. ThefourSPIbussignals,SCLK,MISO(D0),MOSI(D1),andSSareontheP9.22,P9.21,P9.18,andP9.17pins,respectively.WiretheP9.22pintothepinmarkedSCKonthebreakoutboard,andwiretheP9.21pintothepinmarkedSDO.Then,wiretheP9.18pintothepinmarkedSDI,andwireP9.17tothepinmarkedCS.
3. WirethegroundbustotheGNDpinofthebreakoutboardandtheVCCbustotheVCCpinofthebreakoutboard.Leavethe3Vopinofthebreakoutboardunconnected.
www.it-ebooks.info
ThesensorbreakoutboardisnowelectricallyconnectedtotheBBBandisreadyforyouruse.Double-checkyourwiringagainstthediagramofthecompletesensorinterfacingcircuittoensurethateverythingisconnectedproperly.
www.it-ebooks.info
ExploringtheSPIsensorexampleappInthissection,youwillexaminetheexampleAndroidappthatperformstheSPIbusinterfacingonBBB.ThepurposeofthisapplicationistodemonstratehowtousePacktHALtoperformSPIreadsandwritesfromwithinanactualappusingasetofinterfacingfunctions.ThesefunctionsallowyoutosendandreceivedatabetweentheSPIbusmaster(theBBB)andtheSPIbusslave(theSPIsensor).Thelow-leveldetailsofthehardwareinterfacingareimplementedinPacktHAL,soyoucanquicklyandeasilygetyourappsinteractingwiththesensor.
BeforediggingthroughtheSPIapp’scode,youmustinstallthecodetoyourdevelopmentsystemandinstalltheapptoyourAndroidsystem.Thesourcecodefortheappandtheprecompiled.apkpackagesarelocatedinthechapter5.tgzfile,whichisavailablefordownloadfromPackt’swebsite.FollowthesameprocesstodownloadandaddtheapptoyourEclipseADTenvironmentthatwasdescribedinChapter3,HandlingInputsandOutputswithGPIOsandChapter4,StoringandRetrievingDatawithI2C.
www.it-ebooks.info
Theapp’suserinterfaceTheappusesaverysimpleUItointeractwiththesensor.Asitissosimple,theonlyactivitythattheapphas(bydefault)isMainActivity.TheUIconsistsofonlyonebuttonandtwotextviews.
Thesensorsampleappscreenpriortoreceivingitsfirstsetofsamplesfromthesensor
ThetoptextviewhasthetemperatureTextViewidentifierintheactivity_main.xmlfile,andthebottomtextviewhasthepressureTextViewidentifier.Thesetextviewswilldisplaythetemperatureandpressuredatathatisretrievedfromthesensor.ThebuttonwiththeSamplelabelhasthesampleButtonidentifier.ThisbuttonhasanonClick()methodcalledonClickSampleButton()thattriggerstheprocessofinterfacingwiththesensortosamplethetemperatureandpressuredataandthenupdatingthetextdisplayedinthetemperatureTextViewandpressureTextViewtextviews.
www.it-ebooks.info
CallingthePacktHALsensorfunctionsThesensorinterfacefunctionalityinPacktHALisimplementedinavarietyofCfunctionsinthejni/bmp183.cfilewithinthesensorapp’sproject.Thesefunctionsnotonlyinterfacewiththesensor,buttheyalsodoavarietyofconversionandcalibrationtasks.
Theframappinthepreviouschapterusedaspecifickerneldriver(the24c256EEPROMdriver)tointeractwiththeFRAMchip,sotheuser-space-interfacinglogicthatisimplementedinPacktHALisquitesimple.PacktHALdoesnotuseasensor-specifickerneldrivertocommunicatewiththesensor,soitmustusethegenericspidevdrivertocommunicate.ItisuptoPacktHALtoprepare,send,receive,andinterprettheindividualbytesofeverySPImessagethatisgoingtoorfromthesensor.
WhilethereareanumberoffunctionsinPacktHALtohandlethesetasks,onlyfourofthosefunctionsareusedbyoutsidecodetointeractwiththesensor:
openSensor()
getSensorTemperature()
getSensorPressure()
closeSensor()
Theprototypesforthesefunctionsarelocatedinthejni/PacktHAL.hheaderfile:
externintopenSensor(void);
externfloatgetSensorTemperature(void);
externfloatgetSensorPressure(void);
externintcloseSensor(void);
TheopenSensor()functioninitializesaccesstotheSPIbusbyopening/dev/spidev1.0andmakingseveralioctl()callstoconfiguretheSPIbus’communicationparameters(suchastheclockrateofSCLK).
Oncethisconfigurationisperformed,allSPIcommunicationsperformedinsideofPacktHALwillusethisbus.CallingthecounterpartcloseSensor()functionclosesthe/dev/spidev1.0file,whichshutsdowntheSPIbusandfreesitforusebyotherprocessesonthesystem.ThegetSensorTemperature()andgetSensorPressure()functionsperformallofthepreparationoftheSPImessages,SPIcommunication,andsampleconversionlogicrequiredtofetchandconvertthesamplesretrievedfromthesensor.
NoteIfyouwereusingaspecializedkerneldriverdesignedtotalktothespecificsensorthatweareusing,thenthesensor-readinglogicinsidethePacktHALcodewouldbeverysimple(onlyoneortwoioctl()calls).ItisalwaysabalancebetweenplacingHALcodelogicintothekernelversuskeepingitinuserspace.Themorecodethatyoucanpushintothekernel,thesimplerandfastertheuserspacecodewillbe.However,itcanbeverydifficulttodevelopkernelcode,soyoumuststrikeabalancebetweenwhatiseasiesttoimplementandwhatwillprovideyouwiththeperformancenecessaryforyourhardwaredesign.
Thesensorapphasseveralsimilaritiestoappsfrompreviouschapters.Liketheframapp
www.it-ebooks.info
fromChapter4,StoringandRetrievingDatawithI2C,thesensorappusesitsownclassderivedfromAsyncTask,HardwareTask,tomakeJNIcallstotheunderlyingsensor-interfacingfunctionsfromPacktHAL.InterfacingwiththehardwareistriggeredbytheonClick()handlerofabuttonpressedbytheapp’suser,similartowhatboththegpioandframappsdo.
MuchliketheGPIO-interfacingfunctionsfromPacktHALthatyouusedinChapter3,HandlingInputsandOutputswithGPIOsandChapter4,StoringandRetrievingDatawithI2C,thesensor-interfacingmethodsinHardwareTaskareveryfasttoexecute.ItisnotactuallynecessarytoexecutethesemethodsfromwithinaseparatethreadsincetheyarenotlikelytotakesolongtoexecutethattheywilltriggertheANRdialog.However,SPIcanbeusedforawidevarietyofdevices,anditispossibletoneedlongerperiodsoftimetosendlargeamountsofdata,sobettersafethansorry.
TipWhenshouldIuseanAsyncTaskforhardwareinterfacing?
Theshortanswertothisis“allofthetime”.WedidnotwanttodistractyouwiththedetailsoftheAsyncTaskclasswhenyouwereworkingwithGPIOsinChapter3,HandlingInputsandOutputswithGPIOs,sothegpioappmademethodcallstoPacktHALfunctionsintheonClick()buttonhandlers.However,thegeneralruletofollowistoalwaysuseAsyncTasktoperformanysortofI/O.I/Oisnotoriouslyslow,soanyI/O(networking,accessingfilesondisk,andhardwareinterfacing)shouldreallytakeplaceinitsownthreadviaAsyncTask.
www.it-ebooks.info
UsingtheHardwareTaskclassLikethegpioandframapps,theHardwareTaskclassinthesensorappprovidesfournativemethodsthatareusedtocallthePacktHALJNIfunctionsrelatedtosensorhardwareinterfacing:
publicclassHardwareTaskextendsAsyncTask<Void,Void,Boolean>{
privatenativebooleanopenSensor();
privatenativefloatgetSensorTemperature();
privatenativefloatgetSensorPressure();
privatenativebooleancloseSensor();
AsthedetailsoftheSPIbussetupprocessareencapsulatedwithinthePacktHALfunctionsandhiddenfromtheapp,thesemethodstakenoparameters.TheysimplycalltheirPacktHALcounterpartsviathePacktHALJNIwrapperfunctions.
ThethreadcontextsinwhichtheHardwareTaskmethodsandthePacktHALfunctionsareexecuted
Inthesensorapp,theonClick()handlerforthesamplebuttonintheMainActivityclassinstantiatesanewHardwareTaskmethod.Immediatelyafterthisinstantiation,thepollSensor()methodofHardwareTaskiscalledtorequestacurrentsetoftemperatureandpressuredatafromthesensor:
publicvoidonClickSampleButton(Viewview){
hwTask=newHardwareTask();
hwTask.pollSensor(this);
}
ThepollSensor()methodbeginsthehardware-interfacingprocessbycallingtheexecution()methodofthebaseAsyncTaskclasstocreateanewthread:
www.it-ebooks.info
publicvoidpollSensor(Activityact){
mCallerActivity=act;
execute();
}
Theexecute()methodofAsyncTaskcallstheonPreExecute()methodthattheHardwareTaskusestoinitializetheSPIbusviaitsopenSensor()nativemethod.ThesampleButtonmethodisalsodisabledforthedurationofthethreadtopreventthepossibilityofmultiplethreadstryingtousetheSPIbustotalktothesensorsimultaneously:
protectedvoidonPreExecute(){
Log.i("HardwareTask","onPreExecute");
...
if(!openSensor()){
Log.e("HardwareTask","Erroropeninghardware");
isDone=true;
}
//DisabletheButtonwhiletalkingtothehardware
sampleButton.setEnabled(false);
}
OncetheonPreExecute()methodfinishes,theAsyncTaskbaseclassspinsanewthreadandexecutesthedoInBackground()methodwithinthatthread.Forthesensorapp,thisistheproperplacetoperformanySPIbuscommunicationrequiredtogetthecurrenttemperatureandpressuresamplesfromthesensor.ThegetSensorTemperature()andgetSensorPressure()nativemethodsoftheHardwareTaskclassfetchthelatestsamplesfromthesensorviathegetSensorTemperature()andgetSensorPressure()functionsinPacktHAL:
protectedBooleandoInBackground(Void…params){){
if(isDone){//Wasthehardwareneveropened?
Log.e("HardwareTask","doInBackground:Skippinghardware
interfacing");
returntrue;
}
Log.i("HardwareTask","doInBackground:Interfacingwithhardware");
try{
temperature=getSensorTemperature();
pressure=getSensorPressure();
}catch(Exceptione){
...
AfterdoInBackground()iscomplete,theAsyncTaskthreadterminates.ThistriggersthecallingofdoPostExecute()fromtheUIthread.Now,astheapphasfinisheditsSPIcommunicationtasksandreceivedthelatesttemperatureandpressurevaluesfromthesensor,itistimetoclosetheSPIconnection.ThedoPostExecute()methodclosestheSPIbususingthecloseSensor()nativemethodoftheHardwareTaskclass.ThedoPostExecute()methodthenalertstheMainActivityclassofthenewdatareceivedfromthesensorviatheupdateSensorData()method,anditre-enablestheSamplebutton
www.it-ebooks.info
ofMainActivity:
protectedvoidonPostExecute(Booleanresult){
if(!closeSensor()){
Log.e("HardwareTask","Errorclosinghardware");
}
...
Toasttoast=
Toast.makeText(mCallerActivity.getApplicationContext(),
"Sensordatareceived",Toast.LENGTH_SHORT);
toast.show();
((MainActivity)mCallerActivity).updateSensorData(temperature,
pressure);
...
//ReenabletheButtonaftertalkingtothehardware
sampleButton.setEnabled(true);
TheMainActivityclass’updateSensorData()methodisresponsibleforupdatingthedisplayedvaluesinthetemperatureTextViewandpressureTextViewtextviewstoreflectthenewestreceivedsensorvalues:
publicvoidupdateSensorData(floattemperature,floatpressure){
Toasttoast=Toast.makeText(getApplicationContext(),
"Displayingnewsensordata",Toast.LENGTH_SHORT);
TextViewtv=(TextView)findViewById(R.id.temperatureTextView);
tv.setText("Temperature:"+temperature);
tv=(TextView)findViewById(R.id.pressureTextView);
tv.setText("Pressure:"+pressure);
toast.show();
}
Atthispoint,executionofthesensorapphasreturnedtoitsidlestate.IftheuserclicksontheSamplebuttononcemore,anotherHardwareTaskinstanceisinstantiatedandtheopen-sample-closeinteractioncycleofthehardwarewilloccuragain.
TipAreyoureadyforachallenge?
Nowthatyouhaveseenallofthepiecesofthesensorapp,whynotchangeittoaddsomenewfunctionality?Forachallenge,tryaddingacounterthatshowshowmanysampleshavebeentakensofarandtheaveragetemperatureandpressurefromallofthesamplestaken.Wehaveprovidedonepossibleimplementationofthisinthechapter5_challenge.tgzfile,whichisavailablefordownloadfromPackt’swebsite.
www.it-ebooks.info
SummaryInthischapter,weintroducedyoutotheSPIbus.YouconstructedacircuitthatconnectedanSPIpressureandtemperaturesensorbreakoutboardtotheBBB,andyoulearnedabouttheportionsofthePacktHALinit.{ro.hardware}.rcfile’sDeviceTreeoverlaythatareresponsibleforconfiguringandmakingtheSPIbusandspidevdevicedriveravailableforyourapp’suse.ThesensorappinthischapterdemonstratedhowcomplextasksintheHALcanbehiddenfromtheappusingasmallsetoffunctionsthathidethelow-leveldetails.ThesesimplifiedPacktHALfunctioncallscanbemadefromaclassderivedfromAsyncTasktoperformmorecomplexinterfacingtaskssimplyfromwithinanapp.
Inthenextchapter,youwilllearnaboutcombiningGPIO,I2C,andSPItogetherintoanappcapableofprovidingacompletehardwaresolutionthatusesalong-livedhardware-interfacingthread.
www.it-ebooks.info
Chapter6.CreatingaCompleteInterfacingSolutionInthepreviouschaptersofthisbook,youinterfacedwithdevicesusingGPIOs,I2C,andSPI.YouusedAsyncTaskstoperformhardwareinterfacinginbackgroundthreads,andyouexploredhowtostructureanapptointeractwiththosethreads.
Inthischapter,youwillbringalloftheseconceptstogethertocreateacircuitthatusesallthreeinterfacingmethods,andyouwillexploreanappthatusesalltheinterfacestogethertomakeacomplexsystem.
Inthischapter,wewillcoverthefollowingtopics:
BuildingthecompleteinterfacecircuitExploringthefinalexampleapp
www.it-ebooks.info
BuildingthecompleteinterfacecircuitTheinterfacingcircuitusedinthischapterisacombinationofeachofthecircuitsdescribedinchapters3,4,and5.Ifyouhavesuccessfullyconstructedthecircuitsfromthepreviouschapters,youalreadyhaveagoodunderstandingofhowthecircuitinthischapterwillbeputtogether.Leaveanypreviouslyconstructedcircuitsonthebreadboardtosaveyousomeeffortifyouhaveconstructedthosecircuitsbycloselyfollowingtheinstructionsfromearlierchapters.
Thefollowingdiagramshowstheconnectionsbetweenthesensorbreakoutboard,FRAMbreakoutboard,LED,pushbuttonswitch,resistor,andtheBBB.Revisitchapters3,4,and5fortheexactdetailsonhowtoconstructtheGPIO,FRAM,andSPIportionsofthecircuit,ifyouhavenotyetdoneso.
ThecompletehardwareinterfacingcircuitthatusescomponentswhichinterfacewiththeBBBusingtheGPIOs,I2C,andSPIcomponents
www.it-ebooks.info
ExploringthecompleteexampleappInthissection,youwillexaminetheexampleAndroidappthatperformsGPIO,I2C,andinterfacingonBBB.ThepurposeofthisapplicationistodemonstratehowtousePacktHALtoperformavarietyofhardwaretasksfromwithinanactualappusingasetofinterfacingfunctions.Unlikethepreviousexampleapps,whichtakeinputfromtheuser,thisapptakesallofitsinputdirectlyfromthehardwareitself.Thisrequiresaslightlymorecomplexapproachthanthattakenbytheearlierapps.
Beforediggingthroughtheapp’scode,youmustinstallthecodeonyourdevelopmentsystemandinstalltheapponyourAndroidsystem.Thesourcecodefortheappaswellastheprecompiled.apkpackageislocatedinthechapter6.tgzfile,whichisavailablefordownloadfromthePacktwebsite.FollowthesameprocesstodownloadandaddtheapptoyourEclipseADTenvironment,whichwasdescribedinChapter3,HandlingInputsandOutputswithGPIOs.
www.it-ebooks.info
Theapp’suserinterfaceLaunchthecompleteappontheAndroidsystemtoseetheapp’sUI.Ifyouareusingatouchscreencape,youcansimplytouchthecompleteapp’sicononthescreentolaunchtheappandinteractwithitsUI.IfyouareusingtheHDMIforvideo,connectaUSBmousetotheBBB’sUSBportandusethemousetoclickonthesensorappicontolaunchtheapp.
TheappusesaverysimpleUIthatdisplaystwotextviewsinasingleactivity,whichisMainActivitybydefault.
Thecompleteappscreenpriortoreceivingitsfirstsetofsamplesfromthesensor
TherearenobuttonsorotherUIelementsinthisappbecausetheonlyinteractiontheuserhaswiththeappisthroughthecircuit’sGPIOpushbuttonswitch.Whentheuserpressestheswitch,theappperformsaseriesofhardwareinterfacingactions:
TheLEDwillturnontonotifytheuserthattheswitchhasbeenrecognizedaspressed.TheLEDwillremainlituntilalleventsonthelisthaveoccurred.WhiletheLEDison,anyfurtherswitchinputisignored.TemperatureandpressuresamplesarefetchedfromthesensorandwrittenintotheFRAM.TheFRAMisreadtoretrievethestoredtemperatureandpressuresamplevalues.Thevaluesforthetemperatureandpressuresamplesaredisplayedintheapp’sUI.A1-seconddelaywilloccur.TheLEDwillturnoff,andtheswitchcanonceagainbepressedtotriggeranothersample-store-retrieve-displaycycle.
Thevarietyofactionsperformedbytheappmakesitsinterfacingbehaviormorecomplexthanwhatyousawinthepreviousexampleappsinthisbook.Ratherthanfocusingoninterfacingwithasinglehardwarecomponent,thisappinterfaceswiththeGPIO,I2C,andSPIdevicesatthesametimetoprovideacompletesensorsolutionwithpersistentstorage.However,itisbasedonthesamebasicinterfacingconceptsthattheotherexampleappsinthisbookhavedemonstrated.
www.it-ebooks.info
UnderstandinghardwarepollinginanappTheearlierappseitherusedtheonClick()handlerofabuttontointerfacedirectlytothehardware(GPIOs)ortriggeredtheinstantiationandexecutionofAsyncTask(I2CandSPI)tointerfacewiththehardware.Inbothofthesecases,interfacingwiththehardwareisinitiatedbyasoftwareevent,theonClick()handler’sexecution,withintheapp.
Inthischapter’sapp,however,wewanttotriggerthehardwareinterfacinginresponsetothehardwareeventcreatedbytheswitchbeingpressed.Listeningforhardwareeventsisanimportantpartofinterfacingbecauseitallowsthehardwaretotelluswheneventsofinterestoccur.Wedonotalwayshavetheluxuryoftellingthehardwaretodosomethingandexpectingthehardwaretodoit.Sometimes,thehardwareneedstonotifyusthataneventhasoccurred.
Wheninterfacingwithhardwarefromakerneldriver,thedrivercanregistertobenotifiedofahardwareeventofinterestbyregisteringfornotificationofthetimeahardwareinterruptoccurs.Ahardwareinterrupttellsthekernelimmediatelythatsomethingnoteworthyhashappenedwiththehardware,andthekernelwillstopwhatitisdoingtoallowtheappropriatekerneldrivertohandletheinterrupt.
Becauseourappsareperformingtheirhigher-levelinterfacinglogicfromuserspace,weareunabletoregisterforaninterrupttonotifyusthetimeaneventofinterestoccurs.Thishardwareeventcanhappenasynchronouslyatanytime,sotheappmustcontinuallypoll,orcheck,thestateoftheswitchtodeterminewhetherithasbeenpressedornot.AppstypicallydonotpollforeventsbecausetheyrelyonbeingnotifiedbytheAndroidframeworkwhensomethinginterestinghappens,butwhenanappisperforminghardwareinterfacingwithouttheassistanceofamanager,pollingbecomesnecessary.
Thefasteranapppollsthehardware,thelesserthechancethattheappwillmisstheoccurrenceofthehardwareeventofinterest.However,constantlypollinginatightloopisabadideabecauseitwillconstantlyconsumeCPUcycles(andbatterylifeinmobiledevices),whichcanbebetterspentelsewhere.Ifyouincludepollinginyourapps,youmustfindagoodbalancebetweenperformanceandusageofresources.
ItisabadideatoplaceapollingloopinsidethecontextoftheUIthread.RememberthatspendingtoomuchtimeexecutingwithinahandlermethodintheUIthreadcontextwillcauseAndroidtotriggertheANRdialog.Toavoidthisproblem,anappmustinstantiateAsyncTask,whichperformsthehardwarepollinginabackgroundthread.TheearlierexampleappsinthisbookusedanAsyncTaskthreadtoperformcommunicationwithhardwaredevices,buttheAsyncTaskthreadwasshort-lived.TheAsyncTaskthread’sbackgroundthreadwasonlyactivewhileitwasinterfacingwiththehardware.Oncetheinterfacingwascompleted,thethreadterminated.Iftheappneededtocommunicatewiththehardwareoncemore,anewAsyncTaskthreadwasinstantiatedandstartedviaitsexecute()method.
BecauseourappmustuseAsyncTasktocontinuallypolltheswitchtocheckforuserinput,theAsyncTaskthreadusedintheappisalong-livedthread.Insteadofinstantiating
www.it-ebooks.info
andcallingexecute()forAsyncTaskonlyatthemomentswhentheappneedstocommunicatewiththehardware,theappinstantiatesandexecutesAsyncTaskwheneverittransitionstotheresumedstate.TheAsyncTaskthreadcontinuesexecutinginthebackgrounduntiltheapptransitionstothepausedstate.
NoteTolearnthedetailsofhowAndroidappactivitiestransitionamongthevariouslifecyclestates,suchastheresumedstateandpausedstate,refertotheofficialAndroiddeveloperdocumentationathttp://developer.android.com/training/basics/activity-lifecycle/index.html.
www.it-ebooks.info
UsingAsyncTaskwithlong-livedthreadsWehavealreadyusedfourmethodsintheAsyncTaskbaseclassinourpreviousexampleapps.ThesemethodsareusedinAsyncTaskstoimplementbothshort-livedandlong-livedthreads:
onPreExecute()
doInBackground()
onPostExecute()
execute()
Inthischapter,youwillusefiveadditionalmethodsoftheAsyncTaskclass.Theseadditionalmethodscanbeusedforshort-livedthreadstomakethemmorepowerful,andtheywillalmostalwaysbeusedinlong-livedbackgroundthreadstocommunicatewiththethreadandreceivefeedbackfromitwhileitruns:
cancel()
onCancelled()
isCancelled()
publishProgress()
doPublishProgress()
Thecancel(),onCancelled(),andisCancelled()methodsareusedtostopthecurrentlyexecutingAsyncTaskmethodwhentheMainActivityclassofourappleavestheresumedstate.Thecancel()methodiscalledfromwithintheUIthreadcontexttonotifytheAsyncTaskclassthatithasbeencanceledandshouldstopitsexecution.Callingcancel()triggersthecallingoftheonCancelled()methodwithintheAsyncTaskthreadcontext.ThenonCancelled()givestheAsyncTaskclassachancetoperformanynecessarycleanuptasks.TheisCancelled()methodcanbecalledatanytimefromwithintheAsyncTaskthreadcontexttodeterminewhethercancel()andonCancelled()havebeencalled.ThismethodisusuallycalledfromwithinaloopinsideofthedoInBackground()method.
ThepublishProgress()anddoPublishProgress()methodsallowtheAsyncTaskthreadtonotifytheUIthreadofanyinformationthatshouldbedisplayedtotheuserviatheapp’sUI.Forexample,ifanAsyncTaskthreadiscopyingalargefilefromthenetwork,thesetwomethodsnotifytheUIthreadhowmuchofthefilehasbeencopiedandtheestimatedtimeremainingtotransfertheremainderofthefile.TheUIthreadcanthenupdatetheUIwiththisinformationtokeeptheapp’suserinformedoftheAsyncTaskthread’sprogress.
ThesefivenewAsyncTaskmethodswerenotusedintheexampleappsinearlierchaptersbecausethoseappsusedAsyncTaskmethodsthatwereshort-livedthreadsandwhichupdatedthescreenfromtheonPostExecute()method.TheonPostExecute()methodexecutedwithintheUIthread,sotherewasnoneedtousepublishProgress()anddoPublishProgress()inthoseapps.TheAsyncTaskthreadsinthoseappsalsoexecutedwhiletheappwasinaresumedstate,andthethreadsweresoshort-livedthatitwasnotnecessarytousecancel()oronCancelled()toterminatethethreads’execution.Because
www.it-ebooks.info
thoseappsdidnotusealoopwithintheirdoInBackground()methods,itwasnotnecessarytouseisCancelled().
www.it-ebooks.info
UsingtheHardwareTaskclassSimilartotheexampleappsinpreviouschapters,thecompleteappusesaHardwareTaskclassthatisderivedfromAsyncTask.AllofthehardwareinterfacingisperformedviathemethodsinHardwareTask.
ThethreadcontextsinwhichtheHardwareTaskmethodsandthePacktHALfunctionsareexecuted.TheJNIfunctionsinthisimagehavehadtheirfunctionnameprefixesshortened
toHardwareTask.
TheHardwareTaskclassforthesensorappprovidessevennativemethodsthatareusedtocallthePacktHALJNIfunctionsrelatedtoGPIO,FRAM,andsensorhardwareinterfacing:
publicclassHardwareTaskextendsAsyncTask<Void,Void,Boolean>{
privatenativebooleanopenHardware();
privatenativebooleanpollButton();
privatenativebooleanchangeLED(booleanlit);
privatenativebooleanreadSensor();
privatenativefloatgetSensorTemperature();
privatenativefloatgetSensorPressure();
privatenativebooleancloseHardware();
BecausemostofthedetailsofthehardwareinterfacingareencapsulatedwithinthePacktHALfunctionsandhiddenfromthecompleteapp,allbutoneofthesemethodsacceptnoparametersatall.TheysimplycalltheirPacktHALcounterpartsviathePacktHALJNIwrapperfunctions.TheexceptiontothisisthechangeLED()method,whichtakesasingleparametertospecifywhethertheLEDshouldbeturnedonoroff.
www.it-ebooks.info
Inthecompleteapp,theonResume()methodoftheMainActivityclassinstantiatesanewHardwareTaskclasswhenMainActivitychangestotheresumedstate:
publicvoidonResume(){
super.onResume();
//Createourbackgroundhardwarecommunicationthread
hwTask=newHardwareTask();
hwTask.pollHardware(this);
}
ThepollHardware()methodbeginsthehardwareinterfacingprocessbycallingthebaseAsyncTaskclassexecution()methodtocreateanewthread:
publicvoidpollHardware(Activityact){
mCallerActivity=act;
execute();
}
TheonPause()methodoftheMainActivityclasshaltstheAsyncTaskclass’sexecutionwhentheMainActivityclasschangestothepausedstate:
publicvoidonPause(){
super.onPause();
//Releasethehardwarewhentheappispaused
if(hwTask!=null){
hwTask.cancel(true);
hwTask=null;
}
}
Thecancel()methodoftheAyncTaskbaseclassbeginstheprocessofcancelingtheexecutingAsyncTaskthreadbycallingtheonCancelled()methodinHardwareTask.InadditiontonotifyingtheAsyncTaskbaseclassthattheexecutionhasbeencanceled,theisDoneBooleanflagissetintheHardwareTaskclass:
protectedvoidonCancelled(){
Log.i("HardwareTask","Cancelled.");
isDone=true;
}
OnceMainActivityhastransitionedtotheresumedstate,thepollHardware()methodofHardwareTaskbeginstheAsyncTaskthread’sexecution.InonPreExecute(),theisDoneflagisreset,andtheGPIO,I2C,andSPIdevicesareallinitializedviatheopenHardware()method.Ifthehardwareissuccessfullyinitialized,theLEDisthenturnedoffviaachangeLED()call:
protectedvoidonPreExecute(){
Log.i("HardwareTask","onPreExecute");
isDone=false;
...
if(!openHardware()){
Log.e("HardwareTask","Erroropeninghardware");
isDone=true;
www.it-ebooks.info
}else{
changeLED(false);
}
}
AfteronPreExecute()hascompleted,theAsyncTaskbackgroundthreadbeginsrunning.ThedoInBackground()methodbeginsitsexecution.Becausethisisalong-livedthread,thereisawhileloopinsidedoInBackground()thatwillcontinuetoexecuteuntilthethreadiscanceledbythemainUIthread:
protectedBooleandoInBackground(Void…params){
...
//Pollthebuttonuntilanerrorordone
while(!isDone&&!isCancelled()){
Theloopbeginsbypollingthestateofthepushbuttonswitch.Iftheswitchispressed,thehardwareinterfacinglogicwillbegincommunicatingwiththeFRAMandsensor.Iftheswitchisnotpressed,thentheinterfacinglogicisskipped.Inbothcases,aslightdelayisaddedviaaThread.sleep()methodcalltogivethebackgroundthreadanopportunitytosleepandallowotherthreadstorun.Thislimitstheresourceconsumptionofthebackgroundthreadandgivesotherprocessesandthreadsanopportunitytorun:
while(!isDone&&!isCancelled()){
if(pollButton()){
...
}
Thread.sleep(100);
}
...
returnfalse;
}
IfthepollButton()methodstatesthatthebuttonispressed,thehardwareinterfacinglogicbeginsexecuting.ThiscallsthevariousnativemethodsthatinvokethePacktHALJNIfunctions.
First,changeLED()turnsontheLEDtolettheuserknowthatasampleisabouttobetaken:
if(!changeLED(true)){
Log.e("HardwareTask","UnabletoturnLEDon");
}
Next,thesensorsampleistakenandtheresultisstoredintheFRAM.ThereadSensor()nativemethodinteractswiththesensortoretrievethesampledata,andthenstoresthetemperatureandpressuresamplesinthefirsteightbytesofthememoryoftheFRAM:
if(!readSensor())
{
Log.e("HardwareTask","Unabletoreadsensor");
}
www.it-ebooks.info
NoteThetemperaturedataisstoredasa4-bytefloatinthefirstfourbytesoftheFRAM,andthepressuredataisstoredasa4-bytefloatinthesecondfourbytesoftheFRAM.Ifyouareinterestedinthedetailsofhowthisisimplementedinthenativecode,takealookattheJava_com_packt_complete_HardwareTask_readSensor()functioninthejni/jni_wrapper.cfileinPacktHAL.
Afterthat,theFRAMisaccessedtoretrievethetemperatureandpressuresamples:
temperature=getSensorTemperature();
pressure=getSensorPressure();
Finally,themainUIthreadisupdatedwiththenewsampledataviathepublishProgress()method.Thethreadsleepsfor1second,andthentheLEDturnsoff.Atthispoint,thepollButton()checkiscompleteandthewhileloopbeginsagain:
publishProgress();
Thread.sleep(1000);
if(!changeLED(false)){
Log.e("HardwareTask","UnabletoturnLEDoff");
}
}//EndofpollButton()check
ThepublishProgress()methodtriggerstheonProgressUpdate()methodofHardwareTask,whichexecutesintheUIthread.TheonProgressUpdate()methodcallstheMainActivityclassupdateSensorData()method:
protectedvoidonProgressUpdate(Void…values){
((MainActivity)mCallerActivity).
updateSensorData(temperature,pressure);
}
ThisupdateSensorData()methodintheMainActivityclassupdatestheapp’sUIandprovidesaToastmessagetotheuser:
publicvoidupdateSensorData(floattemperature,floatpressure){
Toasttoast=Toast.makeText(getApplicationContext(),
"Updatingsensordata",Toast.LENGTH_SHORT);
TextViewtv=(TextView)findViewById(R.id.temperatureTextView);
tv.setText("Temperature:"+temperature);
tv=(TextView)findViewById(R.id.pressureTextView);
tv.setText("Pressure:"+pressure);
toast.show();
}
ThemainpollingwhileloopintheHardwareTaskclass’doInBackground()methodwilleventuallyexitasaresultofeitherthehardwareinterfacingfailingtoinitializeorthebaseAsyncTaskmethodbeingcanceledbyMainActivity.Oncetheloophasfinished,doInBackground()willexitandtheAsyncTaskbackgroundthreadwillterminate.TheonPostExecute()methodwillthenperformanycleanupofitemsrequired,suchas
www.it-ebooks.info
shuttingdownthehardwareinterfacing:
protectedvoidonPostExecute(Booleanresult){
if(!closeHardware()){
Log.e("HardwareTask","Errorclosinghardware");
}
...
}
TheHardwareTaskinstancehasnowcompleteditsbackgroundthread.IftheMainActivityreturnstotheresumedstate,anewHardwareTaskinstancewillbeinstantiated.ThisHardwareTaskinstancewillcreateanotherlong-livedbackgroundthread,andthehardwareinterfacingprocesswillrepeatitself.
TipAreyoureadyforachallenge?
Nowthatyouhaveseenallofthepiecesofthecompleteapp,whynotchangeittoaddsomenewfunctionality?Forachallenge,trychangingtheapptocontinuallytakesamplesoncethebuttonhasbeenpressed.Stoptakingsamplesifthebuttonishelddownforashortperiodoftime.Wehaveprovidedonepossibleimplementationofthisinthechapter6_challenge.tgzfile,whichisavailablefordownloadfromthePacktwebsite.
www.it-ebooks.info
SummaryInthischapter,weintroducedtheconceptoflong-livedthreadsforhardwareinterfacing.YouconstructedacircuitthatconnectedtheGPIOpushbuttonswitch,GPIOLED,FRAMdevice,andtemperatureandpressuresensorstotheBBB.Unliketheexampleappsinthepreviouschapters,theexampleappinthischapterusedpollingtocontinuallymonitorthestateofthehardware.YoualsoexploredusingfiveadditionalmethodsoftheAsyncTaskclassforcommunicationandcontrolbetweenthebackgroundthreadandthemainUIthreadofyourapp.
NowthatyouhavelearnedmanyofthebasicconceptsofhardwareinterfacingwithAndroidusinganapp,itistimetolookatthebiggerpictureandseehowtoturnyourprototypedsolutionintoamorepermanentsolution.
Inthenextchapter,youwilllearnaboutintegratingyoursolutionwiththeAndroidframework,combiningyoursolutionwithothercapesavailablefortheBBB,andotherinterfacesthatyoucanuseforyourfutureinterfacingprojects.
www.it-ebooks.info
Chapter7.WheretoGofromHereInthepreviouschapter,weexaminedhowanAndroidappcaninterfacewithGPIO,I2C,andSPIatthesametimetoprovideacompletehardware-interfacingsolution.WhileyoumightthinkthatthiscoversmostoftheproblemsofhardwareinterfacingunderAndroid,therearestillmanyotherfactorstoconsider.
Inthischapter,wewillcoverthefollowingtopics:
IntegratingyoursolutionintoAndroidCombiningyourhardwarewithotherhardwareExploringtheBBB’sotherinterfaces
www.it-ebooks.info
IntegratingyoursolutionwithAndroidTheBBBoffersawidevarietyofhardwarefeatures,andtheparticularfeaturesthatyouuseinyourprojectswillvaryasyouchangethecapesandoverlaysusedwithinyoursystem.Whilethisgivesyoualotofflexibilityduringprototyping,youmighteventuallyreachapointwhereyouwillfinalizeyourcustomhardwaredesigntoasingle,staticconfigurationanddecidetomakeitapermanentAndroid-basedsolution.
TheexamplesinthisbookmakethedesigndecisionofhavingappsdirectlyaccessthehardwareoftheBBB.Whilethisapproachmakescreatinghardware-interfacingAndroidappssimple,itisnotanidealapproach.Onceyouhaveahardwaredesignthatyoulikeandsoftwarethatproperlyinterfaceswiththehardware,itistimetofullyintegrateyoursolutionwithAndroid.Dependinguponjusthowcomplexyourhardwaresolutionis,youmightendupcreatingcustomkerneldevicedrivers,orevenmodifyingthemanagerswithintheAndroidOSframework!
www.it-ebooks.info
CreatingacustomkernelandDeviceTreeThefirststeptocreatingapermanentAndroidsolutionistoensurethateverythingontheLinuxsideofthesystemisasitshouldbe.Thismeansthatallhardwaresupport(suchasLinuxkerneldriversneededforyourproject)shouldbeenabledinthekernelandconfiguredandallocatedwithinthekernel’sDeviceTree(forpinmuxingandresourceallocation).Ideally,everythingthatyouneedwillbestaticallybuiltdirectlyintothekernelandDeviceTree.Thiseliminatestheneedtoloadoverlaysandkernelmodulesforyoursolutionviaexplicitcommandsexecutedfromwithintheinit.{ro.hardware}.rcfile.
OuradviceforpreparingthekernelspaceaspectsofyourprojectistodeveloptheseitemsfromwithinLinux.TheLinuxenvironmentprovidesfarmoretoolsforkerneldriverdevelopmentanddebugging,andyou’llbeabletoquicklyandeasilybuildstandaloneuserspacebinariesthatinteractwithcustomandexistingkerneldriversviatheopen(),read(),write(),andioctl()functioncalls.Thecode-compile-test-debugcycleofLinuxuserspacebinariescanbeperformedveryquicklybecauseafulldevelopmenttoolchain,includingcompilersanddebuggers,areavailableunderLinux.UnderAndroid,youmustbuildsuchtestbinariesusingtheAndroidNDKonyourdevelopmentmachineandthenuseadbtopushthemtoanAndroidsystemfortest.Thismakesthedevelopmentcyclemuchslowerandmoredifficult.
DevelopingastaticDeviceTreeforyoursolutionrequiresasimilarprocess.TheDeviceTreeanditsoverlaysarecompiledusingthedtctool,whichisavailableunderLinux,butnotAndroid.UsingstandardLinuxkerneldebuggingtechniques,youcandevelopandtroubleshootanoverlaythatmuxesthepinsforyourprojectandallocatesthenecessarykerneldriverstothesepins.Onceyouroverlayisworkingproperly,youcanintegratetheoverlayintotheDeviceTreepermanently.
TipWherecanIlearnmoreaboutLinuxdevelopmentfortheBBB?
TherearemanytutorialsandresourcesavailableonthewebtohelpyoulearnaboutdevelopingLinuxsoftwareandDeviceTreeoverlaysfortheBBB.ThebestresourcethatwecanrecommendtoyouistheseriesofBeagleBonevideotutorialscreatedbyDerekMolloy.ThesetutorialscovertopicssuchasthesetupandconfigurationofaC/C++developmentenvironment,debugging,DeviceTreeoverlaycreation,andtroubleshooting.Theyalsohaveavarietyofcodeandcircuitexamplestohelpgetyoustarted.YoucanwatchthesetutorialsfromtheBeagleBonesectionofDerek’swebsiteathttp://derekmolloy.ie/beaglebone.
www.it-ebooks.info
AddinghardwarecommunicationintothekernelWhileinterfacingdirectlywithGPIOsandtheI2CandSPIbusesisconvenient,itisnotthemostefficientwaytointerfacewithhardware.TheI2CFRAMexampleinChapter4,StoringandRetrievingDatawithI2C,usesthe24c256kerneldrivertohandlelow-leveldetailsofcommunicationwiththeFRAMchip.CanyouimaginehowdifficultitwouldbetoimplementeverysingledetailneededtodirectlyinterfacewiththeFRAMchip?AsidefromhavingtoknoweverydetailofthecommunicationprotocolbetweentheBBBandtheFRAMchip,suchprotocolscanalsorequirestricttimingguaranteesthataredifficultorimpossibletomeetfromuserspace.
Incaseswhereuserspaceinterfacingwithhardwareisinfeasible,usingakerneldriverisnecessary.Kerneldriversencapsulatethedetailsofcommunicatingwithaspecificpieceofhardware.Thissimplifiesyourinterfacingappsbykeepingthesedetailsoutsideyourapp’simplementation.Kerneldriversalsoprovidemuchstrictertimingguaranteeswhencommunicatingwithhardware.Thisisbecausethekernelhasamuchdeeperunderstandingofschedulingkerneldrivercommunicationeventstomeetthenecessarydeadlines.Inuserspace,aprocesscanbesuspendedatanytimeifthekernel’staskschedulerhasdecidedtogiveanotherprocessanopportunitytoexecute.Evenifauserspaceprocesspriorityisgreatlyincreased,itwillstillalwayshavealowerschedulingprioritywhencomparedtothepriorityofkernel-basedactivities.
Creatingakerneldrivercanbequitecomplex,anditisanactivitythatisfaroutsidethescopeofthisbook.However,ifyoufindyourselftryingtomeetverytighttimingrestrictionswhencommunicatingwithapieceofhardware,youmighteventuallyneedtoexplorethedetailsofkerneldevicedriverdevelopment.
TipWherecanIlearnmoreaboutdevelopingkerneldrivers?
ThebestplacetostartlearningaboutkerneldriverdevelopmentisthebookLinuxDeviceDriversbyCorbet,Rubini,andKroah-Hartman.Thisbookprovidescomprehensiveinstructionsthatwalkyouthroughthedevelopmentprocess.Evenbetter,thethirdeditionofthisbookisfreelyavailablefordownloadathttp://lwn.net/Kernel/LDD3.Thethirdeditionwasoriginallypublishedin2005,soitisabitdated,butthecentralconceptspresentedinthebookarestillvalid.
www.it-ebooks.info
IntegratingintoexistingmanagersInChapter5,InterfacingwithHigh-speedSensorsUsingSPI,youinterfacedwithanSPI-basedtemperatureandpressuresensor.Whileyoucommunicatedwiththesensorusingthespidevkerneldriverfromasingleapp,itisfarcleanertohaveamanagercommunicatewiththesensorinstead.Thisway,allappscanrequestaccesstothesensordatabycommunicatingwiththemanager,ratherthanhavingtounderstandthemanydetailsofSPIcommunicationsandcoordinatingaccessamongthemselves.Italsorestrictswhichappshavepermissiontointeractwiththespidevdriver.
Infact,Androidalreadyhasamanager,Android.SensorManager,thatisdesignedtotalkwithhardwaresensorresourcesthatarecommonlyfoundinphonesandtablets.Appscommunicatewiththemanagerbyrequestinganinstanceofthemanagerandthenrequestinganobjectthatrepresentsaparticulartypeofsensor:
PrivatefinalSensorManagermSensorManager;
PrivatefinalSensormPressure;
PrivatefinalSensormTemperature;
PublicSensorActivity(){
mSensorManager=
(SensorManager)getSystemService(SENSOR_SERVICE);mPressure=
mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
mTemperature=
mSensorManager.getDefaultSensor(Sensor.TYPE_TEMPERATURE);
}
IfSensorManagerwasextendedtointerfacewiththeSPIsensorthatyouusedinChapter5,InterfacingwithHigh-speedSensorsUsingSPI,yourappcouldhavecommunicatedwiththesensorviaSensorManagerwithonlyafewlinesofJavacode!Evenbetter,thefilesystempermissionsofthespidevdevicewouldnothavetobesettosuchaninsecurestateforappstocommunicatewiththesensor.Unfortunately,itcanbequitedifficulttointegratenewhardwarefunctionalityintoanexistingmanagerforafewreasons:
YoumustrebuildtheappropriatepiecesofAndroid,whichtypicallyrequiresyoutobuildthecompleteAndroidsourcecodebaseatleastonce.Thisisatime-consuming(andoftenquiteconfusing)processfortheinexperienced.TheAndroidOpenSourceProjectprovidesinstructionsonhowtobuildAndroidfromsourceathttps://source.android.com/source.TheadditionalinterfacelogicforyournewhardwaremustbeaddedintotheHALofthemanagerthatyouareintegratingwith.Whilethisisoftenfairlystraightforward,thepiecesofthemanager’sHALmightbescatteredthroughouttheAndroidcodebase.Thenewhardwaremustcomplywiththeframework’sAPImethodsthatareprovidedbythemanager.UnlessyouarewillingtobreakAPIcompatibilitytoaddadditionalattributesandmethodstoaparticularmanager’sclass,youmustensurethatyourhardwarefitstheexistinginterfacesthatthemanagerprovides.
Whilethisintegrationcanbedifficult,itisoftenverystraightforward.AsAndroidis
www.it-ebooks.info
designedwithtabletsandphonesinmind,anyhardwarethatcanpotentiallybepartofamobiledeviceplatformprobablyalreadyhasanAndroidmanagerdesignedtointerfacewithit.SensorManagerisagoodexampleofthis.Itisdesignedtoprovidesensorinformationfromavarietyofdifferenttypesofsensorhardware.WhileyouwillneedtointegratesomenativecodeintotheSensorManagerHALtospeakwithyourparticularsensor,thecommunicationbetweentheHALandtheSensorManagerAPImethodsisafairlysimpleprocess.
TipWherecanIfindexamplesofintegratingcustomhardwareintoamanager?
TexasInstrumentsprovidesanumberofevaluationmodules(EVMs)forthevariousprocessorsthattheyproduceandsell.Asmanycommercialproductsarebasedupontheseprocessors,TIfreelyprovidesdocumentationandguidanceonhowtocreatecustomHALcodethatintegratescommonhardwareintoAndroidmanagers.ThebestplacetobeginlookingforthesedetailsisthedocumentationofTI’sSitaraAndroidSDK.TheSDK’swebpageislocatedathttp://www.ti.com/tool/androidsdk-sitara.
www.it-ebooks.info
CreatingnewmanagersforcustomhardwareIfyouareintegratingauniquepieceofhardwareintoAndroid,suchastheenvironmentsampleryoucreatedinChapter6,CreatingaCompleteInterfacingSolution,therewillprobablynotbeanystandardAndroidmanagerthatprovidesthenecessaryAPImethodsforappstoproperlycommunicatewiththehardware.Inthiscase,youmightconsidercreatinganewtypeofmanagerthatspecificallydealswiththeuniquehardware.
Anewmanagercanbetailoredspecificallytothehardwarethatitinteractswith.Forexample,theBBBoffersspecializedhardwarethatallowssoftwaretocommunicatewiththecomputersinsidemostmodernvehicles.SuchfunctionalityisnotavailableinstandardAndroidmobiledevices,sonoexiststohandlesuchcommunication.
CreatinganewmanagertohandlethespecificdetailsofusingthisinterfaceandprovidingacustomAPItousethismanagerfreesappsfromhavingtoknowthedetailsofsuchcommunication.However,thisshouldbeconsideredasalastresortforthefollowingreasons:
Thereisnoexistingmanagercodetobuildupon.Atbest,youmightfindasimplemanagerfromwhichtocopythecodeasastartingpoint.TheAndroidbuildprocessmustbemodifiedtoincludebuildingthenewmanagercode.ThisrequiresaddingthesourcefilesforthenewmanagertotheAndroidmakefilesandthenverifyingthattheAndroidframeworkisnotbroken.BuildingAndroidisalargeandcomplextask,somakinganychangestotheprocessshouldnotbeundertakenlightly.YoumustdesignaproperAPItointerfacewiththenewmanager.AsthisnewinterfaceadditionisnotpartofthestandardAndroidAPI,appswillbeunabletoincludetheseAPIcallsunlessyouspecificallyaddthemtoyourEclipseADTinstallation.Youmustalsoaugmentandroid.Manifest.permissiontoincludeoneormorenewpermissionsettingsthatallowanapptoaccessthefunctionalityofthenewmanager.Asanalternative,youcanpiggybackonanexistingpermissionorchoosetoforegousingpermissionsentirely.
Overall,buildingacustommanagerisalotofworkandnotforthefainthearted.TheprocesstouchesmanydifferentpiecesoftheAndroidframeworkandrequiresexpertiseinthefunctionalityofallofthosepieces.IfyoufindyourselfinapositionwhereyouthinkyouabsolutelyneedtocreateanewmanagertohandleyourhardwareproperlyviatheAndroidframework,youshouldconsiderskippingthemanagerandusinganapproachsimilartotheexamplesinthisbook:haveyourappcommunicatedirectlywithyourhardwareusingJNI.
www.it-ebooks.info
CombiningyourprojectwithotherhardwareNowthatyouhaveconsideredhowtobestmodifythesoftwaresideofyourAndroidsystemtofullyintegrateyourcustomhardwareproject,let’slookatthehardwaresideofthings.Breadboardsdoagreatjobofallowingyoutorapidlycreateandchangeyourhardwareprojectdesigns.Hardwareandsoftwareco-designisaniterativeprocess,soyoumightfindyourselfchangingyourhardwaredesignsasyoudevelopinterfacingsoftware.However,carryingaroundabreadboardtoshowoffyourhardwareprojectsisfarfromideal.
www.it-ebooks.info
ConstructingyourownprototypecapesWhynotcreateyourowncustomcapeboardproject?IfyouhavedevelopedtheperfecthardwareprojectforyourAndroidsystem,youshouldconsidermakingitastand-alonecapeboard.Puttingyourprojectintoacapeformfactormakesiteasytointegrateitwithothercapeboards.Italsoallowsyoutomoveyourprojectfromplacetoplacewithoutworryingaboutdisturbingthecircuitoraccidentallydisconnectinganybreadboardwires.
Creatingaprofessionallylaid-outPCBforacustomcapeisaverydifficulttaskfortheinexperienced.However,youcanstillconstructyourowncapeboardwithalittlesolderingandplanning.Adafruit’sProtoCapeKit(productID572)isagreatplacetostart.ProtoCapeislittlemorethanagenericPCBtoholdcomponentsthataresolderedintosemipermanentcircuits.IfyoupurchasedtheBeagleBoneBlackStarterPack(productID703)thatwementionedinChapter1,IntroductiontoAndroidandtheBeagleBoneBlack,youalreadyhaveProtoCape,asitisincludedinthatkit.
ProtoCapeKitforconstructingsemipermanentcapecircuits(source:www.adafruit.com)
NoteProtoCapealsoofferstheimportantadvantageofremovingthebreadboardwiresthatblocktheopeningsoftheP8/P9connectors.Uptofourcapescanbeconnectedsimultaneouslybystackingthecapes(pluggingonecapeintoanotherviapass-throughP8/P9connectorsoneachcape).ThisprovidestheopportunitytocombinedifferentcombinationsofcapestocreateacustomAndroidsystemthatmakesthemostoutofthecustomhardwarethatyouhavedesigned.IfbreadboardwiresareblockingtheP8/P9connections,othercapescannolongerbeinsertedintotheconnectorsandstackedontopoftheBBB.Thismakesitimpossibletouseabreadboarddesignifthetop-mostcapeinthestackdoesn’thaveapass-throughP8/P9connector(likemostLCDcapes).
www.it-ebooks.info
CommercialcapesthatinterfacewithAndroidThereareanumberofpremadeBBBcapesthatareavailableforpurchaseandwillworkwellwithAndroid.4DSystems(http://www.4dsystems.com.au/)providesseveraldifferentreasonablypricedLCDcapesofvarioussizesandresolutionsthatareavailableinbothtouchscreenandnon-touchscreenmodels.BeagleBoardToys(http://www.beagleboardtoys.com/)alsoprovidesawidevarietyofcapes,suchasLCD,audio,andbatterycapes.BycombiningavarietyofdifferentcapeswithyourBBB,youcanturnyourAndroidsystemintoaportableAndroiddevice!
The4DCAPE-70T(800x480pixels,left)and4DCAPE-43T(480x272pixels,right)4DSystemstouchscreenLCDcapes(source:www.4dsystems.com.au)
TipWhataboutUSBdevices?
OtherhardwarecomponentstoconsiderareUSBdevicessuchasaudiodevices,mice,keyboards,Wi-Fiadapters,Bluetoothadapters,gamepads,andwebcams.AstheLinuxkernelcontainsdriversforallofthesedevices,youcaneasilyexperimentwiththemtoextendyourAndroidplatformanddevelopavarietyofcreativeapps.TheBBBonlyhasasingleUSBport,thoughyoucanconnectaUSBhubtothatporttosupportusingmultipleUSBdevicessimultaneously.
PerhapsyoucancreateanAndroid-basedhand-heldgamingconsolewithGPIOcontrollerinputsandanSPI-orI2C-basedaccelerometer.OryoucandesignacustomautomotivecontrolconsolewithatouchscreenLCDthatgathersreal-timedatafromyourvehicle.Youhavecontrolofboththehardwareandsoftwareoftheentireplatform,andtheAndroidappdevelopmenttoolsareexcellentforcreatingUIsquicklyandeasily.Thepossibilitiesareendless!
www.it-ebooks.info
The5VDCbattery(left)andaudioCODEC(right)CircuitCocapes(source:www.beagleboardtoys.com)
www.it-ebooks.info
ExploringtheBBB’sotherinterfacesSofar,wehaveusedtheBBB’sGPIO,SPI,andI2Cfunctionalityforourinterfacing.ThesearenottheonlyinterfacingoptionsthattheBBBoffers,though.ThefollowingareafewotherinterfacesthatyoushouldkeepinmindasyouconsiderAndroidprojectsontheBBB.
www.it-ebooks.info
Programmablereal-timeunitsEmbeddedwithintheBBB’sAM335Xprocessorareapairofprogrammablereal-timeunits(PRUs).Theseunitsareclockedat200MHz,sotheyexecuteprogramsattherateofasingleinstructionevery5ns.ThekernelloadsprogramsintoaPRUandtheninstructsthePRUtobeginexecution.CommunicationbetweenthePRUandthekerneloccursviasharedmemory.TheexecutionofPRUsiscompletelyseparatefromthatofthemainprocessor,sopushingthePRUstotheirlimitwillnothaveaperformanceimpactonthemainprocessorunlesssomecoordinationbetweentheprocessorandaPRUisrequired.
ThereareanumberofGPIOpinsthatcanbemuxedsothattheyfallunderthedirectcontrolofaPRU.ThePRUcancheckorsetthevalueoftheseGPIOsoneachinstruction,meaningthatPRU-controlledGPIOscantogglefastenoughto“bit-bang”implementationsofcomplexdigitalinterfaces(suchasSPIandI2C).Ifyouhaveacustompieceofhardwareandneedtoimplementahigh-speedinterfacetoit,usingoneorbothofthePRUsisanoption.
www.it-ebooks.info
SerialcommunicationsTheBBBoffersfiveserialcommunicationUARTsthatcanbemuxedtothepinsoftheP8andP9connectors.ThereisalsoasixthUART(UART0)thatprovidestheserialdebugoutputviatheFTDIcable.IfyouareusingtheBBBtocontrolalargenumberofserial-controlleddevices,theseUARTsareaveryusefulresource.
Unfortunately,severaloftheseUARTs(UARTs3,4,and5)conflictwithpinsthatareinusebytheLCDinterfacebusthatprovidesvideodatatoLCDcapesandtheinternalHDMIcape.AsmuchofAndroid’sstrengthcomesfromitsuserinterface,disablingtheLCDinterfacetoreceivemoreUARTsisusuallyaverypoortrade-off.IfyoufindthatyouabsolutelyneedtheseUARTsunderAndroid,alloftheUARTscanbeaccessedusingthestandardLinuxkernelserialdriverandexistingNDKlibrariesthataccessthe/dev/TTYS*filesinthefilesystem.
www.it-ebooks.info
ControllerareanetworkTherearetwocontrollerareanetwork(CAN)busesontheBBB.CANisaserialprotocolthatformsoneofthefiveprotocolsusedintheon-boarddiagnostics(OBD)standardforvehicleinterfacing.VehiclediagnosticshardwareandsoftwareuseCANtocommunicatewiththehostcontrollerofmostmodernautomobiles.TheCANdriverintheLinuxkernelexposeseachCANbusasanetworkinterfacethatcanbecommunicatedwithvianetworksocketprogramming.IfyouareinterestedincreatinganAndroiddevicecapableofcommunicatingwithyourvehicle,suchasastatusdisplayinyourcarorahand-helddiagnosticunit,theCANbusisexactlywhatyouneed.
TheCAN0busismuxedtotheP9.19andP9.20pins,whicharethesamepinsusedbytheI2C2bususedbythecapemgrtodiscovertheidentityofanyconnectedcapes.MuxingtheCAN1bustotheP9.24andP9.26pinscanconflictwithI2C1dependinguponhowyouhavemuxedyourI2Cchannels.Ingeneral,youwon’tbeabletouseSPI,I2C,andCANatthesametime.
www.it-ebooks.info
Theanalog-to-digitalconverterTheBBBisn’tlimitedtoonlydigitalcommunications.Italsoprovidesan8-channel,12-bitanalog-to-digitalconverter(ADC)thatallowstheBBBtoreceiveanalogvoltagelevelsbetween0and1.8V.Thisisusefulwheninteractingwithreal-worldsensorsaswellasmanytouchscreendisplays.However,youmustbeverycarefultoensurethatthevoltageappliedtothesepinsneverexceeds1.8voltsoryouwilldamagetheBBB.
PinsP9.32throughP9.40arepermanentlymuxedwithADC,soyouarefreetousethemforyourownprojects.TheCircuitCoand4DSystemsLCDcapeswithtouchscreensupportpresentlyuseADCchannels4-7forthetouchscreen,leavingchannels0-3availableforyouruse.
www.it-ebooks.info
PulsewidthmodulationTheAM3359processorontheBBBhasaPulseWidthModulation(PWM)subsystemthatisusedfortheprecisecontrolofelectricmotors.PWMsetstheperiodanddutycyclewherevoltageissuppliedtoamotortocontrolitsrotationspeed.ThePWMsubsystemcontainsthreeEnhancedHighResolutionPulseWidthModulator(eHRPWM)modulesandanEnhancedQuadratureEncoderPulse(eQEP)module.Altogether,thesefourmodulesprovideeightPWMchannelsfordrivingmotors.
WhilePWMisoftenseenincontrolofindustrialmanufacturingequipment,roboticservomotors,andvariousothermechanicalsystems,itcanalsobeusedtocontrolthebrightnessoflightingandothertasksthatcanmakeuseofthevariabledutycycleofPWMtoemulatepower/brightness/speedlevelsbetweenoffandonatfullintensity.IfyouareinterestedincontrollingmechanicalsystemswiththeAndroidOS,PWMisdefinitelyafeatureoftheBBBthatyoushouldexplorefurther.
www.it-ebooks.info
SummaryInthischapter,welookedathowtofullyintegrateyourcustomhardwareprojectsintoAndroidontheBBB.WediscussedhowyourcustomdevicedriversshouldbebuiltdirectlyintoyourLinuxkernelandhowyourcustomDeviceTreeoverlaysshouldbecompileddirectlyintothemainDeviceTree.Thisavoidshavingtoincludeaspecialmoduleandanoverlaythatloadscommandsinyourinit.{ro.hardware}.rcfile.
WealsoexploredhowtocustomizethestandardAndroidsoftwareframeworktoincludesupportforyourcustomhardwareprojects.ExistingAndroidmanagerscanbeextendedtosupportcustomhardware.
WelookedatmakingyourcustomhardwaredesignsemipermanentusingProtoCape.Thisallowsyoutoavoidaccidentallydisconnectingbreadboardwireswhenmovingyourprojectaround.ItalsoallowsforeasierintegrationwithcommerciallyavailableBBBcapesbyavoidingtheproblemofblockingtheP8/P9connectorswithbreadboardwires.WealsomentionedthattherearemanytypesofUSBdevicesthatarealsosupportedbyAndroidandareworthexploringwhenconsideringnewprojects.
Finally,weexploredsomeoftheotherBBBinterfacesthatwerenotcoveredbytheexamplesintheearlierchaptersofthisbook.TheBBB’sPRUs,serialUARTs,CANbuses,ADCs,andPWMsubsystemsallofferadditionalfunctionalitytointerfacewiththeoutsideworld.
www.it-ebooks.info
IndexA
AdaFruitURL/Shoppingforthehardwareessentials
AdaFruitProtoPlateabout/Breadboardandthemountingplate
AdvancedLinuxSoundArchitecture(ALSA)driver/UnderstandingtheAndroidHALanalog-to-digitalconverter(ADC)
about/Theanalog-to-digitalconverterAndroid
about/LookingbackonAndroidandBeagleBoneBlackdevelopmentURL,forsourcecode/LookingbackonAndroidandBeagleBoneBlackdevelopmentpreparing,forPacktHAL/PreparingAndroidforPacktHALpreparing,forGPIO/PreparingAndroidforGPIOusecustomhardwareprojects,integratingwith/IntegratingyoursolutionwithAndroid
Android,interfacingwithAndroidHAL/UnderstandingtheAndroidHALPacktHAL,installing/InstallingPacktHALAndroidNDK,settingupforPacktHAL/SettinguptheAndroidNDKforPacktHALBeagleBoneBlackpins,multiplexing/MultiplexingtheBBBpins
Android.4DSystemsURL/CommercialcapesthatinterfacewithAndroid
AndroidHALabout/UnderstandingtheAndroidHALAndroidmanagers/Androidmanagersdevelopmentworkflow/TheHALdevelopmentworkflowPacktHAL,workingwith/WorkingwithPacktHAL
Androidinstallation,onBBBabout/InstallingAndroidontheBeagleBoneBlackpremadeAndroidimage,downloading/DownloadingapremadeAndroidimageAndroidmicroSDcard,creatingwithWindows/CreatingyourAndroidmicroSDcardusingWindowsAndroidmicroSDcard,creatingwithLinux/CreatingyourAndroidmicroSDcardusingLinux
Androidmanagersabout/Androidmanagers
AndroidmicroSDcardcreating,Windowsused/CreatingyourAndroidmicroSDcardusingWindows
www.it-ebooks.info
creating,Linuxused/CreatingyourAndroidmicroSDcardusingLinuxAndroidNativeDevelopmentKit(NDK)
settingup,forPacktHAL/SettinguptheAndroidNDKforPacktHALheader,addingunderLinux/AddingtheheadertotheNDKunderLinuxheader,addingunderWindows/AddingtheheadertotheNDKunderWindows
AndroidOpenSourceProject(AOSP)KitKatAndroid/InstallingAndroidontheBeagleBoneBlackApplicationNotResponding(ANR)/UnderstandingtheAsyncTaskclassAsyncTask
about/Understandinghardwarepollinginanappusing,withlong-livedthreads/UsingAsyncTaskwithlong-livedthreadsisCancelled()method/UsingAsyncTaskwithlong-livedthreadscancel()method/UsingAsyncTaskwithlong-livedthreadsonCancelled()method/UsingAsyncTaskwithlong-livedthreadspublishProgress()method/UsingAsyncTaskwithlong-livedthreadsdoPublishProgress()method/UsingAsyncTaskwithlong-livedthreads
AsyncTaskmethodsdoInBackground()/LearningthedetailsoftheHardwareTaskclassexecute()/LearningthedetailsoftheHardwareTaskclassonPreExecute()/LearningthedetailsoftheHardwareTaskclassonPostExecute()/LearningthedetailsoftheHardwareTaskclass
www.it-ebooks.info
BBB-PACKTPUB-00A0.dtbofile/PreparingAndroidforGPIOuseBBBAndroid
URL/InstallingAndroidontheBeagleBoneBlackabout/InstallingAndroidontheBeagleBoneBlack
BBBAndroidimageabout/InstallingAndroidontheBeagleBoneBlack
BeagleBoardToysURL/CommercialcapesthatinterfacewithAndroid
BeagleBoneBlack(BBB)about/LookingbackonAndroidandBeagleBoneBlackdevelopmenthardware/Shoppingforthehardwareessentialshardwarecomponents/Learningaboutthehardwareyou’llinterfacewithAndroid,installing/InstallingAndroidontheBeagleBoneBlackbootingoptions/InstallingAndroidontheBeagleBoneBlackinterfaces/ExploringtheBBB’sotherinterfaces
BeagleBoneBlackpinsmultiplexing/MultiplexingtheBBBpinskernelDeviceTree/ThekernelDeviceTreeandcapemgrcapemanager(capemgr)/ThekernelDeviceTreeandcapemgrcape,defining/Definingacape
BinderIPC/UnderstandingtheAndroidHALbootingoptions,BeagleBoneBlack(BBB)
onboardeMMC/InstallingAndroidontheBeagleBoneBlackmicroSDcard/InstallingAndroidontheBeagleBoneBlackoverthenetwork/InstallingAndroidontheBeagleBoneBlack
breadboard,BeagleBoneBlack(BBB)about/Breadboardandthemountingplate
www.it-ebooks.info
Ccape
defining/Definingacapecapemanager(capemgr)
about/ThekernelDeviceTreeandcapemgrservices/ThekernelDeviceTreeandcapemgr
CapeManager(capemgr)functionalityabout/InstallingAndroidontheBeagleBoneBlack
chipselect(CS)signal/UnderstandingSPICircuitCo/LookingbackonAndroidandBeagleBoneBlackdevelopmentcompleteexampleapp
about/Exploringthecompleteexampleappuserinterface/Theapp’suserinterfacehardwarepolling/UnderstandinghardwarepollinginanappAsyncTask,usingwithlong-livedthreads/UsingAsyncTaskwithlong-livedthreadsHardwareTaskclass,using/UsingtheHardwareTaskclass
completeinterfacecircuitbuilding/Buildingthecompleteinterfacecircuit
controllerareanetwork(CAN)about/Controllerareanetwork
customappcreating,includingPacktHAL/CreatinganewappprojectthatusesPacktHALPacktHAL,buildingunderWindows/BuildingPacktHALunderWindowsPacktHAL,buildingunderLinux/BuildingPacktHALunderLinux
customhardwareprojectsintegration,withAndroidperforming/IntegratingyoursolutionwithAndroidcustomkernel,creating/CreatingacustomkernelandDeviceTreeDeviceTree,creating/CreatingacustomkernelandDeviceTreehardwarecommunication,addingintokernel/Addinghardwarecommunicationintothekernelexistingmanagers,integratinginto/Integratingintoexistingmanagersnewmanagers,creating/Creatingnewmanagersforcustomhardwarehardware/Combiningyourprojectwithotherhardwarecustomprototypecapes,constructing/Constructingyourownprototypecapescommercialcapes/CommercialcapesthatinterfacewithAndroid
customkernelcreating/CreatingacustomkernelandDeviceTree
www.it-ebooks.info
Ddevelopmentworkflow,AndroidHAL
about/TheHALdevelopmentworkflowDeviceTree
creating/CreatingacustomkernelandDeviceTreedirectorystructure,PacktHAL
about/ThePacktHALdirectorystructure
www.it-ebooks.info
EEclipseAndroidDevelopmentTools(ADT)/LookingbackonAndroidandBeagleBoneBlackdevelopmentelectricallyerasableprogrammableread-onlymemory(EEPROM)chip/DefiningacapeEnhancedHighResolutionPulseWidthModulatormodule(eHRPWM)
about/PulsewidthmodulationEnhancedQuadratureEncoderPulse(eQEP)module
about/Pulsewidthmodulationevaluationmodules(EVMs)/Integratingintoexistingmanagers
www.it-ebooks.info
FfileI/Omethod
about/GPIOaccessmethodsunderAndroidpros/ProsandconsofthefileI/Omethodcons/ProsandconsofthefileI/Omethod
FRAMchip/AddinghardwarecommunicationintothekernelFTDIcable,BeagleBoneBlack(BBB)
about/TheFTDIcableFutureTechnologyDevicesInternational(FTDI)cable/Shoppingforthehardwareessentials
www.it-ebooks.info
GGPIO
about/UnderstandingGPIOsvoltagelevels/NutsandboltsofGPIOon/highstate/NutsandboltsofGPIOoff/lowstate/NutsandboltsofGPIOaccessmethods,underAndroid/GPIOaccessmethodsunderAndroidAndroid,preparingfor/PreparingAndroidforGPIOuse
GPIO-interfacingcircuitbuilding/BuildingaGPIO-interfacingcircuit,ConstructingthecircuitP9.11pin/ConstructingthecircuitP9.13pin/Constructingthecircuitwiring,checking/Checkingyourwiring
GPIOaccessmethodsabout/GPIOaccessmethodsunderAndroidfileI/Omethod/GPIOaccessmethodsunderAndroid,ProsandconsofthefileI/Omethodmemory-mappingmethod/GPIOaccessmethodsunderAndroid,Prosandconsofthememory-mappingmethod
GPIOexampleappabout/ExploringtheGPIOexampleappinstalling,underWindows/InstallingtheappandsourceunderWindowssource,installingunderWindows/InstallingtheappandsourceunderWindowsinstalling,underLinux/InstallingtheappandsourceunderLinuxsource,installingunderLinux/InstallingtheappandsourceunderLinuxuserinterface/Theapp’suserinterfacePacktHALfunctions,calling/CallingthePacktHALfunctionsPacktHALGPIOfunctions,using/UsingthePacktHALGPIOfunctions
www.it-ebooks.info
Hhardware,BeagleBoneBlack(BBB)
about/ShoppingforthehardwareessentialsFTDIcable/TheFTDIcablepowersupply/Powersupplybreadboard/Breadboardandthemountingplatemountingplate/BreadboardandthemountingplatemicroSDcards/MicroSDcards
hardwarecomponents,interfacingwithabout/Learningaboutthehardwareyou’llinterfacewithgeneral-purposecomponents/General-purposecomponentsAdaFruitmemorybreakoutboard/TheAdaFruitmemorybreakoutboardAdaFruitsensorbreakoutboard/TheAdaFruitsensorbreakoutboardbreakoutboards,preparing/Preparingthebreakoutboards
www.it-ebooks.info
II2C
about/UnderstandingI2Cdevices/DevicesthatuseI2Cmultiplexing,onBeagleBoneBlack/MultiplexingforI2ContheBBB
I2C-interfacingcircuitbuilding/BuildinganI2C-interfacingcircuitFRAM,connecting/ConnectingtheFRAMFRAMconnection,checkingwithI2C-tools/CheckingtheFRAMconnectionwithI2Ctools
I2Cdevicesrepresenting,inLinuxkernel/RepresentingI2CdevicesintheLinuxkernelAndroid,preparingforFRAM/PreparingAndroidforFRAMuse
I2CFRAMexampleappabout/ExploringtheI2CFRAMexampleappuserinterface/Theapp’suserinterfacePacktHALFRAMfunctions,calling/CallingthePacktHALFRAMfunctionsAsyncTaskclass,using/UnderstandingtheAsyncTaskclassHardwareTaskclass,using/LearningthedetailsoftheHardwareTaskclass
installation,PacktHALabout/InstallingPacktHALPacktHAL,preparingunderLinux/PreparingPacktHALunderLinuxPacktHAL,preparingunderWindows/PreparingPacktHALunderWindowsPacktHALdirectorystructure/ThePacktHALdirectorystructureAndroid,preparingforPacktHAL/PreparingAndroidforPacktHALPacktHALfiles,pushingunderLinux/PushingPacktHALfilesunderLinuxPacktHALfiles,pushingunderWindows/PushingPacktHALfilesunderWindows
interfaces,BeagleBoneBlack(BBB)programmablereal-timeunits(PRUs)/Programmablereal-timeunitsserialcommunications/Serialcommunicationscontrollerareanetwork(CAN)/Controllerareanetworkanalog-to-digitalconverter(ADC)/Theanalog-to-digitalconverterPulseWidthModulation(PWM)subsystem/Pulsewidthmodulation
www.it-ebooks.info
JJavaNativeInterface(JNI)
about/UnderstandingtheJavaNativeInterface
www.it-ebooks.info
KkernelDeviceTree
about/ThekernelDeviceTreeandcapemgrkerneldrivers/Addinghardwarecommunicationintothekernel
www.it-ebooks.info
Llandgridarray(LGA)/BuildinganSPIinterfacecircuitLinux
used,forcreatingAndroidmicroSDcard/CreatingyourAndroidmicroSDcardusingLinux
LinuxkernelI2Cdevices,representing/RepresentingI2CdevicesintheLinuxkernelSPIdevices,representing/RepresentingSPIdevicesintheLinuxkernel
www.it-ebooks.info
Mmasterin,slaveout(MISO)signal/UnderstandingSPImasterout,slavein(MOSI)signal/UnderstandingSPImemory-mappingmethod
about/GPIOaccessmethodsunderAndroidpros/Prosandconsofthememory-mappingmethodcons/Prosandconsofthememory-mappingmethod
microSDcards,BeagleBoneBlack(BBB)about/MicroSDcards
mountingplate,BeagleBoneBlack(BBB)about/Breadboardandthemountingplate
multiplexing,forI2ConBeagleBoneBlackabout/MultiplexingforI2ContheBBBI2C,connectingviaP9header/ConnectingtoI2CviatheP9headerperforming/MultiplexingforI2C
www.it-ebooks.info
PPacktHAL
about/TheHALdevelopmentworkflowworkingwith/WorkingwithPacktHALinstallation/InstallingPacktHALpreparing,underLinux/PreparingPacktHALunderLinuxpreparing,underWindows/PreparingPacktHALunderWindowsdirectorystructure/ThePacktHALdirectorystructureAndroid,preparingfor/PreparingAndroidforPacktHALfiles,pushingunderLinux/PushingPacktHALfilesunderLinuxfiles,pushingunderWindows/PushingPacktHALfilesunderWindows
PacktHAL,addingtoappsabout/IncludingPacktHALwithinyourappsJavaNativeInterface/UnderstandingtheJavaNativeInterface
PacktHALFRAMfunctionsopenFRAM()function/CallingthePacktHALFRAMfunctionscloseFRAM()function/CallingthePacktHALFRAMfunctionsreadFRAM()function/CallingthePacktHALFRAMfunctionswriteFRAM()function/CallingthePacktHALFRAMfunctions
PacktHALfunctionscalling/CallingthePacktHALfunctions
PacktHALGPIOfunctionsopenGPIO()function/UsingthePacktHALGPIOfunctionscloseGPIO()function/UsingthePacktHALGPIOfunctionsreadGPIO()function/UsingthePacktHALGPIOfunctionswriteGPIO()method/UsingthePacktHALGPIOfunctionsonClickButtonLightOn()method/UsingthePacktHALGPIOfunctionsonClickButtonLightOff()method/UsingthePacktHALGPIOfunctions
PacktHALsensorfunctionsopenSensor()function/CallingthePacktHALsensorfunctionscloseSensor()function/CallingthePacktHALsensorfunctionsgetSensorTemperature()function/CallingthePacktHALsensorfunctionsgetSensorPressure()function/CallingthePacktHALsensorfunctions
pausedstate/Understandinghardwarepollinginanapppowersupply,BeagleBoneBlack(BBB)
about/PowersupplypremadeAndroidimage
downloading/DownloadingapremadeAndroidimageprogrammablereal-timeunits(PRUs)
about/Programmablereal-timeunitsPulseWidthModulation(PWM)
about/Pulsewidthmodulation
www.it-ebooks.info
Sserialclock(SCLK)signal/UnderstandingSPIserialcommunications
about/Serialcommunicationsslaveselect(SS)signal/UnderstandingSPIsmalloutlinepackage(SOP)/BuildinganI2C-interfacingcircuitSparkFun
URL/ConstructingthecircuitSPI
about/UnderstandingSPIserialclock(SCLK)signal/UnderstandingSPImasterout,slavein(MOSI)signal/UnderstandingSPImasterin,slaveout(MISO)signal/UnderstandingSPIslaveselect(SS)signal/UnderstandingSPIchipselect(CS)signal/UnderstandingSPImultiplexing,forBeagleBoneBlack/MultiplexingforSPIontheBBB
SPIdevicesrepresenting,inLinux/RepresentingSPIdevicesintheLinuxkernel
SPIinterfacecircuitbuilding/BuildinganSPIinterfacecircuitsensor,connecting/Connectingthesensor
SPIsensorAndroid,preparingfor/PreparingAndroidforSPIsensoruse
SPIsensorexampleappabout/ExploringtheSPIsensorexampleappuserinterface/Theapp’suserinterfacePacktHALsensorfunctions,calling/CallingthePacktHALsensorfunctionsHardwareTaskclass,using/UsingtheHardwareTaskclass
www.it-ebooks.info
WWin32DiskImagerapplication
URL/CreatingyourAndroidmicroSDcardusingWindowsWindows
used,forcreatingAndroidmicroSDcard/CreatingyourAndroidmicroSDcardusingWindows
WinRARURL/CreatingyourAndroidmicroSDcardusingWindows
www.it-ebooks.info