Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi...
Transcript of Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi...
RaspberryPiBlueprints
TableofContents
RaspberryPiBlueprints
Credits
AbouttheAuthor
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Downloadingthecolorimagesofthisbook
Errata
Piracy
Questions
1.RaspberryPiPirateRadio
Whatyouwillneed
SettingupthePi
ChoosingaLinuxdistribution
WritinganSDcard
Windows
LinuxandMacOS
BootingthePiforthefirsttime
Networkscanning
ConnectingtothePiviaSSH
CommonLinuxcommands
Theinitialsetup
Settingupthepirateradio
TransferringMP3filestothePi
Scriptingamediaplayer
CallingPiFMfromPython
SearchingforMP3files
Gettinginputfromacommandline
Queuingthemediafilestobeplayed
Usingthemediaplayerscript
Summary
2.PortableSpeakerSystem
Whatyouwillneed
Toolsyouwillneed
SettingupLogitechMediaServer
SettingupthePiasaSqueezeboxclient
SettingupWi-FionthePi
Runningsqueezeliteasadaemon
Buildingtheelectronics
Theamplifiercircuit
Runningthespeakersystemonbatterypower
Buildingtheenclosureforthespeakersystem
RunningLogitechMediaServeronthePi
CreatingabackupimageofanSDcard
AutomountingaUSBstoragedevice
InstallingLogitechMediaServer
SettingupthePiasaWi-Fiaccesspoint
Summary
3.MiniRetroArcadeCabinet
Requirements
Settinguptheinputelectronics
Buildingthecabinet
SettingupPiPlay
UsingthebuttonsandjoystickwithPiPlay
Summary
4.GPS-enabledTime-lapseRecorder
Whatyouwillneed
Settingupthehardware
Thecameraboard
ConnectingthecameramoduletothePi
SettinguptheRaspberryPicamera
TheGPSmodule
Settingupthecapturesoftware
Usingthecaptures
Creatingatime-lapsevideo
ExportingGPSdataasCSV
Summary
5.HomeTheaterPC
Whatyouwillneed
SettingupOpenELEC
Thefirstbootandinitialsetup
ConnectingthePitoawirelessnetwork
UploadingmediafilestothePi
Windows
Linux
ShuttingdownthePi
SettinguptheLCD
Settinguptheswitches
Finalassembly
Summary
6.OutdoorWeatherStation
Whatyouwillneed
ReverseengineeringtheMaplinsensors
Understandingthesensors
Wiring
SettingupyourArduino
Settinguptheremainingsensors
DHT11/22
BMP180
Theweatherstationwebapplication
DeployingtheapponthePi
Takingreadingsfromthesensors
Assemblingtheweatherstation
Usingthewebapplication
Summary
7.HomeSecuritySystem
Whatyouwillneed
Thesecuritysystemstructure
Designingyoursecuritysystem
Webapplications
Deployingourapplication
Configuringsensorsandalarms
Interfacingsensors
ThePIRmotionsensors
Magneticdoorsensors
TheRFnetwork
SettinguptheRaspberryPi
SettingupArduino
Troubleshooting
Summary
8.Remote-operatedRoboticArm
Whatyouwillneed
Driveelectronics
Settingupthecamera
Deployingwebapplications
Thearmandchassisconstruction
Calibration
Chassismotors
Arm2andhandservos
Thearm1servos
Troubleshooting
Thevideostreamhasasubstantialdelay
Theservosmakealoudhummingnoise
Controloftherobotislost
Thearmjumpstonewpositions
Summary
9.MagicMirror
Whatyouwillneed
Toolsyouwillneed
Theory
Thewebapplication
Developinganewwidget
ThePythoncode
TheJinjapagetemplate
TheJavaScriptcode
ThePisetup
Rotatingthedisplay
Deployingthewebapplication
SettingupChromium
Enclosureconstruction
Buildingthemirrorwithoutanenclosure
ThePienclosure
Configuration
Widgets
Includedwidgets
Exampleconfigurations
bbc_ticker.conf
clock.conf
Styles
Troubleshooting
Thewebapplicationfailswiththe500InternalServerError
Thedisplaydoesnotwork
Summary
10.BottleXylophone
Whatyouwillneed
Assemblinganotebottle
Electronics
Thewebapplication
Configuration
Tuning
Testing
Troubleshooting
Notesaremissed
Servosdonotmovecorrectly
Summary
Index
RaspberryPiBlueprints
RaspberryPiBlueprintsCopyright©2015PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:March2015
Productionreference:1200315
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78439-290-1
www.packtpub.com
CreditsAuthor
DanNixon
Reviewers
SoumenChandraLaha
MaryalaSrinivas
CommissioningEditor
AkramHussain
AcquisitionEditor
MeetaRajani
ContentDevelopmentEditor
ShubhangiDhamgaye
TechnicalEditor
SiddhiRane
CopyEditor
NehaVyas
ProjectCoordinator
HarshalVed
Proofreaders
SimranBhogal
MariaGould
PaulHindle
Indexer
MariammalChettiyar
ProductionCoordinator
ManuJoseph
CoverWork
ManuJoseph
AbouttheAuthorDanNixonlivesinEnglandandisa20-yearoldsoftwareengineeringstudentwhoiscurrentlystudyingatNewcastleUniversityandisinhisthirdyear.Hehaslonghadaninterestinelectronicsandembeddedcomputingprojects.
Previously,Danhasworkedona360-degreecamerasystemfortheRaspberryPiandthisiswherehisinterestintheplatformstarted.
Currently,heisonayear-longworkplacementandisworkingonneutrondataanalysissoftwareattheRutherfordAppletonLaboratoryinOxford,UK.
Iwouldliketothankmymotherandfatherfortheirsupportwhilewritingthisbook.IwouldalsoliketothankthemembersofMakerSpace,Newcastle,forprovidingthefacilitiestoprototypetheprojectsandallowingmetousesomeoftheirprojectsinthisbook.
AbouttheReviewersSoumenChandraLahahasbeenworkingasaseniorembeddeddesignengineeratWineYardTechnologiessince2008.Hestartedhiscareerasaqualitycontrolengineerandgraduallybecameanembeddeddesignengineer.Hehasbeenworkinginthefieldofembeddedsystemsandhasindustryexperienceofmorethan6yearsinvariousdomains,includingautomotive,consumerelectronics,healthcare,andsoon.Hehashands-onexperienceinvariousmicrocontrollersandmicroprocessors,suchas8051,PIC,AVR,PSoC,ARMCortex,ARM7,ARM9,ARM11,andtheTI-DSPmicrocontroller.HehasdevelopmentexposuretoembeddedLinuxandWindowsCEandknowshowtoportreal-timeoperatingsystemsonvariousARMplatforms.
Heisanelectronichobbyistanddesignerandbelievesincontinuouslearning.Hisstrengthslieindeveloping,maintaining,integrating,anddebugginglargesizedCcodeofapplicationsandsystem-levelembeddedsoftwaredesigns.
MaryalaSrinivasisthefounderandmanagingdirectorofWineYardTechnologies,whichwasfoundedin2006.Hehasover10yearsofexperienceinthefieldofadvancedembeddedsystemsdesignanddevelopment.Heisapassionateandenthusiasticentrepreneur.HispassiontobecomeanentrepreneurmadehimrejectagreatjobofferfromDelhiMetroRailCorporation(DMRC),wherehewastoworkforthesignalingdepartmentintheR&DDivision.HeisassociatedwithJuniorChamberInternational,IndiaandHyderabadDirectors/CEO’sForum(HDCF).HereceivedtheIndiraGandhiSadbhavanaAwardin2012foroutstandingservices,achievements,andcontributionstothenationinthefieldofscienceandtechnology.
Manyofhisarticlesarepublishedinnationalandinternationaljournalsandtechnicalmagazines.HehasaddressedseveraltechnicalconferencesandseminarsinthefieldofembeddedsystemsandRTOSdesign.HewasrecognizedasthestarspeakeratEFYDesignEngineers’Conference,heldatNewDelhiinMarch2012.ManyofthefacultymembersfromuniversitiessuchasNITs,JNTU,AU,andOUandotherprivateengineeringcollegesbenefitedimmenselybythetechnologytalenttransformationworkshopsconductedbyhimatWineYardTechnologies.TheWineYardteamledbyhimhasachievedmanymilestones.Morethan100,000studentsandover400professionals,includingtheteachingfacultyfromuniversitiesandmanyworkingengineers,haveimmenselybenefitedfromthetalenttransformationprograms.
www.PacktPub.com
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.
Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser
FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.
PrefaceTheRaspberryPiisasmallformfactor,singleboard,ARM-basedcomputer.ItiscapableofrunningonmanydesktopapplicationsthatcanberunonastandardLinuxcomputer.WhilethePiisonlyslightlylargerthanacreditcard,itusesverylittlepower.Assuch,ithasbecomeverypopularamongthehackerandmakercommunity,whichusesthePitointegratemorecomputingpowerintheirprojects.
ThePiisveryeasytosetupandinlessthan20minutes,youcanrunitonamodifiedversionofpopular,Linux-basedoperatingsystems.ItwillfunctionjustlikeyouwouldexpectadesktopPCto.Thankstoitssmallformfactor,manypeoplehaveuseditasanalternativetoatraditionalPCforfastaccesstoapplicationsandtheInternet.SincethePidrawsverylittlepower,itcanbeleftrunning.
WherethePireallyexcelsisthatitbringsmorecomputingpowertohardwareandelectronicsprojects.ThisismadepossiblebyawiderangeofinterfacesonthePithataretypicallynotfoundonconventionalcomputers.
ThishasledtoariseinnewprojectsthataremadeusingthePi,whichotherwisewouldhavebeenconsiderablymoredifficultorexpensivetomake.
WhatthisbookcoversChapter1,RaspberryPiPirateRadio,introducesthePiandgivesanoverviewofitssetupandconfigurationprocedureandsomefundamentalLinuxconcepts.ThischapterthendemonstratesthebasicuseoftheGPIOheaderandPythonscripting.
Chapter2,PortableSpeakerSystem,exploreshowtousethePiasaportable,battery-poweredspeakersystemwithaself-containedmediaserverthatcanbeusedwithoutanytiestoapowersupplyorhomenetwork.
Chapter3,MiniRetroArcadeCabinet,demonstrateshowthePicanbeusedtocreateaminiarcadecabinetcompletewithatraditionaljoystickandbuttoncontrolsandhowitcanbeusedtoplayarangeofclassicarcadeandconsolegames.
Chapter4,GPS-enabledTime-lapseRecorder,covershowtousethePiasatimelapserecorderthatcanalsocapturethelocationofeachimageandtriggertheimagecapturebasedonthecurrentpositionofanddistancetraveledbythecamera.
Chapter5,HomeTheaterPC,exploresthewayinwhichthePicanbeusedasahometheaterPCusingthepopularXBMCmediacentersoftwareandacustom,purpose-builtenclosure.
Chapter6,OutdoorWeatherStation,delvesintothetopicofinterfacinghardwaretothePiusingintermediatedevices,inthiscase,Arduino.WealsotakealookatPythonwebapplicationsrunningonthePi.
Chapter7,HomeSecuritySystem,exploreshowtousethePiasahubforawirelessnetworkofsensorsandhowthisdatacanbeusedanddisplayedonawebapplication.
Chapter8,Remote-operatedRoboticArm,focusesonhowtousethePitocontrolandmonitordevicesremotelyintheformofaroboticarmthatcanbecontrolledthroughawebapplication.
Chapter9,MagicMirror,expandsyourknowledgeofwoodworkinganddesigning,whichwillprovetobeimportantskillsforanyfurtherprojectsthatyoudointhefieldofelectronicsandphysicalcomputing.
Chapter10,BottleXylophone,covershowthePi,severalservos,andsomeemptybottlescanbeturnedintoamusicalinstrumentdrivenbyMIDIfiles.
WhatyouneedforthisbookThisbookassumesthatyouarefamiliarwiththebasicsoftheRaspberryPiandLinux.MostofthecodeinthisbookisinPythonwithsomeC++.However,thesourcecodeforeachoftheprojectsisavailablealongsidethebookthatcanbeusedstraightonthePi.
Severaloftheprojectswillalsodealwithsomebasicelectronics,andassuch,somebasictoolswillbeneededforthecompletionofsomeprojects.However,notethatatthestartofeachchapter,theproceduretobuildtheelectronicssideoftheprojectisexplainedstepbystep.
Someprojectswillalsorequireaccesstowoodworkingtoolsinordertoconstructcasesandenclosures.Usually,youwillrequirejustthecommon“gardenshed”tools.However,thereisinformationintherelevantchaptersonwhatyoucandoifnothavingthecorrecttoolscausesanissueintherelevantchapters.
WhothisbookisforThisbookisaimedatthosearejustgettingstartedwiththeRaspberryPi,alreadyhaveafewsmallprojectsundertheirbelt,andarelookingtogetintotheworldofhardwareandphysicalcomputingprojects.
ConventionsInthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnamesdummyURLsanduserinputareshownasfollows:“Wherepath/to/raspbian_image.imgistheextractedimagefileandsdXisthepathtoyourSDcard.”
Ablockofcodeissetasfollows:
#!/bin/bash
sleep20
cd/home/pi
pythonplayer.py-dmusic--random-f99.9&
Anycommand-lineinputoroutputiswrittenasfollows:
ffmpeg-ifile.mp3-fs16le-ar22.05k-ac2-|sudo./pifm-freq22050
stereo
Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,forexample,inmenusordialogboxes,appearinthetextlikethis:“Filescanbeuploadedbyright-clickingonthemandselectingUpload.”
NoteWarningsorimportantnotesappearinaboxlikethis.
TipTipsandtricksappearlikethis.
ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.
Tosendusgeneralfeedback,simplye-mail<[email protected]>,andmentionthebook’stitleinthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.
CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.
DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.comforallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
DownloadingthecolorimagesofthisbookWealsoprovideyouwithaPDFfilethathascolorimagesofthescreenshots/diagramsusedinthisbook.Thecolorimageswillhelpyoubetterunderstandthechangesintheoutput.Youcandownloadthisfilefromhttps://www.packtpub.com/sites/default/files/downloads/2901OS_ColoredImages.pdf.
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.
PiracyPiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.
QuestionsIfyouhaveaproblemwithanyaspectofthisbook,youcancontactusat<[email protected]>,andwewilldoourbesttoaddresstheproblem.
Chapter1.RaspberryPiPirateRadioInthischapter,wewilltakeaquicklookattheRaspberryPihardwareandsomeofthesoftwarethatwillbeusedbothinthisprojectandthemajorityofothersthroughoutthisbook.
AsthePiwasbasedonhardwarethatwastobeincludedinembeddedorportableelectronics(suchassmartphonesandtablets),ithasafewextrahardwarefeaturesthatarenotfoundonatypicaldesktoporlaptopPC,oneofwhichistheGeneralPurposeInputandOutput(GPIO)header.Thisisasetofpins(26onthemodelAandB,and40onthemodelB+)thatallowsyoutocommunicatewithexternalhardwaresuchasGPSsensors,accelerometers,andmotorsthroughprogramminglanguagessuchasPython,C,andC++.Whenwegetfurtherinthischapter,wewilltakealookatalittletrickthatcanbedonetoturnoneofthesepinsintoanFMradiotransmitter.
WhatyouwillneedYouwillneedthefollowing:
TheRaspberryPiandpowersupplyAnSDcardwithatleast4GBmemory(16GBisrecommendedasitholdsagoodamountofmusic)AthickwireorFMradioantennaMaletomale0.1inchpinjumperwires
SettingupthePiInordertogetthePiupandrunning,thebareminimumyouwillneedisaUSBpowersupply,microUSBcable,anEthernetcabletoconnectthePitoyournetwork,andanSDcardthathasatleast4GBmemory.Although,lateron,someprojectswillneedalargercapacityoftheSDcard.
Whileamonitor,mouse,andkeyboardcanalsobeusedforalotoftheprojectsinthisbook,theyarenotactuallyrequiredassumingthatyouhaveanetworkthatrunsaDHCPserver,whichyoucanconnectwiththePiinordertosetitupoverSSH.
ItisworthmentioningnowthatforaUSB-powereddevice,thePiisquitepower-hungry(drawingaround600-700mA),therefore,whilethePicanbepoweredfromaUSBport,whichisusuallyratedforaround500mA,itisrecommendedthatyouuseamainspoweredadapter.Withoutthis,thePicanbecomeunstablewhenadditionaldevicesareconnectedthatdrawmorepower,forexample,aUSBWi-Fidongleorcameramodule.
ChoosingaLinuxdistributionThereareawiderangeofLinuxdistributionsavailableforthePi,someofwhichareverygeneralpurposewhileothersarebuiltforspecificpurposes(acoupleofwhichwillbeusedinthelaterprojectsofthischapter).Fornow,wewillusethemoststandarddistribution,Raspbian,whichasthenamesuggestsisbasedontheDebiandistribution.
NoteTheRaspberryPidownloadspage(http://www.raspberrypi.org/downloads)hasagoodselectionofgeneralpurposedistributions.
AnotherrelativelynewdistributionthatisworthmentioningisMinibian(http://minibianpi.wordpress.com),adistributionbasedonRaspbian,whichhasthemajorityofitsdefaultsoftwareremoved.Whilethismaynotseemthathelpful,itmeansthatthePibootsinauseableOSinaround25secondsandsavestheSDcardspace.ThistypeofOSismoresuitedtoaprojectthathasfinishedbeingdevelopedandisgoingintoamorenaturalusageenvironment.YouusuallywouldnotexpectaWi-Firoutertotake3minutestoboot,sowhyshouldyourPi-basedInternetradio?
WritinganSDcardWhenyouhavealltherelevanthardware,headovertohttp://www.raspberrypi.org/downloadsanddownloadtheZIParchiveforRaspbianandextractit.
Thenextstepsvarydependingonyouroperatingsystem.
WindowsWindowsdoesnotnativelyincludeatoolusedtowritediskimages,therefore,theWin32DiskImager(http://sourceforge.net/projects/win32diskimager)applicationisusedtowriteimagestoanSDcard.
First,gotothedownloadlinkmentionedintheprecedingparagraph,download,andinstallWin32DiskImager.Aswritingimagestodrivesrequiresadministratorpermissions,youwillneedtorunWin32DiskImagerbyright-clickingonitsentryintheStartmenu,andselectingRunasadministrator:
Next,selectthe.imgfilethatwasextractedfromtheRaspbianZIPfileusingthefoldericonunderImageFileandthedriveletteroftheSDcardfromthedrop-downbox:
NoteEnsurethatthecorrectdriveletterisselected,andtheSDcarddoesnotcontainanydatathathasnotbeenbackedup,asthisoperationwilldestroyallofthedataalreadypresentinthecard.
Finally,clickonWritetowritetheimagetotheSDcard.
LinuxandMacOSUnixandUnix-likeoperatingsystemsalreadyhaveatooltoreadandwriteimagestoexternalstorage—dd.
First,youwillneedtofindthepathforyourSDcard.Theeasiestwaytodothisistousetheudevmanagementtool,udevadm,tomonitortheudevlog,whichlogsactivityfromvariousdevicesonthesystem,includingtheSDcardbeinginsertedandwillallowyoutoseethedevicepaththatwasassignedtoitandthepartitionsalreadyexistingonit.Thiscanbedonebyrunningthefollowingcommand:
udevadmmonitor--udev
Then,inserttheSDcard,atwhichpoint,youshouldseeasetoflogmessagessimilartotheonesshowninthefollowingscreenshot:
Here,theimportantinformationcanbeseenonthelastthreelines,whichtellsusthatin
thiscase,thepathfortheentirecardis/dev/sdb,withtwopartitionsat/dev/sdb1and/dev/sdb2.
WemustnowensurethatnoneofthesepartitionsontheSDcardarecurrentlymounted,assomedesktopmanagers(suchasGNOME,thedefaultdesktopmanageronUbuntu)willtrytoautomaticallymountpartitionswhentheyaredetected.
Todothis,wewillrunthefollowingcommandforeverypartition(thatis,inmycase,/dev/sdb1and/dev/sdb2),wherePATHisthepathtothepartition:
umountPATH
Ifthepartitionwasmounted,youwillnotseeanyoutputfromthecommand;however,ifthepartitionwasnotmounted,youwillgetthefollowingmessage:
OnceyouknowthepathforyourSDcardandhaveensuredthatnoexistingpartitionsaremounted,youcanthenwritetheRaspbianimagetoyourSDcardusingthefollowingcommand,wherePATHisthepathtotheSDcard(/dev/sdbinmycase):
sudoddif=path/to/raspbian_image.imgof=PATH
NoteBecertainthatthepathtotheSDcardiscorrect,andthecarddoesnotcontainanydatathathasnotbeenbackedupasthisoperationwilldestroyallofthedataalreadypresentonthecard.
Wherepath/to/raspbian_image.imgistheextractedimagefileandsdXisthepathtoyourSDcard.Notethatthisstepcantakeupto5-8minutes,sincenooutputisgivenonthescreen,theSDcardreader’sbusy/dataLEDisagoodindicationthattheimageisbeingwritten.
TipSincetheGNUCoreutils(whichincludecommandssuchascp,mv,dd,andsoon)donotprovidemuch(orany)outputtoindicatetheprogress,youmaywanttotakealookattheCoreutilsViewertool(https://github.com/Xfennec/cv),whichshowstheprogressoftheCoreutilscommands.
BootingthePiforthefirsttimeOnceyouhavetheimagewrittentothecard,itistimetobootthePiandperformtheinitialsetup.Themostcommonwaytodothisisbyusingakeyboard,mouse,andmonitor;however,ifyouhaveaccesstoanetworkthatprovidesDHCP(asmosthomenetworksdo),thenthesetupcanbedoneentirelyoverSecureShell(SSH).
First,setupthehardwareandbootthePibyinsertingtheSDcard,connectingthepower,andtheEthernetcable.Withinafewseconds,youwillseethattheACTLEDstartstoflicker.Ifitflashesforveryshortpulsesordoesnotlightatall,thenthisindicatesanissuewitheithertheSDimage,theconnectionbetweenthecardandthePi(acommonissueforthemodelsAandB),orthecarditself.
OncethePihasbooted(indicatedbylessfrequentflashingoftheACTLED),youwillneedtodetermineitsIPaddress.Therearetwomainwaystodothis:byaccessingtheDHCPallocationsviayourrouterorbyscanningthelocalnetwork.
NetworkscanningThecross-platformtool,theNmaputility(http://nmap.org)canbeusedtoscananetwork.
Todoso,youwillneedtofindtheIPaddressofyourPC(inordertofindthesubnetonyourlocalnetworktosearchforthePiin).OnWindows,thiscanbedonebyopeningtheCommandPromptandexecutingthiscommand:
ipconfig
Thisshouldgiveyoutheinformationaboutyournetworkinterfacessimilartothefollowing:
OnUnix,thiscanbedonebyusingthefollowingcommand:
ifconfig
Thiscommandgivesoutputsimilartothefollowing:
ThesearchIPrangethatisgiventoNmapisobtainedbyreplacingthelastnumberofIPv4orInetAddresswith*.Inourcase,itwillbe192.168.0.*.
Nowthatweknowtheaddressrangeinwhichwewillbelooking,wecanopenaterminalandrunthefollowingcommand:
nmap--open192.168.0.*
ReplacingtheIPrangewithyoursearchrangewilltrytomakecontactwitheveryhostinthegivenIPaddressrangeandwillreturnwithalistofeveryhostthatisup,withalistoftheiropenports,andwhatservicestheycorrespondto.Inourcase,wearelookingforanyhoststhathaveanopenSSHport:
StartingNmap5.21(http://nmap.org)at2014-09-2111:58BST
Nmapscanreportfor192.168.0.8
Hostisup(0.0064slatency).
Notshown:999closedports
PORTSTATESERVICE
22/tcpopenssh
Nmapdone:256IPaddresses(5hostsup)scannedin5.84seconds
Here,IhaveonlyshownthereportforthePi.Usually,afterthefirstboot,SSHwillbethe
onlyservicethatisstarted,soitisusuallygivenawayasthedevicethatonlyprovidesSSH.
ConnectingtothePiviaSSHOnUnix,accessingthePiviaSSHisassimpleasexecutingthefollowing:
sshpi@[PiIP]
Here,PiIPistheIPaddressofthePi.Youmaygetawarningsimilartothisthefirsttimeyourunthecommand:
Theauthenticityofhost'192.168.0.8(192.168.0.8)'can'tbeestablished.
ECDSAkeyfingerprintis32:4c:46:1b:dd:7e:8b:52:a0:31:c3:f5:9f:73:d1:c6.
Areyousureyouwanttocontinueconnecting(yes/no)?
ThiscansafelybeignoredbytypingyesandpressingEnter.Youwillthenbeaskedforapassword,andasthisisthefirstboot,thedefaultisraspberry.
OnWindows,PuTTY(http://www.putty.org)canbeusedtoSSHintothePi.Oncedownloaded,runPuTTYandentertheIPaddressofthePiandtheHostNamefield,ensuringthatPortissetto22andSSHisselected.Then,clickonOpen:
Youwillseeawarningmessagesimilartothefollowingabouttheidentityofthehost:
Again,thiscanbeignoredbyclickingonYes.YouwillthenbeaskedforausernameandpasswordinthePuTTYterminalwindow.Sincethisisthefirstboot,thedefaultsarepiandraspberry.
CommonLinuxcommandsAtthispoint,itwouldbegoodtolearnafewLinuxshellcommands,whichyouwillnodoubtcomeacrosswhileworkingwiththePi:
cd:Thechangedirectorycommandsetstheworkingdirectorytoagivendirectory,forexample,cd/home/pils:Thelistcommandliststhecontentsofthecurrentworkingdirectorymkdir:Themakedirectorycommandcreatesanewdirectorywithinthecurrentworkingdirectory,forexample,mkdircodecat:Theconcatenatecommandcanperformoperationsontextfiles,anditcanalsodisplayitscontentsontheconsole,forexample,cat/etc/passwdpwd:Theprintworkingdirectorycommandtellsyouthedirectoryyouarecurrentlyinchmod:Thechangemodecommandchangestheaccesspermissiontoafile,forexample,chmod744file(thisgivesread,write,andexecutepermissionstotheowner,andread-onlypermissiontoeveryoneelse)sudo:Thesuperuserdocommandexecutesthefollowingcommandsasroot,forexample,sudoapt-getupgrademv:Themovecommandmovesthefileordirectoryinthefirstargumenttothesecond,forexample,mvfile.txtmisc_filescp:Thecopycommandcreatesacopyofafileordirectoryinanotherdirectory,forexample,cpfile.txtmisc_files/file2.txtrm:Theremovecommanddeletesafile,forexample,rmfile.txt
Moreinformationcanbeobtainedaboutagivencommandviaitsmanpage,whichcanbeaccessedusingthefollowingcommand,wherecommandisthecommandyouwishtoknow
moreabout:
mancommand
TheinitialsetupOnceyouareabletoSSHinthePi,runtheconfigurationutilityusingthefollowingcommand:
sudoraspi-config
ThisutilityallowsyoutoconfigurethePihardwareandperformusefulconfigurationtaskssuchaschangingpasswordsandresizingtherootpartitionontheSDcard,bothofwhich,wewilldonow.
First,selecttheExpandFilesystemoptionandpressEnter.Theutilitywillmodifythepartitiontableandreportthatithascompleted,andthatthechangesmadewillonlyaffectthefilesystemafterthenextreboot.PressEnteragaintoreturntothemainmenu.
Now,selectChangeUserPasswordandhitEntertwice.Youwillbetakenbacktotheshellandpromptedtoenteranewpassword,whichhastobeenteredtwice.Oncedone,aconfirmationboxwillnotifyyouthatthepasswordwaschangedsuccessfully;pressEntertoreturntothemenu.
Asthisisallthatneedstobedoneinraspi-configfornow,presstheleftarrowkeytwicetoselectFinishandEntertoconfirm.Youwillbeaskedwhetheryouwanttorebootnow;selectYesandpressEnter.OncethePiisrebooted,SSHbackintoitusingyournewpassword.
Onceyouhaveaccessagain,checkwhetheryounowhaveaccesstothefullstoragespaceontheSDcardusing:
df-h
ThecommandshouldreportthesizeofrootfsmuchclosertotheSDcardcapacity:
rootfs16G2.5G13G17%/
AllthatislefttodonowistomakesurethatthesoftwareonthePiisuptodate.Sinceweareusinganimagethatwasjustdownloaded,itisnotlikelythattherewillbealargenumberofupdates;however,itisagoodpracticetokeepaninstallationuptodate.
Runningthefollowingcommandswillfirstupdatethelistofavailablepackagesthenupdateanyinstalledpackageswithnewerversionsthanwhatwasinstalled:
sudoapt-getupdate
sudoapt-getupgrade
Notethatthisprocesscantakeupto10minutesdependingonthenumberofupdates,andusuallytakeslongerthanadesktopPCorlaptopasthisprocessiswritingtoanSDcardratherthanatraditionalharddrive.
SettingupthepirateradioIt’snowtimetodownloadandsetupthePiFMsoftware,whichwillallowyoutousetheGPIOheaderasanFMtransmitter.First,we’llneedtodownloadthesoftwareusingthefollowingcommands:
wgethttp://omattos.com/pifm.tar.gz
tar-xzvfpifm.tar.gz
ThiswillgetthegzippedarchivethatcontainsthePiFMsoftware,thePythonlibrary,andsometestfilesanduncompressthem.
Fornow,asinglemaletomale0.1inchpinjumperwillsufficeasanantenna;thisshouldbeconnectedtoGPIO4(pinnumber7)ontheGPIOheaderandmadetostandasuprightaspossibletoensurethebestrange(refertothefollowingimage):
YouarenowreadytotestthesetupwithanFMradio;firstly,youwillneedtochooseafrequencythatwillnotoverlapwithanylicensedbroadcastsinyourareaandiswithintheFMradiotransmissionrangeinyourarea(usuallybetween88Mhzand108Mhz).Alotof
radiosthatdoautomatictuningalsotendtopreferfrequenciesthatareamultipleof0.1MHz(forexample,99.9,101.3,andsoon).
Onceyouhavechosenyourfrequency,tuneyourradiointoit,andrunthefollowingcommandonthePi,wherefreqisthefrequencyyouwishtobroadcaston:
sudo./pifmleft_right.wavfreq22050stereo
Youshouldnowhearasampleautoclipdemonstratingtheabilitytobroadcaststereoaudio.
TransferringMP3filestothePiForourmediaplayer,wearegoingtoneedaselectionofMP3filesonthePiSDcard.Therearetwomainwaystodothis,eitherbymovingthecardbacktoyourPCandmountingitlikearegularSDcard,orbyusingtheSecureFileTransferProtocol(SFTP).
Inthiscase,sincethePiisalreadyrunning,IhaveoptedtouseSFTP.ThiscanbedoneusingtheFileZilla(https://filezilla-project.org)FTPclient.Onceinstalledandopened,enterthesamedetailsthatyouusedtoconnecttothePioverSSHinthefieldsatthetopofthewindow(using22forPort),andclickonQuickconnect.
YoushouldnowbeabletobrowsethefilesystemsofbothyourcomputerandthePi,asshowninthefollowingscreenshot.Filescanbeuploadedbyright-clickingonthemandselectingUpload.
InordertoplaythemusicyouhavejusttransferredtothePi,youwillneedtoinstalltheffmpegutility,whichisatoolthatiscommonlyusedtotranscodemediafilesandcanbeinstalledusingthefollowingcommand:
sudoapt-getinstallffmpeg
NowthatyouhavesomeofyourownmusiconthePi,youcantryplayingitbypipingthe
outputofffmpegtoPiFM:
ffmpeg-ifile.mp3-fs16le-ar22.05k-ac2-|sudo./pifm-freq22050
stereo
Here,fileistheMP3filetobebroadcastedandfreqisthefrequencytobroadcastiton.Sincewearetellingffmpegtoprovideoutputfortwoaudiochannels(-ac2)andgivingthestereooptiontoPiFM,thisshouldgiveastereoaudiobroadcast.
ScriptingamediaplayerNowthattheFMtransmitterisworking,wecanmakeitdosomethingalittlemoreuseful;inthiscase,wewilluseittobroadcastapersonalizedradiostationwithacollectionofyourownmusic.
Todothis,wewillwriteaPythonscriptthatmanagestosearchforMP3filesandcallsPiFMtobroadcastthem.
CallingPiFMfromPythonInthePiFMdownloadandonthePiFMwebsite,youmayhavenoticedthatthereisaPythonlibrarythatcanbeusedtocontrolPiFM.Although,lookingatthesourcecodeforit,youcanseethatallthelibrarycandoiscallthepifmexecutablewiththeminimumnumberofcommands,andthereforewillnotallowustoplayMP3files.
However,itisasimpleprocesstocreateourownfunctionthatwillallowustopassthefilenameofanMP3,afrequency,andthatwillallowPythontocallffmpegandPiFMinordertobroadcasttheaudiointhefileforus:
defplay_file(filename,frequency):
command='ffmpeg-i"%s"-fs16le-ar22.05k-ac2-|sudo./pifm-%f
22050stereo'%(filename,frequency)
subprocess.call(command,shell=True)
Thiscodeisanextractfromtheplayer.pyfile;allwearedoinghereistakingtheshellcommandsusedtoplayanMP3fileandreplacingthefilenameandbroadcastfrequencywithvaluesthatarepassedtothefunctionasparameters.Then,weareusingthePythonsubprocessmoduletoexecutethecommandasifitwastypedintoashell.
TipDownloadingtheexamplecode
Youcandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.comforallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
SearchingforMP3filesForourscripttoplayanyMP3files,itneedstobeabletofindthemfirst.FindinganMP3fileinvolvestakingalookateachfileinastartingdirectorytocheckwhetherafileisanMP3file,andthenrepeatingthisprocessforeverydirectorywithinthestartdirectory.Thankfully,Pythonmakesthisveryeasy:
mp3_files=list()
forroot,dirs,filesinos.walk(directory):
forfilenameinfiles:
iffilename.endswith(".mp3"):
mp3_files.append(os.path.join(root,filename))
Here,directoryisthedirectorywewanttosearchforfilesmediain.Theos.walkfunctionreturnsatuple;thefirstelement(root)isastringthatcontainstheabsolutepathtothesearchdirectory,dirsisalistofdirectorieswithinthesearchdirectoryanditssubdirectories,andfilesisalistofallthefileswithinthesearchdirectoryanditssubdirectories.
TheifstatementisasimplewaytocheckwhetherafileisanMP3filebasedsolelyonitsfileextension.Ifithasthe.mp3extension,itisaddedtothemp3_fileslist,whichisthenpassedtotheplaylistcode.
GettinginputfromacommandlineInordertosetvarioussettingsforourplayerscript,forexample,thedirectoryinwhichyoucansearchforfiles,weneedawaytogetinputfromtheuserviaacommandline,andinthiscase,fromtheargumentspassedtothescriptwhenitisstarted.Todothis,wewillusetheargparsePythonmodule:
parser=argparse.ArgumentParser(description='BroadcastasetofMP3sover
FM')
parser.add_argument(
'-f','--frequency',
default=101.1,
type=float,
help='Frequencyonwhichtobroadcast')
params=parser.parse_args()
TheargparsePythonmoduleallowsyoutodefineasetofargumentsthatcanbepassedtoaPythonprogram,itallowsyoutoparsetheargumentswhenthescriptisrun,anditautomaticallyallowsyoutogenerateahelppage(accessedbypassing-htothescript).
Inthiscase,wewilladdanargumentforthebroadcastfrequency,whichissetusingeither-for--frequency;typeisusedtovalidateinputfromtheuser,defaultiswhatisreadbytheprogramiftheuserdoesnotsetavalue,andhelpiswhatisshownforthisargumentonthehelppage.
QueuingthemediafilestobeplayedOurmediaplayerwillalsoneedawaytomanagewhichfileshouldbeplayednext.Wewillimplementthisintwoways:linearplaybackintheorderthefileswerediscoveredandrandomizedplayback:
file_number=-1
whileTrue:
ifparams.random:
file_number=random.randint(0,len(filenames)-1)
else:
file_number+=1
iffile_number>=len(filenames):
return
play_file(filenames[file_number],params.frequency)
Here,ifthe--randomparameterhasbeenpassedtoourscript,wheneverweareabouttoplayafile,thefiletobeplayedwillbeselectedatrandomusingtherandintfunctionintherandomPythonmodule.Thisnumberisthenusedtogetacertainfilefromthelistoffilenamesthatwerepreviouslydiscovered.
UsingthemediaplayerscriptTheplayer.pyscriptcanbeinvokedusingthefollowingcommand:
pythonplayer.py-dmusic-f99.9--random
ThiswillsearchforallMP3filesunderthemusicdirectoryandbroadcastthemat99.9MHzinarandomorder.Afulllistofcommandswillbeavailabletoyouifyourun:
pythonplayer.py-h
SincetheradioisnotmuchofusewhenyouhavetoSSHintoittostartplayingthemusic,wewilladdacronjobthatwillstarttheplayer.pyscriptwhenthePibootsup.
Todothis,wewilluseashellscripttostartthePythonscript(start_player.sh):
#!/bin/bash
sleep20
cd/home/pi
pythonplayer.py-dmusic--random-f99.9&
Thiswillensurethattheplayerscriptisexecutedinthecorrectfolder,inthiscase,/home/pi,asthisiswhereourPiFMexecutablesandmusicdirectoriesare.
Next,wewilladdanentryinthecrontab,whichiswherecronjobsaredefined.Thiscanbeeditedwiththefollowingcommand:
sudocrontab-e
Thiscommandwillopenthedefaultcommand-linetexteditonthePi,nano,whichwillallowyoutoaddentriestothecrontab.Tostartourmediaplayerscript,wewillneedtoaddthefollowinglinetotheendofthecrontabthatisopened:
@reboot/home/pi/start_player.sh
Inourcase,wewillusethe@rebootcronruleinsteadofspecifyingatimeforthecommandtoberun,andasthenamesuggests,thiswillrunthegivencommandwhentheOSstarts.
PressCtrl+XfollowedbyYandEntertosavethechangestothecrontab,thenusethefollowingcommandtorebootthePi,andifallgoesasplanned,startyourpersonalizedradiostation:
sudoreboot
SummaryInthischapter,wecoveredthebasicsetupofthePihardwareandRaspbianOS.YoulearnedhowtodiscovertheIPaddressofthePiinordertoallowremoteaccesstoitoverSSH;thisprocesswillbeusedinthemajorityoftheprojectslaterinthisbook.
WealsotookaquicklookattheGPIOexpansionheader,andhowitistypicallyusedtointerfacewithexternalhardware.WealsousedthisasacrudeFMtransmitterthroughwhichwewroteasinglePythonscripttobroadcastmusic.
Inthenextchapter,wewillgointofurtherdetailsregardinghowtosetupvarioussoftwarepackagesinordertorunthemonthePi,aswellasyouwilllearnthevariouswaystoconfigurenetworkingwhenwemakeaportablespeakersystemthatrunstheLogitechMediaServer.
Chapter2.PortableSpeakerSystemInthischapter,wewillbuildawireless,battery-poweredspeakersystemthatcanbecontrolledusingawebbrowserorsmartphone.
Toprovidethemusicforthespeakersystem,wewillusetheLogitechMediaServersoftware,whichisapieceofsoftwarethatcanbeusedtostreammusic,videos,andphotosfromonecomputeronanetworktomultipleotherdevices.Italsoallowsustocontroltheplaybackfromanycomputerorsmartphoneonthesamenetwork.
Initially,wewillsetupthePitoconnectittoanexistingserver(theonerunningonalaptopforinstance),whichissuitableforusearoundyourhomeorgarden.Later,wewilllookathowtomakethesystemtrulyportablebyremovingtheneedforanexistingserverandnetwork.
ThesystemwillbeselfcontainedwithinastandardflightcasewiththespeakersexposedwhenthelidisopenedasitispossibletorunLogitechMediaServeronthePiitself.Itisnotnecessarythatyouhaveanycontrolsonthesystemitselfotherthanapowerswitch.
ThisprojectisbasedonasimilarprojectmadebyIainYarnallatMakerSpace,Newcastle.
WhatyouwillneedThisisalistofthepartsthatyouwillneedforthisproject;specificpartshavealinkofwheretheycanbepurchased(itisrecommendedthatyouusethesespecificpartsasothersimilarpartsmayneedanassemblythatdiffersfromtheinstructionsgivenhere),andallotherpartscanbepurchasedfromanelectronicscomponentsstore:
TheRaspberryPiAUSBstoragedevicetostoreamedialibrary(itispossibletouseaharddrive;however,tokeepthewiringsimple,itisadvisablethatyouuseamemorystick)AWi-Fiadapter(uk.rs-online.com/web/p/product/7603621/)Aflightcase(http://www.maplin.co.uk/p/flight-case-triple-pack-with-dividers-n50ju)Alengthof26AWGwireAlengthof32AWGwireA3.5mmstereoaudioconnectorAstripofterminalblocksAfuseholderand1AmpfuseEight20mmM3screws,washers,andnutsTwofull-rangespeakers(http://cpc.farnell.com/visaton/2133/speaker-full-range-5-60w-black/dp/LS02184)Twomonoamplifiermodules(http://cpc.farnell.com/1/1/85173-amplifier-module-18w-m033n-kemo-electronic.html)Avariableswitchmodevoltageregulator(http://imall.iteadstudio.com/im130731002.html)Apowerswitch(http://cpc.farnell.com/arcolectric-switches/c1300abaaa/switch-spst-16a-250vac-black-i/dp/SW05094)Volumecontrol(stereopotentiometer)(http://cpc.farnell.com/_/lp-200-8/speaker-l-pad-stereo/dp/LS00544)Abattery(http://www.hobbyking.com/hobbyking/store/__11945__Turnigy_nano_tech_2200mah_4S_35_70C_Lipo_Pack.html
ToolsyouwillneedThisisalistoftoolsthatyouwillneedforthischapter;theycanallbepurchasedfromeitheranelectronicscomponentsstoreoratool/hardwarestore:
Drillanddrillbitsrangingfrom3mmto10mmAjigsawAtrysquare(optional)AsolderingironandsolderAmultimeterAsmall,flatscrewdriverAsmallPosidrivescrewdriver
SettingupLogitechMediaServerWewillfirststartbydownloadingandinstallingLogitechMediaServer,whichistheserverbackendthatmanagesthemedialibraryandcontrolstheplayersbasedonthecommandsfromdevicesthatcancontroltheserver(knownascontrollers).Examplesofcontrollersincludethewebinterfaceandsmartphoneapplications.
Theplayersaredevicesthatactuallyoutputaudio(alsoknownasSqueezeboxclients),ourPi,forexample.Itispossibletohaveseveralcontrollersandplayersrunningfromthesameserver.
Togetstarted,gotohttp://www.mysqueezebox.com/download,anddownloadthecorrectversionforyourOS.Inmostofthecases,thedownloadisanexecutableorapackagefilethatcanbeinstalledinthesamewayasanyotherpieceofsoftware.
OnceLogitechMediaServerisinstalled,openawebbrowseronthesamePCandnavigatetolocalhost:9000;youshouldseetheLogitechMediaServerwebinterface,asshowninthefollowingscreenshot.Thisallowsyoutobrowsethemedialibraryandstreammediatoplayersconnectedtothatserver.
InordertomakeyourmediaavailableinLogitechMediaServer,youmayneedtochangethesearchpathandperformalibraryrescan;thiscanbedonebyclickingontheSettingslinkinthebottom-rightcorneroftheBasicSettingspage:
Next,selectBrowseonthefolderthathasMusicticked;thiswillopenadirectorytreethatwillallowyoutobrowsethedirectoryyourmusicisstoredin.Onceyoudothis,clickonClose,andunderRescanMediaLibrary,clickonRescan.Thiswilllookintheconfigureddirectoriesformediafilesandaddthemtothelibrary,whichmaytakeafewminutesdependingonthesizeofyourmediacollection;theprogressofthisprocesscanbeviewedintheInformationtab.ClickonApplyinthebottom-rightcornerofthescreentoreturntothelibraryview.
Oncebacktothelibraryview,youmayhavetorefreshthepageinordertodisplayyournewmedia;thiscanbedonebyclickingontheLogitechMediaServertextinthetop-leftcornerofthepage.
SincethisisallLogitechMediaServercanwithoutaplayer,wewillnowsetupthePiasaSqueezeboxclient.
SettingupthePiasaSqueezeboxclientInordertousethePiasaSqueezeboxclient,wewillusetheopensourcesoftware,squeezelite(https://code.google.com/p/squeezelite).
First,weneedtoinstallsomeprerequisitesonthePiwhicharerequiredtorunthesqueezelitesoftware,whichcanbedoneusingthefollowingcommand:
sudoapt-getinstall-ylibflac-devlibfaad2libmad0
Next,wewilldownloadtheprecompiledsqueezelitebinaryfromtheGoogleCodepageusingwget.Wewillgiveitexecutepermissionstoitandmoveitintothebinarydirectory,allowingittobeexecutedlikeanyothercommand-lineapplication:
wgethttp://squeezelite-downloads.googlecode.com/git/squeezelite-armv6hf
sudochmoda+xsqueezelite-armv6hf
sudomvsqueezelite-armv6hf/usr/bin
Nowthattheclientapplicationisinstalled,wewilldoalittlebitoftestingtobesurethatthesetupisworkingproperly.Wewilldothistodeterminetheparametersthatneedtobepassedtotheclienttogetthebestaudioqualityandperformance.
Tostart,executethefollowingcommand:
squeezelite-armv6hf-nPi-a160
Thiscommandwillstartsqueezeliteinanauto-discoverymodeinwhichitwillsearchthenetworkforaLogitechMediaServerinstanceandconnecttothefirstoneitfinds.Ifyouhavemorethanoneinstanceandwanttospecifytheservertoconnectto,thenyoucanusethe-sparameter:
squeezelite-armv6hf-sserver_ip:port-nPi-a160
The-nparameterdefinesthenameoftheclientandsubsequently,whatitwillbecalledinLogitechMediaServer;thisisusefulforidentificationwhenyouareusingmorethanoneclientonthesameserver.The-aparameterisusedtospecifyadditionalALSAparametersthataretobeusedwhileopeningtheoutputaudiodevice;inthiscase,wewillincreasethedefaultbuffersize,whichwillhelpustorectifysomeaudioqualityissuesthatmayoccurwiththePi.
OncesqueezeliteisrunningonthePi,gobacktotheLogitechMediaServerwebinterfaceandselecttheplayerfromthedrop-downlistinthetop-rightcornerofthepage(youmayneedtorefreshthepagetodisplaytheplayer).
YoucanthenbrowseyourmedialibraryandqueuethemusictobeplayedonthePiusingtheaddandplaybuttons,whichcanbeseenwheneachmediaitemishighlighted,asshowninthefollowingscreenshot:
SettingupWi-FionthePiRunninganEthernetcablethroughthePiisalittlebitunrealisticforthisuse.Hence,wewillconnectthePitoawirelessnetwork.SincenotallWi-FiadaptersworkwellwiththePi,itisagoodideatocheckthelistofthesupporteddevices(http://elinux.org/RPi_USB_Wi-Fi_Adapters)beforepurchasingonespecificallyforthisproject.
Firstly,wewillmakesurethatwehavealltheWi-Fitoolsinstalledusingthefollowingcommand:
sudoapt-getinstallwpasupplicantwireless-tools
ThereisagoodchancethatthesepackageswillalreadybeinstalledonRaspbian,butitisasimplesteptocheckbeforehand.
Itislikelythatyoualreadyknowtheservicesetidentifier(SSID)ornameofthewirelessnetworkyouwanttoconnectto,butifnot,orjusttocheckwhetheritisbeingpickedupbytheWi-Fiadapter,usethefollowingcommandtogetalistofalltheWi-Finetworksavailableintherange:
sudoiwlistwlan0scan|grepESSID
Youwillgetoutputsimilartothefollowing:
Nowthatweknowthenameofthenetworkwewanttoconnectto,wecangoaheadandaddanentryinthewpa_supplicantconfigurationfile,whichcontainstheconnectiondetailsforthenetwork.Thiscanbeeditedbythenanotexteditor,usingthefollowingcommand:
sudonano/etc/wpa_supplicant/wpa_supplicant.conf
Attheendofthefile,addthefollowinglinesandreplaceSSIDandPASSWORDwithSSIDandthepasswordforyourwirelessnetwork:
network={
ssid="SSID"
psk="PASSWORD"
key_mgmt=WPA-PSK
}
Oncethelineshavebeenaddedtothefile,savethechanges,exitnano,andrebootthePiusingthefollowingcommand:
sudoreboot
OncethePihasbooted,SSHbackintoitandmakesurethatthePihasaWi-Ficonnection,usingthefollowingcommand:
ifconfig
Iftheconfigurationissuccessful,youwillseeoutputsimilartothis,whichshowsanactiveEthernet(on192.168.0.2)andaWi-Fi(on192.168.0.18)connection:
Afterthis,youshouldbeabletoSSHinthePiviaitsWi-FiIPaddressanddisconnecttheEthernetcable.
RunningsqueezeliteasadaemonSincewewantthePitobereadytostreammusicwithouthavingtodoanythingotherthanapplypowertoit,weneedawaytolaunchsqueezelitewhenthePiboots;thistime,wewilllookatanotherwayofdoingthis,usingadaemon.
Adaemonisaprogramthatrunsinthebackgroundandisnotdirectlyvisibletotheuser;becauseofthis,itisoftenusedforapplicationssuchasservers.
Inourcase,wewillusethestart-stop-daemonutilitytocreateadaemonthatwillstartsqueezeliteonboot.Wewilldothisbywritingashellscriptandplacingitinthe/etc/inti.ddirectory:
#!/bin/bash
###BEGININITINFO
#Provides:squeezelite
#Required-Start:
#Required-Stop:
#Default-Start:2345
#Default-Stop:016
#Short-Description:Squeezeliteclient
#Description:Logitechmediaserverclient
###ENDINITINFO
DAEMON_USER=pi
PIDFILE=/var/run/squeezelite.pid
DAEMON=/usr/bin/squeezelite-armv6hf
DAEMON_OPTS="-nPi-a160"
do_start()
{
start-stop-daemon--start--background--pidfile$PIDFILE--make-pidfile
--user$DAEMON_USER--chuid$DAEMON_USER--startas$DAEMON—$DAEMON_OPTS
}
do_stop()
{
start-stop-daemon--stop--pidfile$PIDFILE--retry10
}
case$1in
start)
do_start
;;
stop)
do_stop
;;
restart)
do_stop
do_start
;;
*)
;;
esac
Makethescriptexecutableandmoveittothe/etc/init/ddirectory:
sudochmoda+xsqueezelite
sudomvsqueezelite/etc/init.d/squeezelite
Finally,usethefollowingcommandtoupdatethelistofdaemons:
sudoupdate-rc.dsqueezelitedefaults
Toensurethatthedaemonisworkingproperly,trytostartsqueezelitebyexecuting:
sudoservicesqueezelitestart
Checkwhethertheprocessisrunning:
psaux|grepsqueeze
Thisshouldgiveyououtputsimilartothefollowing:
Theprecedingoutputshowsthatthesqueezeliteprocessisrunning;thiscanalsobeverifiedifyouattempttostreammusicintheplayer.
BuildingtheelectronicsTheelectronicsforthespeakersystemcanbesplitintotwomainsections—thepowercircuitandtheaudiocircuit.
Thecircuitstructureoftheelectronicsisshowninthefollowingdiagram:
Thespeakersystemblockdiagram
Notethecolorcodingofthewiring.Here,blackshowsthepowerground,grayshowstheaudioground,cyanshowstheunamplifiedaudio,blueshowstheamplifiedaudio,yellowrepresentsthebatteryvoltage,andredshows5V.
Notethecolorcodingofthewiring.Thisisimportantasitisthemostcommonwayinwhichdifferentsignalsandpowersuppliesareidentifiedwithinanelectronicproduct.Thereareafewcommonconventionsthat,whilearenotusedhere,aregoodtoknow;blackisalwaysground,redandyellowusuallyindicateapowersupply(5Vand12V,respectively),andyellowandgreenstripesusuallyrepresentamainsearth.
Forsmallprojects,suchasthis,followingastandardcolorcodeforwiringisnotasimportant.Differentsignalshaveacoloredwireoftheirowntomakeidentificationandtroubleshootingeasier.
NoteUnlessotherwisestated,a26AWGwireshouldbeused.Thewirecoloryouchoosetousedoesnothavetomatchtheonesshownintheprecedingdiagrams;however,itispreferablethatyoufollowittomakeidentificationeasier.
TheamplifiercircuitFirstly,wewillwirethetwomonoamplifiermodulestoastripofterminalblockstomakeastereoamplifiermodule.Thisisdonebyconnectingthecommonconnectionsfromeachamplifiertogetherandkeepingthesignalandoutputconnectionsseparate,asshowninthefollowingdiagram:
Next,takethevolumecontrolandsolderthewiresontoitintheconfiguration,asshowninthefollowingdiagram:
Theaudioinputwiresshouldberelativelyshort(around50mm)andconnectedtoastripofthreeterminalblocks;theoutputshouldhaveenoughwiretoreachtheamplifiermodule(around150-200mm).Thisvolumecontrolisessentiallycomprisedoftwopotentialdividerswiththeirwipersfixedtogethersuchthateachpotentialdividerisalwaysatthesameposition.
Now,wecansolderwirestothe3.5mmaudiojack;sincethisisabitsmalleranditwillonlycarrytheunamplifiedaudiosignal,wecanusea32AWGwireforthis:
Theaudioconnectorcannowbeconnectedtotheterminalblockonthevolumecontrol;atthisstage,theorientationoftheleftandrightchannelsisnotimportant.
Then,connecttheoutputfromthevolumecontroltothefirstthreeconnectionsontheamplifierterminalblocks;again,theorientationisnotimportantatthisstage.
Sincethepowergroundconnectionontheamplifierwillhavetobeconnectedtoboththespeakers,thebatteryandtheDC-DCconvertertopowerthePiwillbebesttoextendthespeakersconnectionstotheirownstripofterminalblocks.Thiswillreducethenumberofconnectsthathavetobemadeinthesameconnection.
Thisissimplyacaseofaddingashortlengthofwire(around50-100mm)tothetwospeakeroutputsandpowergroundfromtheamplifierterminalblocksandconnectingthemtoastripofthreeterminalblocks:
Next,weneedtosolderawire(around300mm)tothetwospeakers.Notethatthespeakerwillhavemarkingsthatshowthecorrectpolarityitistobewiredin:
Now,connecteachspeakertothestripofthreeterminalblockscomingfromtheamplifiermodules.Onceagain,thecorrectspeakerorientationisnotimportantatthisstage.
Thisisallwithrespecttothewiringfortheaudiosectionofthespeakersystem.
RunningthespeakersystemonbatterypowerSincethebatterywewilluseisratedat14.4V,weareabletopowertheamplifierdirectlyfromthebattery.However,thePimustbepoweredwith5V.So,wewillneedapowerconvertertobeabletopowerthePiusingthebattery.
ThepowerconverterwewilluseisaDC-DCswitchmodeconverter,whichwillacceptinputvoltagefromthesetoutputvoltageupto35V.Therefore,wewillcontinuetopowerthePiasthebatteryvoltagedropswhileunderheavierload(forexample,whenplayingathighervolumes)orasthebatterystartstodrain.
Aslithiumpolymerbatteriescanbeverydangerousifusedincorrectly,itisvitalthatafuseisusedinlinewiththepowerswitchtoprotectthebatteryjustincasethere’safaultinthespeakersystem.Aratingofaround0.8to1.5Awillbesuitableforthispurpose.
Wewillstartwithpoweringjusttheamplifiers.Thisisafairlysimpletaskasallitinvolvesisconnectingthebatterypositiveterminaltothepowerconnectorontheamplifierterminalblocksviatheswitchandfuse.Thegroundisconnecteddirectly,asshownintheearlierdiagram.Performthefollowingstepstoconnectthecircuit:
1. Taketheconnectorforyourbattery,andassumingthatithasleadspresolderedontoit,connectthemtoastripoftwoterminalblocks.Iftheydonothaveleadssolderedontothem,thenthisshouldbedonefirstusingashortlengthofwire(around50mm).
2. Soldera100mmlengthofwireontoonepoleofthepowerswitchandconnecttheotherendtothepositiveterminalonthebatteryterminalblock.
3. Soldera50mmlengthofwirefromtheotherswitchpoletoonecontactofthefuse.4. Soldera50mmlengthofwirefromtheotherfusecontactandconnecttheotherend
tothepositivepowerconnectionontheamplifierterminalblocks.5. Connectthegroundsofthebatteryterminalblockandtheamplifierterminalblocks
witha100mmlengthofwire.
Oncethesestepshavebeencompleted,thesetupshouldlooklikewhatisshowninthefollowingimage:
Nowwouldbeagoodtimetogivetheaudioelectronicsatestbyconnectingthebatteryandpoweringontheamplifiers.YoucaneitherusethePipoweredfromaUSBoranyothermediaplayerastheaudiosource.Itisbesttohavethevolumecontrolsettoitslowestsettingandgraduallyincreaseit.
Next,wewanttopowerthePifromthebatteryusingtheDC-DCconverter.Therearetwomainwaysofdoingthis:eitherbyapplyingpowertotheGPIOheaderorbyback-poweringthePiusingapoweredUSBhub.Inthiscase,IwillbepoweringviatheGPIOheader,whichwilllikelybesufficientforwhatwearedoinghere.PoweringusingapoweredUSBhubwillonlybeneededifyouareusinganexternalharddrivetostorethemusiclibrary.
First,weneedtosolderwirestoeachoftheterminalsoftheDC-DCconverterandnotethepolarityoftheconnectionstoensurethatthecolorcodingofthewiringisconsistent.Alengthofaround100mmissufficientforeachconnection.
Next,connectthepositiveandgroundconnectionsonthepowerinputsideoftheconvertertothepositiveandgroundconnectionsontheamplifierterminalblocks,andconnectthetwoleadsfromtheoutputterminalsoftheDC-DCconvertertoastripoftwoterminalblocks.
NowthatwehavetheDC-DCconverterconnected,weneedtosetittothecorrectoutputvoltagebeforeweconnectittothePi.Todothis,setamultimetertothevoltagemodeandplacetheprobesacrossthetwoconnectionsontheterminalblocksconnectedtotheDC-DCconverter’soutput(ifpossible,screwthetipsoftheprobesintotheterminalblockstoavoidhavingtoholdtheminplace).Turnthepoweron,andifneeded,adjusttherangeonthemultimeter.
Usually,Ifindthattheseconverterscomepresettotheoutputjustbelowtheinputvoltage,
whichwouldbefartoohighforthePi,whichisdesignedtooperateat5V.Inordertoadjustthevoltage,useasmall,flat-headscrewdrivertoadjustthesquarebluepotentiometer.Thisisamultipleturnpotentiometer,sodonotbesurprisedifittakesafewrotationsofthepotentiometerforthevoltagetochange.Areasonablevoltagetoaimforis5.1V,asunderload,thevoltageisexpectedtodropslightly.
Oncethevoltageiscorrected,turnthepoweroff,removethemultimeterfromtheoutputoftheDC-DCconverter,removeoneendoftwo0.1inchjumperleads,andconnectthemtotheterminalblockontheoutputoftheDC-DCconverter.Connectthepositiveleadtopin4oftheGPIOheadersonthePiandthegroundleadtopin6.
Bynow,thesetupshouldlooksimilartothefollowing:
Oncethisisdone,applypoweroncemoreandwithinafewseconds,thePishouldstartbootingup.Ifitdoesnot,turnthepoweroffimmediatelytopreventpossibledamagetothePiandbattery,anddouble-checkallofthewiringagainsttheblockdiagramshownearlierinthechapter.
BuildingtheenclosureforthespeakersystemSinceweareusingapremadeflightcaseasthebaseforourspeakersystem’senclosure,allwehavetodoiscutasinglepanelthatwillholdthespeakers,volumecontrol,andpowerswitchonapanelthatisexposed.Wecandothisbyopeningthecase,thushidingthePi,battery,andelectronicsbehindit.
Tomakethispanel,wewillusea3mmmediumdensityfiberboard(MDF);thisisacheapmaterialandisveryeasytoworkwith.
First,wewillneedtocutasquareofMDFthatisjustsmallerthantheopeningintheflightcase.Todothis,firstmeasurethelengthandwidthoftheinsideoftheflightcaseandmarkthisdistanceawayfromtwoedgesofasheetofMDF,asshowninthefollowingimage:
Next,takeatrysquareanddrawalineparalleltoeachedgeinlinewiththemarkingsinordertogiveanoutlineofwherethesquareneedstobecuttogetourpanelasshowninthefollowingfigure.
NoteWhenusingpowertools,propersafetyprecautionsshouldbeundertaken.Eyeprotectionshouldalwaysbewornandmains-poweredtoolsshouldbeprotectedusingaresidualcurrentdevice(RCD).
Oncethisisdone,wecantakeajigsawandcutalongthelinestogetthepanel,whichshouldbeabletosnuglyfitintheopeningoftheflightcase.
Nowthatwehavethebasicpanelfortheenclosure,wewillcutthetwospeakerholes.Sincedifferentspeakersaremountedindifferentways,Iassumethatyouareusingthesamespeakersthatarelistedonthepartslisthere.
Mountingthespeakerswillfirstinvolvecuttingalargeholeintothesheettosetthespeakersinandthendrillingfoursmallerholesthatareusedtoboltthespeakertothepanel.Fortunately,forthespeakers,thelargeholecanbemarkedouteasilybytracingaroundaCD.
Onceyouhavetheoutlineofthespeakerpositionedcorrectly,drilla10mmholeneartheedgeofeachcircle,asshowninthefollowingimage.Thiswillallowustogetinsidethecirclewiththejigsawinordertocutalargeholeinthepanel.
Oncethisisdone,insertthebladeofthejigsawintotheholeandcutaroundtheoutlineofthecircleforeachspeaker.Itisn’tvitalthattheholesarecutneatlyoraccurately,sincethespeakerwillcoverthisedgewheninstalled;however,itisimportantthatthespeakersitsflatwhenitismountedonthecutout.
Next,weneedtodrillthemountingholesthatwillbeusedtoboltthespeakerstotheMDFpanel;inthiscase,wewilldrill4mmholesanduseM3screwsandnutstomountthespeakers.
First,markthepositionsofeachholebyplacingthespeakerintotheholeandmakingamarkontheMDFthroughtheholeinthespeakerfascia(withapencil,forexample).
Next,drilla4mmholeineachmarkedposition.Itwouldbeagoodideatocheckwhethertheholeslineupwiththespeakercorrectlybytrialfittingitwithjustthescrews;however,wewillmountthespeakersproperlylater.
Next,weneedtodrillasingleholelargeenoughfortheshaftofthevolumecontrol.Thebestplacetopositionthisisinbetweenthespeakers,butfarawayenoughtoleaveroomforthefrontplate.Oncethepositionismarkedout,drilltheholeandremoveanyloosepiecesofmaterial.
Theholeforthepowerswitchisprobablythemostdifficultsinceitisasquarehole.Forthis,wewilldrilltwo10mmholesandusethejigsawtomakethetwoendssquareandremovethematerialinbetweenthem.
Thetwoholesshouldbearound15-20mmapart.Thisshouldallowasnugfitoftheswitchoncethefullholehasbeencutoutusingthejigsaw.Inthiscase,sincetheedgeofthecutmaybemorevisible,itisagoodideatotakeasmallamountofmaterialoffineachpassandtokeepcheckingwhethertheswitchfitsneatly.
Nowthatallthemountingholeshavebeencutoutofthepanel,itistimetomounteachcomponentonthepanel.Wewillstartwiththetwospeakers,whichcanbemountedbyinsertingthespeakerintothelargeholeandfasteningitinplaceusinganM3machinescrewineachmountingholewithacorrespondingwasherandnut.Tomakethewiringneater,itisagoodideatohavetheterminalsofeachspeakerfacingthesamedirection.Irecommendhavingthemfacethebackoftheflightcase.
Next,thepowerswitchcanbefitted;thisrequiresyoutodisconnecttheconnectionstotheamplifierterminalblocksfirst.Oncedisconnected,thisissimplyacaseoffeedingthewiringandfuseholderthroughthemountingholeandpushingtheswitchintothehole.Onceinplace,itshouldbekeptsecurelyinplacebyfrictionalone.
Next,thevolumecontrolcanbemountedbypushingthethreadedshaftthroughtheholedrilledforitfromthebackoftheMDFpanel.PlacetheplasticfrontplateovertheshaftonthefrontoftheMDFpanelandfastenitinplaceusingtheincludednuts.Theknobshouldthenbepushedon,ensuringthattheindicatorlinesupwiththeminimumindicatorontheplasticfrontpanel.
Bythistime,thefrontoftheMDFpanelshouldlooksimilartothefollowingimage:
AllthatislefttodonowismounttheDC-DCconverterandamplifierstothebackofthepanel,reconnect,andtidyupthewiring.
Sincetheamplifiermoduleshavemountingholes,Iusedthesetothreadsomelargecabletiesthroughandfastenedthemtothetwospeakers.ThisallowsasecuremountingoftheamplifiersthatdoesnotneedadditionalholestobedrilledintheMDFpanel.
TheDC-DCconvertercanbemountedanywhereontheMDFpanelusinganysuitableadhesive.Iwouldrecommendhotglueasitallowsfairlyeasyremovalwithoutriskingdamagetotheconverter,butyoucanalsousedouble-sidedtape.
Thenextstepistoreconnectallthewiringthatiscurrentlydisconnected.Whiledoingso,itisagoodideatotrimanywiresthatareexcessivelylongsothateachwireisjustlongenoughtoreachwhereitshouldconnectto.Thisismainlydonejusttomakethewiringtidier.
Bynow,thebackshouldlookasshowninthefollowingimage:
AssumingthatyouareusingthesameflightcasethatIused,therearetwodividersincludedthatmakeaperfectspacertokeeptheMDFpanelagooddistancefromthebottomoftheflightcase,thespacersshouldbeplacedaround40mmfromeachsideofthecase.
AllthatislefttodonowisreconnectthePiandbatteryandgivethesystematest.
RunningLogitechMediaServeronthePiOurcurrentsolutionisallwellandgoodifyouonlywanttousethesystemaroundthehomeandgarden.However,tomakethesystemtrulyportable,weneedtomovethemediacollection,LogitechMediaServer,andwirelessnetworktothePi.
CreatingabackupimageofanSDcardSincewewillnowbemakingafewchangestothesoftwarerunningonthePi,itmaybeworthwhilethatyoutakeanimageoftheSDcardsothatlater,itiseasytorestorethePitoitsworkingstate.
Fortunately,thisisaverysimplethingtodo,andsinceitisessentiallyjustthereverseofwritingtheOSimagetothecard,itcanbedonewiththeddutility:
sudoddif=/dev/sdbof=working.img
ThiswillcreateanimageoftheSDcardat/dev/sdbandsaveittotheworking.imgfile.ThiscanlaterberewrittentotheSDcardinthesamewayasafreshOSimage.
OnethingworthnotingaboutthismethodisthatitwilltakeanimageoftheentireSDcard,includinganyfreespace.Hence,thesizeoftheimageisequal(ormarginallysmallerinthemajorityofcases)tothecapacityoftheSDcard.Thismeansthattorestoretheimage,youneedanSDcardofatleastthecapacityofthecardtheimagewastakenfrom.Forthisreason,itisgoodtotryanduseanSDcardthatisjustbigenoughforwhatyouneed,inordertobothrestoretheimageontoalargerrangeofSDcardsandtoreducetheamountofstoragerequiredtokeeptheimages.
AutomountingaUSBstoragedeviceSinceitslikelythatyourmediacollectionmaynotentirelyfitonasingleSDcard(aswellasRaspbian),wewillopttostorethisonanexternalUSBdevice,thiscouldeitherbeaUSBmemorystickoranexternalharddrive.Theprocessofdoingthisisthesameforallstoragedevices.
First,weneedtoknowthepathtothestoragedeviceandthefilesystemituses.Bothcanbeobtainedusingthefollowingcommand:
sudoblkid
Thiswillgiveoutputsimilartothefollowing.Here,youcanseethetwopartitionsontheSDcard(mmcblk0p1andmmcblk0p2)aswellasaUSBmemorystick(/dev/sda1).Ensuringthatyouassignalabeltothepartitionwhileformattingitwillhelptomakeidentificationeasier:
/dev/mmcblk0p1:SEC_TYPE="msdos"LABEL="boot"UUID="787C-2FD4"TYPE="vfat"
/dev/mmcblk0p2:UUID="3d81d9e2-7d1b-4015-8c2c-29ec0875f762"TYPE="ext4"
/dev/sda1:SEC_TYPE="msdos"LABEL="DANNIXON"UUID="321A-15D0"TYPE="vfat"
NotethepathtothedeviceattheverystartofthelineandthepartitiontypegivenbyTYPE.Wewillneedbothofthesepiecesofinformationwhenwesetupthepartitiontobemountedattheboottime.
Next,wewillcreateadirectoryforthepartitiontobemountedon.Thisisthepaththatwillbeusedtoaccesstherootofthepartitionwhenitismounted.Inthiscase,wewillcreateadirectoryunder/media.InLinuxthisisthedirectoryusedformountingremovablefilesystems;thenameofthedirectoryisnotcritical,butsomethingdescriptiveisrecommended:
sudomkdir/media/music
Nowthatthemountpointhasbeencreated,wewillmodifythefilesystemtable(fstab)toautomaticallymountthedrivewhenthePiboots;thiscanbedoneusingthenanotexteditor.Thefilesystemtableneedstobemodifiedasroot:
sudonano/etc/fstab
ToaddthepartitionofourUSBdevice,thefollowinglineshouldbeaddedtotheendofthefile,replacing/dev/sda1withthepathtoyourpartitionandvfatwiththepartitiontype(whichwerediscoveredearlier):
/dev/sda1/media/musicvfatdefaults00
Oncefinished,pressCtrl+Xtosaveandexit.RebootthePiusing:
sudoreboot
OncethePihasbooted,checkwhetherthepartitionhasbeenmountedandisaccessibleusing:
ls/media/music
ThisshouldshowyouthefilesanddirectoriesattherootofthepartitionontheUSBstoragedevice.
InstallingLogitechMediaServerNowthatwehavethemusiccollectionstoredlocallywiththePi,weneedtomoveourLogitechMediaServerinstancethere.Officially,thereisnosupportforLMSonthePi,however,AllThingsPi(http://allthingspi.webspace.virginmedia.com/)hasalreadydonetheworkofportingLMStorunonthePi.
Firstly,thereareafewmorelibrariesthatarerequiredbyLogitechMediaServerthatmayneedtobeinstalledfirst.Thiscanbedonewiththefollowingcommand:
sudoapt-getinstalllibjpeg8libpng12-0libgif4libexif12libswscale2
libavcodec53
Now,wecandownloadandinstalltheDebianversionofLogitechMediaServerfromtheLogitechwebsite:
wget
http://downloads.slimdevices.com/LogitechMediaServer_v7.7.2/logitechmediase
rver_7.7.2_all.deb
sudodpkg-ilogitechmediaserver_7.7.2_all.deb
Asitis,theinstallationneedssomemodificationsbeforeitcanbeusedonthePi.Beforewestartwiththis,weneedtoensurethatLMSisnotalreadyrunning;thisisdonebyattemptingtostoptheservice:
sudoservicelogitechmediaserverstop
Next,weneedtodownloadandextracttherequiredfilesthatwillbeusedtomodifytheLMSinstallationfromAllThingsPi:
wgethttp://allthingspi.webspace.virginmedia.com/files/lms-rpi-
raspbian.tar.gz
tar-zxvflms-rpi-raspbian.tar.gz
Now,wecanperformtherequiredmodificationsusingthefollowingcommands:
sudopatch/usr/share/perl5/Slim/bootstrap.pmlms-rpi-bootstrap.patch
sudomvarm-linux-gnueabihf-thread-multi-64int
/usr/share/squeezeboxserver/CPAN/arch/5.14/
sudomvlibmediascan.so.0.0.0libfaad.so.2.0.0/usr/local/lib
sudomv/usr/share/squeezeboxserver/Bin/arm-linux/faad
/usr/share/squeezeboxserver/Bin/arm-linux/faad.old
sudomvfaad/usr/share/squeezeboxserver/Bin/arm-linux
sudoln-s/usr/local/lib/libmediascan.so.0.0.0
/usr/local/lib/libmediascan.so
sudoln-s/usr/local/lib/libmediascan.so.0.0.0
/usr/local/lib/libmediascan.so.0
sudoln-s/usr/local/lib/libfaad.so.2.0.0/usr/local/lib/libfaad.so
sudoln-s/usr/local/lib/libfaad.so.2.0.0/usr/local/lib/libfaad.so.2
sudoldconfig
sudochown-Rsqueezeboxserver:nogroup/usr/share/squeezeboxserver/
Oncewearefinished,LogitechMediaServershouldbereadytouse.However,IhadtorebootbeforeIwasabletonavigatetothewebinterface:
sudoreboot
OncethePihasbooted,navigatetoPI_IP:9000(wherePI_IPistheIPaddressofyourPi)toaccesstheLMSwebinterface.Here,youcanfollowthesamestepsdescribedearliertosetupyourmedialibrary.KeepinmindthatthewebinterfaceandmediascanningmayseemslightlyslowerthanonastandardPC.ThisismainlyduetothelowersystemresourcesofthePi.
SettingupthePiasaWi-FiaccesspointSincewewanttobeabletousethespeakersystemwhereverwego,weneedawaytoconnecttothePiwithoutrelyingontheavailabilityofawirelessnetwork.TheeasiestwaytodothisistoturnthePiintoaWi-Fiaccesspointthatwecanconnecttousingasmartphone.
First,wewillassignastaticIPaddresstotheWi-Fiinterface.Startbyopeningtheinterfacesfileinnano:
sudonano/etc/network/interfaces
Editthefilesothataftertheallow-hotplugwlan0line,itlookslikethefollowingcode.Thiscodeistellingthewlan0interfacetotakeastaticIPaddressratherthanusingDHCPaswasdonepreviously:
allow-hotplugwlan0
ifacewlan0inetstatic
address192.168.42.1
netmask255.255.255.0
#ifacewlan0inetmanual
#wpa-roam/etc/wpa_supplicant/wpa_supplicant.conf
#ifacedefaultinetdhcp
Next,wewillsetuptheDHCPserver,whichwillprovideanIPaddresstoanydevicesthatconnecttotheWi-Finetwork:
sudoapt-getinstallisc-dhcp-server
sudonano/etc/dhcp/dhcpd.conf
ThiswillopennanotoedittheDHCPserverconfiguration.First,uncommenttheauthoritativeline.ThistellstheserverthatitisthemainDHCPserveronthenetwork.Next,commentoutthefollowingtwolines:
optiondomain-name"example.org";
optiondomain-name-serversns1.example.org,ns2.example.org;
Next,addthefollowinglinestotheendofthefile:
subnet192.168.42.0netmask255.255.255.0{
range192.168.42.10192.168.42.50;
optionbroadcast-address192.168.42.255;
optionrouters192.168.42.1;
default-lease-time600;
max-lease-time7200;
optiondomain-name"local";
optiondomain-name-servers8.8.8.8,8.8.4.4;
}
Then,weneedtotelltheDHCPserverwhichinterfacestouse.Thisisdonebyeditingthefollowingconfigurationfile:
sudonano/etc/default/isc-dhcp-server
Addwlan0tothelistofinterfacessothatthelinelookslikethis:
INTERFACES="wlan0"
Next,wewillinstallandconfiguretheaccesspointdaemon.Thisinvolvescreatingaconfigurationfilefortheaccesspoint:
sudoapt-getinstallhostapd
sudonano/etc/hostapd/hostapd.conf
Addthefollowinglinestotheconfigurationfile,replacingNETWORKandPASSWDwiththeSSIDandkeyyouwishtouseforthewirelessaccesspoint:
interface=wlan0
driver=nl80211
#driver=rtl871xdrv
ssid=NETWORK
hw_mode=g
channel=6
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=PASSWD
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
Now,weneedtotellthedaemontousethisconfigurationfilewhenitstarts.Thisisdonebyeditingthedaemonstartupoptions:
sudonano/etc/default/hostapd
ReplacetheDAEMON_CONFlinewiththefollowing:
DAEMON_CONF="/etc/hostapd/hostapd.conf"
Finally,rebootthePiandyoushouldbeabletoconnecttotheWi-Finetworkusingtheloginusedintheconfigurationfile.YoucanthenuseeitherawebbrowserorsmartphoneapplicationtoconnecttotheLogitechMediaServerinstanceat192.168.42.1.
IftheWi-Finetworkisnotshowingupinasearch,youmayneedtouseanalternativedriver.Tocheckwhetherthisisthecase,runthefollowingcommands:
sudoapt-getinstalliw
iwlist
Ifyouseeamessagesimilartonl80211notfound,thenopen/etc/hostapd/hostapd.confandswapthecommentedoutdriverlinessothatrtl871xdrvisuncommented.Next,weneedtodownloadamodifiedversionofhostapdusingthefollowingsetofcommands:
wgethttp://www.adafruit.com/downloads/adafruit_hostapd.zip
unzipadafruit_hostapd.zip
sudomv/usr/sbin/hostapd/usr/sbin/hostapd.ORIG
sudomvhostapd/usr/sbin
sudochmod755/usr/sbin/hostapd
Oncethecommandshavefinishedexecuting,rebootthePiandyoushouldbeabletopickuptheWi-Finetwork.
SummaryInthischapter,wetookalookatsomebasicelectronicsthatweretobeusedtopowerthePiandexternaldevicesandtoamplifytheaudiofromtheaudiooutputonthePi.
Wealsotookthefirststepstodesignandmanufacturecustomenclosuresandfittingsforhardwareprojectsbyadaptinganexistingcasefortheenclosureofthespeakersystem.Inlaterprojectsinthisbook,wewillusetheseskillstomanufactureenclosuresfromscratch.
Inthenextchapter,wewilllookfurtherintodesigningandmanufacturingcustomizedenclosures,aswebuildaminitabletoparcademachine.
Chapter3.MiniRetroArcadeCabinetInthischapter,wewillbuildaminiretro-stylearcadecabinet,whichrunsaselectionofemulatorsthatcanplaygamesfromawidevarietyofgameconsolesandarcademachines.ThiswillbedoneusinganoperatingsystemcalledPiPlay(formallyknownasPiMAME).
Anarcadecabinetisessentiallyastandardcomputerandmonitorinacustom-builtcabinetusedtomimicthestyleandshapeofretroarcademachines.
Thisprojectwillalsobethefirstthatinvolvesasignificantamountofwoodworkandcarpentryinthemakingofthecabinetforthearcadesystem.Althoughitseemslikeadauntingtaskforanyonewhohasnotundertakenaprojectlikethisinthepast,theconstructionisrelativelysimpleandcanbedonewithcommonhouseholdtools.
Tocontrolthegames,wewilluseaselectionofarcadecontrolsthatarereadilyavailableonline.WewillinterfacethemtothePiusingtheGPIOportandsomesoftwarewrittenbyAdafruit.
ThisprojectisbasedonasimilarprojectbuiltbyTonyDixonatMakerSpace,Newcastle.
RequirementsForthisproject,youwillneedthehardwareandtools.Hereisthelistofthehardwarerequired:
TheRaspberryPiAUSBkeyboard(forsetuponly)ArcadebuttonsandajoystickAmonitor(andanHDMIadapterifneeded)Asheetof6mmplywood(seetheBuildingthecabinetsectionforthesizerequired)Asheetof12mmplywood(seetheBuildingthecabinetsectionforthesizerequired)Female-to-female0.1inchpinjumpers
Toolsrequiredforthisprojectarelistedasfollows:
AsolderingironandsolderWirecuttersAPozidrivscrewdriverAdrillmachineA30mmForstnerdrillbitSandpaper(80,120,and240grit)Ajigsaw
SettinguptheinputelectronicsInthissection,wewillsetuptheinputhardwaretothearcadecabinet.Thecabinetwewillbuildcomprisesajoystickandsevenpushbuttons.AllofthedevicesusedforthisaresimpledigitallogicdevicesthatcanbeconnecteddirectlytotheGPIOheaderonthePiwithoutexternalelectronics.
Firstly,wewillsoldertheconnectingwirestoeachofourarcadebuttonsandjoystick.ThebuttonsusedhavethreeconnectionsonthemthataremarkedasCOM,NC,andNO,whichstandforcommon,normallyclosed,andnormallyopen.
NoteThebuttonsandjoystickthatIhaveusedarefromaselleroneBaycalledultracabs(http://www.ebay.co.uk/usr/ultracabs)whosellsavarietyofhardwareforarcadecabinets.Whileanybuttonsandjoysticksshouldwork,Iwillbeusingtheseintheinstructions.
Inourcase,wewanttocreateacircuitwhenthebuttonispressed,soweneedtosolderwirestoCOMandNO.Inthiscase,wewillusefemale-to-female0.1inchjumperwireswithoneendremovedandstripped,asthiswillalloweasierconnectiontothepinsonthePiGPIOport,asshowninthefollowingimage:
Next,weneedtosolderthesameconnectingwiresontothejoystick.Forthis,therearefoursimilarswitchestowhatwereusedonthebuttonsaroundtheundersideofthejoystickassemblythatneedstobeconnected.
NotethattheparticularjoystickIrecommendonlyhasCOMandNOconnections,sosincethereareonlytwoconnectionsontheswitch,gettingthewiresconnectedinthecorrectwayislessimportanthere.
Here,itisworthconnectingtheCOMconnectionsofeachswitchtogetherwithshortpiecesofstandardwire,sothatweonlyneedasinglecommonwirerunningtothe
joystick.
Next,aswiththebuttons,soldera0.1inchjumperwiretoeachswitchcontactandasinglejumperwiretooneofthecommonconnections:
Oncethisisdone,theelectronicspartofthisprojectisprettymuchcomplete.WewillconnectthebuttonsandjoysticktothePilater,oncetheyaremountedonthecabinet.
BuildingthecabinetFirstly,itisimportanttohaveagoodideaofthedimensionthatweneedforeachpartofthecabinet.ThefollowingdiagramshowsthedimensionofthecabinetImadewiththeheightandwidthofthemonitor.Whileyouarefreetoadaptthedesigntowhateverstyleyoulike,beawareofthedimensionsthatarelikelytochangethroughoutthedesign.Inthefollowingdiagram,notethatallthesizesareinmm:
Notethattheanglebetweenthemonitorandjoystickpanelisnotfixed,asitwilldependonthesizeofthemonitorandjoystick/buttonpanel.Thedimensionslistedinthediagramareonlyaroughguideandyouareencouragedtodrawasidepaneloutinascaleof1:1tocheckthedimensionsbeforedecidingonthem.
NoteWhenusingpowertools,propersafetyprecautionsshouldbeundertaken.Eyeprotectionshouldalwaysbewornandmains-poweredtoolsshouldbeprotectedusingaresidualcurrentdevice(RCD).
Thefirstpartswewanttocutarethetwosidepanelsfortheenclosure.Thesewillbothbecutfroma12mmplywood.Aswewillbeusingajigsawtocutthepanels,wewillcutboththeleft-handsideandright-handsidepanelsatthesametime,sinceitisverydifficulttogetexactlythesamecuttwicewhenyou’reguidedbyeyealone.
NoteFormycabinet,IoptedtouseBirchplywood,asithasamuchnicerappearanceandisstrongerthanstandardplywood.However,itmoreexpensiveandcanbehardertoworkwith.
Forthis,weneedtoensurethatthetwosheetsofplywooddonotmoverelativetoeachotherduringthecut.Therearemultiplewaystodothis,butthewayIchosewastoscrewthetwosheetstogetheratregularintervalsjustoutsidethecutline(refertothefollowingimage).Thisisprobablyoneofthebestways,asthismethodoffixingisveryeasytoremoveandwillwithstandalotofforce(morethanyouwilleverexertonitwhilesawing)beforethesheetsstarttomove.
Onceboththesheetsofmaterialarefixedtogether,youwillneedtomarkoutthecutpathinfaintpencilmarkingsononesideofthematerial.Ensuringthatthisisasfaintaspossiblewillmakeitiseasiertoremoveanyleftovermarkingswhilesandingthepanels
downlater.
Oncethepanelshavebeencutoutasshowninthefollowingimage,theywillhavefairlyuntidyedges,especiallywhenyoucutagainstthegrainofthetoplayerofmaterial.Aseachpanelismade,itisagoodideatotakeapieceofalow-gritsandpaper(around40-60)andquicklyremoveanyuntidyedges.Whenitistimeforthepaneltobeassembledinitsfinalposition,youshouldtaketimetosandtheedgesandsurfaceswithprogressivelyhighergripsandpaperstoachieveasmoothandtidyfinish.Agoodprogressionwouldbe80,then120,andthen240.
NoteThegritclassificationofsandpaperisbasedonthenumberofabrasiveparticlespersquareinchofmaterial.Theycanrangefrom24(verycoarse)to1,000(veryfine).
Next,wewillcutthebottompanelofthecabinet.Also,cutfromthe12mmplywood,asshowninthediagramatthestartofthissection.Thewidthofthispanelwillbearoundthewidthofthemonitorplus10mm,andthedepthwillbewhateverthedesiredwidthofthecabinetis(inthecaseofthediagram,itis400mm).
Aswiththesidepanels,theyshouldbesandeddowntoremoveanyroughedges.However,asonlyoneedgewillbeexposedtothefrontofthecabinet,gettingaperfect
finishhereisnotessential.
Next,wewillattachthebottompaneltothetwosidepanels.Todothis,wewillusebothscrewsthroughthesidepanelsthatgointotheedgeofthebottompanelandseveralplasticassemblyfittingsliketheonesshowninthefollowingimage.Thiswillhelptoensureagoodquality,durablejoint.
NoteForamorepermanentfitting,PVAwoodgluecanalsobeusedonthejointsbetweentwoplywoodpanels.
First,placethebottompanelonaflatsurfaceandaligntheonesidepanelnexttothematchingedgeofthebottompanel.Next,drillaseriesofpilotholesthatarearound1-2mmsmallerthanthescrewsthatwillfixthetwopanelstogetheratregularintervalsalongtheedgeofthesidepanel.Theywillalsoscrewthesidepaneltothebottompanel,asshowninthefollowingimage.Thescrewsusedhereshouldbedome-headed,self-tappingwoodscrewsaround1.5incheslong.Here,itisimportanttoensurethatthepilotholesaredeepenoughtopreventtheplywoodfromsplittingasthescrewsareinserted.
Next,ontheinsideofthecabinet,screwseveraloftheplasticassemblyjointsatthecornerbetweenthetwopanelsbyusingcountersunkself-tappingwoodscrewsaround3/4inchlong.Ensurethataround30mmofspaceisleftateachendtogiveenoughclearanceforotherpanelsandtheirassemblyjoints,asshowninthefollowingimage.Repeatthisprocessforthesecondsidepanel:
Next,wewillcutthepanelthatwillholdthemonitorinplace.Thispanelneedstobearound150mmhigh,thesamewidthasthebottompanel,andcutfrom12mmplywood.Thiscanbemarkedoutandcutinthesamewayastheotherpanels.
Onceyou’vecutoutthepanel,followthenextdiagramtomarkoutthefourholesthatwillbeneededtoattachthemonitor.Here,IamassumingthatthemonitorusestheVESA100standard,whichisthemostcommonsizefoundon15-22inchcomputermonitors.Itwouldbeworthcheckingthisstandardwhenyou’relookingforamonitorforthisproject.VGAmonitorswiththistypeofmountingareverycommononInternetauctionsitesandoftensellverycheaply.Notethatthefollowingdiagramisnottoscaleandthatthecenterofthepanelisindicatedbytheredcross:
OncetheVESAholesaredrilled,youcanpreparethemonitortobemountedonthepanelbyremovinganydeskstandithad(theprocedurefordoingsovariesforeachmonitor;itisworthsearchingonlineifitisnotobvioustoyouhowitcanberemoved).AttachthemonitorusingfourM4machinescrewsintheholesyou’vejustdrilled,asshowninthefollowingimage.Itisimportanttouseawasheronbothsidesoftheplywoodpaneltohelpspreadtheweightofthemonitorandtopreventthescrewheadsfromdiggingintotheplywood.
Next,wewillattachthemonitormounttothetwosidepanels.Tomakethepositioningofthemonitoreasier,first,tipthecabinettoitssidesothatthemonitor’sweightissupported.Now,movethemonitorpaneluntilthemonitorisinthedesiredposition.Thisshouldleaveatleast5mmatthetopforcoolingandthebottomshouldbejustabovewherethebuttonpanelwillbe.
Now,attachthemonitorpaneltothetwosidepanelsusingtwoassemblyjointsoneachsideofthepanel.Thiswillkeepthepanelinplacefornow.However,aswiththebottompanel,weneedtoaddsomelongerscrewsthatgothroughthesidepaneltoprovideenoughsupportfortheweightofthemonitor.
Todothis,unscrewthemonitorandmarktheoutlineofthemonitorpanelontheinsideofeachsidepanelandthenremovethescrewsholdingtheassemblyjointstothesidepanels.Thiswillleaveanindicationthatthepanelwasmounted.
Next,drilltwoholesineachsidepanelthatwillbeusedtoguidethescrewsintothesideofthemonitorpanel,asshowninthefollowingimage.Itisimportantheretoensurethatthepositionoftheholeswillnotcausethescrewstocollidewiththescrewsalreadyinthepanelfromtheassemblyjoints.
Oncethisisdone,reattachthemonitorpanelwiththeassemblyjointsandusetheholesdrilledinthesidepanelstodrillpilotholesintheedgeofthemonitorpanel,similartowhatwasdoneinthebottompanel.Tofinish,screwtwoofthesamescrewsusedforthebottompanelintoeachsideofthemonitorpanelandreattachthemonitor.Bynow,thebackofthecabinetshouldlooksimilartowhatisshowninthefollowingimage:
Next,wewillcutthefront,top,andbutton/joystickpanels.Allofthesepanelscanbecutfrom6mmplywoodandthewidthofthesewillbethesameasthebottomandmonitorpanels.Theexactwidthofthesewilldependonyourdesign,basedonthediagramearlierinthissection.Onceyouhavethedimensionsofthepanels,theycanbecutinthesamewayastheotherpanels.
First,wewillattachthetoppanel.Thisshouldbemountedonthetopbetweenthetwosidepanelsandcanbeheldinplacewithtwoassemblyjointsoneachsideofthepanel,asshowninthefollowingimage.Sincethisplywoodisthinner,youwillneedtousehalfinchscrewsforthis.
Next,weneedtodrillaholeinthefrontpanelforthesingle-playerarcadebutton.Todothis,wewillusea30mmForstnerdrillbit.First,startbymarkingthecenteroftheholeforthebutton.Thiswillbeusedtoalignwiththesharppointinthecenterofthedrillbit.
Althoughholeslikethisarebestdrilledusingapillardrillordrillpress,theycanbedrilledusingahandheldelectricdrill(abattery-poweredcordlessdrillisunlikelytohaveenoughpowertodriveaForstnerbitofthissize).Itisimportanttoholdthedrillasverticalandsteadyaspossibletoensurethattheholedoesnotbecomeoutofshapebythe
drillasitmovesrelativetothepanel.
Whendrillingbyahandhelddrill,itisbesttostartslowtoensurethatthedrillgetsagoodpositioninthecenteroftheholeandgraduallyspeeduptodothebulkofcutting.Itmaytakeseveralminutestofullycutthroughthepanel,anditisworthstoppingoccasionallytocleananymaterialthathasbuiltuponthedrillbit.Becarefulwhendoingthis,asfrictioncancausethedrillbittoheatupenoughtocauseburns.Thedrilledholeisshowninthefollowingimage:
Oncetheholeisdrilled,removeanyloosematerialaroundtheedgesoftheholeusingmedium-lowgritsandpaper(either80or120)andinsertthebuttonthroughthehole.Todothis,youwillhavetoremovethemicroswitchfromthebacksideoftheswitch.IntheswitchthatIused,thisisdonebyliftingtheclipsononesideoftheswitch,whichallowsthemicroswitchtobeleveredout.
Oncetheswitchisfittedandtheedgesofthepanelaresandeddown,thepanelcanbefittedusingfourassemblyjoints,asshowninthefollowingimage.Dependingontheaccuracyofthecut,youmayfindthatthepanelisatightfitinbetweenthetwosidepanels.Ifthisisthecase,thenloosenthescrewsthatholdthesidepanelstothebottompanelsothatthesidepanelscanbemovedoutwardsslightly.Thisallowsthefrontpaneltobeinsertedeasily.
Notethatintheprecedingimage,Iused12mmplywoodforthefrontpanel.Whileitispossibletodothis,itisnotrequired.Drillingthe30mmholetakesmuchlonger.
Next,wewanttomarkthepositionofthebuttonsandjoystickonthefrontpanel.Thebestwaytodothisistoplacethepanelinpositiontoseewhichpositionwillfeelmostcomfortableorintuitivetoplay.Onceyouhavedonethis,markthepositionofthecenterofeachbuttonandthejoystick,asshowninthefollowingimage:
Nowthatwehavethepositionsofeachparttobemountedonthispanel,wecanstartdrillingtheholesforthem,startingwiththejoystick.
Withthejoystick,Irecommendthatyoudrillone30mmholefortheshaftofthejoystickandfour4mmholesforthemountingscrews.Startbydrillingthe30mmholecenteredonthemarkyoumadeforthecenterofthejoystick.Thisholewillbecutusingthe30mmForstnerbitinthesamewayastheholeforthebuttononthefrontpanel.
Oncethisisdone,insertthejoystickintotheholewiththeswitchsideonthebacksideofthepanel(youwillneedtounscrewtheredballfromthetopofthejoystickfirst)andmarkthepositionofthefourholesinthecornerofthemetalplate.Thisiswherewewilldrilltheholesthatwillbeusedtomountthejoystick.
Aftertheholeshavebeendrilled,thepanelshouldlooksomethinglikewhat’sshowninthefollowingimage:
Wewillmountthejoysticklateron.Now,itistimetodrilltheholesforourarcadebuttons.Thisisdoneinthesamewayaswasdoneforthesingle-playerbuttononthefrontpanel.
Eachofthebuttonscannowbemountedonthepanel.Whilenonessential,mountingthemsothatallofthemicroswitcheslineupparalleltoeachothermakescablemanagementeasier,asshownintheupcomingimage.
Next,wecanfastenthejoystickinpositionwithfourM3machinescrewsbyusingawasherforboththesidesofthemetalplateonthejoystick.Finally,placetheround,blackdiscthatcamewiththejoystickoverthejoystickshaftandreattachtheredball.
Bythispoint,thebackofthefrontpanelshouldlooksomethinglikewhat’sshowninthefollowingimage:
Allthatislefttodonowistoattachthebutton/joystickpaneltotherestofthecabinet.Aswithalltheotherpanels,thiscanbeeasilydonebyusingseveralassemblyjoints.
Whileitispossibletousefourjointsheretofixthepanelinasingleposition,Ifounditusefultoonlyattachthepanelusingtwojointsatthebackofthepanel(closesttothebottomofthemonitor).ThiswillallowthefrontpaneltobeliftedupforeasyaccesstothePiandwiring,asshowninthefollowingimage:
Ialsochosetouseasetofmale-to-female0.1inchjumperwirestoextendthewiresthathadbeensolderedontothebuttonandjoystickswitches.Again,thisisnotessential,butmayhelptomakewiringtheswitchestothePieasier.
Ofcourse,thisisjustonepossiblewaytodesignthecaseforthearcadecabinet.Hereareanothertwoveryuniquedesignsofasimilarproject:
http://www.instructables.com/id/NaCade-The-Naked-Raspberry-Pi-Arcade-Machine/http://www.instructables.com/id/MAME-gaming-table-with-Raspberry-Pi/
SettingupPiPlayFirst,youshouldheadtothePiPlaywebsite(http://pimame.org),downloadthelatestversionoftheOS,andwritetheimagetoanSDcard.ThisisthesameprocedurethatwefollowedwithRaspbianinthetwopreviousprojects.
OncetheimageiswrittentotheSDcard,connectanetworkcable,USBkeyboard,andmonitortothePiandpoweritup.Afterafewminutes,youshouldseethePiPlaymainscreen,asshowninthefollowingscreenshot:
Thisshowsalistofalltheinstalledemulatorsandacountofhowmanygamesareinstalledforeachoneinthesmallredsquares(obviously,foracleaninstall,therewillnotbeanygamesinstalled).
PiPlayhasawebinterfacethatcanbeusedtouploadgamestothearcadesystem.ThisisaccessedusingtheIPaddressofthePi,asshowninthefollowingscreenshot:
ThisinterfacecanalsobeusedtoshutdownandrebootthePiusingtheToolsmenu.Fornow,wewilluseROMUploadertoaddanewgametotheGameboyemulator.Thelistofalltheinstalledemulatorsisshowninthefollowingscreenshot:
NoteTherearemanywebsiteswhereROMscanbedownloaded.Ifyou’relookingforaparticulargame,thebestoptionistouseasearchenginewithaquerycontainingthenameofthegameandtheplatformyouwanttoemulateiton.
Here,wewillselecttheGameboyemulator.ThisshowsapagewhereyoucandraganddropanyROMfilesfromyourPCthataretobeuploadedtothePi:
Oncetheuploadiscomplete,thenewgamewillbeavailableinthemenuforthatemulator.
Whenanewgamehasbeenaddedforacertainemulator,PiPlaywillaskwhetheryouwanttodownloaditsinformationfromanonlinedatabase,asshowninthefollowingscreenshot.Thiswillautomaticallycorrectthenameofthegameanddownloadacoverimageifitisavailable;itisnotrequiredthatyoudothistoplayagame.
Whenanemulatorisselected,amenusimilartotheoneshowninthefollowingscreenshotisshown,whichlistsallthegamesuploadedtothePiforthecurrentemulator.Tostartone,selectitusingthearrowkeysandpressEnter.ToreturntothemainPiPlaymenu,pressEsc.
UsingthebuttonsandjoystickwithPiPlayWhiletheabilitytouseGPIOinputsasinputtoemulatorsisplannedforafuturereleaseofPiPlay,thecurrentversiondoesnotsupporttheuseofswitchesconnectedviatheGPIOportasinputtogameemulators.Hence,weneedanadditionalpieceofsoftwaretodothis.
Fortunately,AdafruithasalreadywrittenadriverthatconvertsswitchsignalsfromtheGPIOporttokeypresses(https://github.com/adafruit/Adafruit-Retrogame),whichwewilluseforourarcadebuttonsandjoystick.
First,weneedtoinstallsomerequiredprogramsandlibrariesthatwillallowustorecompiletheretrogamesoftwarewhenwemakechangestoit;thesecanbeinstalledusing:
sudoapt-getinstallgitlibexpat1libexpat1-devlibncurses5libncurses5-
dev
Next,wewilldownloadtheretrogamesoftwareandmovetothedirectoryitwassavedinbyusingthefollowingtwocommands:
gitclonehttps://github.com/adafruit/Adafruit-Retrogame.git
cdAdafruit-Retrogame
Whilethereisalreadyaprecompiledversionofthesoftwareavailable,itwillnotbesuitableforthetypeofarcadesystemwehavebuilt.So,weneedtomakeafewmodificationstothecodefirst.Usethefollowingcommandtostarteditingtheprogram:
nanoretrogame.c
Next,lookforthelinethatstartswithioStandardandreplacethelinesuptotheENDOFLISTmarkerwiththefollowingcode.NotethatifyouareusingaPiBversion1,youneedtoreplace27with21inthiscode:
ioStandard[]={
{25,KEY_LEFT},
{11,KEY_RIGHT},
{8,KEY_UP},
{9,KEY_DOWN},
{24,KEY_ENTER},
{22,KEY_S},
{17,KEY_D},
{10,KEY_Z},
{23,KEY_X},
{27,KEY_C},
{7,KEY_ESC},
{-1,-1}
};
Oncethisisdone,thecodeshouldlooksomethinglikethefollowing:
Oncethisisdone,recompilethecodeusingthefollowingcommand:
make
Thismaytakeacoupleofminutesandwilloutputamessagesimilartothefollowing:
Ifthisisthecase,thenallisgoodandyoucanmoveontothenextstep.IfyougetamessagewiththewordErrorinitanywhere,thenyouwilllikelyhaveerrorsinthesyntax
oftheprogramcode.Inthiscase,checkwhetherthecodeyouhavematcheswhat’sshownintheprecedingscreenshot.Youcanalsogetanerrorwhenoneofthelibrariesusedbythecodeisnotinstalledcorrectly;inwhichcase,tryupdatingtheinstalledpackagesusingthefollowingcommands:
sudoapt-getupdate
sudoapt-getupgrade
sudoapt-getinstallgitlibexpat1libexpat1-devlibncurses5libncurses5-
dev
Oncetheretrogameprogramiscompiledsuccessfully,weneedtoaddaudevruletoensureitscompatibilitywithemulatorsusingthelatestSDL2library.Todothis,createanewrulefileusingthefollowingcommand:
sudonano/etc/udev/rules.d/10-retrogame.rules
Onasingleline,addthefollowingcode:
SUBSYSTEM=="input",ATTRS{name}=="retrogame",ENV{ID_INPUT_KEYBOARD}="1"
Next,wewanttoensurethattheretrogameprogramstartsassoonastheOSbootsinordertoremovetheneedtoattachakeyboardtothePi.Thiscanbedonewithanadditiontotherc.localfile:
sudonano/etc/rc.local
Addthefollowinglinetothescriptjustbeforetheexit0line:
/home/pi/Adafruit-Retrogame/retrogame&
Thescriptshouldnowlooksimilartothefollowing:
ThisscriptisrunattheendoftheLinuxbootsequence,soitisagoodplacetoaddcodethatshouldbeexecutedaftertheoperatingsystemhasfinishedbooting.
Finally,rebootthePiandmoveontoconfigurethebuttonswithinPiPlay:
sudoreboot
ThenextstepistowireupthebuttonsandjoysticktotheGPIOport.Thismustbedone,asshowninthefollowingdiagram,toensurethatthebuttonmappingisasexpectedandbasedonthecodechangedinretrogame.c.ItwouldbeworthdoingthiswiringwiththepowertothePiturnedofftoreducethechancesofmistakesandpermanentdamagetothePi.
NotethatPLR1isthebuttononthefrontpanel,B1-3isthebottomrowofbuttonsfromlefttoright,andT1-3isthetoprowofbuttonsfromlefttoright.
Oncealltheconnectionshavebeenmade,theinsideofthefrontofthecabinetshouldlooksomethinglikewhat’sshowninthefollowingimage.AlsonotethatthewhiteHDMItoVGAconverterallowsyoutouseanoldPCmonitorforthisproject.
Intheprecedingimage,youmaynoticethatIampoweringthePifroma5Vpowersupply,whichisconnecteddirectlytothe5VandgroundpinsontheGPIOport.Thisisnotessential,butifyoufindthatthePibecomesunstableorhasproblemswithUSBdevicesorinmaintaininganetworkconnection,thenthismaybethecasebecausethepowersupplycannotsupplyenoughcurrent.Thiscanhappenespeciallyifyou’reusingaHDMItoVGAconverter,whichrequiresacertainamountofpowertooperate.
Oncethisisdone,repowerthePi.WhenthePibootsbackintoPiPlay,youwillnoticethatthejoystickandbutton1willalreadybeabletomovethecursorandselectemulators.However,youwillneedtoconfigurethekeymappingfortheadditionalbuttonsusedbyeachemulator.
Toconfigurethejoystickandbuttonsforacertainemulator,presstheTabkeyonthekeyboard.Thisshouldbringupamenusimilartotheoneshowninthefollowingimage.UsethearrowkeystoscrolldowntoControllerSetupandpressEnter.
ThiswillshowanothermenuthatshowsalltheemulatorsthatPiPlaycancontrolthekeymappingof.Here,itisbesttoselectasingleemulatorandassignitskeymappingindividually,forinstance,selectarcadefromthismenu.
Thiswillthenshowapreviewofthecontrollerasshowninthefollowingimageandyouwillbepromptedtopresscertainbuttonstoconfigurethekeymapping.Certainemulatorsmayhavemorebuttonsthanwhatareavailableonthecabinet.Inthiscase,theywillhavetobemappedtokeysontheUSBkeyboard.(Ihaveonlyfoundthistobethecasewithacoupleofemulators,forexample,thepauseandcreditbuttonsofMAMEemulatorshavetobemappedtokeysonthekeyboard.)
Oncethisisdone,youwillbetakenbacktothemainmenuandcanthenselectanyoftheemulatorsusingthejoystickandarcadebuttons.Notethatthetop-leftarcadebuttonisusedtoselectamenuoptionandthefront,single-playerbuttonisusedtoreturntothePiPlaymainmenu.
SummaryInthischapter,wehadagoodlookattheprocessofdesigningandbuildingacustomenclosureforaprojectbasedontherequirementsofspecificpartsthataretobeusedintheproject.
WealsomademoreuseoftheGPIOportonthePibyusingitasanadditionalinputdevicetocontrolavarietyofgamesmadeavailableonthePiPlayoperatingsystem.
Inthenextchapter,wewillusetheRaspberryPicameramoduletocreatealocation-awaretime-lapserecorderthatcanbeusedtorecordaseriesofstillimagesoveralongperiodoftime.
Chapter4.GPS-enabledTime-lapseRecorderOneofthepossibleusesoftheRaspberryPicameramoduleistherecordingoftime-lapsecaptures,whichtakesastillimageatasetintervaloveralongperiodoftime.Thiscanthenbeusedtocreateanacceleratedvideoofalong-termeventthattakesplace(forexample,abuildingbeingconstructed).
Onealterationtothisistohavethecameramountedonamovingvehicle.Usethetimelapsetorecordajourney;withtheadditionofGPSdata,thiscanprovideaninterestingrecordofareasonablylongjourney.
Inthischapter,wewillusetheRaspberryPicameramoduleboardtocreatealocation-awaretime-lapserecorderthatwillstoretheGPSpositionwitheachimageintheEXIFmetadata.
Todothis,wewilluseaGPSmodulethatconnectstothePiovertheserialconnectionontheGPIOportandacustomPythonprogramthatlistensfornewGPSdataduringthetimelapse.
Forthisproject,wewillusetheRaspbiandistribution.InstructionsonhowthisisinstalledcanbefoundinChapter1,RaspberryPiPirateRadio.
WhatyouwillneedThisisalistofthingsthatyouwillneedtocompletethisproject.Alloftheseareavailableatmostelectroniccomponentsstoresandonlineretailers:
TheRaspberryPiArelativelylargeSDcard(atleast8GBisrecommended)ThePicameraboardAGPSmodule(http://www.adafruit.com/product/746)0.1inchfemaletofemalepinjumperwiresAUSBpowerbank(thisisoptionalandisusedtopowerthePiwhennootherpowerisavailable)
SettingupthehardwareThefirstthingwewilldoissetupthetwopiecesofhardwareandverifythattheyareworkingcorrectlybeforemovingontothesoftware.
ThecameraboardThefirst(andthemostimportant)pieceofhardwareweneedisthecameraboard.Firstly,startbyconnectingthecameraboardtothePi.
ConnectingthecameramoduletothePiThecameraisconnectedtothePiviaa15-pinflat,flexribboncable,whichcanbephysicallyconnectedtotwoconnectorsonthePi.However,theconnectoritshouldbeconnectedtoistheonenearesttotheEthernetjack;theotherconnectorisfordisplay.
1. Toconnectthecablefirst,liftthetopretentionclipontheconnector,asshowninthefollowingimage:
2. Inserttheflat,flexcablewiththesilvercontactsfacingtheHDMIportandtherigid,blueplasticpartoftheribbonconnectorfacingtheEthernetportonthePi:
3. Finally,pressdownthecableretentioncliptosecurethecableintotheconnector.Ifthisisdonecorrectly,thecableshouldbeperpendiculartotheprintedcircuitboard(PCB)andshouldremainseatedintheconnectorifyoutrytousealittleforcetopullitout:
4. Next,wewillmoveontosetupthecameradriver,libraries,andsoftwarewithinRaspbian.
SettinguptheRaspberryPicameraFirstly,weneedtoenablesupportforthecameraintheoperatingsystemitselfbyperformingthefollowingsteps:
1. Thisisdonebytheraspi-configutilityfromaterminal(eitherlocallyoroverSSH).Enterthefollowingcommand:
sudoraspi-config
Thiscommandwillopenthefollowingconfigurationpage:
Thiswillloadtheconfigurationutility.ScrolldowntotheEnableCameraoptionusingthearrowkeysandselectitusingEnter.
2. Next,highlightEnableandselectitusingEnter:
Oncethisisdone,youwillbetakenbacktothemainraspi-configmenu.Exitraspi-config,andrebootthePitocontinue.
3. Next,wewilllookforanyupdatestothePikernel,asusinganout-of-datekernelcansometimescauseissueswiththelow-levelhardware,suchasthecameramoduleandGPIO.WealsoneedtogetalibrarythatallowscontrolofthecamerafromPython.
Bothoftheseinstallationscanbedonewiththefollowingtwocommands:
sudorpi-update
sudoapt-getinstallpython-picamera
4. Oncethisiscomplete,rebootthePiusingthefollowingcommand:
sudoreboot
5. Next,wewilltestoutthecamerausingthepython-picameralibrarywejustinstalled.
Todothis,createasimpletestscriptusingnano:
nanocanera_test.py
6. Thefollowingcodewillcaptureastillimageafteropeningthepreviewfor5seconds.Havingthepreviewopenbeforeacaptureisagoodideaasthisgivesthecameratimetoadjustcaptureparametersoftheenvironment:
importsys
importtime
importpicamera
withpicamera.PiCamera()ascam:
cam.resolution=(1280,1024)
cam.start_preview()
time.sleep(5)
cam.capture(sys.argv[1])
cam.stop_preview()
7. SavethescriptusingCtrl+XandenterYtoconfirm.Now,testitbyusingthefollowingcommand:
pythoncamera_test.pyimage.jpg
8. Thiswillcaptureasingle,stillimageandsaveittoimage.jpg.ItisworthdownloadingtheimageusingSFTPtoverifythatthecameraisworkingproperly.
TheGPSmoduleBeforeconnectingtheGPSmoduletothePi,thereareacoupleofimportantmodificationsthatneedtobemadetothewaythePibootsup.
Bydefault,Raspbianusestheon-boardserialportontheGPIOheaderasaserialterminalforthePi(thisallowsyoutoconnecttothePiandruncommandsinasimilarwaytoSSH).However,thisisoflittleusetoushereandcaninterferewiththecommunicationbetweentheGPSmoduleandthePiiftheserialterminalisleftenabled.Thiscanbedisabledbymodifyingacoupleofconfigurationfiles:
1. First,startwith:
sudonano/boot/cmdline.txt
2. Here,youwillneedtoremoveanyreferencestottyAMA0(thenamefortheon-boardserialport).Inmycase,therewasasingleentryofconsole=ttyAMA0,115200,whichhadtoberemoved.Oncethisisdone,thefileshouldlooksomethinglikewhatisshowninthefollowingscreenshot:
3. Next,weneedtostopthePibyusingtheserialportfortheTTYsession.Todothis,editthisfile:
sudonano/etc/inittab
4. Here,lookforthefollowinglineandcommentitout:
T0:23:respawn:/sbin/getty-LttyAMA0115200vt100
Oncethisisdone,thefileshouldlooklikewhatisshowninthefollowingscreenshot:
5. Afterboththefilesarechanged,powerdownthePiusingthefollowingcommand:
sudoshutdown-hnow
Next,weneedtoconnecttheGPSmoduletothePiGPIOport.OneimportantthingtonotewhenyoudothisisthattheGPSmodulemustbeabletorunon3.3Voratleastbeabletousea3.3Vlogiclevel(suchastheAdafruitmoduleIamusinghere).
NoteAswithanydevicethatconnectstothePiGPIOheader,usinga5VlogicdevicecancauseirreparabledamagetothePi.
Next,connecttheGPSmoduletothePi,asshowninthefollowingdiagram.IfyouareusingtheAdafruitmodule,thenallthepinsarelabeledonthePCBitself.Forothermodules,youmayneedtocheckthedatasheettofindwhichpinstoconnect:
Oncethisiscompleted,thewiringtotheGPSmoduleshouldlooksimilartowhatisshowninthefollowingimage:
AftertheGPSmoduleisconnectedandthePiispoweredup,wewillinstall,configure,andtestthedriverandlibrariesthatareneededtoaccessthedatathatissenttothePifromtheGPSmodule:
1. Startbyinstallingsomerequiredpackages.Here,gpsdisthedaemonthatmanageddatafromGPSdevicesconnectedtoasystem,gpsd-clientscontainsaclientthatwewillusetotesttheGPSmodule,andpython-gpscontainsthePythonclientforgpsd,whichisusedinthetime-lapsecaptureapplication:
sudoapt-getinstallgpsdgpsd-clientspython-gps
2. Oncetheyareinstalled,weneedtoconfiguregpsdtoworkinthewaywewant.Todothis,usethefollowingcommand:
sudodpkg-reconfiguregpsd
3. Thiswillopenaconfigurationpagesimilartoraspi-config.First,youwillbeaskedwhetheryouwantgpsdtostartonboot.SelectYeshere:
4. Next,itwillaskwhetherweareusingUSBGPSreceivers.Sincewearenotusingone,selectNohere:
5. Next,itwillaskforthedevice(thatis,serialport)theGPSreceiverisconnectedto.Sinceweareusingtheon-boardserialportonthePiGPIOheader,enter/dev/ttyAMA0here:
6. Next,itwillaskforanycustomparameterstopasstogpsd,whenitisexecuted.Here,wewillenter-n-G.-n,whichtellsgpsdtopolltheGPSmoduleevenbeforeaclienthasrequestedanydata(thishasbeenknowntocauseproblemswithsome
applications)and-GtellsgpsdtoacceptconnectionsfromdevicesotherthenthePiitself(thisisnotreallyrequired,butisagooddebuggingtool):
NoteWhenyoustartgpsdwiththe-Goption,youcanthenusecgpstoviewtheGPSdatafromanydevicebyusingthecommandwhere[IP]istheIPaddressofthePi:
cgps[IP]
7. Finally,youwillbeaskedforthelocationofthecontrolsocket.ThedefaultvalueshouldbekeptheresojustselectOk:
8. Aftertheconfigurationisdone,rebootthePiandusethefollowingcommandtotesttheconfiguration:
cgps-s
Thisshouldgiveoutputsimilartowhatisshowninthefollowingscreenshot,ifeverythingworks:
IfthestatusindicationreadsNOFIX,thenyoumayneedtomovetheGPSmoduleintoanareawithaclearviewoftheskyfortesting.Ifcgpstimesoutandexits,thengpsdhasfailedtocommunicatewithyourGPSmodule.Gobackanddouble-checktheconfigurationandwiring.
SettingupthecapturesoftwareNow,weneedtogetthecapturesoftwareinstalledonthePi.
1. First,copytherecorderfolderontothePiusingFileZillaandSFTP.2. WeneedtoinstallsomepackagesandPythonlibrariesthatareusedbythecapture
application.Todothis,firstinstallthePythonsetuptoolsthatIhaveusedtopackagethecaptureapplication:
sudoapt-getinstallpython-setuptoolsgit
3. Next,runthefollowingcommandstodownloadandinstallthepexiflibrary,whichisusedtosavetheGPSpositionfromwhicheachimagewastakenintotheimageEXIFdata:
gitclonehttps://github.com/bennoleslie/pexif.gitpexif
cdpexif
sudopythonsetup.pyinstall
4. Oncethisisdone,SSHintothePicanchangedirectorytotherecorderfolderandrunthefollowingcommand:
sudopythonsetup.pyinstall
5. Nowthattheapplicationisinstalled,wecantakealookatthelistofcommandsitacceptsusing:
gpstimelapse-h
Thisshowsthelistofcommands,asshowninthefollowingscreenshot:
Afewoftheoptionsherecanbeignored;--log-file,--log-level,and--verboseweremainlyaddedfordebuggingwhileIwaswritingtheapplication.The--gpsoptionwillnotneedtobeset,asitdefaultstoconnecttothelocalgpsdinstance,whichiftheapplicationisrunningonthePi,willalwaysbecorrect.
The--widthand--heightoptionsaresimplyusedtosettheresolutionofthecapturedimage.Withoutthem,thecapturesoftwarewilldefaulttocapture1248x1024images.
The--intervaloptionisusedtospecifyhowlong,inseconds,towaitbeforeitcapturesanothertime-lapseframe.Itisrecommendedthatyousetthisvalueatleast10secondsinordertoavoidfillingtheSDcardtooquickly(especiallyifthetimelapsewillrunoveralongperiodoftime)andtoensurethatanyvideocreatedwiththeframesisofareasonablylength(thatis,nottoolong).
The--distanceoptionallowsyoutospecifyaminimumdistance,inkilometers,thatmustbetravelledsincethelastimagewascapturedandbeforeanotherimageiscaptured.Thiscanbeusefultorecordatimelapsewhere,whateverholdsthePi,maystopinthesamepositionforperiodsoftime(forexample,ifthecameraisinacardashboard,thiswouldpreventitfromcapturingseveralidenticalframesifthecariswaitingintraffic).
Thisoptioncanalsobeusedtocaptureasetofimagesbasedaloneonthedistancetravelled,disregardingtheamountoftimethathaspassed.Thiscanbedonebysettingthe--intervaloptionto1(avalueof1isusedasdataisonlytakenfromtheGPSmodule
everysecond,socheckingthedistancetravelledfasterthanthiswouldbeawasteoftime).
Thefolderstructureisusedtostoretheframes.Whilebeingslightlycomplexatfirstsight,thisisagoodmethodthatallowsyoutotakemultiplecaptureswithouteverhavingtoSSHintothePi.
Usingthe--folderoption,youcansetthefolderunderwhichallcapturesaresaved.Inthisfolder,theapplicationlooksforfolderswithanumericalnameandcreatesanewfolderthatisonehigherthanthehighestnumberitfinds.Thisiswhereitwillsavetheimagesforthecurrentcapture.
Thefilenameforeachimageisgivenbythe--filenameoption.Thisoptionspecifiesthefilenameofeachimagethatwillbecaptured.Itmustcontain%d,whichisusedtoindicatetheframenumber(forexample,image_%d.jpg).
Forexample,ifIpass--foldercaptures--filenameimage_%d.jpgtotheprogram,thefirstframewillbesavedas./captures/0/image_0/jpg,andthesecondas./captures/0/image_1.jpg.
Herearesomeexamplesofhowtheapplicationcanbeused:
gpstimelapse--foldercaptures--filenamei_%d.jpg--interval30:Thiswillcaptureaframeinevery30secondsgpstimelapse--foldercaptures--filenamei_%d.jpg--interval30--
distance0.05:Thiswillcaptureaframeinevery30seconds,providedthat50metershavebeentravelledgpstimelapse--foldercaptures--filenamei_%d.jpg--interval1--
distance0.05:Thiswillcaptureaframeinevery50metersthathavebeentravelled
Nowthatyouareabletorunthetime-lapserecorderapplication,youarereadytoconfigureittostartassoonasthePiboots.RemovingtheneedforanactivenetworkconnectionandtheabilitytointerfacewiththePitostartthecapture.
1. Todothis,wewilladdacommandtothe/etc/rc.localfile.Thiscanbeeditedusingthefollowingcommand:
sudonano/etc/rc.local
2. Thelineyouwilladdwilldependonhowexactlyyouwanttherecordertobehave.Inthiscase,Ihavesetittorecordanimageatthedefaultresolutioneveryminute.Asbefore,ensurethatthecommandisplacedjustbeforethelinecontainingexit0:
Now,youcanrebootthePiandtestouttherecorder.AgoodindicationthatthecaptureisworkingistheredLEDonthecameraboardthatlightsupconstantly.Thisshowsthatthecamerapreviewisopen,whichshouldalwaysbethecasewiththisapplication.
Alsonotethat,thecapturewillnotbeginuntiltheGPSmodulehasafix.OntheAdafruitmodule,thisisindicatedbyaquickblinkevery15secondsonthefixLED(nofixisindicatedbyasteadyblinkoncepersecond).
OneissueyoumayhavewiththisprojectistheamountofpowerrequiredtopowerthecameraandGPSmoduleontopofthePi.Topowerthiswhileonthemove,IrecommendthatyouuseoneoftheUSBpowerbanksthathavea2Aoutput(suchpowerbanksarereadilyavailableonAmazon).
UsingthecapturesNowthatwehaveasetofrecordedtime-lapseframes,whereeachhasaGPSpositionattached,thereareanumberofthingsthatcanbedonewiththisdata.Here,wewillhaveaquicklookatacoupleofinstancesforwhichwecanusethecapturedframes.
Creatingatime-lapsevideoThefirstandprobablythemostobviousthingthatcanbedonewiththeimagesisyoucancreateatime-lapsevideoinwhich,eachtime-lapseimageisshownasasingleframeofthevideo,andthelength(orspeed)ofthevideoiscontrolledbychangingthenumberofframespersecond.
Oneofthesimplestwaystodothisisbyusingeithertheffmpegoravconvutility(dependingonyourversionofLinux;theparameterstoeachareidenticalinourcase).ThisutilityisavailableonmostLinuxdistributions,includingRaspbian.TherearealsoprecompiledexecutablesavailableforMacandWindows.However,hereIwillonlydiscussusingitonLinux,butrestassured,anyinstructionsgivenherewillalsoworkonthePiitself.
Tocreateatimelapse,formasetofimages.Youcanusethefollowingcommand:
avconv-framerateFPS-iFILENAME-c:vlibx264-r30-pix_fmtyuv420p
OUTPUT
Here,FPSisthenumberofthetime-lapseframesyouwanttodisplayeverysecond,FILENAMEisthefilenameformatwith%dthatmarkstheframenumber,andOUTPUTistheoutput’sfilename.Thiswillgiveoutputsimilartothefollowing:
ExportingGPSdataasCSVWecanalsoextractGPSdatafromeachofthecapturedtime-lapseimagesandsaveitasacomma-separatedvalue(CSV)file.Thiswillallowustoimportthedataintothird-partyapplications,suchasGoogleMapsandGoogleEarth.
Todothis,wecanusetheframes_to_gps_path.pyPythonscriptincludedinthecodeforthischapter.Thistakesthefileformatforthetime-lapseframesandanamefortheoutputfile.
Forexample,tocreateaCSVfilecalledgps_data.csvforimagesintheframe_%d.jpgformat,youcanusethefollowingcommand:
pythonframes_to_gps_points.py-fframe_%d.jpg-ogps_points.csv
TheoutputisaCSVfileinthefollowingformat:
[framenumber],[latitude],[longitude],[imagefilename]
Thescriptalsohastheoptiontorestrictthemaximumnumberofoutputpoints.Passingthe--max-pointsNparameterwillensurethatnomorethanNpointsareintheCSVfile.Thiscanbeusefulforimportingdataintoapplicationsthatlimitthenumberofpointsthatcanbeimported.
SummaryInthischapter,wehadalookathowtousetheserialinterfaceontheGPIOportinordertointerfacewithsomeexternalhardware.TheknowledgeofhowtodothiswillallowyoutointerfacethePiwithamuchwiderrangeofhardwareinfutureprojects.
WealsotookalookatthecameraboardandhowitcanbeusedfromwithinPython.Thiscameraisaveryversatiledeviceandhasaverywiderangeofusesinportableprojectsandubiquitouscomputing.
Youareencouragedtotakeadeeperlookatthesourcecodeforthetime-lapserecorderapplication.ThiswillgetyouonyourwaytounderstandthestructureofmoderatelycomplexPythonprogramsandthewaytheycanbepackagedanddistributed.
Inthefollowingchapter,wewilltakeamoreintricatelookathowtointerfacewithexternalhardwareaswebuildahometheaterPC.
Chapter5.HomeTheaterPCInthischapter,wewillcreatealow-powerhometheaterPCcapableofplayingavarietyoflocalmediafilesfromaUSBmemorystickorharddriveaswellasthecontentstoredonyourlocalnetworkandcloudservices,suchasYouTube.
Todothis,wewillusetheOpenELEC(http://openelec.tv)operatingsystem,whichisanoperatingsystemdesignedspecificallyforhometheaterPCsrunningonthePi.
WewillalsocreateacustomenclosureforthemediaPCthatwillhousea20columnby4row(20x4)LCD,whichcanbeusedbyXBMCtodisplayinformationofthecurrentlyplayingmediaorinformationrelatedtothecursorpositionintheonscreenmenu.WewillalsoincludeasetofbuttonsthatcanbeusedtocontrolXBMCwithoutaUSBkeyboardoranyotherremote;boththeseandtheLCDwillbeinterfaceddirectlytotheGPIOportonthePi.
WhatyouwillneedThisisthelistofpartsandmaterialsyouwillneedforthisproject.Theycanbepurchasedatanyelectroniccomponentsstoresandonlineretailers.
TheRaspberryPiAUSBkeyboard(forsetuponly)A600x600mmsheetofa3mmMDFA20x4LCD(www.amazon.co.uk/2004-Characters-Display-Module-Blacklight/dp/B009GXWFSM)0.1inchfemale-to-femalejumperwiresAsmallsectionofstripboard/prototypingboard(www.maplin.co.uk/p/veroboard-copper-stripboard-100x160mm-a62rl)Two10Kmultipleturnpotentiometers(http://cpc.farnell.com/1/1/24068-trimmer-24-turn-10k-m64z103kb40-vishay-spectrol.html)Arowof0.1inchpinheaders(http://cpc.farnell.com/starconn-connectors/phw-40-rv/0-1-pm-header-single-row-40-pms/dp/CN00870)Arowof0.1inchright-angledpinheaders(http://cpc.farnell.com/starconn-connectors/phw-40-rd/0-1-pin-header-right-angle-40-pms/dp/CN00871)ADCbarreljack(http://cpc.farnell.com/1/1/1498-2-1mm-dc-socket-psg01769-pro-signal.html)Sixpush-to-make(PTM)buttons(www.rapidonline.com/electronic-components/miniature-red-push-to-make-switch-78-0100)
Inthisproject,wewillalsouseanewmanufacturingtechnique:lasercutting.WhileIdon’texpectalasercuttertobeatoolthatmanypeopleactuallyown,accesstoitismorereadilyavailablethanyouthink.Itisworthcheckingwhetherthereisahackspaceinyourlocalarea.Ifso,theymayeitherhaveamachinethatyouwouldbeabletouse(oratleasthavesomeonewhocanhelpyoumachineyourdesign)ormaybeabletopointyouintherightdirectionforwhereyoucanhaveitdonelocally.Alternatively,therearemanyservicesthatallowyoutouploadadesignonlineandpaytohaveitcutfromthematerialofyourchoice.
NoteHackspacesarecommunity-organized(andusuallycommunityfunded)workspacesthatprovideavarietyoftoolsandequipmentsthatmaynotusuallybeavailabletoyou.Theyalsoprovideagoodplacewhereyoucancollaborateonprojectsandseekadvicefromtheexpertsforaproblemyouarefacinginyourownprojects.
SettingupOpenELECOpenELECisaveryminimaloperatingsystemthatispreconfiguredwiththeXBMCmediacentersoftware(http://kodi.tv)andarangeofutilitiesspecificallysetupforhomemediasharing,suchastheSambafileserver.
First,headtohttp://openelec.tv/get-openelecand(underRaspberryPiBuilds)downloadthelateststableSDimage(thetitlewillbesomethinglikewhatisindicatedinthefollowingscreenshot).Onceyouhavethefiledownloaded,decompressitandwriteittoyourSDcard.
UnderWindows,youneedtousesoftwaresuchas7-Zip(www.7-zip.org)todecompressthistypeoffile.
OnLinuxandMac,thefollowingcommandcanbeused,whereFILENAMEisthenameofthefilethatyoudownloadedfromtheOpenELECwebsite:
gzip-dFILENAME.gz
OnceyouhavetheSDimagewrittentothecard,itistimetobootthePiforthefirsttime.Here,youneedthePiconnectedtoaTVormonitor(here,IwillbeusingHDMI)anda
USBkeyboardconnectedtoit.IwillalsoconnectaUSBWi-Fiadapter,butyoucaneasilyjustuseanEthernetconnectioninsteadofWi-Fi.
Fornow,wecanpowerthePifromaUSBconnection,asweareyettoconnectanyadditionalperipheralstoit.However,lateron,weneedtopowerthePiusingamoresubstantial5VpowersupplytoprovideenoughpowerforthePiandtheLCD.
ThefirstbootandinitialsetupWhenyoufirstbootOpenELEC,itwillshowascreensomethingsimilartothefollowingscreenshot.Itmaydisplaythisforsometime,asitiscurrentlyresizingthemediastoragepartitionoftheSDcard.
WhenOpenELECboots,itwillbootstraightintoXBMC.Sincethisisthefirsttimeithasbeenbooted,youwillalsobegreetedwiththeOpenELECfirst-timesetupwizard.ThisoftentakesawhiletobedisplayedafterXBMChasstarted.
Tonavigatethemenus,simplyusethearrowkeystomovethecursorandEntertoselectamenuoption;performthefollowingsteps:
1. First,youareaskedbyOpenELECtoselecttheappropriateregionalsettings.SelectthebuttonthatdefaultstoEnglishtochangethesettingsandselectNexttocontinue.
2. Next,youareaskedtoenteranewhostnameforthemediacenter.Itisnotrequiredthatyouchangeit.However,ifyouintendtohavemultiplemediacenters,thenitwouldbeessentialasnotwodevicesshouldshareahostname.ThiswillmakeidentificationofthePionthenetworkeasier.
3. Thenextoptionasksyoutoconfigurenetworkinterfaces.AsweareusingWi-Fi,wecannotdoanythinghereyet,aswirelessadaptersaredisabledbydefaultandwiredconnectionsdonotrequireconfiguration.JustselectNexttocontinue.
4. Next,youwillbeaskedwhatserversyouwanttoenableonthePi.Bydefault,SSHisdisabledandSambaisenabled.Iwouldrecommendyoutoenableboth,asyouwillneedSSHtoconfiguretheLCDandbuttonsandSambatouploadmediatothePi.
5. Afterthisstep,theinitialconfigurationiscomplete.SelectNexttoreturntotheXBMChomescreen.
6. Fornow,thereisoneadditionalsettingthatweneedtochange.Todothis,navigatetotheSettingsoptionundertheSYSTEMmenuusingthearrowkeysandtheEnterkey.
7. Next,navigatetotheSystemmenuandselectitusingEnter.
8. Next,navigatetoInputdevicesanddisabletheEnablemouseandtouchscreensupportoption,asneitherofthesedeviceswillbeusedwithXBMCthewaywewillbeusingthem.
9. Onthismenu,settingsareautomaticallysavedwhentheyarechanged,soyoucannowuseEsctogobackuntilyoureturntothemainmenu.
ConnectingthePitoawirelessnetworkIfyouplantouseWi-Fitoconnecttoyournetwork,thenyouwillneedtofirstenableitinordertojoinyourwirelessnetwork.UsingWi-FiasopposedtoEthernetallowsyoutoinstallthemediaPCwithouthavingtoworryaboutrunninganEthernetcabletoit.However,yournetworkperformancewillbelower,soitisonlyrecommendedifitisessential.Toconnecttothewirelessnetwork,performthefollowingsteps:
1. SelecttheOpenELECoptionundertheSYSTEMmenu:
2. Fromhere,navigatetoNetworkandselecttheActiveoptionunderWirelessNetworks.ThiswillenabletheWi-Fiadapterandstartsearchingforwirelessnetworksinrange.
3. Toconnecttoanetwork,navigatetotheConnectionsmenu.Here,youshouldseealistoftheWi-Finetworksthathavebeenfoundinyourrange.Toconnecttooneofthem,navigatetoit,pressEnter,andselecttheoptionJoin.
4. Youwillthenbeaskedforthepasswordforthenetwork.TypeitinandpressEnter.Oncedone,thiswillreturntotheConnectionsmenu;youshouldnowseethatthenetworkyouselectedhasanIPaddresslistedalongsideit.Thisshowsthatthe
connectionwassuccessful.
UploadingmediafilestothePiTheeasiestwaytouploadmediatothePiisbyaccessingtheSambafilesharesthatareprovidedbythePi.
Thesharesaresplitbythetypeofcontentthatshouldbestoredonthem.Afewofthemostcommononesare:
Music:Thisisusedtostoremusicfiles,forexample,.mp3Pictures:Thisisusedtostoreimagefiles,forexample,.jpeg,.pngVideos:Thisisusedtostorevideofiles,forexample,.mkv,.mp4Userdata:ThisiswheretheXBMCconfigurationfilesarestored
WindowsOnWindows,youcanuseWindowsExplorertobrowseallsharesonaserveratonce.Todothis,pressWinKey+Rtoopentherunpromptandenter\\IP\,whereIPistheIPaddressofthePi,andclickonOK.
ThiswillopenaWindowsExplorerwindow,whichwillallowyoutobrowsethesharesonthePiandcopyfilestoandfromit,asifitwerealocalfolder.
Whenyou’vemovedthefiles,simplyclosetheExplorerwindow.
LinuxOnLinux,assumingyoualsoknowthenameoftheshareyouwanttoaddfilesto,youcanmountashareusingthefollowingsetofcommands,whereIPistheIPaddressofthePiandSHAREisthesharename:
1. First,weneedtocreateadirectorywheretheSambasharewillbemounted(knownasthemountpoint).Thisonlyhastobedoneonce.
sudomkdir/media/openelec
2. Next,usethefollowingcommandtomounttheSambasharetothejust-createdmountpoint:
sudomount-tcifs//IP/SHARE/media/openelec
3. Youwillbeaskedforapassword,butsinceOpenELECdoesnotputapasswordonSambasharedbydefault,justpressEnter.
4. Ifthecommandexitswithoutanerror,youcangoaheadandcopyfilesto/media/openelectouploadthemtothePi.Ifyoudogetanerror,thenyoumaybemissingapackageneededtomountSambashares.Thiscanbefixedusingthefollowingcommand,whichisusedtoinstallanymissingpackages:
sudoapt-getinstallsamba4cifs-utils
5. Whenyou’vemovedthefiles,youshouldunmounttheSambashareusingthe
followingcommand:
sudoumount/media/openelec
ShuttingdownthePiToshutdownthePi,youcanusethepowermenuinXBMC,whichcanbefoundinthebottom-leftcornerofthehomescreenintheformofapowersymbol.
ThiswillgiveyoutheoptiontoshutdownandrebootthePiaswellastheabilitytosetashutdowntimer,whichwillshutdownthePiafteragivenamountoftimehaselapsed.
SettinguptheLCDNowthatwehaveconfiguredOpenELEC,wecanstartaddingourownhardwaretothemediacenter,startingwiththeLCD:
1. First,wewillstartbymakingasmallboardthatwillbeusedtomounttwopotentiometers(orvariableresistors),whichwillallowtheadjustmentofthebacklightbrightnessandcontrastfortheLCD.Thisboardwillalsohaveafew0.1inchpinheadersthatwillbeusedtoconnecttheswitchesandvariouspowersupplies.
Toconstructthisboard,firsttakeapieceofstripboard(alsoknownasprototypingboard)andcuta1”x2”sectionusingapairofsidecutters.Then,cutastripof0.1”ofaright-angledpinheadertothelengthindicatedinthefollowingdiagram.Arrangethemonthecomponent-sideofthestripboard(thatis,thesidewithnocopperstrips)andsolderthemtotheboard.
Takeextracareherenottobridgethegapbetweenthecopperstrips,andensurethatthecoppersurfaceiscleanbeforeyoustartsoldering.Thesurfacecanbecleanedbyrubbingitwithsomehigh-gritsandpaper,orpreferably,wetanddrypaper.Inthefollowingfigure,notethattheyellowstripsrepresentthecopperstripsontheboard.Thisisviewedfromthecomponentsideoftheboard:
Oncethepinheadersareinplace,notethatthereisacrossonthediagram.Thismarkisusedtoindicatethatthecopperstripmustbecutinthisposition.Theeasiestwaytodothisistotakea4mmdrillbitandrotateitbyhandintheholealreadydrilledinthesoldersideuntilthecopperconnectionisremovedbythedrillbit.Ifneedbe,thiscanbeverifiedbycheckingtheresistanceacrosseithersideofthecutusingamultimeter.
2. Next,insertthetwopotentiometers,asshownintheprecedingdiagram,andsolderthemtotheboard.Whenyou’redone,youwillneedtotrimtheexcessmaterialfromthepinswiththehelpofadjacentpinsortrackstopreventthisfromshorting.
3. WecanconnecttheLCDtothePiusingseveral0.1inchfemale-to-femalejumperwiresbyfollowingthewiringinformationshowninthefollowingimage.NotethatsincetheLCDandbacklightmaydrawasignificantamountofpower,anexternal5
Vsupplyisneededherethatisconnectedtothe+5VandGNDconnectionstothefarrightoftheboardwehavejustsoldered.
Thisconnectorshouldbesoldered,asshownintheprecedingphotograph,wheretheredwireis+5Vandthewhitewireisground.Ifindoubtaboutthepinoutoftheconnector,youcanverifyitbytestingthepairsofthepinsusingamultimeter,whenthereisapoweradapterconnected.
ThefollowingtwodiagramsprovidedetailsforthewiringofthehometheaterPC.Notethatallconnectionsshouldbemadedirectlytotheotherpinwiththesamelabel,withtheexceptionofthosethatareusedforbuttons(thatis,allstartingwithB_),inwhichthepush-to-makebuttonshouldbewiredinserieswiththisconnection.
Thefollowingdiagramdetailstheconnectionstothepowerdistributionboard.Notethatthe+5VandGNDpinsonthefarrightoftheboardaretobeconnectedtotheinputpowerfromthepowersupply.
Oncethisiscomplete,itistimetoconfigurethesoftwarethatwillcommunicatewiththeLCDandallowXBMCtoupdatethedisplay.ThesoftwarethatwillactuallyinterfacewiththeLCDiscalledLCDproc.ThisispreinstalledonOpenELEC,soitonlyrequiresconfiguration.
AllthatisrequirednowistomovetheLCDd.conffileincludedwiththisprojecttothe/storage/.configdirectoryontheSDcard.ThiscanbeeasilydoneoverSFTP,aswehavedoneinthepreviousprojects.
Afteropeningthefile,youwillseethefollowingimportantlines:
Line53tellsLCDprocthatwewanttousetheHD44780driverforthedisplayweareconnectingto.Lines76-82areusedtospecifythetestthatistobeshownontheLCDastheoperatingsystembootsupandshutsdown.Line539tellstheHD44780driverthatourdisplayisconnectedtotheGPIOportonthePi.Thisconfigurationoptionisadevice-specificoptionthatwasaddedduetoitspopularitythatitusesthePiforthispurpose.Line581tellstheHD44780driverhowbigourdisplayisinnumberofcolumnsbynumberofrows.
NoteHD44780isaverycommonLCDcontrollerchipmadebyHitachi.YouwillfindeitherthisspecificchiporonethatiscommandidenticaltoitisprettymucheverycharacterLCDmodule.The16-pininterfaceisusuallyagoodsignasitcanbeusedwithdriversthatsupportHD44780.
OncetheLCDd.conffilehasbeenmoved:
1. RebootthePiusingthefollowingcommand.YoushouldbeabletoseethehellomessagedisplayedshortlyafterthePistartstoboot:
reboot
Youmayneedtoadjustthebacklightandcontrastcontrolstogettheclearesttextonthedisplay.Thiscanbedoneusingasmall,flatscrewdriverwiththesmallbrassscrewsonthetwopotentiometers.Astheyaremultipleturnpotentiometers,itmaytakeawhilebeforeyouseeanoticeabledifferenceinthedisplay.
Ifthehellomessageisnotdisplayed,thenyoumayhavemadeamistakewhenwiringtheLCD.Double-checkthewiringandrebootagain.
2. Next,weneedtoinstalltheLCDprocadd-ontoXBMCinordertoenableittocommunicatewithLCDprocandshowinformationonthedisplay.ThisisdonefromtheAdd-onsmenu,whichcanbefoundunderthemainsettingsmenuofXBMC:
3. Fromhere,selectSearch,enterlcd,andpressEnter.
ThissearchshouldfindtheXBMCLCDprocadd-on.Ifnoresultswerefound,tryrebootingthePi,asIfoundproblemswiththelistofadd-onsnotbeingupdatedifthenetworkconnectionwasjustsetup.
4. SelecttheLCDprocadd-onusingEnterandselecttheInstalloption.Thiswillnowdownloadandinstalltheadd-on.Whentheprocessiscomplete,youwillseeanotificationinthebottomrightofthescreen,andtheentryinthesearchresultswillhaveanEnabledindicatornexttoit.
5. Whenthisisdone,selecttheadd-onfromthesearchresultsagain,andselecttheConfigureoption.
Thishassomeoptionsthatcontrolhowcertaintextisdisplayed.Someoptionsyoumaywishtochangehereare:
Navigationdisplayduration:Thisisthedurationofhowlongthedisplaywill
showthemenupositionafteritischanged.Scrollmode:Thischangesthewaytextwrapsaroundthedisplay,whenitisscrolling.Itisbesttotrybothandseewhichyouprefer.Delayforscrollingtext:Thiscontrolsthespeedofthetextscrolling.Ifitissetto0,textscrollingwillbedisabled.
OtheroptionsunderBacklightandConnectionarenotasimportant,aswedonothaveabacklightthatLCDproccancontrolandwedon’twanttochangethedefaultconnectioninformation.
6. Whenfinished,saveanychangesyou’vemadetothesettingsbyselectingOK.7. Finally,youcancustomizethewayinformationisdisplayedontheLCDby
uploadinganLCD.xmlfiletothePi.ThisisthenreadbyXBMC;itdictateswhatshouldbeshownoneachlineoftheLCDinarangeofdifferentsituations.
IhaveincludedasampleLCD.xmlfileinthefilesforthisproject.ThisshouldbeuploadedtotheuserdatafolderwithinXBMC,whichcanbeaccessedeitherthroughSFTPvia/storage/xbmc/userdataorthroughSambaviatheUserdatashare.
ThereisdocumentationandsomefurthersampleLCDconfigurationfilesavailableontheXBMCwikiathttp://kodi.wiki/view/LCD.xml.
SettinguptheswitchesThenextpieceofhardwarewewillsetupisthesixswitchesthatwillbeusedforthefourdirectionkeys,back,andenter.Althoughtheycanbeeasilyremappedtowhateversetofcontrolsyoulike.
1. Thefirststephereistosolderwireswitha0.1inchfemalepinsocketatoneendtoeachswitchterminal.ThisprocessisverysimilartowhatwedidforthearcadebuttonsinChapter3,MiniRetroArcadeCabinet.
2. Oncethisisdone,itwouldbeworthwrappingtheconnectionsinsomeinsulationtapetogivethecablesextrarelieffromthestrain,asshowninthefollowingimage:
3. Next,itistimetowiretheswitchestothePi.Todothis,wewillfollowthesamewiringdiagramsusedintheprevioussectiontoconnecttheLCD.
Oncethisisdone,wecanmoveontothesoftwaresetupforthebuttons.TointerfacewiththeGPIOhardware,wewillusethesysfsbindingsthatareavailablebyreadingandwritingtofilesunderthe/sys/class/gpio/directory.ThismethodisusedbecauseOpenELECdoesnotincludethelibrarytoaccessGPIOthroughPython,andbecausetheoperatingsystemrunsmostlyfromaread-onlyfilesystem,itisdifficulttoinstallthislibrary.
4. Ifyouwishtouseadifferentbuttonmapping,thenyoucanchangeitinthelines131-136ofbutton_watcher.py:
BUTTONS['enter']=(4,'Input.Select')
BUTTONS['back']=(9,'Input.Back')
BUTTONS['up']=(27,'Input.Up')
BUTTONS['down']=(22,'Input.Down')
BUTTONS['left']=(10,'Input.Left')
BUTTONS['right']=(11,'Input.Right')
NoteNotethatfortherevision1board,theupbuttonmustbeswappedfromGPIO27toGPIO21.
Here,thefirstentryinthetupleforeachbuttonistheGPIOnumber(notthepinnumber)thebuttonisconnectedtoandthesecondentryisthecommandthatissent
totheXBMCAPIwhenthebuttonispressed.
ChangingthevaluesfortheseentriesallowsyoutoremapthebuttonstoanyfunctionssupportedbytheAPI.FulldocumentationoftheAPIisavailableontheXBMCwiki(http://kodi.wiki/view/JSON-RPC_API/v4).Hereisalistofsomecommonremotecontrolfunctionsthatcanbeused:
Input.Up:ThisnavigatesupintheGUIInput.Down:ThisnavigatesdownintheGUIInput.Left:ThisnavigatesleftintheGUIInput.Right:ThisnavigatesrightintheGUIInput.Select:ThisselectsthecurrentitemintheGUIInput.Back:ThisnavigatesbackonelevelintheGUIInput.Home:ThisreturnstothehomemenuintheGUIPlayer.PlayPause:ThispausesorresumesplaybackPlayer.Stop:ThisstopsplaybackPlayer.GoPrevious:ThistakesyoutothepreviousitemintheplaylistPlayer.GoNext:Thistakesyoutothenextitemintheplaylist
5. Onceyouhavethebuttonsmappedaccordingtoyourliking,goaheadandcopythebutton_watcher.pyscripttothe/storage/.config/directoryontheSDcard.ThisiseasilydonebyusingSFTP.
6. Whenthisisdone,usethefollowingcommandtorunthescriptandtesteachofthebuttons:
python/storage/.config/button_watcher.py
Ifalliswell,youshouldseeanoutputsimilartothefollowingontheconsoleandXBMCshouldreactaccordingtowhatthebuttonhasbeenconfiguredtodoinbutton_watcher.py.Toexitthescript,pressCtrl+C.
Ifyouseeanerrorstatingthatthedeviceisbusyorunavailable,checkthemappinginbutton_watcher.pyandensurethatalloftheGPIOportnumbersarecorrectandthatyou
havenotmappedabuttonoveranotherbuttonortheLCD.
1. Whenthescriptisworkingasintended,itistimetoconfigureitinordertostartitwhenOpenELECbootsup.ThisisdoneinaslightlydifferentmannerinOpenELEC,asopposedtoRaspbian.First,wemustcreateascriptthatOpenELEClooksfortorunonstartup:
touch/storage/.config/autostart.sh
chmod+x/storage/.config/autostart.sh
nano/storage/.config/autostart.sh
2. Here,thefirstcommandcreatesthefile,thesecondcommandmakesthefileexecutable,andthethirdopensitinnanoforustoedit.Here,wewilladdthefollowinglinetotheendofthefile:
#!/bin/sh
python/storage/.config/button_watcher.py&
3. ThistellstheshelltorunthePythonscriptinthebackground(notedbythe&trailing).Now,simplyexitnanousingCtrl+XandrebootthePiusingthefollowingcommand:
reboot
WhenthePihasbootedbackintoOpenELECandXBMCisrunning,youshouldnowbeabletousethebuttonsrightaway.
FinalassemblyThefirstthingyoumustdobeforegettingthepartsforthecasemachinedisdecidewhichvideoconnectoryouwilluse.YoucanuseeitherHDMIorcompositevideoand3.5mmaudiojacks.ThiswilldeterminewhichsideofthePiisnexttothesideoftheenclosure,sincethetwovideooutputsareontheoppositesidesoftheboardandassuch,therearedifferencesbetweenthedesignsofeachenclosure.
Forbothtypesofenclosure,thefilesintheenclosurefolderinthefilesforthisprojectmustbemachined.Therearetwofolders,hdmiandcomposite_video,thatcontainthepartsspecifictoeachvideooutputtype.
Thepartsneededforeachtypeareshowninthefollowingfigure:
Thetwoenclosurevariants:compositevideoontheleftandHDMIontheright
Onceyouhavethepartsyouneedfortheenclosuretypeyouhavedecidedtobuild,itwouldbeagoodideatoremoveanywiringalreadydonesofartomaketheassemblyprocesseasier.
Oncethisisdone,performthefollowingsteps:
1. StartbymountingtheLCDintothefrontpanel.ThisshouldbedonewithfourM4machinescrewsandnuts.EnsurethatyoudonotovertightenthenutsandputexcessstrainonthePCB.
ThefrontpanelissymmetricalwiththehorizontalcenteroftheLCDmodule,soitdoesnotmatterwhichsideorwhichorientationthefrontpanelisinwhenyoumounttheLCD.Dotrytopickthesidethatisbetterlooking.
2. Next,mounteachofthepushbuttonsinthetoppanelusingthewashersandnutsthatcamewiththebuttons,asshowninthefollowingimage:
3. Next,wecanassemblethetop,bottom,back,andsidepanelsthatwillincludethecutoutforthevideoconnector,thatis,ifyouarebuildingthecompositevideoversionoftheenclosure,youwillhavetheoppositesideattachedtowhatisshowninthefollowingimage:
4. Aroundtheedge,themiddlepanelsconnecttothesidepanels.Here,youwillseeaseriesoffittingssimilartothoseshowninthefollowingimage.TheserequireanM4nuttobeinsertedintotheslotandanM4machinescrewtobeinsertedthroughtheholeinthesidepanel,asshowninthefollowingimage:
Thescrewfitting—beforebeingtightened(left)andafterbeingtightened(right)
NoteItisimportantnottoovertightenthesescrewfittings,astheloadistakenentirelybytheapproximately2mmofMDFthatisincontactwitheachnut.
5. Next,mountthePiintotheenclosureusingtwoM4machinescrewsthroughthebottompanel.Here,itisusefultouseastackofwatcherstospacethePCBapartfromthebottompaneltohelpremovestraininthePCB.Beforedoingthis,itisimportanttoverifythatthewashersyouintendtousearesmallenoughtopreventcausingashortwithanyexposedcomponentsatthebottomofthePi.
ThisisalsoagoodpointtostartrewiringthePi,LCD,andthesmallboardwemadetocontroltheLCDbrightnessandcontrast.
6. Next,wewillrewirethebuttonstothePiasbeforeandattachthetoppanelinthesamewayastheotherthree.
Bythispoint,themediacenterwiringshouldbecomplete.Now,youcanmounttheDCbarreljackthatwillbeusedtopowerthePiexternallytothebackpanelusingthenutandwasherthatwassuppliedwithit.
7. Atthispoint,youarereadytoattachtheremainingsidepanelandgivethemediacenteratestbeforefasteningtheremainingscrewfixings.
8. IfallseemstobegoodandboththeLCDandbuttonsworkasintended,youcangoaheadandfastentheremainingsidepanelusingthesamescrewfixingsthatwereusedfortheotherside.
Here,itisimportanttokeeptheenclosuretiltedsothatifoneofthenutsfallsoutoftheslot,itwillfalloutsideoftheenclosureratherthaninsideit.
SummaryInthischapter,welookedatyetmorehardwarethatcanbeusedwiththeGPIOportonthePiandadditionalwaysinwhichitcanbecontrolledbysoftware.
Wealsotookalookatanotherapplication-specificoperatingsystemavailableforthePi,howtheycanbeverydifferenttothegeneralRaspbianOS,andhowtheapproachtosolveaproblem(suchasthebuttonsinthisproject)hastobechangedbasedontheenvironmentinwhichitwillbeimplemented.
Wealsotookaquicklookathowtouselasercuttingtomanufactureprofessionalqualityenclosuresquicklyandeasily.Thisisaveryversatilemanufacturingprocessandcanbeusedtocreatesomeveryimpressiveproducts.Iwouldhighlyrecommendyoutoconsideritinanyprojectsyoumayundertakeinthefuture.
Inthenextchapter,wewilllookathowtointerfacetheRaspberryPiwithavarietyofsensorsusingtheArduinoprototypingplatformtocreateanoutdoorweatherstation.
Chapter6.OutdoorWeatherStationInthischapter,wewillmakeanoutdoorweatherstationthatisaccessibleovertheInternet,whichwillallowremotemonitoringandrecordingoftheweatherconditions.
Todothis,wewillhavealookatanewskillthatwillallowustotakesomeexistingsensorsandadaptthemforuseinourproject—reverseengineering.Thisisessentiallytheprocessoftakingapartofanexistingproductandderivingthecommunicationmethodbetweenitandtherestoftheproduct,sothatyoucanreplaceeitheraspecificpartorawholeproduct.
WewillalsotakeaquicklookathowtousethePiasawebserverandthemethodusedtodevelopanddeployaPythonwebapplication.
WhatyouwillneedThisisalistofallthepartsyouwillneedinordertocompletethisproject.Mostoftheseareavailableathigh-streetelectroniccomponentsstoresandonlinedistributors:
ARaspberryPiAWi-FidongleAlongmicroUSBcableAclear/translucentTupperwareboxADHT11(www.adafruit.com/product/386)orDHT22(www.adafruit.com/products/385)sensorBMP180(www.adafruit.com/product/1603)AMaplinanemometer(windspeedsensor)(www.maplin.co.uk/p/maplin-replacement-wind-speed-sensor-for-n96fy-n82nf)AMaplinwinddirectionsensor(www.maplin.co.uk/p/maplin-replacement-wind-direction-sensor-for-n96fyn96gy-n81nf)AMaplinraingauge(www.maplin.co.uk/p/maplin-replacement-rain-gauge-for-n25frn96fyn96gy-n77nf)AnArduinoUno(www.adafruit.com/product/50)Aselectionofresistors(www.maplin.co.uk/p/e12-025w-resistor-610-piece-pack-fa08j)A1inchsquaresectionofastripboard(www.maplin.co.uk/p/veroboard-copper-stripboard-100x160mm-a62rl)Arowoffour0.1inchpinheadersAstripofterminalblocksMale-to-malepinjumperwiresFemale-to-femalepinjumperwires
NotethateventhoughIhavespecificallylistedanArduinoUno,anystandard8-bitAVR-basedArduinoshouldworkfineforthisproject,forexample,theUno,Mega,Nano,andDuemilanove.
IhavealsospecifiedtwodifferentDHTsensorsthatcanbeused.TheonlyrealdifferencebetweenthemisthatDHT22hasawideroperatingrangethanDHT11;DHT11canreadtemperaturesbetween0and50degreesCelsiusandhumiditybetween20and80percentRH(relativehumidity),whereastheDHT22canreadtemperaturesbetween-40to80degreesCelsiusandhumiditybetween0to100percentRH.
Wewillmakeuseofdifferentvaluedresistorsacoupleoftimes.Thesearesmalldevicesthatareusedtolimittheflowofcurrentthroughacircuit.TheirresistanceismeasuredinOhmsandisdenotedbyΩ.Sincethesedevicesdonothavetheirresistancevalueprintedonthem,acolorcodemustbeused.Tofindthecolorcodeusedtodenoteaparticularresistance,agoodreferencechartcanbefoundatwww.digikey.co.uk/en/resources/conversion-calculators/conversion-calculator-resistor-color-code-4-band.Throughoutthischapter,resistorsarereferredtobybothvalueandcolorcode.
NotethatwewillnotusethefullpackofresistorsIprovidedalinkto.However,theyareveryhandytohaveashavingtoorderpartslikeresistorsasandwhentheyareneededslowsdownthistypeofelectronicsproject.
ReverseengineeringtheMaplinsensorsBeforewestartcreatingourownelectronicstotakereadingsfromthesesensors,weneedtostartwithalittletheoryandtestingtogetagoodunderstandingofhowthesesensorsworkandhowwewillbeabletointeractwiththem.
UnderstandingthesensorsTostartwith,let’stakealookatthemechanicsandelectronicsusedinthedevicestoknowhowtheofficialdevicewouldhavetakenmeasurementsfromthem(notethatyoudonothavetodisassembleyoursensorshere).
Wewillstartwithprobablythesimplestofallthree—theraingauge.Ifweunclipthetopsection,wewillbeabletonoticeaseesaw-likemechanismthatcarrieswaterfromthespoutofthefunnelinthetopcoveredsectiontoeithertheleft-handsideorright-handsideofthesensor,dependingonthepositionoftheseesaw.
Witheachmovement,theseesawtriggersareedswitch,asmallswitchthatisactivatedusingamagnetinthecenteroftheseesawthatcompletesacircuit,whichcanbemonitoredbythemeasurementdevice.
Whilethismethodisquiteeffectiveatmeasuringwhenthereisrainfall,itcannotaccuratelydeterminehowmuchrainfalltherehasbeen,asthiswillpartiallydependontherateofrainfall.Sincethisrelationshipisnotlinear,itwouldtakemoreeffortthanwhatitisworthtoderive.Simplyrepresentingthenumberoftimestheswitchistriggeredoveragivensampletimewillbesufficientforourweatherstation.
Let’smoveontotheanemometernow.Thisisthedevicethatwillbeusedtodeterminehowfastthewindisblowing.Ifyouremovethethreescrewsatthebottomofthesensor,wecannoticethatithasasimilarreedswitch.Byattachingamultimeterinresistancemode,wecantellthattheswitchpulsesclosedcircuitandthenopencircuittwiceperrevolutionofthesensor.
Giventhatweareabletomeasuretimerelativelyaccurately(uptomillisecondprecision)usingArduino,wecanusethesignalfromthisreedswitchtomeasuretherevolutionsperminute(RPM)travelledbytheanemometer.Then,wecanmultiplythisbythecircumferenceoftheanemometermeasuredfromthecenterofthecupstofindthedistancetravelledbyasinglecupinoneminute.Finally,convertthisresulttoastandardunit(inourweatherstationthiswillbeinmilesperhour(MPH))togetthewindspeed.
Thefinal(andmostinteresting)sensoristhewinddirectionsensor.Thisisessentiallyavanethatpointsinagivendirectionifforceisexertedonthesideofthevanebythewind.Ifweopenthebottomofthissensor,wecanseeaprintedcircuitboard(PCB)thatcontainseightreedswitchesandasocket,whichisusedtoconnecttheanemometer.
IfyouremovethisPCB,youcanseethatthetwomiddleconnectionsofthesocketareconnecteddirectlytothemiddletwoconnectionsofthecablerunningfromthewinddirectionsensor,leavingjusttheoutertwowiresofthecableforthedirectionsensor.
OnthereversesideofthePCB,youwillalsonoticeeightresistorsmarkedwithagivenuniqueresistanceonthePCB.Here,everyreedswitchhasitsownresistance(asshowninthefollowingcircuitdiagram),andbecauseofthespacingoftheswitches,onlyonecanbeactivatedatonce.Therefore,bymeasuringtheresistanceacrossthecircuit,youcansetthepositionofthedirectionsensoraccurateto45degrees.
Nowthatweknowexactlyhoweachofthesensorswork,wecanstartinterfacingthemwithourownelectronics.Sincethisinvolvestheneedforaccuratetimingtomeasurethewindspeed,wecannotusetheRaspberryPitodirectlytakereadingsfromthesensors,asthePirunsascheduledoperatingsystem.Thismeansthatagiventaskcanbestoppedandrestartedatrandomtimeswithoutnotice,whichcausesproblemswhenyouhavecodethatmustkeepanaccuratetrackoftime.
Arduino,however,isareal-timesystem.Thismeansthatthecodeyouwritewillneverbestoppedorpaused(withtheexceptionofinterrupts).Thisallowsyoutoensurethatcertainpartsofitwillbeexecutedinagivenamountoftime.ArduinoalsosupportshardwareinterruptsonitsGPIOs,whichallowafunctiontobecalledwheneverthestateofagivenpinchanges.Thiswillbeusedwithboththerainsensorandanemometertokeepaprecisetrackofthereadingstakenfromthesesensors.
Althoughitisnotoriginallysoldasaweathersensor,wewillalsobeincludingalight-dependentresistor(LDR),whichwillbeusedtomeasureambientlightlevels.Asthenamesuggests,thisisessentiallyaresistorthathasaresistancethatvariesdependingontheintensityofthelighthittingitssurface.
Sincethisisananalogueoutput(aswiththewinddirectionsensor),wecannotusethePitotakereadingsfromit,astheGPIOpinsonthePiareonlydigital,whereasArduinohasseveralanalogueinputsthatcanbeusedwithsensorssuchasthis.
NowisagoodtimetogooversomeofthetheoryofhowtheinputstomicrocontrollerssuchasArduinowork.Withbothofourdigitalinputshere,wewillessentiallyconnectaswitchbetweentheinputpinandgroundpin.ThechipusedonArduinohasapull-upresistoroneachpin,whichcanbetoggledinthesoftware.Thiscanbeusedtoessentiallymakethereadingfromthepinreadhighunlessthereisapathtothegroundwithalowerresistancethanthepull-upresistor,whichinourcasewillbethereedswitchesthathavenegligibleresistance.
Withtheanalogueinputs,wewilluseanadditionalresistortocreatewhatiscalledapotentialdivider.Thisisacircuitthat,asthenamesuggests,outputsavoltagethatissomewhereinbetweentwoinputvoltages,inourcase,5Vandground(0V).Thepotentialdividermakesitpossibleforamicrocontrollertomeasureresistancebyfirstconvertingittovoltage.
WiringNowthatwehaveanideaofhowoursensorswork,wecanstarttocreatethecircuitthatwillallowustointerfacewiththesensors.Sincealotofthesensorsarequitesimple,thisisarelativelyeasytask.
Firstly,weneedtopreparetheMaplinweathersensorstobeconnectedtoArduino.Whilethiscanbedonebypurchasingthecorrecttypeofsocketfortheconnectorstheycomefittedwith,itwillbeeasierinthiscasetosimplycutthemoffandconnectthemusingstripsofterminalblocks.Todoso,performthefollowingsteps:
1. Cutthetwoconnectorsofftheendsofthelongcablesthatareconnectedtotheraingaugeandwinddirectionsensor.Donotremovetheconnectionfromtheanemometerasthisconnectsittothesocketonthewinddirectionsensor.
2. Removearound1-2inchesofthegreyinsulationtoexposethecoloredwires.3. Striparound10mmofinsulationfromeachofthecoloredwires.4. Connectthetwowiresfromtheraingaugetoonesideofastripoftwoterminal
blocks.5. Connectthefourwiresfromthewinddirectionsensortoonesideofastripoffour
terminalblocksintheorderblack,red,yellow,andgreen.Thisshouldbethesameorderforthewiresarrangedinsidethecable.
6. Inserta1kΩresistor(color-codedasbrown,black,andred)betweentheblackandredwirescomingfromthewinddirectionsensoronthesamesideasthemontheterminalblock.
7. Ontheothersideofeachoftheterminalblocks,attachamale-to-malepinjumperwire.Notethatthecolordoesnothavetomatchwiththatofthewirefromthesensors.Wheneverwerefertothesewires,wewillrefertothembythecolorofthewirefromthesensor.
Bynow,thewiringfromthesensorsshouldlooksomethinglikewhatisshowninthefollowingimage:
Next,wewillpreparetheLDR:
1. TakeastripofthreeterminalblocksandconnecttheLDRtothecenterandtheleftmostterminal.
2. Onthesameside,connecta4.7kΩresistortotherightmostterminalandthecenterterminal.
3. Ontheothersideoftheterminalblock,connectamale-to-malepinjumperwiretoeachterminal.
Now,theterminalblockwiththeLDRshouldlooksimilartothefollowingimage:
Nowthatwehavethecircuitsrequiredforoursensorsbuilt,wecanconnectthemtotheArduino,asshowninthefollowingdiagram.ThissamewiringdiagramwillworkforthemajorityofArduinoboards,includingtheUno,Mega,Leonardo,andDuemilanove:
SettingupyourArduinoThefinalsteptobetakenforthesensorstoworkisuploadingthesoftwarethatwillmonitorthesensorsandreportinformationbacktothePiviayourArduino.Todothis,weneedtofirstdownloadandinstallversion1.0.6oftheArduinoIDEfromhttp://arduino.cc/en/main/software.Whenitisinstalled,followtheseinstructionstocompileanduploadthecodetoyourArduinoandperformthefollowingsteps:
1. ConnectyourArduinotoyourcomputerandopentheArduinoIDE.2. SelectFileandOpenandbrowsetotheMaplinWeatherInstrumentDriverfolderin
theprojectfiles.OpentheArduinosketchinsidethatfolder.Whenloaded,itshouldlooksomethinglikethefollowingscreenshot:
3. SelectthetypeofArduinoonwhichyouwillbeuploadingtheprogrambynavigatingtoTools|Board.
4. SelecttheserialportyourArduinoisattachedtobynavigatingtoTools|SerialPort.5. Now,clickontheuploadbuttoninthetop-leftcorneroftheArduinoIDE.Thisisthe
roundbuttonwithanarrowpointingtotheright.TheArduinoIDEwillthengiveamessagethatitisuploadingthesketchtotheboard,asinthefollowingscreenshot:
Assumingthattheuploadiscompletedsuccessfully,youshouldseethemessageDoneuploadingintheIDE,asshowninthefollowingscreenshot:
Ifyougetanerrorhere,thencheckwhetheryourboardandserialportoptionsarecorrect.Iftheerrorstillpersists,thendisconnectyourArduinoandrestarttheArduinoIDEandtryagain.Thisusuallyfixesanyproblemsthatoccurhere.
Oncetheuploadiscomplete,youcanopentheserialmonitorusingthebuttoninthetop-rightcorneroftheArduinoIDEthathasthemagnifyingglasssymboltocheckwhetherthesensorsareworkingcorrectly.Here,youshouldbeabletomanuallymovethesensorsandseetheoutputprintedtotheserialconsole.
Note
Inregardstowinddirection,thedirectionisrepresentedbyavalueof0to7,where0isnorth.Thevalueincreasesin45degreeincrements,so1isnortheast,2iseast,andsoon.Thisgoesonupto7,whichisnorthwest.
Thefollowingscreenshotdisplaystheoutputprintedintheserialconsole:
SettinguptheremainingsensorsNowthatwehavetheMaplinsensorsandtheLDRworkingproperly,usingtheArduinoboard,wecanturnourfocustotheremainingsensorsthatwillmeasuretemperature,humidity,andthebarometricpressure.
Forthis,wewilluseDHT11orDHT22tomeasurethetemperatureandhumidityandBMP180tomeasurethebarometricpressure.ThesedevicescanbeinterfaceddirectlytoandpoweredfromtheGPIOportonthePi.
DHT11/22DHT11andDHT22useaone-wirecommunicationprotocoltosenddatabacktothePi,whichrequiresanadditional10K(brown,black,andorange)resistortobeaddedbetweenthedataand3.3Vpinsonthesensor.TheeasiestwaytodothisisbymountingtheDHTsensor,resistor,andarowofmalepinheadersonasmallsectionofastripboard,asshowninthefollowingdiagram:
Oncethisiscomplete,theboardshouldlooksimilartothefollowingimage:
Thecoppertracksrunverticallyfromthetopoftheprecedingimagetothebottom.Asthisissimplyataskofaddingaresistoracrosstwotracks,thereisnoneedtocreateanybreaksinthecoppertracks.
NowthatwehaveaboardfortheDHT11/22sensor,wecanmakethefollowingconnectionstothePiGPIOportbyusingfemale-to-femalepinjumperwires:
Pin1(theleftmostpinintheprecedingimage)tothePipin6(GND)Pin2shouldnotbeconnectedPin3tothePipin7(GPIO4)Pin4(therightmostpinintheprecedingimage)tothePipin1(3.3V)
Oncethewiringiscomplete,wecannowconfigurethesoftwarefortheDHT11/22sensorwiththefollowingsteps:
1. First,installsomepackagesthatwillbeneededtosetupthedrivers:
sudoapt-getinstallbuild-essentialgit
2. Next,clonetherepositoryfortheAdafruitdriverandtheBMP180sensor:
gitclonehttps://github.com/adafruit/Adafruit_Python_DHT.git
3. Changethedirectorytotherepositorywejustclonedandrunthesetupscript:
cdAdafruit_Python_DHT
sudopythonsetup.pyinstall
4. Toensurethatthesensorisworkingcorrectly,changethedirectorytotheexamplesdirectoryandrunthesamplescript.Notethatifyou’reusingtheDHT22sensor,youwillneedtochange11to22inthefollowingcommand:
cdexamples
sudo./AdafruitDHT.py11/224
Assumingthateverythingwentasitshould,youshouldseeanoutputsimilartothefollowingscreenshot,withthereadingstakenfromthesensor:
Ifthisoutputisnotproduced,gobacktothewiringandsetupstepsandensurethatthesensoriswiredandconfiguredcorrectly.Itisworthdouble-checkingthesolderingonthestripboardtoensurethatthesensoriswiredwiththecorrectpinandthattherearenosolderbridgesbetweenthetracksonthestripboard.
BMP180TheBMP180sensorcomesalmostreadytouseandrequiresnoexternalcircuitrytoconnectittothePi,asitusestheverycommonandstandardizedI2Cbus.Theonlyassemblysteptoperformhereistosoldertherowof0.1inchpinheadersontothePCB.BecarefulwhenyoudothisanddonotgettheirontooclosetoanyofthecomponentsalreadymountedonthePCB.
Oncethepinsareinplace,wecanthenwirethesensortothePi.ThisisdonebymakingthefollowingconnectionsbetweenthesensorPCBandthePiGPIOheaderbyusingfemale-to-femalepinjumperwires:
VINtothePipin17(3.3V)GNDtothePipin25(GND)SDAtothePipin3(I2C1SDA)SCLtothePipin5(I2C1SCL)
Oncethewiringiscomplete,wecannowconfigurethesoftwarefortheBMP180sensor:
1. Editthe/etc/modulesfiletoenablethekernelmodulesthatwillallowustousetheI2CinterfacebusontheGPIOheader:
sudonano/etc/modules
2. Addthefollowinglinestothefile:
i2c-bcm2708
i2c-dev
Theoutputshouldlooklikethefollowingscreenshot:
3. InstallsomepackagesthatwillallowustousetheI2CbusfromPythonandatoolthatwecanusetodetectwhichdevicesarecurrentlyconnectedtothebus:
sudoapt-getinstalli2c-toolspython-smbus
4. Next,weneedtocheckwhetherthe/etc/modprobe.d/raspi-blacklist.conffileexists,andifso,therearesomelinesthatmustbecommentedout.Wecancheckwhetheritexistsbyopeningthefileinnano;ifitdoesnotexist,thenanoeditorwindowwillbeempty:
sudonano/etc/modprobe.d/raspi-blacklist.conf
5. Ifthefileisempty,youcanskipthenextstep,otherwise,commentoutthefollowinglines:
blacklistspi-bcm2708
blacklisti2c-bcm2708
Thefileshouldlooksimilartothefollowingscreenshot:
6. Atthispoint,weneedtorebootthePitoloadthenewdrivers:
sudoreboot
7. OncethePireboots,usethefollowingcommandtocheckwhethertheBMP180sensorhasbeendetectedbythePicorrectly:
sudoi2cdetect-y1
Ifso,youshouldseeanoutputsimilartothefollowingscreenshot:
8. AssumingthatthedeviceisnowbeingdetectedcorrectlyontheI2Cbus,wecanclonetherepositoryforthedriverthatwillinterfacewithitoverthebuswiththefollowingcommand:
gitclonehttps://github.com/adafruit/Adafruit_Python_BMP.git
9. Changetothedirectoryforthedriverwejustdownloadedandrunthesetupscript:
cdAdafruit_Python_BMP
sudopythonsetup.pyinstall
10. Toensurethatthedriveriscommunicatingwiththesensorcorrectly,changetotheexamplesdirectoryandruntheexamplePythonscript:
cdexamples
sudopythonsimpletest.py
Thisshouldgiveanoutputsimilartothefollowingscreenshotwiththereadingstakenfromthesensor:
Ifyoudidnotgetthisoutput,thenyoumayneedtodouble-checkthewiringbetweenthesensorandPi.IfthatlooksOK,thenitisworthrebootingthePiandtryingagain.
TheweatherstationwebapplicationTomakethedatawerecordfromtheweathersensorsabitmoreaccessible,wewilluseawebapplicationwritteninPythontodisplaythecurrentandhistoricaldatarecordedfromourweatherstation.
Todothis,wewillmakeuseofaPythonwebapplicationframeworkcalledFlask(http://flask.pocoo.org/),anapplicationservercalledGunicorn(http://gunicorn.org/),andareverseproxyservercalledNginx(http://nginx.org/).
Thewebapplicationwillhavetwopages,onewillshowthecurrentweatherconditionsandtheotherwillshowthehistoryoftheweatherconditionsoveragiventimerange.Tohelpvisualizethedataonboththepages,wewillusetheGoogleChartsAPI(https://developers.google.com/chart/).ThisisaJavaScriptAPIthatallowsthecreationofinteractivechartsonawebpage.
DeployingtheapponthePiIt’snowtimetodeployourwebapplicationonthePi.Todothis,wewillusetheNginxreverseproxyserverandtheGunicornwebapplicationservertohosttheapplication.Here,Gunicornistheserverthatactuallyhoststheapplicationandrelatedfiles,andNginxisanintermediateserverbetweentheGunicornandtheclientthatisusedtoforwardrequestsfromaclienttothecorrectwebserver.
AfterloggingintothePioverSSHanduploadingconfig_filesandweather_station_webapptothe/home/pidirectory,theprocesstoconfigurethewebapplicationisasfollows:
1. Installsomeprerequisitepackages:
sudoapt-getinstallpython-pippython-devgunicornsupervisornginx
2. ClonetherepositoryforFlask,thePythonwebapplicationframeworkthatourwebappisbuiltwith:
gitclonehttps://github.com/mitsuhiko/flask.git
3. ChangetothedirectoryfortherepositorywejustclonedandinstallFlaskonthePi:
cdflask
sudopythonsetup.pyinstall
4. CopytheconfigurationfileforNginxtothedirectoryofalltheavailablesites:
sudocpconfig_files/nginx/weather-station.conf/etc/nginx/sites-
available/weather-station.conf
5. Createasymboliclinktothesiteconfigurationfromthesites-enableddirectory.ThistellsNginxthatitshouldhandlerequestsforthissite:
sudoln-s/etc/nginx/sites-available/weather-station.conf
/etc/nginx/sites-enabled/
6. RemovethedefaultsitethatNginxhostswhenitisfirstinstalled:
sudorm/etc/nginx/sites-enabled/default
7. Oncealltheconfigurationisdone,itcansavealotofdebuggingtimetohaveNginx.Verifyitsconfiguration,whichcanbedonebyusingthefollowingcommand:
sudonginx-t
Assumingthattheconfigurationwasvalidatedcorrectly,youshouldseearesultsimilartothefollowingscreenshot.Ifnot,gobackthroughtheconfigurationstepsandensurethattheconfigurationisperformedcorrectly:
8. Assumingthattheconfigurationisvalidatedsuccessfully,youcannowrestarttheNginxserviceforittostarthandlingrequestsforourwebapp:
sudoservicenginxrestart
9. Next,changetothedirectoryforthewebapp:
cd~/weather_station_webapp
10. Beforewestarttoservethewebapp,weneedtoinitializeanemptydatabasetorecordmeasurements.Thiscanbedoneusingthefollowingcommand:
flask--app=weather_station_webappinitdb
11. Now,wearereadytotestthewebapplicationbyrunningGunicorn,whichcanberunusingthefollowingcommand:
gunicorn-b127.0.0.1:5000weather_station_webapp:app
Here,Gunicornisservingthewebapplicationonport5000onthelocalloopbacknetworkinterface,whichisonlyavailabletothePi.Then,arequestcomesinfromanexternalclientonport80(thestandardportforwebpagestobeserved).Nginxforwardsthistrafficto127.0.0.1:5000,wheretherequestisthenprocessedbyGunicorn.
Totestwhetherthisisworkingproperly,browsetotheIPaddressofthePifromanothercomputeronthesamenetworkasthePi.Youshouldbegreetedwithapagesimilartotheupcomingscreenshot.
IfyoureceiveapagewithaBadRequesterrormessage,thenyoumayneedtorebootthePiandtrythelaststepagain.IfyoureceiveInternalServerError,thenyoumayneedtorunthecommandtoinitializethedatabaseagain.
Assumingthatthewebappisloadedcorrectly,wecannowperformthefinalstep,whichwillstarttheGunicornserverautomaticallywhenthePiboots.Todothis,wewillusetheSupervisor(http://supervisord.org/)application,whichisaprocesscontroltoolthatmakesthecreationofdaemoninstancesofprogramsveryeasy,andperformthefollowingsteps:
1. First,weneedtocopytheconfigurationentryforthewebapplicationintotheSupervisorconfigurationdirectory:
sudocpconfig_files/supervisor/weather-station-webapp.conf
/etc/supervisor/conf.d/weather-station-webapp.conf
2. Next,runthissetofcommandstoupdatethesuperuserconfigurationandstartthewebapplicationasabackgroundprocess:
sudosupervisorctlreread
sudosupervisorctlupdate
sudosupervisorctlstartweather-station-webapp
Youmayreceivewhatlookstobeanerrormessagewhenrunningthefinalcommandhere.However,thissimplystatesthattheprocessisalreadyrunningandcansafelybeignored.
3. Finally,rebootthePitofinishthedeployment:
sudoreboot
OncethePihasrebooted,browseonceagaintotheIPaddressofthePiandyoushouldbeabletoseethesamepageasbefore.Ifso,youhavesuccessfullydeployedthewebapplicationonyourPi.
TakingreadingsfromthesensorsNowthatourappissetup,weneedtoconfigurethePitoregularlytakereadingsfromthesensorsandupdatethedatabasewiththelatestweatherconditions.Todothis,wewilluseaPythonscriptthatwillcommunicatewiththeDHT11/22andBMP180sensorsusingtheirAdafruitlibrariesandtheMaplinsensorsusingthepySeriallibraryandperformthefollowingsteps:
1. WemustfirstinstallthepySeriallibrarytobeusedbythescript.AlltheotherlibrariesusedareeitherinstalledbydefaultorwereinstalledwhenwehadsetuptheDHT11/22andBMP130sensors:
sudopipinstallpyserial
2. Next,wewillmodifytherc.localfiletoperformthescriptrunwhenthePiboots:
sudonano/etc/rc.local
3. Here,addthefollowinglinetothefile:
python/home/pi/sensor_manager.py--database
/home/pi/weather_station_webapp/weather.db--poll-interval10--submit-
interval600&
Theoutputshouldlookasshowninthefollowingscreenshot:
NoteTheintervalatwhichthescripttakesreadingsfromthesensorsandstorestheminthedatabasecanbeconfiguredbychangingthe--poll-intervaland--submit-intervalarguments.Notethatifthe--submit-intervalsettingissetanylowerthan300seconds(5minutes),thenthiscanmakethehistoryviewinthewebapplicationslowtoload.
4. Finally,rebootthePiandtrytoaccessthewebinterfacetocheckwhetherthedata
updateafterthesubmitintervalhaselapsed.
AssemblingtheweatherstationNowthatourweatherstationissetupandtakesthereadingscorrectly,it’stimetoassembletheweatherstationandsetitupoutside.
Beforewedothis,youmaywanttoconsiderhowthePiwillconnecttoyournetworkandreceivepower.Here,IwouldrecommendyouuseWi-Fifornetworking.ThiscanbesetupbyfollowingthesameprocedurethatweusedinChapter2,PortableSpeakerSystem.Forpower,Iuseda10footmicroUSBcable,whichwaslongenoughtoreachasfaroutsideasIhadlocatedtheweatherstation.
FortheMaplinweathersensors,simplyassemblethetwomastsandfixboththeanemometerandwinddirectionsensoratthetopoftheirownmastsbyusinga30mmM3screw.Thesemastscanthenbepushedrelativelyeasilyintothesoil.Sincetheyarenotparticularlytall,itisbettertoplacetheminanareaasopenaspossibletoimprovetheaccuracyofthereadingstakenfromthem.
Asanenclosurefortheremainingsensors,theArduino,andthePi,theeasiestthingtouseisaTupperware(orsandwich)box.Thisshouldbeatleast6incheswideby4inchesdeep,around3inchestall,andeitherclearorverylightlytranslucent,sothatthelightintensitydoesnotfalltoomuchbetweentheoutsideandinsideofthebox(asthelightsensorwillbemountedontheinside).
Thereareafewmodificationsthatmustfirstbemadetotheboxtomakeitsuitableforuseasanenclosurefortheweathersensors.Firstly,theremustbesomewaytomaintaintheairflowthroughtheboxtoensurethattheDHT11/22andBMP180sensorsgetaccuratereadings.Thiscanbedoneeasilybydrillingapatternofsixholesoneithersideofacornerofthebox,asshowninthefollowingimage.ThisprovidesapathforairtoflowthroughthecornerofthecasewithoutallowingmoistureandwatertogettothePiandArduino(whichwillbelocatedattheoppositeendofthebox).
Thenextthingwewillneedisawaytoruncablesinsidethebox.Thiscanbedonebyremovingthelipononesideofthebox,sothatwhenthelidisreplaced,thereisagaplargeenoughtorunthewiresthrough.Thelipcanberemovedbyusingapairofwire/sidecutterstocreateagapwideenoughforthecablesfromtheraingauge,winddirectionsensor,andamicroUSBcable,asshowninthefollowingimage:
NoteBeverycarefulwhilecuttingawaythelipoftheboxlikethis.Usingtoomuchforceortryingtocutawaytoomuchatoncecancausepartsoftheboxtochipawayathighspeed.Eyeprotectiongearshouldbewornwhiledoingthis.
Next,weneedtoassembletheelectronicsandsensorsinthebox.TheonlyrequirementhereisthattheLCDfacesdirectlyupwardsandthattheDHT11/22andBMP180sensorsareclosetothepathofairwhichgoesthroughthecorneroftheboxwheretheholesweredrilled.
Youshoulduseanadhesiveorgluetokeeptheelectronicsfrommoving.Youcanuseanythingfromatemporaryfixing,suchasBlu-Tack,toamorepermanent(butstillremovable)adhesive,suchashotglue.Whicheveryoudecidetouse,itisimportanttokeepadhesivesawayfromsensitiveareasoftheelectronics,suchasthemetallicsensorchipontheBMP180PCBorthesurfacemountcomponentsonthebackofthePi.
Thefollowingimageshowstheassembledelectronicsandsensorsinthebox:
Finally,allthatislefttodoistoreplacetheboxlid,setuptheweatherstationoutside,andapplypower.Wecannowmoveontotesttheweatherstationandlookatsomedatafromit.
Notethatwhileinstallingthewinddirectionsensor,itisimportanttoalightitproperlywiththenorthdirection.Itmustbeinstalledsuchthatwhenthearmisinposition,asshowninthefollowingimage,thevanemustpointtonorthandtheroundpointoppositethevanemustpointtosouth:
UsingthewebapplicationWhenyoufirstbrowsetotheIPaddressofthePi,youaregreetedbyapagethatwilllooksimilartothefollowingscreenshot.Thisshowsthecurrentweatherconditionsthathavebeenrecordedoverthelastmeasurementperiod(thatis,theperiodspecifiedbythe--submit-intervalparametertothesensor_manager.pyscript).
ByclickingontheHistorylinkinthetop-rightcornerofthepage,youareabletobrowsethroughalltherecordingsthathavebeentakenbytheweatherstation.
Bydefault,itdisplaysthehistoryforthepreviousweek.Thiscanbechangedbyusingthetwooptionsatthetopofthepage(notethattheseoptionsmayonlyrendercorrectlyinChrome,Opera,orSafariwebbrowsers).
Youcanalsochangewhichrecordedvaluesaretobedisplayedonthegraphbyusingtheselectionofcheckboxesatthetopofthepage.Notethatsomemeasurementsmaynotbesuitedtobedisplayedatthesametimeastheyhavedifferentranges,forexample,rainfallandthelightlevel.
Ifyoueverwanttotakeabackupoftheweatherdata,youcandosobytakingacopyoftheweather.dbfileinthe/home/pi/weather_station_webapp/directory.Ifyouwanttoerasealltherecordeddata,youcansimplyruntheinitializedatabasecommandagain.
Notetheunitsforthemeasurements:
Windspeed:Thisismeasuredinmilesperhour(MPH)Temperature:ThisismeasuredindegreesCelsiusHumidity:ThisismeasuredinpercentageRH(relativehumidity)Pressure:kPa(kilopascal),where1kPa=10mb(millibar)Lightlevelandrain:Arbitraryunits
SummaryInthischapter,welookedatthestepsneededtodesignanddeployaPython-basedwebapplicationonthePiusingtheFlaskframework.Thisisatechniquewewillbeusinginacoupleofchapterslaterinthebook,wherewewillcreateweb-basedcontrolpanelsandinformationdisplays.
WealsolookedatyetmorewaystointerfacedevicestothePi,bothdirectlyviatheGPIOportandbyusinganintermediatedevice;inourcase,anArduino.Wealsolookedattheadvantagesthiscanbringwithcertaintypesofsensor.
Inthenextchapter,wewillfurtherexploretheuseofsensors,aswecreateahomesecuritysystemthatconnectsseveralsensorsusingawirelessnetwork.
Chapter7.HomeSecuritySystemInthischapter,wewilllookathowtocreateasimplisticsecuritysystemthatwillbeabletomonitorbasicsecuritysensors,suchasdoorpositionsensorsandpassiveinfrared(PIR)sensors.Thesearecommonforstandardhomesecuritysystemsandsende-mailalertswhencertaincombinationsofsensorsaretriggered.
WhatyouwillneedThisisthelistoftheminimumpartsyouwillneedtocompletethisprojectbyfollowingthesamplesystemsetup,whichisdescribedinthefirstsectionofthischapter:
TheRaspberryPiAtleasttwonRF24L01modules(http://imall.iteadstudio.com/im120606002.html)AtleastoneArduinoUno0.1inchfemale-to-femalepinjumperwires0.1inchmale-to-femalepinjumperwiresAselectionofsecuritysensors:
ThePIRsensor(www.rapidonline.com/Electronic-Components/Pir-Module-61-1516)Magneticdoorsensorsorreedswitches(www.rapidonline.com/Electronic-Components/Surface-Mounting-Proximity-Switch-78-1672)
Thenumberofsensors,Arduinoboards,andRFmodulesyouwillneedforthisprojectwillgreatlydependonhowmanyroomsyouwantthesecuritysystemtocoverandhowmanysensorswillbeusedineachroom.Inthischapter,itwouldbeworthreadingatleastthesectiononhowtodesignyoursecuritysystembeforeyouorderanyparts.Dothistoensurethatyouhaveenoughrequirementstobuildasystemthatwillworkwellforyourscenario.
ThesecuritysystemstructureThesecuritysystemwillbedividedintofivemainparts:theArduinosensornodes,theRFnetworkthatconnectseachnodetotheRaspberryPi,theMQTTbrokerthatconnectstheRFnetworktothewebapplication,thewebapplicationthatmanagesthesenoreventsandalerts,andthedatabasethatstorestheconfigurationofthesensorsandalarmsandthehistoryofeachsensor.
EachsensornodeiscomprisedofanRFmodulethatallowscommunicationbetweenthenetworkofsensornodesandseveralsecuritysensors,suchasPIRmotiondetectorsandreedswitchdoorsorwindowsensors,andboththestandardsensorsusedonthestandardhomesecuritysystems.Whilethesenodescanbebatterypoweredforbetterreliability,wewillpoweroursbyusingaUSBportandUSBpowersupply.
TheRaspberryPiwillserveasboththehostserverforthewebapplicationanddatabaseandthebasenodeintheRFnetwork.ThiswillusethesameRFmodulesandsoftwarelibrariesastheArduinosensornodes.
Oursecuritysystemwillnotuseabellorsounder,suchasaconventionalsecuritysystem;instead,itwillsende-mailalertstoanaddressconfiguredviathewebinterface.Itwillalsoallowalarmstobeconfiguredmuchmorefreelythanaconventionalsystem,allowingyoutosetseveralalarmsforeachdifferentareainahouse.Itwillalsoallowthealarmstoactindependentofeachother.
DesigningyoursecuritysystemFortherestofthechapter,wewillassumethatthesecuritysystemhasthreesensornodes;here,allthreehavemagneticdoorsensorsandonlytwooutofthreehavePIRmotionsensors.
Atthisstage,youneedtothinkaboutwhereeachnodewillbelocated,astheRFmodulescanonlytransmitoveracertaindistancebeforethesignaleitherbecomestooweaktoensurereliablecommunicationorislostcompletely.Frommyowntesting,Ihavefoundthatthelinkbetweentwonodescanrarelytravelmorethanonewallorfloor.
Therefore,inordertohavealongerdistancebetweenthebasenodeandsensornode,thesensornodemustcommunicatethroughanodethatactsasarepeater.Thisishandledbythenetworkprotocollibraryusedonthesensor’snodesandthePi.Wewilllookatthisinmoredetaillaterinthischapter,butfornow,provisioningatleastonesensornodeineachroomyouwanttohaveasensorinaswellasanyroombetweennodeswillbesufficient.
Thefollowingdiagramroughlyshowsthestructureofthesystemwewillusefortherestofthechapter:
Ifyouareusingyourownsystemdesign,thenithelpstomakeyourowndiagramsimilartothis.Makesuretonotethesensornodeaddress,location,andMQTTtopicofeachsensortohelpmaketheprogrammingofeachofthesesensornodesandtheadditionofthesensorstothewebapplicationeasier.
WebapplicationsThesecuritysystemwillbebasedonawebapplicationthatwillbeusedtorecordandvieweventsfromthesensorsandwillallowaconfigurationofsensorsandalarms.
Forthis,wewillusetheFlaskframeworkforPython,whichwasusedinthepreviouschapter,andtheMQTTprotocoltoestablishcommunicationbetweenthesensorsandwebapplication.Thisprotocolisapublisherandsubscribermodel,whereclientscansubscribetoinformation(topics)theyareinterestedinandreceivenewdataasitismadeavailable(published)byotherclients.
Anoverviewofthestructureofthewebapplicationisshowninthefollowingdiagram.Aswedidinthepreviouschapter,wewillusetheSQLitedatabaseengine:
DeployingourapplicationWewillfirststartbydeployingthewebapplicationonthePi.Thiswillmostlybethesameprocessaswasusedinthepreviouschapterfortheweatherstationwebapplication.However,thereareadditionalstepshereasthesecurityapplicationrequiresanextraconfigurationfiletosetoptionsforthelogindetails,MQTTbroker,ande-mailalerts:
1. First,wewilladdanadditionalsourcetothelistofrepositoriesthatAPTsearchesfor.Whenweinstallnewpackages,thiswillallowustoinstalltheup-to-dateversionoftheMosquittoMQTTbrokerneededforthesecuritysystem:
wgethttp://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudoapt-keyaddmosquitto-repo.gpg.key
cd/etc/apt/sources.list.d/
sudowgethttp://repo.mosquitto.org/debian/mosquitto-wheezy.list
cd
2. Nowthattherepositoryhasbeenadded,weneedtoupdatethelocalcopyofthelistofpackagesthatareavailableandinstallanyupdateswhileweareatit:
sudoapt-getupdate
sudoapt-getupgrade
3. NowthatthePiisuptodate,wecanstartinstallingthepackageswewillneedforthesecuritysystem.Don’tworryifyougetamessagesayingapackageisalreadyinstalledorisuptodate,assomeofthesemayormaynotbealreadyinstalled:
sudoapt-getinstallmosquittomosquitto-clientspython-pipgitpython-
devgunicornsupervisornginx
sudopipinstallpaho-mqtt
4. Fromhereon,theprocedurewillbesimilartothatusedwhileinstallingFlashinthepreviouschapter.However,wewillbemakingacoupleofmodificationsthistime,sowewillgothroughthefullprocedurehere.ContinuebycloningtheFlashcoderepositoryandinstallFlaskonthePi:
gitclonehttps://github.com/mitsuhiko/flask.git
cdflask
sudopythonsetup.pyinstall
5. Next,weneedtocopytheNginxconfigurationfilesforthesecuritywebapplicationsite.EnablethesiteconfigurationandremovethedefaultNginxsite:
sudocpconfig_files/nginx/security.conf/etc/nginx/sites-
available/security.conf
sudoln-s/etc/nginx/sites-available/security.conf/etc/nginx/sites-
enabled/
sudorm/etc/nginx/sites-enabled/default
6. Now,wecanletNginxtesttheconfigurationandassumingthatthetesthaspassed,restarttheservice.Ifthetestfailed,gobacktotheconfigurationandensurethatallthefileshavebeencopiedcorrectly:
sudonginx-t
sudoservicenginxrestart
7. Next,wecantestthewebapplicationbyrunningitmanuallywithGunicorn.Here,itisnotimportantthattheapplicationismissingtheconfigurationfile,soitcanbestartedwiththefollowingcommands:
cd~/security_webapp
flask--app=securityinitdb
gunicorn-b127.0.0.1:5000security:app
NoteNotethatwhileinitializingthedatabase,youmaygetanerrorsimilartothatshowninthefollowingscreenshot;thisiscausedbytheexitoftheapplicationwhiletheMQTTclientisstillrunningandcanbesafelyignored.
8. Now,browsetheIPaddressofthePionacomputerofthesamenetworkandyoushouldseeapagesimilartothatshowninthefollowingscreenshot.Asitis,thisistheonlypageofthesitethatwillwork,astheapplicationisrunningwithouttheconfigurationfile:
Ifthewebpagedoesnotappear,thenyoumayneedtorebootthePibeforetrying
againtoflushoutanybadconfiguration,whichmaystillbeappliedtooneoftherunningservices.Ifthisdoesnotwork,thengobacktotheconfigurationstepsandensurethateachfilewascopiedcorrectly.
9. Next,wewillconfigurethewebapplicationthatwillstartautomaticallywhenthePibootsusingthesupervisor:
sudocpconfig_files/supervisor/security-webapp.conf
/etc/supervisor/conf.d/security-webapp.conf
sudosupervisorctlreread
sudosupervisorctlupdate
sudosupervisorctlstartsecurity_webappp
NoteHere,youcantrytoaccessthewebapplicationagain.Thisshouldgivethesameloginpageasbefore.Thiswillstillbetheonlyfunctionalpageintheapplicationatthispoint.
10. Nowthatthewebapplicationisdeployed,weneedtoedittheconfigurationfiletoenablelogin,MQTTbrokerconnection,ande-mailalerts:
sudosupervisorctlstopsecurity_webappp
sudocpconfig_files/security.conf~
nano~/security.conf
11. Now,weneedtomodifytheconfigurationfilesothatitsuitsthesetupwehavefortheMQTTbroker,e-mailalerts,andthecredentialsusedtologintothewebapplication.Here,wemustalsosetasecretkeythatallowsourapplicationtosaveinformationinabrowsersession.
Intheconfigurationfile,youwillfindthatalltheconfigurationentriesarealreadythere;theysimplyneedtobepopulatedwithcustomizedvalues.NotethatwhiletheSECRET_KEYvaluewillallowyoutologintotheapplication,itshouldbechangedtosomethinguniquetoyourapplicationbeforeyoustartusingthesystemproperly.
TheMQTT_BROKERandMQTT_PORTconfigurationparametersareusedtodeterminewhichMQTTbrokertheapplicationshouldconnectto.Here,weareusingthebrokerrunningonthePilocally,sothesecanbeleftastheparameters’defaultvalues.
TheUSERNAMEandPASSWORDparametersareusedtosetthecredentialsthatyouwilluseontheloginpagetoaccessthewebapplication.Asitis,thewebapplicationonlysupportsasingleuser.
TheSMTP_SERVER,SMTP_USERNAME,SMTP_PASSWORD,andFROM_EMAILparametersareusedtoconfigurethesendingofe-mailalerts.Currently,onlyGmailandGoogleAppse-mailaccountshavebeentestedwiththeapplication,soitishighlyrecommendedthatyouuseoneoftheseaccounts.However,thePythonSMTPlibrary(https://docs.python.org/2/library/smtplib.html)iswelldocumented,somodifyingthesend_mail()functioninsecurity.pyisalwaysanoptionifyouwanttouseadifferente-mailprovider.
AssumingthatyouwilljustuseaGmail(orGoogleApps)e-mailaccountfore-mailalerts,theSMTP_SERVERparameterisalreadysettothecorrectvalue.SMTP_USERNAMEandSMTP_PASSWORDmustbesettoyouraccountlogindetails,whichareyourfulle-mailaddressandpassword.TheFROM_EMAILparameterisusedtosetthee-mailaddressthemessageissentfrom;thisshouldbesettothesameastheSMTP_USERNAMEparameter.
Oncetheconfigurationfileiscomplete,itshouldlooksomethinglikewhatisshowninthefollowingscreenshot:
Nowthattheconfigurationfilehasbeenmodified,thelaststepistostartthewebapplicationoncemore:
sudosupervisorctlstartsecurity_webappp
Oncethisfinalstepiscomplete,youcantrytoaccessthewebapplicationbybrowsingtotheIPaddressofthePionacomputeronthesamenetwork.Thisshouldpresentyouwiththesameloginscreenasbefore.
ConfiguringsensorsandalarmsNowthatthewebapplicationisdeployedcorrectly,itistimetologintoitandconfigurethesensorsandalarmswewilluseforthesystem:
1. StartbybrowsingtotheIPaddressofyourPiandenterthelogindetailsinthepageyouaretakento.Theselogincredentialsaretheonesthatwereconfiguredintheconfigurationfileintheprevioussection.
2. Onceloggedin,youwillbegreetedwiththeSensorspage.Thisshowsalistofallthesensorsthatarecurrentlyconfiguredonthesecuritysystem.WewillstartbyfirstaddinganewsensorbyclickingontheAddNewSensorlinkatthetopofthepage.
3. Here,wearegivenoptionsforthenameandidentificationofthesensor,bothinrelationtothepositioninthehouseandtheMQTTtopicthatitmapsto.Wewillsetthissensortobethedoorsensoronthefirstsensornode.Forallthesensorswewilluse,thevalueofTriggeredtextshouldbe1.
4. Oncethisiscomplete,clickonAddandyouwillseeamessagesayingthatthesensorhasbeenadded.Atthebottomofthisscreen,youwillseeasectionthatdisplaysthelastrecordedeventforthissensor.Sinceithasjustbeenadded,noeventshavebeenrecordedyet.
5. Followthisprocedurefortheremainingsensorsinyoursetup,followingthesystemstructurediagramyoumadeearlierinthischapter.Oncethisiscomplete,youwillhaveafairfewsensorsaddedtothesystem,asdepictedinthefollowingscreenshot:
6. Next,wewillmoveontoaddanalarmforsomeofthesensors.Thiswillcontrolhow
andwhenyoureceivealertswhenthestateofthesensorsinthenetworkchanges.Tostart,clickonAlarmstonavigatetothealertspageandaddanewalarm.
7. Onthisscreen,youwillbegiventheoptiontogivethealarmanameanddescriptiontoassistidentificationaswellasafieldforane-mailaddresstosendnotificatione-mailswhenthealarmistriggered.
8. Atthebottomofthescreenisalistofallthesensorsthathavebeenaddedtothesecuritysystem.Checkallofthemthatyouwanttohaveaneffectonthisalarm.
9. Next,choosethealarmtypefromtheAlertWhendrop-downbox.Thiscontainsseveraloptionsforhowsensorsmustbehaveinordertotriggerthealarm.Typically,youwillusuallysetthistoAnyOneTriggered.Thereisalsoanoptiontodisablethealarmifneeded.
Atthispoint,thesystemissufficientlyconfiguredtobehaveasasimplesecuritysystemandsendalertswhensensorshavebeentriggered.However,shouldyoueverneedtolookupthehistoryofasensortoseewhenithasbeentriggered,thereisaneventspage,whichwilldisplayalltherecordedsensoreventsandthetimetheywererecordedat.
Thiscanalsobehandytoverifythatasensorisfunctioningcorrectly.
Asweareyettoaddanysensorstothesystem,youcansimulatethetriggeredsensorsusingtheMosquittocommand-linetools.Ifnotalreadyinstalled,theycanbedownloadedusingthefollowingcommand:
sudoapt-getinstallmosquitto_clients
Oncetheseareinstalled,youcansimulate,forinstance,adoorbeingopenedandclosedusingthefollowingtwocommands,wherePI_IPistheIPaddressofthePi:
mosquitto_pub-h192.168.0.17-tdoor2-m1
mosquitto_pub-h192.168.0.17-tdoor2-m0
OntheEventspageofthewebapplication,thiswillappear,asshowninthefollowingscreenshot:
Whenanalarmistriggeredandavalide-mailaddresshasbeensetintheconfigurationpage,ane-mailsimilartothefollowingwillbedeliveredtotheconfigurede-mailaddress:
InterfacingsensorsThetwosensorswewilluseinthisprojectarefairlysimpletointerfacewithArduino,asbothuseasimpledigitalsignal.WewillnowlookattheelectricalconnectionbetweenthesensorsandArduinoandtheconfigurationrequiredintheArduinocodeforeachsensor.
Inthecodeforthesensornodes(therf_network/SensorNode_Arduinodirectory),therearetwoimportantvariablesrelatedtotheconfigurationofsensorsonagivennode:NUM_SENSORSandsensors.Thefirstisacountofhowmanysensorsareattachedtothecurrentsensornodeandthesecondisanarrayofconfigurationsforeachsensor.
Theconfigurationforeachsensorisstoredinastructwiththefollowinginitialization:
{"MQTT_TOPIC",PIN,ACTIVE_LOW,PULL_UP}
Here,MQTT_TOPICistheMQTTtopicwherethechangestothestateofthesensorwillbepublished,PINistheArduinoIOpinthesensorisconnectedto,andACTIVE_LOWshowswhetherthesensorshouldbeconsideredastriggeredwhentheinputislow.Ifthisisthecase,thisshouldbesetto1,otherwise0.PULL_UPdictateswhethertheinternalpullupresistorshouldbeactivatedforthesensor;ifso,thisshouldbesetto1,otherwise0.
ThePIRmotionsensorsThePIRmotionsensorshavethreewires:ground,power,andsignal,wherethesignaloutputishighwhenmotionisdetectedinthefieldofviewofthesensor.
Thesesensorsoperatebydetectingarelativechangeintemperatureacrossthefieldofviewofthesensor.Thisisdonebypositioningthetwoinfrareddetectorsatslightlydifferentanglesfromthelens.Whenatemperaturechangeoccurs,thevoltageacrossthetwosensorsrelativetoeachotherchanges,whichisthenprocessedonthesensorthatistobeconvertedintoadigitaloutput.
Ifyoulookfromthetopofthesensor(thatis,withthelensfacingtowardsyou),thethreewiresareground,power,andsignalfromlefttoright.Thesignalwireisindicatedwithagreystripealongit.
TowirethisuptoArduino,connectthegroundwiretoanArduinopinmarkedGND,sendpowertoeithertheArduinopinmarkedas+5VorVinandthesignalwiretoanyunuseddigitalinput(any,from2to8).
NoteNotethatifyouplantopowertheArduinosensornodeusingapowersupplyhigherthen5V,thenyoushouldconnectthePIRsensorspowerwireto+5VandnotVin.Supplyingthesensorwithmorethan5VmaycausepermanentdamagetoArduinoorthepower
supply.
WithintheArduinocode,aPIRsensorshouldbeaddedwiththevalueofACTIVE_LOWandPULL_UPsetto0.
MagneticdoorsensorsThissensorcanbeusedtodeterminewhentwoobjects,commonlyadooranditsframe,moveapart.Thisissimplyareedswitchandmagnet,thereforeallthatisrequiredtousethissensoristodetectwhenadigitalinputsignallevelchanges.
Althoughtherearefourwirescomingfromthesensor,onlytwoareneededforourusage.Thesetwohavetheendsofthewirestripped,revealingasectionoftheconductor,andareslightlylongerthantheothertwo.Thetwounnecessarywirescanbecutoffifdesired.
WithintheArduinocode,amagneticdoorsensorshouldbeaddedwiththevalueofACTIVE_LOWsetto0andPULL_UPsetto1.
TheRFnetworkTheRFnetworkthatwillbeusedforthesensornodesisprovidedbytheRF24Networklibrary(https://github.com/TMRh20/RF24Network).ThisallowsRNnodestobenetworkedinatreestructureinwhicheachnodecanhaveuptofivechildnodes,sinceeachindividualnodecanlistentouptosixothernodesatonce.
Assuch,theaddressesforthenodesareoctalandfollowthestructure,asshowninthefollowingdiagram,where000isalwaysthebasenode,001isachildofthebasenode,021isachildnodeof001,andsoon:
Thisallowsamessagetobepassedtoanynodeonthenetworkbyfirsttransmittingitupwardsthroughthetreeuntilitreachesthefirstnodethatisacommonpathforboththesendingandreceivingnode.
SettinguptheRaspberryPiTosetupthePiasthebasenodefortheRFnetwork,wemustfirstconnecttheRFmoduletotheGPIOportandinstallthedriversthatwillallowustoreceivemessagessendtoitbyusingaPythonscript.Todothis,performthefollowingsteps:
1. First,startbywiringthemoduletotheGPIOportusingthefollowingwiringdiagram:
2. Next,installthedriverfortheRFmodule.Thisisthedriverthatallowsbasicpoint-to-pointcommunicationusingtheRFmodules:
sudoapt-getinstalllibboost-python-devgit
gitclonehttps://github.com/TMRh20/RF24.git
cdRF24
sudomakeinstall
cdRPi/pyRF24
sudopythonsetup.pyinstall
3. Nowthatthedriverisinstalled,returntothehomedirectory:
cd
4. Next,wewillinstalltheRFnetworkdriver.Thisisthenetworklayerthatprovidesthetreenetworkrouting:
gitclonehttps://github.com/TMRh20/RF24Network.gitRFNetwork2
mvRFNetwork2/RPi/RFNetwork~
cdRFNetwork
sudomakeinstall
cdRF24Network2/RPi/pyRF24Network
sudopythonsetup.pyinstall
5. Oncethetwolibrariesareinstalled,youwillneedtocopytheBaseNode_RPi.pyscriptfromtherf_networkdirectoryinthefilesforthisprojecttothehomedirectoryonthePi.
6. Nowthatthedriversforboththemoduleandthenetworklayerareinstalled,wecan
testthebasenodescriptusingthefollowingcommand:
sudopythonBaseNode_RPi.pylocalhost1338
Thisshouldgiveanoutputsimilartothefollowing.Ifyouseearepeatingpatternintheconfigurationdataorallthebitsaresettothesamevalue,thenyoumayhaveanissuewiththewiringbetweentheRFmoduleandthePi.
Assumingthattheoutputofthescriptwassimilartothepreviousscreenshot(suchthatthevaluesarenotall0x00or0xFF),wecangoaheadandconfigurethebasenodescripttostartwhenthePiboots.Todoso,performthefollowingsteps:
1. Opentherc.localfileinnano:
sudonano/etc/rc.local
2. Addthefollowinglinetotheendofthefile,justbeforetheexit0line:
python/home/pi/BaseNode_RPi.pylocalhost1883
Thisisshowninthefollowingscreenshot:
Oncethisiscomplete,rebootthePitorunthebasenodeandwebapplicationonboot.ThiscompletestheconfigurationthatneedstobedoneonthePi.
SettingupArduinoIt’snowtimetoprogrameachoftheRFnodesthatwillbeusedinthesensornetwork.Wecanprogramtheseusingthecodeintherf_network/SensorNode_ArduinodirectoryinthefilesforthisprojectandtheArduinoIDE.
YoushouldalreadyhavetheArduinoIDEinstalledfromwhenitwasusedinapreviouschapter.However,wefirstneedtodownloadsomeadditionallibrariesfortheRFmodule:
1. Thetwolibrariesneededcanbedownloadedfromhttps://github.com/TMRh20/RF24andhttps://github.com/TMRh20/RF24Network.YouwillseetheDownloadZIPoptionattheright-handsidebarofthewebsite.
2. Oncethesearedownloaded,extractboththearchivesandplacethemintothesketchbook/librariesdirectory.ThesketchbookdirectoryiswheretheArduinoIDEstoressavedcodefilesbydefaultandwhereitsearchesforthird-partylibraries.Bydefault,thisfolderisinyourhomedirectory.
Whendoingthis,ensurethattheprogramusedtounzipthearchivesdoesnotcreateanadditionaldirectory(thisisknowntohappenwhenyouunzipthemwithWindowsExplorer).Thedirectorystructureshouldbesimilartothatshowninthefollowingscreenshot:
3. Next,wewillconnectanRFmoduletoeachArduinothatwewilluseasasensornode.ThisshouldbedonebyfollowingthenextdiagramandwhentheArduinoisnotpowered:
Next,usingthefollowingsteps,programeachArduinobyusingthesensornodecodebasedonthesystemstructurediagramgivenearlierinthischapter:
1. ConnecttheArduinotoyourPCandopenanunmodifiedversionoftheSensorNode_Arduino.inocodeintheArduinoIDE.
2. ChangetheTHIS_NODE_ADDRvariabletotheaddressofthenodeyouhaveconnected.Notethathaving0atthestartoftheaddressisrequired,thatis,iftheaddressis23,youmustuse023asthevalue.
3. SettheNUM_SENSORSandsensorsvariablesasdescribedintheInterfacingsensorssection.
4. Ifyouprogramthenodesinorderoftheirpositionawayfromthebasenode(forexample,002,012,and003),youwillbeabletotesteachnodeasyouprogramit.Thisisassimpleasopeningtheeventspageonthewebapplicationandverifyingthatneweventsshowupforthesensorwhenitischanged.Ifthisdoesnothappen,refertotheTroubleshootingsection.
5. Assumingthatthesensornodeworksasintended,youcannowdisconnectthenodefromyourPC.Although,ifyouwishtokeeptestingadditionalnodes,youwillneedtopowerthenodeexternally.
Onceallthesensornodesareprogrammedandtested,theycanbeinstalledintheirintendedpositions.IfoundthatBlu-Tackisagoodtemporaryfixforthenodesthatareto
beplacedabovethedoors.
ThesensornodewithadoorswitchandPIRsensorinstalledaboveadoorframeusingBlu-Tack
TroubleshootingIfyoufindthatasensornodeisnotupdatingthesecuritywebapplicationwhenthesensorsaretriggered,youmayneedtofirstcheckthewiringandconfigurationofthesensornode.Dothistocheckwhetherthesensornodehasavalidaddressandthatitistryingtoconnecttoaparentnodethatexistsonyournetwork(refertothestartofTheRFnetworksection).
Ifthisdoesnotseemtobetheissue,thenyoumaysimplybeoutofrangeofthesensorsorhaveasignalintegrityissuecausedbyotherdevicesusingthesamefrequencyrange.Ifyoususpectthistobethecase,youcantrychangingthevalueoftheCHANNELvariablesintheBaseNode_rPi.pyandSensorNode_Arduino.inocodefiles.ThisvaluesetsthefrequencythattheRFmoduleoperateson.Thefrequencycanbederivedbyf=2400+CHANNELMHz.
Hence,thedefaultvalueof90givesafrequencyof2.49GHz.TheRFmodulecanoperateanywherebetween2.4GHzand2.525GHz.
SummaryInthischapter,wegainedmoreexperiencewithexpandingthePi’shardwarecapabilitybyaddingadditionalmeansofcommunicationtoitandaddinghardwareusinganewprotocol,thatis,SPI.
ArduinoalsoplayedalargepartinthischapterandhashelpedtoprovideanexampleofawiderangeofhardwarethatcouldpossiblybeusedwiththePi.Evenifasensor,motor,orotherdevicecannotbecontrolleddirectlyfromthePi,itisalmostguaranteedthatthereisanadditionalpieceofhardwarethatcansitbetweenthePiandthedeviceandallowcontrolofthedevicefromthePi.
Wealsohadamorein-depthlookatthetypeofwebapplicationsthatcanbecreatedusingPythonandFlaskandintroducedquiteafewnewfeaturesintothesecuritywebapplicationovertheapplicationmadeinthepreviouschapter.
WewillcontinuetoexplorethewaywebapplicationscanbeusedasaninputmethodforthePiandcontrolphysicalhardwareinthelaterchaptersinthisbookbyusingseveralnewwaysofinterfacingcustomelectronics.
Chapter8.Remote-operatedRoboticArmInthischapter,wewillusetheRaspberryPitocreateasimpleroboticarmactuatedwithseveralmicroservosmountedonamovablebaseusingtwomotors.AllofthesewillbecontrolledthroughawebinterfaceviathePiGPIOport.
Wewillalsomountthecameramoduleatthefrontofthebaseandstreamittothewebinterface,enablingafullremoteoperation.
WhatyouwillneedThisisalistofthepartsthatyouwillneedtocompletethisproject.Mostofthemwillbeavailableateitheralocalelectroniccomponentsstoreoranonlineretailer:
TheRaspberryPiA3mmMDF(600x600mm)M3andM4screws,washers,andnutsTheM3threadedbar4xmicroservos(www.amazon.co.uk/Vktech-MG90S-Geared-Helicopter-Airplane/dp/B00FF26480)Servoextensioncables(www.amazon.co.uk/300mm-Servo-Extension-Cable-Futaba/dp/B009REWWGU)Arelayboard(www.ebay.co.uk/itm/New-8-Channel-5V-Relay-Module-Board-for-Arduino-PIC-AVR-MCU-DSP-ARM-UK-/151105724470)Gearedmotors(www.rapidonline.com/Electrical-Power/950d5001-Gearbox-and-Motor-500-1-6mm-Shaft-6-15v-37-1114)0.1inchpinheaders0.1inchfemale-to-femalepinjumperwires0.1inchmale-to-femalepinjumperwiresA18AWGwireThickcopperwire(www.clasohlson.com/uk/Copper-Wire-1.2-mm/30-5028)Asmallsectionofaprototypingboard(www.maplin.co.uk/p/veroboard-copper-stripboard-100x160mm-a62rl)A9VbatteryA9Vbatteryclip(www.maplin.co.uk/p/pp3-snap-battery-clip-hf28f)AUSBpowerbank(www.maplin.co.uk/p/lithium-ion-6000mah-portable-power-bank-n48lk)The38mmversionofacastor(www.clasohlson.com/uk/Swivel-Castors/Pr309743000)AnoldUSBcableTheRaspberryPicameramodule
DriveelectronicsThefirststepistowireupandconfigurethedriveelectronicsandmotorsthatwillmovethevariouspartsoftherobotarm;thiswillconsistoffourmicroservosthatwillmovethearm,andtwogearedmotorsthatwillprovidedrivetothechassis.
Theservosarepoweredbya5Vpowersupplyandcanbedrivenusingapulseddigitalsignal(throughPulseWidthModulation(PWM))fromthePiGPIOports,whichdefinethepositionthatthearmoftheservoistobekeptin.
Themotorswillbedrivenusingarelayboard,whichallowsthePiGPIOporttoswitchthehighercurrentsneededtopowerthemotor.Thisisjustoneofthemanywaysthiscanbedone.AnotherpossibilityistouseaMOSFETH-bridge,whichwillalsoallowcontrolofthespeedofthemotors.However,therelaysolutionissimplerinbothcodeandelectronicconstruction,soitwillbeusedhere.
Thewiringforthedriveelectronicsisshowninthefollowingdiagram:
ThewiringofthePiGPIOheaderisshowningreaterdetailinthefollowingdiagram:
Wewillstartbyconstructingthepowerboard;thisissimplytwosetsof0.1inchpinheadersonasmallsectionofthestripboardthatwilldistributethe5Vandgroundpowerrails.Wewillneedatleastsevenheadersforboththe5Vandgroundrails;however,addingmoreheaderswillallowpossibleexpansionlater.
Theboardshouldbelaidoutasshowninthefollowingdiagram:
Nowthatwehaveallthepartsneededforthedriveelectronics,wecanstartassemblingthemtotestwiththewebapplication,laterinthechapter:
1. Soldera18AWGwireontoeachterminalofbothmotors,asshowninthefollowing
image:
2. Takesomemore18AWGwiresandwireuptherelayboard,asshowninthediagramearlierinthechapter.
3. ConnectthemotorsandPP3batterycliptotherelayboard.Bynow,theboardwiringshouldlooksomethinglikewhatisshowninthefollowingimage:
4. Removethesmallorangepinjumperonthethree-pinconnectionontherelayboard;itcanbestoredbyconnectingonesideofittothemiddlepinofthisheader,asshowninthefollowingimage:
5. Now,takethepowerboardandconnectthefourservostoit,asshowninthefollowingimage,toprovidethemwithpowerandleavethesignalpinaccessiblefromthesideoftheboard:
6. Next,takefourmale-to-femalepinjumpercablesandconnecttheservostotheGPIOheader,asshownintheprecedingdiagram.
7. TaketheUSBcableandcutthecable10cmawayfromtheUSBAconnector.8. Striptheouterinsulationandshieldingtorevealfourwires.9. Striptheredandblackwires.Thesearethe5Vandgroundpowerconnectionsthat
wewillusetopowertherobotarmfromtheUSBpowerbank.10. Connectthewirestothetwomale-to-femalepinjumpersusingastripoftwo
terminalblocks,asshowninthefollowingimage:
11. Finishoffanyremainingwiringbyfollowingthewiringdiagramshownearlier.
Nowthatthewiringiscomplete,attachtheUSBpowerbanktotheUSBcabletoprovidepowertothePiandservos.Ensurethatyouusethehigheroutputcurrentportonthebank(usuallymarkedaseither2.1Aorusedfortabletcharging)andconnecta9VPP3batterytothebatteryclipattachedtotherelayboard.
SettingupthecameraThereareafewwaysinwhichwecouldstreamavideofromtheRaspberryPicameramoduletoawebpage.TheeasiestofwhichistousetheVideoforLinux2(V4L2)driver(whichisdocumentedingreaterdetailatwww.linux-projects.org/modules/sections/index.php?op=viewarticle&artid=14),whichincludesaserverthatallowsthecameratobecontrolledandstreamedoveranetworkconnection.
First,wewillconnectandconfigurethecameraintheRaspbianOSandperformthefollowingsteps:
1. Withthepowerdisconnected,connectthecameramoduletotheCameraSerialInterface(CSI)portonthePijustbehindtheEthernetport.Youcandothisbyliftingthecableclip,insertingtheflat,flexcable,asshowninthenextimage,andpressingdownontheclipsuchthatthecableisfirmlyheldinplace:
2. Next,bootintoRaspbianandruntheconfigurationutility:
sudoraspi-config
3. SelecttheEnableCameraoptionusingthearrowkeysandpressEnter:
4. SelecttheEnableoptionandpressEnter:
5. ExittheconfigurationutilitybyselectingtheFinishoptionandrebootthePi.
ThePicameraisnowenabledwithintheOS.WewillnowinstalltheV4L2driverwiththefollowingsteps:
1. Beforeinstallingthedriver,wefirstneedtoaddanadditionalrepositorytotheAPTpackagemanager.ThismanagerrequiresyoutodownloadandaddanAPTkey,whichisdoneusingthefollowingtwocommands:
wgethttp://www.linux-projects.org/listing/uv4l_repo/lrkey.asc
sudoapt-keyadd./lrkey.asc
2. Next,wemustaddtherepositorytothelistofsourcesusedbyAPT.Thisisdonebyeditingthesources.listfileusingnano:
sudonano/etc/apt/sources.list
3. Next,addthefollowinglinetothesources.listfile:
debhttp://www.linux-projects.org/listing/uv4l_repo/raspbian/wheezy
main
Thislookssimilartowhatisshowninthefollowingscreenshot:
4. Now,weneedtorefreshthelistofpackagesknowntoAPTandfinishbyinstallingtherequiredpackages:
sudoapt-getupdate
sudoapt-getinstalluv4luv4l-raspicamuv4l-raspicam-extrasuv4l-
server
5. Oncetheinstallationiscomplete,rebootthePitocompletethesetup.
Nowthatthecameramoduleandstreamingserverarebothsetup,thecameracanbetestedbybrowsingtheIPaddressofthePiontheport8080usingaPCconnectedtothesamenetworkasthePi.Thisisdonebyentering,forexample,192.168.0.56:8080intothebrowseraddressbarassumingthat192.168.0.56wastheIPaddressofthePi.
Assumingthattheserversetupwentaccordingtoyourplan,youshouldseeawebpagesimilartothatshowninthefollowingscreenshot.Here,youwillseetwolinks:onetoviewthevideostreamfromthePicameraandonetoconfigurethecamerasettings.
Althoughwewillbeabletoviewastreamstraightaway,wewillgotothesettingspagefirst(showninthefollowingscreenshot)inordertochangethecaptureresolutiontoincreasetheframerateofthevideostream.
Here,wewillchangetheimagewidthandheightoptionsatthetopofthepage.Theoptimalvalueswilldependonthenetworkconnectionbeingused.However,Ihavefoundthat600x400isareasonablestartingpoint,asthisstreamswellonmostconnectionsandgivesanimageofsufficientqualityforwhichwewillusethecamera.
Tosetthis,enterthecorrespondingoptionsintheheightandwidthfieldsatthetopofthepageandclickontheApplybuttontowardstheendofthepageasshowninthefollowingscreenshot.Oncethisisapplied,youwillberedirectedbacktothesettingspage.Togetbacktothemainpage,eitherusethehomelinkatthebottomofthepageornavigatetothepagemanuallybyusingthesameaddressweusedpreviously.
Onceyou’rebackonthemainpage,selectthevideostreamlinktoviewthelivefeedfromthePicamera.Thefollowingscreenshotdisplaysthemainpageonwhichthevideoisstreamed:
Youwillnoticesomedelaybetweenthemovementinthefrontofthecameraanditbeingdisplayedonthewebpage.ThisiscausedbyoverheadsinthestreamingprotocolandthenetworkthePiandcomputerareconnectedto.Unfortunately,thereislittlethatcanbedoneaboutthis,however,Ihaveonlyevermanagedtomeasureatmostthreesecondsofdelay.
DeployingwebapplicationsNext,wewilldeploythewebapplicationthatwillallowustocontrolthearmandchassisremotelyandviewthevideostreamfromthePicamera.SincethiswebapplicationisalsobuiltusingtheFlaskframework,theprocessofdeployingitwillagainbesimilartothatusedinthepreviouschapters.
Beforewestart,besuretocopytheconfig_filesandrobot_arm_webappdirectoriesfromtheprojectfilestothe/home/pidirectoryonthePi:
1. First,wewillinstalltherequiredpackagesandlibraries,includingtheRPIOPythonlibraryusedtocontroltheGPIOpinsfromPython:
sudoapt-getupdate
sudoapt-getupgrade
sudoapt-getinstallpython-pipgitpython-devgunicornsupervisor
nginx
sudopipinstallRPIO
2. Next,downloadandinstalltheFlaskframework:
gitclonehttps://github.com/mitsuhiko/flask.git
cdflask
sudopythonsetup.pyinstall
cd
3. Now,copytheNginxconfigurationandperformtheconfigurationself-test:
sudocpconfig_files/nginx/robot_arm.conf/etc/nginx/sites-
available/robot_arm.conf
sudoln-s/etc/nginx/sites-available/robot_arm.conf/etc/nginx/sites-
enabled/
sudorm/etc/nginx/sites-enabled/default
sudonginx-t
sudoservicenginxrestart
4. Copythesupervisorconfigurationandtellthesupervisortorereadtheconfigurationfiles:
sudocpconfig_files/supervisor/robot_arm_webapp.conf
/etc/supervisor/conf.d/robot_arm_webapp.conf
sudosupervisorctlreread
5. Copythewebapplicationconfigurationfiletothehomedirectory.ThisdefinesthecalibrationsettingsfortheservopositionsandtheGPIOpinseachdeviceisconnectedto.TheGPIOsettingsshouldnotbechangediftheelectronicswerebuiltbyfollowingthewiringdiagram.Wewilllookatthecalibrationvaluesingreaterdetaillaterinthischapter.However,itwouldbeusefultoopenthefileandbefamiliarwiththeoptionsthatareavailablethere.
sudocpconfig_files/robot_arm.conf~
nano~/robot_arm.conf
6. Finally,tellthesupervisortostartthewebapplication:
sudosupervisorctlupdate
sudosupervisorctlstartrobot_arm_webappp
Nowthatthewebapplicationhasbeendeployed,wecantesttheelectronicsandcamerastreamingthroughthewebapplication.
ThemainpageofthewebapplicationshowsthemovementcontrolsforthechassisandpiArm:
7. First,testthemovementcontrolsandensurethatboththemotorsrotateinthesamedirectionwhenyouselectForwardandintheoppositedirectionwhenyouselectReverse.
8. Next,ensurethatthearmcontrolsmovetheservoscorrectly.ForJoint2andHand,asingleservoshouldmoveandforJoint1,twoservosshouldmoveintheoppositedirection.
Thevideopage(accessedusingtheVideolinkinthetop-rightcornerofthewebapplication)showsthelivevideostreamfromthePicameramodule.Belowthestream,thereisalinktothecamerasettingspageprovidedbythestreamingserver.Notethatthereisnolinkbacktothewebapplicationfromthecamerasettingspage,soyoumustnavigatebacktoitmanuallyafterfollowingthislink.
ThereisalsoapagethatshowsboththevideostreamandcontrolsaccessedusingtheControl&Videolinkinthetop-rightcornerofthewebapplication.
ThearmandchassisconstructionNowthattheelectronicsareassembled,itistimetoassembletheroboticarmandchassis.Firstly,wewillgooverwhatpartsareneededtoconstructtherobot.
Inthecaddirectoryintheprojectfiles,thereareseveralDXFfilesforpartsthatareneeded;thefollowingisalistofallthepartsthatareneededtoconstructtherobot:
1xArm1_Main.dxf2xArm1_ServMount.dxf1xArm2_Main.dxf2xWheel.dxf1xSpacers.dxf1xCameraMount.dxf1xClaw_ServoAttachment.dxf1xBaseLayer.dxf
Onceallofthepartsaremachined,wecanstarttheassembly:
1. First,weneedtoattachthetwogearedmotorsandcastortothechassisbase.ThisisdoneusingfourM3screwsandnutsforeachmotorandfourM4screwsandnutsforthecastor.
2. Next,wecanattachtherelayboardandthePitothechassisbaseusingM3screwsandnutsaswellastwoofthespacersbetweenthechassisbaseandPCBs.
3. Next,wewillattachtheclawattachmenttooneoftheservos,whichwillbemountedattheendofthesecondarmassembly.First,useoneoftheplasticattachmentssuppliedwiththeservotomanuallymovetheservotohalfofitstravel(thisistoallowplentyoftraveloneithersideofthecurrentpositionforthecalibrationsteplateron).
4. Oncetheservoshaftisinthecorrectposition,wecanremovetheplasticattachmentandattachtheMDFclawattachment.Thisisdonebypushingtheservoshaftintotheholeinthecenterofthecircle.Thiswilltakesomeforce,butwillensurethattheMDFhasagoodgripoftheservoshaft.
5. Oncetheclawattachmenthasbeenattachedtotheshaft,useanM3washerandthescrewthatcamewiththeservostofastentheattachmentontotheservoshaftusingthetappedthreadattheendoftheservoshaft.
6. Next,wewillattachtheservotothearm2section;thisisdonebyfirstthreadingthecablethroughthesquarecutoutinoneofthearmsectionsandusingsomehotgluetofixtheservointothecutout,asshowninthefollowingimage:
7. Next,weneedtocutsix50mmlengthsofM4threadedbar,whichwilllaterbeusedtoassemblethetwoarmsections.
8. Next,wewillassembletheupperarmassembly.StartbyassemblingthetwosectionsoftheupperarmbyusingtwosectionsoftheM4barinthefirsttwoholesnearesttotheclawandspacethegapusingnineoftheMDFspacers.
9. InsertasectionoftheM4threadedbarthroughthetwoholesattheendoftheupperarmsection;thiswillbeusedtoconnecttotheservo,whichwillmovetheupperarmsection.
10. Next,wewillattachtheservothatwillmovetheupperarmsectiontothelowerarmsection;again,theservomustfirstbesetto50percentofitstravelbeforeyoudothis.
11. Now,attachasinglearmtotheservoandscrewitontotheservoshaft.12. Attachtheservoontothelowerarmpanelinthesamewayaswasdonewiththe
previousservo,asshowninthefollowingimage:
13. Next,wewilltaketheremainingtwoservosandattachthemtothetwomountingbracketsthatareattachedtothechassisbase.Theseservosshouldbothbesetto50percenttravelandalignedsuchthatoneservoisinthetop-rightcornerofthecutoutandtheotherisinthetop-leftcorner.Thisistoensurethattheshaftshavethebestchanceofliningupwhentheyareattachedtothechassisbase.
14. Next,thetwolowerarmpanelsmustbeattachedtothetwoservos.ThisisdonebypressingtheshaftintotheholesinthelowerendofthearmpanelsandfasteningtheshaftwithM3washersandthescrewssuppliedwiththeservos.
15. Now,thelowerarmassemblycanbeassembledinthesimilarwaytotheupper-armsectionbyfasteningthetwopanelstogetherusingtwooftheM4threadedbarsectionsandelevenoftheMDFspacers.
16. TheupperandlowerarmsectionscannowbejoinedusingasectionoftheM4threadedbar,asshowninthefollowingimage.Notethatthisshouldbeafairlyloosefasteningtoreducethefrictioninthisjointandthereforereducetheloadontheservo.
17. Now,wecanattachtheentirearmassemblytothechassisbasebyusinganM3screwoneachoftheservobrackets,asshowninthefollowingimage:
18. Now,wecanconnecttheservomountedinthelower-armsectiontothebaracrosstheupper-armsectionusingapieceofrigidcopperwire.Thisshouldbeattachedtogetthedesiredfieldofmovementontheupper-armsection,whichcanbemeasuredbymanuallymovingtheservoarm.
19. Thefinalstepoftheassemblyistoattachthecameratothemountingbracket;thecamerashouldfirstbedisconnectedtofeedtheflat,flexcablethroughtheslotatthebottomofthebracket,asshowninthefollowingimage:
20. Next,attachthecameratothebracketbyusingsmallsectionsofBlu-Tack(thisallowsustoadjusttheangleofthecameratotheoptimalangle)andplacethecameraattachmentintotheslotinthechassisbase.
Oncefullyassembled,therobotshouldlooksomethinglikewhatisshowninthefollowingimage:
CalibrationNowthatthearmandchassisarebuilt,weneedtocalibratethemotorsandservostoensurethattheyreactinthecorrectwaytothecommandsfromthewebapplication.Inthecaseoftheservos,donotattempttomovethemtoofarasthiswillcausedamagetothemorotherpartsoftheroboticarm.
ChassismotorsFirstly,wewillensurethatthechassismotorsbehavecorrectly.Thisissimplyacaseofrunningthemotorsineachoftheirdirectionstoensurethatthechassismovesinthedirectionintended.
Whenrunninginforwardorreversemotion,ifonemotorisrunninginthewrongdirection,thiscanbecorrectedbyswappingthepolarityofthemotor.Youcanswapthepolaritybyswappingtheconnectionsonthetwowiresleadingtoitfromtherelayboard.
Whenthemotorrunsintheclockwiseorcounterclockwiserotation,ifthebaserotatesinthewrongdirection,thenbothmotorsneedtohavetheirpolarityswapped.
Arm2andhandservosSincethesetwoservosoperateindependently,theyarefairlysimpletocalibrate,asallthatneedstobedoneistofindthelimitsoftherangeyouwanttheservostomovein.
Tofindthis,wewillusetheRPIOlibraryfromthePythonconsoletosetdifferentvaluesontheservo:
1. First,fromanSSHsessiononthePi,openanewPythonconsoleasroot(rootaccessisrequiredasthelibraryneedstoaccessmemorydirectlytocontroltheGPIOpins):
sudopython
2. Next,importtheRPIOlibraryusingthefollowinglineandcreateaServoobject:
importRPIO.PWMaspwm
s=pwm.Servo()
3. Now,youcansetthepositionoftheservousingthefollowinglineofcode,whereGPIOistheGPIOnumbertheservoisconnectedtoandVALUEisthetimingvalueforthePWMsignalsenttotheservo(thisshouldbebetween500and2500):
s.set_servo(GPIO,VALUE)
4. Repeatthelaststepuntilyoufindgoodvaluesforthemaximumandminimumvaluesoftheservothatgivereasonablelimitstothemotionoftheservo.
Oncetheoptimalvaluehasbeenfound,itshouldbeenteredintherobot_arm.confconfigurationfileintheappropriate_MAXand_MINconfigurationoptions.
Thearm1servosSincethesetwoservosoperateparallelywitheachother,thecalibrationprocedureisslightlymorecomplex.Wemustfirstdetermineapointonboththeservoswheretheyareinequalpositionsandarenotmovingtotryandcanceleachotherout.
1. Firstly,openaPythonconsoleasbefore:
sudopython
2. ImporttheGPIOlibrary:
importRPIO.PWMaspwm
3. Next,createtwoservoobjects,oneforeachservo:
s1=pwm.Servo()
s2=pwm.Servo()
4. Now,setastartingvalue(VALUE)forthefirstservo(onGPIOnumber,GPIO)thatiswithintherangeofmovementforthelowersectionofthearm(1500isagoodstartingvalue;however,youmayneedtoexperimenttofindthebestvalue):
s1.set_servo(GPIO,VALUE)
5. Now,weneedtofindavalue(VALUE)onthesecondservo(onGPIOnumber,GPIO)atwhichbothservosareatrestandnottryingtomove.Thisindicatesthatthetwoservosareinthesameposition.Notethatyoumayneedtomovethearmslightlytostoptheservosfromtryingtomove.Theweightofthearmmaykeeptheservosinmotioneventhoughtheyareinthesameposition:
s2.set_servo(GPIO,VALUE)
6. Oncethetwoservosareinthesameposition,makeanoteofthetwovalues(forexample,1400and1600)andcalculatethemidpointofthetwo(1500).Thisvalueshouldalsobeapositioninwhichboththeservoswillbeinthesameposition.
7. Nowthatweknowthisvalue,wecandefinethesetsfunction,whichwillsetboththeservostoagivenoffset,allowingustoderivetheupperandlowerlimitsforbothservos.Here,GPIO_1andGPIO_2aretheGPIOnumbersthateachservoisconnectedtoandVAListhemidpointvaluecalculatedinthepreviousstep:
defsets(position_delta):
s1.set_servo(GPIO_1,VAL+position_delta)
s2.set_servo(GPIO_2,VAL–position_delta)
8. Wecannowusetrialanderror,aswiththepreviousservos,tofindtheoptimalmaximumandminimumservospositionsbymakingcallstothesetsfunction:
sets(-300)
sets(0)
sets(1000)
…
9. Nowthatwehavethemaximumandminimumvaluesthatcanbepassedtothesets
function,wecaneasilyderivethevaluesthatneedtobesetintheconfigurationfileas(whereVAListhecalculatedmidpoint,SETS_MINandSETS_MAXarethemaximumandminimumvaluespassedtothesetsfunction,SETS_MINisnegative,andSETS_MAXispositive):
ARM_1_A_SERVO_MIN=VAL+SETS_MINARM_1_A_SERVO_MAX=VAL+SETS_MAXARM_1_B_SERVO_MIN=VAL-SETS_MAXARM_1_B_SERVO_MAX=VAL–SETS_MIN
Oncethesevaluesarederived,theycanbeenteredintotherobot_arm.confconfigurationfile.
TroubleshootingThefollowingareafewissuesyoumaycomeacrosswhilebuildingandusingtheroboticarm,wherethecausesoftheissuesandinformationonhowtheproblemcanbefixed.
ThevideostreamhasasubstantialdelayThisdelaycanbecausedifyouattempttostreamattoohighofaresolution.Thefirstthingtodoistotryandreducetheresolutionyouarestreamingat(notethatthishastobedoneeverytimethePiisrebooted).
Iftheissueisstillthere,thenyoumaywanttotryreducingtheJPEGqualityandframerateoptionsonthestreamingserverconfigurationpage(whichisaccessibleviathelinkonthevideostreampageofthewebapplication).
TheservosmakealoudhummingnoiseTheservoscanoftenmakealoudhummingsoundwhentheyareundersubstantialload.Usually,thisisthecasewhenthearmisfullyextendedorisattemptingtoliftaload.Ifthiscontinues,anextendedlengthoftimewillconsumemorebatterypowerandcouldlowertheexpectedlifetimeoftheservos;however,inthisproject,thisbehaviorisnormaloperation.
ControloftherobotislostIfthecontroloftherobotislost,themostlikelycauseisthelossoftheWi-Fisignal.However,othercausescanincludelowpowerintheUSBbatterybankoradditionalloadontheservosthatcausesthemtodrawmorepowerthanusual(however,thisshouldonlyevercauseanissuewhenthebatterybankisrunninglow).
ThearmjumpstonewpositionsThiscanbecausedbytoomanyrequeststomoveanaxisofthearminagivendirectionbeingsentinaperiodoftime.Ifyoufindthatittakestoolongtomovethearm,thenconsiderincreasingthevalueofSERVO_DELTAinthewebapplicationconfigurationfile.
SummaryInthischapter,wehadalookatyetmorewaystointerfacewithhardwareovertheGPIOportthatincludesusingpulsewidthmodulation,whichcanbeusedtodrivedevicessuchastheservosusedinthischapter.Wealsotookalookathowtoemulateananalogsignal,whichcanthenbeused,forexample,tocontrolthebrightnessofanLED.
WealsotookalookatthewaysinwhichtheRaspberryPicameracanbeaccessedremotelyusingtheV4Lstreamingserver.Intheserver,thesamecontrolandstreamingoptionsthatareavailabletothelocalapplicationsaremadeavailabletothedevicesonthesamenetwork.
Inthenextchapter,wewilllookathowtousethePiforatrueubiquitouscomputingproject,whichwillcombineaninformationdisplayintoafairlystandardmirror.
Chapter9.MagicMirrorInthischapter,wewillcreateamirrorthatiscapableofbeingbothareflectivesurfaceandaninformationdisplaythatcanbeusedtoshowcustomizedinformation.
Thiswillbedonebytakingadvantageofthepropertiesofatwo-waymirror(commonlyusedforshopsecurity),whichwillallowlighttopassthroughitasifitwasaglasswhentheothersideisdarkerandbehavelikearegularmirrorotherwise.
ThisprojectisbasedontheMagicMirrorprojectbyMichaelTeeuw.Moreinformationabouthisoriginalversioncanbefoundathttp://michaelteeuw.nl/tagged/magicmirror.
WhatyouwillneedThefollowingisalistofthingsthatyou’dneedforthisproject:
TheRaspberryPiAUSBkeyboard(forsetuponly)AVGAmonitorA6mmplywoodA12mmplywoodAsheetoftwo-waymirroredacrylic(www.cutplasticsheeting.co.uk/mirrored-sheeting/two-way-acrylic-mirror)M4machinescrewsandwashers
ToolsyouwillneedThefollowingisalistoftoolsyouwillneedtoconstructtheplywoodenclosureforthemirror:
A25mmForstnerdrillbitAlargeelectricdrillordrillpressAjigsawArouterandtableAstraight,topbearing,andguidedrouterbit(www.screwfix.com/p/titan-flush-trim-bit-with-bearing-shank-12-7-x-25mm/72588)A4mmrebaterouterbit(www.screwfix.com/p/biscuit-router-cutter-no-20-shank-41mm/86179)
Notethathere,arouterandtablearerequiredtomachinetheplywoodenclosureforthemirror,whicharebothtoolsthatyoumaynothaveeasyaccessto.Ifthisisthecase,aswithlasercuttinginthepreviouschapters,agoodplacetostartwouldbetolookforalocalhackerspace,whichwouldlikelyhavethesetoolsandmemberswhowouldbehappytohelpyouusethem.
TherouterbitsIhavelinedherearefora1/2inchshank,whichmustfittherouteryouintendtouse.Ifyourroutercanonlyfind1/4inchshank,thenyouwillneedtofindalternativecutters.
Ifyoustillhavetroublegettingaccesstoone,thereisanalternativewaytobuildthisprojectthatwillforgotheplywoodenclosureattheexpenseofsomeaestheticappealofthemirror.
Themonitoryouselectshouldpreferablybewidescreenifyouintendtousethemonitorinportraitmode(aswillbedoneinthischapter).Althoughitisnotrequired,thebuildprocessismadeeasierifthecontrolbuttonsforthemonitoraremountedonthebackofthedisplay.
TheoryThetwo-waymirrorthatwillbeusedinthisprojecthasanimportantproperty.Whenonesideofthemirrorisexposedtoabrighterambientlightthantheother,thislightisreflectedinthemirrorsurfaceandisallowedtopassthroughtotheother(darker)sideofthemirror.
Typically,thispropertyisusedtocontrolhowthemirrorisusedinsecurityapplications,forexample,ashopmayfitsuchamirrorbetweenanofficeandtheshopfloorsothatthoseintheofficecanstillseewhatishappeningontheshopfloor.Forthistohappen,theofficemusthaveveryminimallightingtoensurethatthebrightlightfromthealreadywell-litshopfloorpassesthroughtotheofficeandthatnolightfromtheofficeleaksthroughthemirror,exposingittotheshopfloor.
Inourproject,wewillusethispropertytocreateadisplaythatshowswhitetextandgraphicsonamirroredbackgroundbyplacingasectionofthemirrorinfrontofanLCDmonitor.
Thisispossibleifyoukeepthedisplaydarkintheareaswherethemirrorsurfaceshouldbepreservedandusebrightwhitetextandgraphicswheretheyshouldbeshowninsteadofthemirrorsurface.Bydoingthis,youcanallowthemtopassthroughthemirrorsurfaceprovidedthatthebrightnessofthedisplayisgreaterthanthatoftheambientlightintheroomtheprojectisin.
Forthisreason,itisworthnotingthatthisprojectwillnotworkifthemirrorsurfaceissubjecttobrightsourcesoflight,soitisbesttokeepthemirrorpointedawayfromlargewindowsorlights.
Whilesearchingforasuitablemonitor,itisalsobettertogetthehighestcombinationofbrightnessandcontrastratiopossible,asthiswillallowyoutogetbrightertextandgraphicsfromthedisplay.Thisinturnwillimprovethequalityoftheimageonthemirrorsurfacewhilemaintainingadarkbackgroundsoasnottocauseanylightleakagewherethedisplayshouldremainamirror.
ThewebapplicationThewebapplicationwewilluseforthemirrorisessentiallyaframeworkbuiltusingFlask,whichprovidesacommoninterfaceforindividualwidgetsdisplayedonthemirror.Inordertogetthedesiredeffectwherethewidgetsarevisiblethroughthemirror,thepagemusthaveablackbackgroundwithwhitetextandgraphics.Forbestresults,thetextshouldbeaslargeaspossiblesothatitallowsmaximumlighttopassthroughthemirror’ssurface.
DevelopinganewwidgetEachtypeofwidgetthatcanbeshownonthemirroriscomprisedoffourfiles:
Aserver-side(Python)scriptfile(widgets/CLASSNAME.py)AJinja-styletemplatefile(templates/widgets/CLASSNAME.html)ACSSfile(static/widgets/CLASSNAME/style.css)Aclient-side(JS/jQuery)scriptfile(static/widgets/CLASSNAME/script.js)
Here,CLASSNAMEistheclassnamegiventothewidgetthatisusedinthewidgetconfigurationfilestocreateaninstanceofthewidgetonthemirrordisplay.Templatesforthesefilescanbegeneratedusingthefollowingscript(assumingthatyouarecurrentlyinthemirror_webapp/directory):
./make_new_widgetCLASSNAME
Wewillnowtakealookatthedemowidgettoseewhatneedstobedoneifyouwanttoimplementyourownwidgets.
ThePythoncodeThefirststeptodevelopanewwidgetistocreateaPythonscriptthatwillprovidethewebapplicationwiththedataitneedstooperate.Thiswillhaveaccesstotheconfigurationoptionsthataresetunderthe[widget]sectionoftheconfigurationfile.ThemainpartofthePythonscriptistheget_datafunctionwhichmustreturnadictionarythatwillbemadeaccessiblefromthewidgetdatawebserviceandtranslatedintoJavaScriptObjectNotation(JSON):
fromAbstractWidgetimportAbstractWidget
classDemoWidget(AbstractWidget):
defget_data(self,config):
self.logger.info('Gettingdatafordemowidget')
data={'greeting':'NoTextSet!'}
if'text'inconfig:
data['greeting']=config['text']
returndata
Here,youcanseetheget_datafunction,whichtakesthewidgetconfigurationasadictionaryparameterandreturnsadictionary.Thisisonlyasimpleexamplethatreturnsatextstringtakenfromtheconfigurationfile.However,thereisalotofscopefortheadditionalprocessingthatcanbedonehere(refertothecodeforsomeoftheotherwidgets,forexample).
Youwillalsonoticethatthefirstlineofthefunctionisusedtologinformation.Thiscanbeveryusefulfordebuggingtheapplication.Thelogiskeptinthe/home/pi/mirror_webapp/mirror_app.logfileandcontainsthelogoutputfromtheframeworkapplicationandeachconfiguredwidget.
Textcanbeoutputtothelogatseverallevels,fromleastseveretomostsevere:debug,info,warning,error,andcritical.
Thedatareturnedbytheget_datafunctionismadeavailableonthewidgetdataweb
serviceavailableat[PI_IP]/widget_data/[widget_id].Here,PI_IPistheIPaddressofthePiandwidget_idisthewidgetIDthatisgivenbythefilenameoftheconfigurationfile(thatis,awidgetwiththeconfigurationfilenameclock.confwillhavethewidgetIDclock).
TheJinjapagetemplateThewebpagefortheapplicationisgeneratedbyFlaskusingJinja2templates.ThisallowsaverysimpleandcleanwayofbuildinganHTMLstructuredynamically.
Thefirstthingrequiredinthefileistheextendsstatement,whichtakesacommonsectionofcodeusedforeachwidgetandaddsthecontentsblocktoitbasedontherestofthefile:
{%extends"widget.html"%}
Thenextsectionisthewidget_contentsblock.Thisiswheretheactualcontentsofthewidgetshouldbewritten.
Here,youhaveaccesstoadatavariablethatcontainsthedatareturnedbytheget_datafunctioninthePythoncodeforthewidget:
{%blockwidget_contents%}
<p>{{data.greeting}}</p>
{%endblock%}
Typically,youwillfindthatalotofdynamiccontentishandledbyJavaScript,asoncethePihasbooted,thewebpagewillneverberefreshedundernormaloperation.Hence,thisHTMLgenerationstepisonlyeverperformedonce.
TipFormoreinformationontheJinjatemplatelanguage,refertothedocumentationathttp://jinja.pocoo.org/docs/dev/.
TheJavaScriptcode
Sincethedemowidgetdoesnothaveanydynamiccontent,thefunctionsintheJavaScriptfilearejustemptyplaceholders.However,themainpointtobeshownhereishowthefunctionsarecalledbytheframework.
Firstly,thereisaclosure(awayoflimitingscopeinJavaScripttogetsomethingthatbehavessimilartoaclassinobject-orientedlanguages)thatdefinesthewidget.Thiscanbeusedtostoreinstance-specificvariablesforthewidget:
varDemoWidget=function(){
}
Next,thereisapublicfunctionthatisexecutedwhenthepagefirstloads.Thisisusedtogetthewidgetintoitsinitialstate(forexample,populatingalistofRSSitemsbeforethenextupdateorsettingthetimeofaDateobject):
DemoWidget.prototype.init=function(widgetDOM){
return;
};
Thenextfunctioniscalledatintervalsoftheupdate_timevariablesetinthewidgetconfigurationfile(refertotheConfigurationsectionlaterinthischapter).Thisshouldbeusedtoupdatethecontentsofthewidgetsothatthemirrorkeepsdisplayingnewinformation,forexample,refreshingalistofnewsstoriesorincrementingthesecondhandofaclock:
DemoWidget.prototype.update=function(widgetDOM){
return;
};
ThewidgetDOMparametergiventoboththefunctionsistheDocumentObjectModel(DOM)ofthewidgetcontainerelement.ThisprovidesasafeandeasywaytoaccesstheelementsofyourwidgetwithouthavingtorelyonIDattributesintheHTML.
Forinstance,toaccessacertainparagraphelementofthewidget,youwouldfirstassignaclasstotheelementintheHTMLtemplate,shownasfollows:
<pclass="news-story-title"></p>
Then,youcaneasilyaccesstheelementandchangeitstestusingthefollowinglineofJavaScript:
widgetDOM.getELementsByClassName("news-story-title")[0].innerText="Hello,
World!"
TipFormoreinformationonJavaScriptdevelopment,refertothew3schoolsreferencepagesatwww.w3schools.com/jsref.
ThePisetupTheinitialstepstosetupthePiaretogetacopyofRaspbianinstalledonanSDcardofatleast4GB(although8GBorlargerispreferable),asdescribedinChapter1,RaspberryPiPirateRadio,andifdesired,connectthePitoyourWi-Finetwork.ThisprojectwillkeepthePioutsidethedisplayenclosuresothatWi-Fiisonlyreallyneededifawiredconnectionisnotavailable.
RotatingthedisplayYoumaywishtorotatethedisplaytousethemirrorinaportraitorientation,inwhichcasethevideooutputofthePiwillalsoneedtoberotated.Fortunately,thisisdonebyasimplechangetoaconfigurationfile:
1. Openthebootconfigurationfileusing:
sudonano/boot/config.txt
2. AddthefollowinglineandreplaceNwithoneoftheoptionsdescribedinthenextscreenshot:
display_rotate=N
Theconfigurationfilelookssimilartothefollowingscreenshot:
3. SavethefileandrebootthePitoseethechanges:
sudoreboot
ThepossibleoptionsthatcanbegivenforNare:
0:Normaldisplay1:Rotate90degreesclockwise2:Rotate180degreesclockwise3:Rotate270degreesclockwise
DeployingthewebapplicationNowthatthePiissetup,wecangoaheadwiththedeploymentofthewebapplicationonthePi.Onceagain,thisisaFlaskapplication,sotheprocedurewillbeverysimilartothatusedinthepreviousprojects:
1. First,startbycopyingtheconfig_filesandmirror_webappdirectoriestothe/home/pidirectoryontheRaspberryPi.
2. Now,wewillensurethatthesoftwareonthePiisuptodateandinstalltherequiredsoftwaretorunthewebapplication(notethatthelastlinesherearePythonlibrariesrequiredbysomeofthewidgets):
sudoapt-getupdate
sudoapt-getupgrade
sudoapt-getinstallpython-pipgitgunicornsupervisornginx
sudopipinstallrequestspytzfeedparser
3. Next,wewilldownloadtheFlaskcoderepositoryandinstallit:
gitclonehttps://github.com/mitsuhiko/flask.git
cdflask
sudopythonsetup.pyinstall
cd
4. Now,wewillcopytheNginxconfigurationforthemirrorwebapplication,enableit,andrestartNginxsothatitstartshandlingrequestsforthemirrorwebapplication:
sudocpconfig_files/nginx/mirror.conf/etc/nginx/sites-
available/mirror.conf
sudoln-s/etc/nginx/sites-available/mirror.conf/etc/nginx/sites-
enabled/
sudorm/etc/nginx/sites-enabled/default
sudonginx-t
sudoservicenginxrestart
5. Next,wewillcopythesupervisorconfigurationfortheapplication,whichwillallowthewebapplicationtobeservedbythePi,assoonasitboots:
sudocpconfig_files/supervisor/mirror_webapp.conf
/etc/supervisor/conf.d/mirror_webapp.conf
6. Next,copythedefaultwidgetconfigurationfiles.Fornow,wewilljustusethedefaultsuntilthemirrorisfullysetupandgooverthestepstoconfigurewidgetsandstyleslaterinthechapter:
cpconfig_files/mirror_app.conf~
cp-rconfig_files/widgets/widget_configs/
7. Finally,updatesupervisortoenablethewebapplication:
sudosupervisorctlreread
sudosupervisorctlupdate
sudosupervisorctlstartmirror_webappp
Oncethishasbeendone,youshouldbeabletobrowsethewebapplicationusingtheIPaddressofthePifromanyPConthesamenetwork.Ondoingso,youshouldbegreetedwithapagesimilartothatshowninthefollowingscreenshot:
Don’tworryifthepagelooksbadlyrendered,asthedefaultwidgetconfigurationisdesignedtobeshownonaportraitmonitorandthefontsizesaresetrelativetothewidthofthescreen.WhendisplayedonthePi,thislooksalotbetter.
SettingupChromiumNowthatwehavethewebapplicationsetup,wecanmoveontoinstalltheChromiumbrowser.WewillusethebrowserinthekioskmodetodisplaythewebapplicationonthePIautomatically,whenitboots.TosetupChromium,performthefollowingsteps:
1. Firstly,wemustconfigurethePitobootstraightintoLXDE(thedefaultwindowmanagerusedonRaspbian)insteadofaconsole.ThiscanbedoneusingthePiconfigurationutility:
sudoraspi-config
2. Next,selecttheEnableBoottoDesktop/ScratchoptionandhitEnter.
3. Now,selecttheDesktopLoginasuser‘pi’atthegraphicaldesktopoptionandhitEnter.
4. Next,selecttheFinishoptionandwhenaskedwhetheryouwouldliketorebootnow,selectNo.
5. Oncethatiscomplete,wenowneedtoinstalltheChromiumbrowser:
sudoapt-getinstallchromiumx11-xserver-utilsunclutter
6. Next,wewillmodifytheLXDEautostartscriptsothatChromiumautomaticallystartsandbrowsestothewebapplicationpagewhenthePiboots:
sudonano/etc/xdg/lxsession/LXDE/autostart
7. Commentoutthefollowingline.Thiswilldisablethedefaultscreensavertoensurethatthewebapplicationalwaysremainsvisible:
@xscreensaver-no-splash
8. Addthefollowinglinesattheendofthefile.Thefirstthreedisablethepowersavingfeaturesthatwouldautomaticallyturnthemonitorblankandturnitoffafteraperiodofinactivity.ThefinallinewillstarttheChromiumbrowserinafullscreenkioskmodeandbrowsetothewebapplication:
@xsetsoff
@xset-dpms
@xsetsnoblank
@chromium--kiosk--incognitohttp://localhost
Bythispoint,theautostartfileshouldlooksimilartothefollowingscreenshot:
9. Finally,rebootthePitotestthesetup:
sudoreboot
Allbeingwell,youshouldseethePibootintoLXDE(indicatedbytheRaspberryPilogoshownonawhitebackground)andshortlyafterthat,Chromiumshouldstartandbrowsetothewebapplication.
EnclosureconstructionNowthattheelectronicsandsoftwareinstallationiscomplete,wecanmoveontobuildtheplywoodenclosureforthemirror.Ifyoudonothaveaccesstoarouterandtableforthisproject,thenrefertotheBuildingthemirrorwithoutanenclosuresectiondescribedlaterinthechapterforinstructionsonhowtoconstructthedisplaywithouttheplywoodenclosure.
NoteWhenusingpowertools,propersafetyprecautionsshouldbetaken.Eyeandearprotectionshouldalwaysbewornandmains-poweredtoolsshouldbeprotectedbyusingaresidualcurrentdevice(RCD).
First,weneedtomeasurethemonitortodetermineboththesizeofthemirroredacrylicsheetthatneedstobeorderedandthesizestowhichthepanelsfortheenclosureshouldbecut.
Theupcomingdiagramshowsthepanelsthatmustbecutouttomaketheplywoodenclosure.Eachofthedimensionsaregivenbythefollowingcalculations:
W=monitorwidth+24H=monitorheightWb=W+10Hb=H+10T=monitorthickness+9
NoteNotethatallthesizesareinmm.
Toconstructtheenclosure,performthefollowingsteps:
1. Whiletakingthemeasurementsoftheheightandwidth,itisadvisabletoleavearound2mmoneachsideofthemonitor,whichwillallowustorectifyanyerrorsinthemeasurementwhilemanufacturing.
2. Inordertotakethenextmeasurement,wemustfirstremovethefrontplasticbezelfromthemonitor.Thisisusuallyheldonwithaseriesofsmallplasticclipsaroundtheedgeofthemonitor,asshowninthefollowingimage.Toremovethem,useasmall,flatscrewdrivertoprizeopenthegapbetweenthebackofthemonitorcaseandthefrontbezel.Gradually,workaroundthemonitoruntilalltheclipsarereleased.Thefrontbezelshouldnowliftoffwithease.
3. IfthemonitorhasanybuttonsorLEDsonthefrontpanel,thereislikelyanadditionalPCBthatmustberemovedfromthefrontbezel.Thisusuallyrequiresustounscrewtheboard.
4. Oncethebezelisremoved,wecannowmeasurethespacerequiredinsidetheboxforthemonitor.Thisisthedistancefromthebackofthemonitor(specificallytheVESAmountingpoints)tothefront(preferablylevelwiththedisplaysurface),asshowninthefollowingimage.Itisadvisabletoaddatleastanadditional5mmtothismeasurement,asitiseasytoaddwasherstomovethemonitorforwardifthepanelsarecuttoolarge.However,thisisimpossibletorecoverifyoucutthepaneltoosmall.
5. Onceyouhavethesethreemeasurements,youcansubstitutethemintothecalculationsshowninthediagram.Usingajigsaw,cutthepanelstosize.Youwillneedtwoofboththelongandshort12mmplywoodsidepanelsandoneoftheback6mmplywoodpanel.
6. Oncethesepanelsarecut,itistimetocuttheslotsinthemtoplacethemirroredacrylic.Thisisdoneusinga4mmrebaterouterbitinaroutertable,whichcanbeseenintheupcomingimage.Todothis,performthefollowingsteps:
1. Firstly,ensurethattherouterisfirmlyfixedintothetableandthebitistightenedcorrectlyintotherouter.
2. Next,usetherouter’sdepthlocktofixtheheightoftherouter,sothattheloweredgeofthebladesarearound4-5mmabovethetable.
3. Now,movethefencesothataround5-6mmofthecutterisexposedonthefrontofthefence(thatis,thecuttercanonlycutupto5-6mmfromthematerialpassedalongthefence).
7. Oncetherouterandtablearesetup,itisagoodideatomakeafewtestcutsonascrappieceofmaterialtoensurethattherouterissetupcorrectly.Aimtogetaslotthatisaround5-6mmdeepintotheplywoodandaround4mmawayfromoneedge,asshowninthefollowingimage:
8. Onceyouarehappythatthesetupiscorrect,youcanmachinetheactualpanelstoendupwithasetofpanels,asshowninthefollowingphotograph.Atthisstage,itisagoodideatosandthepanelswithsomecoarsegritsandpapertoremoveanyraggededgesleftbytherouterorjigsaw.
9. Thenextstepistoassemblethefoursidepanelsthatformtheoutsideoftheenclosure.Thisisdoneusingtwoscrewsateachendofthelongpanelsthatarescrewedintotheendsofthetwoshortpanels.Forthis,wewillusescrewsthatareatleast1inchinlength,butnomorethan2inch.Performthefollowingsteps:
1. First,wemustdrillclearanceholesintotheendsofthetwolongsidestoallowthescrewshafttopassthrougheasily.Thisholeshouldbejustlargerthantheshaftofthescrew,butsmallerthanthehead.
2. Next,alignoneofthelongpanelsagainstashortone,asshowninthefollowingfigure,andusetheclearanceholeasguidancetodrillapilotholeintheendoftheshortsidepanel.Thisholeshouldbearound0.5-1mmsmallerthantheshaftofthescrew.
3. Repeatthepreviousstepuntilallthejointshavebeenfastened,ensuringthattheslotforthemirrorrunsallthewayaroundtheinsideedge,asshowninthefollowingphotograph:
10. Thenextstepistoattachtherear6mmplywoodpaneltothebackoftheenclosureframe.Thiscanbedoneusingseveralself-tappingscrewsaroundtheedgeoftheenclosure.Notethatthispanelhasintentionallybeenmadelargerthanwhatisrequired.
1. Firstly,withtheenclosureplacedontopoftherearpanel,drawaroundtheinsideoftheenclosuretohelpmarkoutthepositionsfortheclearanceholessothatthescrewsholdontothebackpanel.
2. Next,usingthismarkingasaguide,drillseveralclearanceholesaroundtheperimeteroftheenclosure.Typically,twoholesontheshortpanelsandthreeholesonthelongonesshouldbeenough.
3. Oncethisisdone,drillpilotholesforthescrewssothattheygointothesidepanelsandattachthebackpaneltotherestoftheenclosure.
11. Thenextstepistotrimtheexcessmaterialfromthebackpanel(thewholeideaherewastoremovetheneedforaccuracywhilecuttingandfittingthebackpanel).Thisisdoneusingastraight,bearingguided,routercutter.
1. Firstly,movethefencetowardthebackoftheroutertable(wewillnotuseitasaguidehere)andfitthestraightbitintherouter.
2. Next,usingthedepthstop,movetheroutertoapositionwherethebearingisonthesamelevelasthe12mmsidepanels,sothatthereisenoughclearancetoallowthecuttertoremovetheexcessmaterialonthebackpanelonly.
3. Now,youcanmachineawaytheexcessmaterialonthebackpanelbykeepingtheenclosuretightagainsttherouterbitwhilemakingapassalongalltheedgesoftheenclosure.Oncethisisdone,thepanelshouldlooksimilartothefollowingimage:
12. ThenextstepistomarkthepositionoftheVESAmountsonthebackpanelinordertodrilltherequiredholesinthebackpanel.Theeasiestwaytodothisistocarefullyremovethedisplayassemblyfromtherearplastichousing,usingthefollowingstepsasaguide:
1. Thedisplayassemblyisrarelyfixedintotheplastichousingbyanythingotherthanthefactthatitisenclosedby.So,ifwegiveenoughforce,thedisplaypanelandelectronicsenclosurebehindthedisplaypanelwillberemoved.
NoteBecarefulwhenremovingthedisplayassemblyasthedisplaypanelandelectronicsenclosureareusuallynotfixedtoeachotherandexcessstresscoulddamagethecablesrunningbetweenthetwo.
Itisalsonotadvisedthatyouapplypowertoamonitorwiththebackcoverremovedastherearepotentiallydangerousvoltagesintherearelectronicscabinet.
2. Oncethisisdone,youshouldbeabletoplacetherearplasticcaseintotheenclosureandeasilymarkthepositionsofthefourVESAmountingholes.
3. Atthisstage,itwouldalsobeusefultomarkthepositionoftheholethatwillallowpowerandvideocablestoreachthemonitor.Thisholeshouldbeatleast25mmindiametersothatitaccommodatesanIECpowerconnector.
4. Oncetheholesaremarked,youcannowputthedisplayassemblybackintotherearplasticcase.
13. Oncetheholesinthebackpanelaremarked,thepanelcanberemovedandtheholesdrilledwiththefollowingsteps:
1. ThefourholesfortheVESAmountcanbedrilledusinga4.5mmdrillbit.2. The25mmholewillhavetobedrilledwitheitherafairlypowerfulmainshand
drillor,better,adrillpressusingaForstnerdrillbit.
14. Oncethebackpanelhastherequiredholesdrilledinit,itisworthgivingitaquicksandoverbyusingacoarsegritsandpaper,justtotidytheedgeleftbytherouterandForstnerdrillbit.
15. Next,reattachthebackpanelontotherestoftheenclosureusingthescrewholesmadepreviously.
16. Atthispoint,itisworthpoweringupthemonitorandensuringthatthedisplayissettofairlyhighcontrastandbrightnesssettingsinordertogetthebestimagequalitythroughthemirroredacrylic.
17. Oncethisisdone,feedthecablesthroughtheholepreviouslymadeforthem.LineuptheVESAmountwiththeholesdrilledforthemandscrewthemonitorintoposition.
Ifyourmonitorhasbuttonsmountedonthefrontpanel,youcansimplyplacethePCBtheyaremountedonbehindthemonitorwithintherangeofthecablethroughwhichtheyareconnectedtothemonitor.
Notethatifthemonitoristoofarbackintheenclosure(thatis,thedisplaysurfaceismorethan1mmawayfromtheslotforthemirror),thenyoumayneedtoaddsomewashersandspacerstothescrewstomovethemonitorslightlyforward,asshowninthefollowingimage:
Bythispointtheenclosureshouldlooksomethinglikethefollowingimage:
18. Thefinalstepistoinsertthemirroredacrylicpanelintotheslotcutforit.Thiscanbeeasilydonebyremovingoneoftheshortsidepanelswiththefollowingsteps:
1. Firstly,removethescrewsthatholdtheshortpanelinplaceonboththelongsidepanelsandthebackpanelandremovethepanel.
2. Youshouldnowbeabletoslidethemirroredacrylicpanelintotheenclosureeasily.
3. Atthispoint,youmaywishtopoweronthemonitoroncemoretocheckwhetherthedisplaysettingsleakanylightthroughthemirrorpanelwhenthedisplayisblack.Ifso,turnthebrightnessdownslightly.
4. Thefinalstepistoreattachtheshortsidepanelandtheenclosureiscomplete.
Sincethebuttonsonthemonitorarenolongereasilyaccessiblefromoutsidetheenclosure,itisimportanttoensurethatthemonitorwillautomaticallyturnonwhenpowerisappliedtoit.Thiswillbethemethodusedtoenableanddisabletheinformationdisplayonthemirror.
NoteAstheenclosureisalmostfullyenclosed,itisdiscouragedthatyouleavethemonitoronforalongperiodoftimetoavoidexcessivebuildupofheatinsidetheenclosure.Instead,itisrecommendedthatyouonlyapplypowertothemonitorwhentheinformationdisplayisdesired.
Ifdesired,hardwarefittingscanbeusedtomakethemirrorwallmountable.However,fornow,wewilluseoursasadeskmountedmirroronly.Itisrecommendedthatyouplacethemirroragainstawalltoensuregoodstability,asitshighcenterofgravitydoesmakeitmoreliabletofalloverevenifverylittleforceisappliedtoit.Ifthisisanissue,thenyoucoulduseitinthelandscapemodebychangingthedisplayrotation.
BuildingthemirrorwithoutanenclosureIfyoudonothaveaccesstothetoolsrequiredtobuildtheplywoodenclosure(orwouldsimplypreferamoremodern-stylemirror)thenyoucanadaptanexistingmonitorintoamirrorrelativelysimplywithoutanytools.Allthatisrequirednowisanadhesive.
Youmaywishtouseatemporaryadhesive,suchasacleartapeorhotglueforthistoensurethatthemonitorcanbereusedifyoudecidetoremovethemirrormaterial.Althoughnothingisstoppingyouusingsomethinglikeacontactadhesive,suchasAraldite,foramorepermanentfitting.
1. Thefirststeptoconstructthedisplayistomeasurethesizeofthemirrormaterialthatwillbeneeded.Theseareessentiallythedimensionsofthescreenthatisexposedontheinsideoftheplasticbezelaroundthesideofthemonitor(refertothefollowingimage).Orderthemirrormaterialtobecutafewmillimeterssmallertoensurethatitwilldefinitelyfitwithintheinsideofthebezel.
2. Onceyouhavethemirrormaterial,youshouldfindthatitsimplydropsintothebezelwitharound1mmsparedoneachside.
3. Next,usingyouradhesiveofchoice,fixthemirrormaterialintothebezelofthemonitor.Itisimportantheretoavoidgettingadhesiveofanytypeonthedisplaysurface,asthiscandamagethemonitor.
ThePienclosureSincethePiisnotpartoftheenclosurewehavebuilt,youmaywishtokeepthePiinanexternalenclosure.Therearemanyoftheseavailableatonlineretailers.OneofmypersonalfavoritesisthePibowrangebyPimoroni(http://shop.pimoroni.com/products/pibow-raspberry-pi-case).
ConfigurationNowthatthewebapplicationhasbeendeployedtothePiandthedisplayenclosureisconstructed,itistimetoconfigurewhatinformationisshownandhowitisshownonthemirror.
Notethatwhenchangingthestylesheet,simplyreloadthepageinChromiumbypressingF5onaconnectedkeyboardtoshowthechange.Changestowidgetconfigurationswillrequireyoutorestartthewebapplicationbyusingthefollowingcommands:
sudosupervisordstopmirror_webapp
sudosupervisordstartmirror_webapp
WidgetsThewidgetsareconfiguredusingseveralconfigurationfilesinthe/home/pi/widget_configs/directory.Eachwidgetthatisdisplayedonthemirrorrequiresitsownconfigurationfile.
Theconfigurationfilesaredividedintoseveralsections:core,ui,position,andwidget,eachcontainingseveralvaluesrelatedtothewidget.Theseoptionsaredescribedasfollows:
core
class:Thenameofthewidgetclassupdate_time:TheintervalatwhichtheUIisrefreshed(inseconds;itdefaultsto1minuteiftheintervalnotprovided)title:Thetitleofthewidget(canbeleftblanktohidethetitle)
ui
width:Thisisthewidthallocatedtothewidget(inpixels)show_borders:Ifaborderistobedrawnaroundthewidget
position
type:Thisisthetypeofpositioning(top,bottom,left,right,andfloating)index:Thisisthenumberthatdenotesthepositionofthewidgetinabar(onlyvalidifthetypeisoneoftop,bottom,left,andright)x:Thisisthedistancebetweentheleft-handsideofthewidgetandtheleftofthemirror(onlyvalidiftypeissettofloating)y:Thisisthedistancebetweenthetopofthewidgetandthetopofthemirror(onlyvalidiftypeissettofloating)
widget:Thiscontainsconfigurationinformationspecifictothewidget
Theeffectsofthepositionconfigurationoptionsareshowninthefollowingdiagram:
IncludedwidgetsHereisalistofthewidgetsthatcomewiththemirrorwebapplicationandalistoftheirconfigurationoptions:
Digitalclock(class:DigitalClock)
timezone:Thetimezoneforwhichthetimeisdisplayed(forexample,US/Eastern)
Analogclock(class:AnalogClock)
timezone:Thetimezoneforwhichthetimeisdisplayed(forexample,US/Eastern)
Textcalendar(class:TextCalendar)
timezone:Thetimezoneforwhichthedateisdisplayed(forexample,US/Eastern)
Currentweather(class:Weather)
location:Thelocationforwhichthecurrentweatherconditionsaredisplayed(forexample,Oxford,UK)
RSSfeed(class:RSSFeed)
feed_url:TheURLfortheRSSfeednum_items:Thisisthenumberoffeeditemstobedisplayed(itdefaultsto10ifitisnotset)
RSSheadlineticker(class:RSSTicker)
feed_url:TheURLforRSSfeednum_items:Numberoffeeditemstofetch(thisdefaultsto10ifitisnotset)text_type:Thisisthetypeoftexttobedisplayed(eithertitleforashortheadlineorsummaryforamoredetaileddescription)ticker_update_time:ThisisthetimeintervalshownbetweennewRSSitems(inseconds)
ExampleconfigurationsHereareacoupleofexampleconfigurationfileswithanexplanationofwhateachvaluedoes;botharetakenfromthedefaultwidgetconfigurationincludedinthecodeforthischapter.
bbc_ticker.conf
TheBBCnewsticketisshownatthebottomofthemirrorusingthedemoconfiguration.ThiswidgetgivesanewheadlinefromtheBBCUKnewsRSSfeedevery10seconds:
[core]
class=RSSTicker#UsingtheRSSTickerwidget
title=BBCUKNews#Giveitatitle
[ui]
show_borders=true#Showtheroundedbordersroundthewidget
width=450#Allowthewidgettobeupto450pixelswide
[position]
mode=bottom#Putthewidgetinthebottombar
index=1#Thisisthesecondwidgetfromthecorner
[widget]
#ThisistheBBCUKnewsRSSfeedURL
feed_url=http://feeds.bbci.co.uk/news/uk/rss.xml
text_type=summary#Justdisplaytheshorttitle
ticker_update_time=10#Giveanewheadlineevery10seconds
clock.conf
Theanalogclockisshownatthetop,intheleft-handcornerofthemirrorusingthedemoconfiguration:
[core]
class=AnalogClock#UsingtheAnalogClockwidget
update_interval=1#Clocksmusthavethissetto1second
[ui]
width=200#AnalogClockmustbesettoawidthof200
show_borders=false#AnalogClocklookbetterwithbordersdisabled
[position]
mode=top#Puttheclockinthetopbar
index=0#Thiswillbethefirstitem
[widget]#Donotneedanyconfigurationhere
StylesTheglobalstyleisconfiguredusingthemirror_webapp/static/style.cssstylesheet.Thiscontainsthestylesthatareusedinallotherwidgetsandistheeasiestwaytomakealterationstofontsizesandlayoutmargins.
TipForanyconfigurationthatshouldonlyaffectasinglewidget,thestyle.cssfileforthatspecificwidgetisabetterplacetomakethechange.
Themainsectionsthatyoumaywishtomakealterationstoareasfollows:
Thisdefinesthedefaultstyleforallthetextdisplayedonthemirror,includingthefont.Ifyouwishtouseanalternativefont,thiswouldbetheplacetomakethechange(bydefault,IamusingtheRobotofontbyChristianRobertson):
h1,h2,h3,h4,h5,h6,p,li{
font-family:'Roboto',sans-serif;;
margin:0;
font-weight:normal;
color:#FFF;
}
Thefollowingsetofstylesdefinethesizeofeachofthedifferentlevelsoftext.Bydefault,theyusetheviewportwidthCSSsize:
h1{font-size:5vw;}
h2{font-size:3.75vw;}
h2,h3,h4,h5,h6{font-size:3.25vw;}
p{font-size:2.5vw;}
p.small{font-size:1.8vw;}
li{font-size:2.5vw;}
Inmirror_webapp/templates/mirror.html,youwillalsonoticethefollowinglineatthetopofthepage.ThisisusedtoloadtheRobotofontfromtheGoogleFontservice(www.google.com/fonts):
<linkhref='http://fonts.googleapis.com/css?family=Roboto:400,100'
rel='stylesheet'type='text/css'>
Oncetheconfigurationiscomplete,rebootthePiandyoushouldbegreetedwithyourcustomizedinformationdisplay.
TroubleshootingThissectiondetailssomeofthecommonissuesyoumayencounterwhilebuildingthisprojectandthestepstobetakentoresolvethem.
Forissuesnotlistedhere,checkeitherthelogfilesinthe/home/pidirectory(anditssubdirectories)ortheChromium(orGoogleChrome)developerconsole.
Thewebapplicationfailswiththe500InternalServerErrorThiscanbecausedbyavarietyofreasons.Moreinformationastothecauseoftheproblemwillbeavailableinthe/home/pi/mirror_webapp/mirror_app.loglogfile.
Someofthecommonissuesthatarelikelytocausethisare:
ThelackofInternetconnectionmaycausefailuretoupdatewidgets,suchasweatherandRSSTickerErrorsinwidgetconfigurationfilescancausefailureoftheserver-sidePythonscriptingErrorsinthewidgetcodeitselfwillalsocausethisissue;althoughthisislesslikely
ThedisplaydoesnotworkTherecanbeissueswiththeusageofcertainHDMItoVGAadapterswiththePi.Editthe/boot/config.txtfileanduncommentthefollowingline:
hdmi_force_hotplug=1
ThisforcesthePitooutputthevideoontheHDMIoutputevenifitfailstodetectadeviceconnectedtoit.
Ifyoustillhaveproblemsafterthis,thenthereislikelyanissuewiththepowersupplyyouareusingtopowerthePi.SinceHDMItoVGAadaptersalsodrawpower,alargerUSBpowersupply(preferablycapableofoutputtingupto2A)isneededtoperformstableoperations.
SummaryInthischapter,welookedathowtorunawebapplicationonthePiusingFlaskandPythontocreateaframeworkthatprovidesaneasywaytoaddnewinformationdisplaystothemirrordisplay.
Wealsohadalookatsomemoreadvancedtechniquestomanufactureanenclosure,whichcanbeappliedtoawiderangeofprojectsyoumaywishtopursueafterthisbook.
Inthenextchapter,wewilllookatyetanotherexampleofhowthePicanbeusedtocontrolelectronicdevicesinrealtime,whenwewillbuildanelectronicxylophonethatplaysmusicfromMIDIfiles.
Chapter10.BottleXylophoneInthischapter,wewillbuildaconfigurableMIDI-controlledxylophone-likeinstrumentmadewithemptyglassbottlesandasetofservos.ThiswillmakeuseofalmostallofthePi’sGPIOheaderstodrivetheservos.
TheservosarecontrolledusingawebapplicationthatallowsyoutouploadaMIDIfile,setatemp,andallowsthePitoplaythefileonthebottlesusingaconfigurationfiletotellitwhichbottleistunedtowhichnote.Thetuningitselfisdonebyvaryingthelevelofwaterineachbottle.
SincethisprojectrequiresalotofGPIOpins,youmaywishtooptforaB+model,whichhasanadditionalnineGPIOpinsonits40-pinconnector.
WhatyouwillneedForthisproject,youwillneedthefollowing:
TheRaspberryPiB+AsmallsectionofaprototypingboardUSBpowersupplyandamicroUSBcableHighcurrent5VpowersupplySeveral1000uFcapacitors(www.maplin.co.uk/p/1000f-35v-85c-radial-electrolytic-capacitor-vh51f)Abreadboard(www.maplin.co.uk/p/ad-100-breadboard-ag08j)Astripof0.1-inchpinheaders0.1-inchmale-to-femalepinjumpersM3nutsandmachinescrewsCableties15xemptyglassbottles15xmicroservosA15xservomountbaseA15xservomount
Ifoundthatthelarger500mlbottlesarebetterforthisasopposedtothe330mlones.Anythinglargerthen500mlwillstillwork;however,theymaynotfitontheservomountbasecorrectly(thisshouldnotstoptheservofromworkingcorrectly).
Tomaketuningeasier,itisrecommendedthatyouusethesamesizebottlesforallthe15notes.
Theamountofcapacitorsyouwillneedisdeterminedbythepoweroutputofthepowersupplyyouareusingandthenumberofservosyouhave;atleastfivecapacitorsarerecommendedforthis.Thepowersupplyshouldberatedforatleast2Atoensurereliableoperation.
AssemblinganotebottleThebottlemountsarecomprisedoftwolasercutsectionsof3mmmaterial.Thiscanbeanyrigidmaterial,suchasMDF,plywood,oracrylic.IwouldrecommendyouuseMDF,asitislesspronetodamageunderforceandcanbesandedeasilyifthejointsaretootight.
Thebasedesignhastwolayers,oneforthesectionthatistobecutandasectionthatshowstheroughplacementofthebottles.Thiscanbeengravedifyouwouldlikeitaspartofthe“notebottle”assembly;however,thisisnotrequired.
Thepartsrequiredtoassembleonenotebottle
Theservoarmsthatactuallyhitthebottleswillbemadeusingashortsectionofmetalbar.Thiscanreallybeanymetalbaraslongasalltheservosusethesametypeinordertomaketuningeasier.Todothis,performthefollowingsteps:
1. Thefirststepistocut15lengthsofthemetalbar.Todothis,useapieceofkitchenrolltotightlygripthebarattheedgeofatableandcutasectionaround10cmlongusingahacksaw.
2. Oncethisisdone,youcanthenattachthebarstotheplasticservoarmsthatcamewitheachservo.Todothis,wewillusethearmwithtwolargeservoarmsoppositeeachother(asshowninthefollowingimage)toattachthemetalbartotheservousingtwocableties.
3. Thenextstepistoattachthesmallservomounttothelargermountbase.Youcanattachthemountoneitherofthesetsofthemountingholes;however,youonlyneedtoattachoneservomountperbase.
4. Ifthejointisslack,thenyoucanuseanM3nutandmachinescrewstotightenthejoint.Whetherthisisneededornotdependsontheresolutionofthelasercutterusedtomachinetheparts.Ifthejointfeelsfairlytightonitsown,thenyoucanskipthisstep.
5. Now,allthatisleftistoattachtheservototheservomount.Thiscanbedoneusingeitherthesmallscrewsthatcamewiththeservoorusinganadhesive,suchashotglueorAraldite.
Oncethisisdone,youshouldhaveanotebottleassemblythatlookssimilartotheoneshowninthefollowingimage:
ElectronicsNowthatthenotebottleassemblyisbuilt,itistimetobuildtheelectronicsthatwillconnecttheservostothePi.Thisstepisrelativelysimple,asallthatyouneedtodoisconnectthePidirectlytothesignalwireoftheservos(usuallyyelloworwhite,sometimesorange)andprovidepowertotheservos.
SincethisprojecthasthescopetousealotofGPIOpins,wewillusethePiB+forthisproject,whichhasanadditionalnineusableGPIOpinsonits40-pinheaderthanontheolderPimodelB’s26pinheader.
Forreference,thecircuitwewillconstructislaidoutsimilartothefollowingdiagram(notethatforsimplicity,onlyoneservoisshownhere):
Thefirststeptocreatetheelectronicpartsofthisprojectistobuildapowerdistributionboardthatcanbeconnectedtoalltheservosinordertoreceivepower.ThisboardisverysimilartotheoneusedfortheservosontheroboticarminChapter8,Remote-operatedRoboticArm.Performthefollowingstepstobuildapowerdistributionboard:
1. Takeasectionoftheprototypingboardand0.1-inchpinheadersandsolderthem,asshowninthefollowingdiagram,suchthattherearetwolongstripsofconnectedpins:
Oncethisiscomplete,youshouldhaveaboardthatlookssimilartothis:
2. Ifyourpowersupplyisratedfor3Aorless,youwillmostlikelyneedtoincludeacapacitorbanktoensurethatthereisaconstantreliablepowersupplyforthemotors.Thiscanbebuiltbysimplyconnectingthecapacitorsalongwithoneofthepowerrailsofabreadboard.Usingtwomale-to-femalejumperwires,connectthistotheservopowerdistributionboard.
NoteWhilebuildingthecapacitorbank,ensurethatallthecapacitorsarewiredinthecorrectway.Therewillbealightstripwithseveralnegative(-)symbolsnexttothelegthatmustbeconnectedtotheground.Thislegisalsoshorterthanthepositiveleg.
Ifthistypeofcapacitorisconnectedintheincorrectwayinthecircuit,thenitcanswell,leak,orexplode.
3. Next,wewillconnecteachoftheservostothepowerdistributionboardsuchthatthesignalpinisoverhangingontheedge.Notethatbecauseofthewidthoftheservoheaders,youarebetteroffifyouconnecttheminsetsoffive,asshowninthefollowingimage:
4. Finally,wecanconnecttheservosignalwirestothePi.Thefollowingdiagram
showsthepinsthatareavailableonboththePimodelB(justthepinsabovetheblueline)andthemodelB+(theentireconnector).Inordertousethedefaultconfigurationsuppliedwiththecode,youmusthaveanotebottleonthesepins:4,17,18,27,22,23,24,10,9,25,11,8,7,and5.ThefollowingdiagramshowstheGPIOpinsavailabletoconnecttheservostoandthecommongroundpin:
Oncethisiscompleteandallthebottlesareinplace,thefinishedsetupshouldlooksomethinglikethis:
Ifyoufindthatyoucannotlayouteachofthenotebottlesinaverysuitablewayduetotheshortcablesontheservos,youcanusesomeextensioncablesthatgivearoundanother30cmofcablelength.Suchcablescanbefoundatwww.amazon.co.uk/Remote-Control-Servo-Extension-Cable/dp/B007SUKUXM.
ThewebapplicationAswiththepreviouschapter,thewebapplicationthatcontrolstheservosisbuiltusingtheFlaskframeworkandservedusingNginxandGunicorn.Hence,thedeploymentprocedurewillbeverysimilarhere:
1. First,wemustensurethattheRaspbianinstallationisuptodateandinstallthepackagesthatweneedtodeployonthewebapplication:
sudoapt-getupdate
sudoapt-getupgrade
sudoapt-getinstallpython-pipgitpython-devgunicornsupervisor
nginxswiglibasound-dev
sudopipinstallRPIO
2. Next,wewillclonethecoderepositoryfortheMIDIparsinglibrarythatwillbeusedtoreadMIDIfilesandtheninstallitusingPythonsetuptools:
gitclonehttps://github.com/vishnubob/python-midi.git
cdpython-midi
sudopythonsetup.pyinstall
cd
3. Next,wewillclonethecoderepositoryfortheFlaskframeworkandinstallitusingPythonsetuptools:
gitclonehttps://github.com/mitsuhiko/flask.git
cdflask
sudopythonsetup.pyinstall
cd
4. Next,wewillcopytheNginxconfigurationfilesfromtheprojectfoldertotheconfigurationdirectories;wewillhaveNginxverifytheconfigurationandapplytheconfigurationbyrestartingtheNginxservice:
sudocpconfig_files/nginx/bottle_xylophone.conf/etc/nginx/sites-
available/bottle_xylophone.conf
sudoln-s/etc/nginx/sites-available/bottle_xylophone.conf
/etc/nginx/sites-enabled/
sudorm/etc/nginx/sites-enabled/default
sudonginx-t
sudoservicenginxrestart
5. Now,wewillcopythesupervisorconfigurationandhavethesupervisorrereaditsconfigurationfiles:
sudocpconfig_files/supervisor/bottle_xylophone_webapp.conf
/etc/supervisor/conf.d/bottle_xylophone_webapp.conf
sudosupervisorctlreread
6. Next,wewillcopythewebapplicationconfiguration,whichwillbereadbyourwebapplication.Itcontainstheconfigurationfortheservooutput:
cpconfig_files/bottle_xylophone.conf~
7. Finally,wewillupdatethesupervisorandstartthewebapplication:
sudosupervisorctlupdate
sudosupervisorctlstartbottle_xylophone_webappp
Nowthatthewebapplicationhasbeendeployed,youshouldbeabletobrowsetotheapplicationusingtheIPaddressofthePifromaPConthesamenetworkasthePi.Whenyoudoso,youshouldseeapagesimilartothefollowing:
ConfigurationChancesarethatthePiandbottleswillneedtobereconfiguredandretunedonapersongbasisduetothelimitednumberofnotesthatcanbeconfiguredatthesametime(ifyouusethePimodelB+,thismaynotbeabigproblem).Tohelpmakethisprocesseasier,thereisascript(midi_note_summary.py)includedwiththischapterthatwilltakeaMIDIfileandgenerateareportofexactlywhatnotesareusedinthefile.ThiswillmakeiteasierforustodeterminewhichnoteshavetobeconfiguredonthePiandaccordingly,thebottlescanbetunedforthem.
Thisscriptshouldbeusedwiththefollowingcommand,whereMIDI_FILEisthefilenameoftheMIDIfile:
pythonmidi_note_summary.pyMIDI_FILE.mid
Itsoutputisshowninthefollowingscreenshot:
NotethatthisscriptwillworkstraightawayonthePiwithoutadditionalconfiguration,asalltherequiredlibrariesareinstalledwhenthewebapplicationisdeployed.However,tousethescriptonadifferentPC,youwillfirsthavetodownloadandinstallthepython-midilibrary(https://github.com/vishnubob/python-midi).
Onceyouhavedeterminedtherangeofnotesthatareneededforaparticularsong,youcanthenmodifythebottle_xylophone.confconfigurationfiletosettheGPIOpinsthatwillbeusedforeachMIDInote.
Thisfilemustfirstcontaintwosettingsthatdeterminetheservotimingoutputvaluesthatcorrespondtotheretractedposition(whichtheservoisinwhenitisnotbeingused)andhitposition(thepositionatwhichtheservoarmwillhitthebottle).Thesesettingswillbeappliedtoalltheconfiguredservosunlessstatedotherwisewithaservo-specificconfiguration:
DEFAULT_HIT=1700
DEFAULT_RETRACT=1500
ThefollowingsectionoftheconfigurationfileshouldnowcontainthemappingbetweentheMIDInoteandGPIOnumber.Thegeneralformatforthisisasfollows:
MIDI_GPIO_[NOTE]=[GPIO]
Here,[NOTE]istheMIDInotenumberand[GPIO]istheGPIOnumber.Anexampleofhownotesshouldbemappedisshownasfollows:
MIDI_GPIO_49=4
MIDI_GPIO_50=17
MIDI_GPIO_51=18
MIDI_GPIO_53=27
Inthecasewhereaparticularservohasdifferenthitandretractpositionsfromtheothers(forexample,becauseofadifferentsizedbottleorservoarm),thiscanbeconfiguredusingthegeneralformat:
MIDI_HIT_[NOTE]=[SERVOOUTPUT]
MIDI_RETRACT_[NOTE]=[SERVOOUTPUT]
Here,[NOTE]istheMIDInotenumberand[SERVOOUTPUT]istheservotimingvaluetotheoutput.Anexampleofthisisshownasfollows:
MIDI_HIT_49=1800
MIDI_RETRACT_49=1550
MIDI_HIT_50=1850
Onceyouhaveconfiguredthewebapplication,itisworthchangingthedefaultloglevelfromDEBUGtoeitherINFOorWARNINGtoreducetheamountofinformationthatissavedtothelogfile.Thiscanbedoneusingthefollowingentryintheconfigurationfile:
LOG_LEVEL=[LOGLEVEL]
Here,[LOGLEVEL]iseitherINFOorWARNING.
Whenyouarefinishedmakingchangestotheconfigurationfile,makesuretoreloadthewebapplicationusingthefollowingtwocommands:
sudosupervisorctlstopbottle_xylophone_webapp
sudosupervisorctlstartbottle_xylophone_webapp
TuningTogetassistancefortuningthebottles,itisbesttouseatonegeneratortogetanideaofthesoundyouareaimingforwhenyoustrikethebottles.Theseareavailableinmanyforms;onegoodwebsitethatdoesthisishttp://plasticity.szynalski.com/tone-generator.htm,whichallowsyoutoselectanynoteandplayasampleofit.Audacity(http://audacity.sourceforge.net/)isanexampleofapieceofdesktopsoftwarethatdoesasimilarthing.Therearealsomanysmartphoneapplicationsthathavesimilarfeatures.
Thefirststeptotuneasetofbottlesistosortthebottlesintogroupsofuniquecombinationsofshapesandsizes.Thecombinationofthesetwopropertieswilldefinethepitchofthesoundabottlewithoutanyliquidmakeswhenitisstruck(thefrequencyofwhichisknownasthebottle’snaturalfrequency,thatis,thefrequencyatwhichitwilloscillatewhennotexposedtoexternaldampening).Wewillthenusethebottleswiththelowestpitchforthelower-pitchedMIDInotesandviceversa.
Onceyouhaveasourceoftheactualnoteyouareaimingfor,yousimplyhavetohiteachnotewithoneoftheservoarms(detachedfromtheservoitself)andchangethelevelofwaterinthebottleuntilthenotesoundssimilartothetargetnote.
TestingNowthatwehavefinishedbuildingthebottlexylophone,itistimetogiveitatestusingaMIDIfile.First,browsetotheIPaddressofthePiandyoushouldbegreetedwithapagesimilartothefollowing:
Towardthebottomofthepage,youwillhavetheoptiontobrowseforaMIDIfile(withthe.midfileextension)andtouploadit.Onceyouhavedoneso,youwillseethefilelistedintheMIDIFilessectionofthepageaswellasaconfirmationmessagethatthefilewassuccessfullyuploaded,asshowninthefollowingscreenshot:
Ifrequired,thetempoatwhichthefilewillbeplayedcanbemodifiedusingthetemposettingatthetopofthepage.ThismustbesetbeforeyouselectafiletobeplayedbychangingthevalueinthefieldandbyclickingonSubmit.Oncethetempohasbeenchanged,youwillseeanotification,asshowninthefollowingscreenshot:
Onceyouarereadytoplayafile,simplyclickonthe[play]linknexttothefilename.Youshouldseeanotification,asshowninthefollowingscreenshot,andtheservosshouldstarttomove.Ifyouhaveanyissueshere,refertotheTroubleshootingsectionlaterinthischapter.
Playbackcanthenbestoppedusingthe[stop]linknearthetopofthepage.
TroubleshootingThissectiondetailssomeofthecommonissuesyoumayencounterwhilebuildingthisprojectandstepsyoucanusetoresolvethem.
NotesaremissedThemostcommoncauseofmissednotesisthedelaybetweenthenoteoneventandnoteoffeventintheMIDIfile.IftheMIDIfileistooshort,itwillnotgivetheservoarmtimetoextendandretract.Thiscanberectifiedusingthemidi_note_expand.pyscriptincludedinthecodeforthischapter.
Thisscriptcanberunusingthefollowingcommand;here,MIDI_FILEisthefilenameoftheMIDIfile,DELAYisthedesiredminimumdelayinmillisecondsbetweennoteonandnoteoffevents,andTEMPOisthetempoyouintendtoplaythefileat(thedelaytimewillvarydependingonthetempoatwhichthefileisplayed):
pythonmidi_note_expand.py-fMIDI_FILE.mid-dDELAY-tTEMPO
Thisscriptwillproduceanoutputsimilartothatshowninthefollowingscreenshot.Bydefault,itsavesthemodifiedfileasMIDI_FILE_modified.mid.Bydefault,thescriptwillonlymodifythedelaybetweenthenotesifitislessthanthevaluesetusingthe-dparameter.Thescriptcanalsobeusedtosetthedelaybetweennoteeventsforallthenotesinthefiletothesamevaluebyaddingthe-sflagtotheendofthecommand.
ServosdonotmovecorrectlyIftheservosseemtobebehavingerratically,thenthereisalmostcertainlyanissueregardingalackofsufficientpowersupplyforalltheservos.Thiscanbeconfirmedbymeasuringthevoltageacross5Vandgroundconnectionsontheservopowerdistributionboard.
SummaryInthischapter,wecontinuedtolookatthepossibilitiestocontrolhardwareusingtheGPIOportsandhadaquicklookattheadditionalfeaturesofthePimodelB+.
Wealsolookedatsomeoftheissuescausedbydrivinglargenumbersofelectronicdevicesthatrequirealargeamountofpowerduringtheiroperations.Wealsolookedathowtheseissuescanbeovercome.
Nowthatyouhavecompletedalltheprojectsinthisbook,itistimeforyoutoembarkonyourownprojectsusingtheRaspberryPiandthevastrangeofdevicesthatcanbeusedwithittocreatesomeimpressiveprojectsthatcaninteractwiththeworldaroundyou.
IndexA
AdafruitURL/UsingthebuttonsandjoystickwithPiPlay
AllThingsPiURL/InstallingLogitechMediaServer
Arduinosettingup,forMaplinsensors/SettingupyourArduinosettingup,forRFnetwork/SettingupArduino
ArduinoIDEURL/SettingupyourArduino
AudacityURL/Tuning
Bbottlexylophone
requisites/Whatyouwillneednotebottle,assembling/Assemblinganotebottleelectronics,configuring/Electronicswebapplication,creating/Thewebapplicationconfiguration/Configurationtuning/Tuningtesting/Testingtroubleshooting/Troubleshooting
Ccalibration,roboticarm
chassismotors/Chassismotorsarm2/Arm2andhandservoshandservos/Arm2andhandservosarm1servos/Thearm1servos
camerasettingup,forroboticarm/Settingupthecamera
CameraSerialInterface(CSI)about/Settingupthecamera
captures,GPS-enabledTimelapseRecorderusing/Usingthecapturestimelapsevideo,creating/Creatingatime-lapsevideoGPSdata,exportingasCSV/ExportingGPSdataasCSV
capturesoftware,GPS-enabledTimelapseRecordersettingup/Settingupthecapturesoftware
Chromiumsettingup/SettingupChromium
closureabout/TheJavaScriptcode
comma-separatedvalue(CSV)fileabout/ExportingGPSdataasCSV
configuration,MagicMirrorwidget/Widgetsstyles/Styles
CoreutilsViewerURL/LinuxandMacOS
DDocumentObjectModel(DOM)
about/TheJavaScriptcodedriveelectronics
configuring,forroboticarm/Driveelectronics
Eelectronics,PortableSpeakerSystem
building/Buildingtheelectronicsamplifiercircuit,connecting/Theamplifiercircuitbattery,using/Runningthespeakersystemonbatterypower
enclosureconstruction,MagicMirrorinstructions/Enclosureconstructionwithoutplywoodenclosure/BuildingthemirrorwithoutanenclosurePienclosure/ThePienclosureURL,forPienclosure/ThePienclosure
extensioncablesreferencelink/Electronics
FFileZilla
URL/TransferringMP3filestothePiFlask
URL/Theweatherstationwebapplication
GGoogleChartsAPI
URL/TheweatherstationwebapplicationGoogleFonts
URL/StylesGPS-enabledTimelapseRecorder
requisites/Whatyouwillneedhardware,settingup/Settingupthehardwarecapturesoftware,settingup/Settingupthecapturesoftwarecaptures,using/Usingthecaptures
GunicornURL/Theweatherstationwebapplication
HHackspaces
about/Whatyouwillneedhardware,GPS-enabledTimelapseRecorder
settingup/Settingupthehardwarecameraboard/Thecameraboardcameramodule,connectingtoRaspberryPi/ConnectingthecameramoduletothePiRaspberryPicamera,settingup/SettinguptheRaspberryPicameraGPSmodule,settingup/TheGPSmodule
homesecuritysystemrequisites/Whatyouwillneedstructure/Thesecuritysystemstructuredesigning/Designingyoursecuritysystemwebapplication,creating/Webapplicationssensors,interfacing/InterfacingsensorsRFnetwork/TheRFnetworktroubleshooting/Troubleshooting
hometheatrePCrequisites/WhatyouwillneedOpenELEC,settingup/SettingupOpenELECLCD,settingup/SettinguptheLCDswitches,settingup/Settinguptheswitchesassembling/Finalassembly
Iinstallation,LogitechMediaServer
about/InstallingLogitechMediaServer
JJavaScriptdevelopment
referencelink/TheJavaScriptcodeJavaScriptObjectNotation(JSON)
about/ThePythoncodeJinjatemplatelanguage
referencelink/TheJinjapagetemplate
LLCD
settingup/SettinguptheLCDLCDconfigurationfiles
referencelink/SettinguptheLCDLCDproc
about/SettinguptheLCDlight-dependentresistor(LDR)
about/UnderstandingthesensorsLinux
SDcard,writing/LinuxandMacOSLinuxdistribution
selecting,forRaspberryPi/ChoosingaLinuxdistributionLinuxshellcommands
cd/CommonLinuxcommandsls/CommonLinuxcommandsmkdir/CommonLinuxcommandscat/CommonLinuxcommandspwd/CommonLinuxcommandschmod/CommonLinuxcommandssudo/CommonLinuxcommandsmv/CommonLinuxcommandscp/CommonLinuxcommandsrm/CommonLinuxcommands
LogitechMediaServersettingup/SettingupLogitechMediaServerrunning/RunningLogitechMediaServeronthePibackupimage,creatingofSDcard/CreatingabackupimageofanSDcardUSBstoragedevice,automounting/AutomountingaUSBstoragedeviceinstalling/InstallingLogitechMediaServerPi,settingupasWi-Fiaccesspoint/SettingupthePiasaWi-Fiaccesspoint
MMacOS
SDcard,writing/LinuxandMacOSMagicMirror
requisites/Whatyouwillneedrequiredtools/Toolsyouwillneedtheory/Theorywebapplication,developing/ThewebapplicationPisetup/ThePisetupenclosure,constructing/Enclosureconstructionconfiguration/Configurationtroubleshooting/Troubleshooting
magneticdoorsensorsusing/Magneticdoorsensors
Maplinsensorsusing/ReverseengineeringtheMaplinsensorsworkingwith/Understandingthesensorswiring/WiringArduino,settingup/SettingupyourArduino
measurementunitsforwindspeed/Usingthewebapplicationfortemperature/Usingthewebapplicationforhumidity/Usingthewebapplicationforpressure/Usingthewebapplicationforlightlevelandrain/Usingthewebapplication
mediafilestypes/UploadingmediafilestothePi
mediaplayerscripting/ScriptingamediaplayerPiFM,callingfromPython/CallingPiFMfromPythonMP3files,searching/SearchingforMP3filesinput,obtainingfromcommandline/Gettinginputfromacommandlinemediafiles,queuing/Queuingthemediafilestobeplayedplayer.pyscript,using/Usingthemediaplayerscript
mediumdensityfiberboard(MDF)about/Buildingtheenclosureforthespeakersystem
milesperhour(MPH)about/Understandingthesensors
MinibianURL/ChoosingaLinuxdistribution
miniretro-stylearcadecabinetrequisites/Requirementsinputelectronics,settingup/Settinguptheinputelectronics
cabinet,building/Buildingthecabinetreferencelink/BuildingthecabinetPiPlay,settingup/SettingupPiPlaybuttons,usingwithPiPlay/UsingthebuttonsandjoystickwithPiPlayjoystick,usingwithPiPlay/UsingthebuttonsandjoystickwithPiPlay
miniretro-stylearcadecabinet,requisiteshardware/Requirementstools/Requirements
mountpointabout/Linux
MP3filestransferring,toRaspberryPi/TransferringMP3filestothePi
Nnetwork
scanning,withNmaputility/NetworkscanningNginx
URL/TheweatherstationwebapplicationNmaputility
URL/Networkscanningused,forscanningnetwork/Networkscanning
OOnlineToneGenerator
URL/TuningOpenELEC
settingup/SettingupOpenELECbooting/ThefirstbootandinitialsetupPi,connectingtowirelessnetwork/ConnectingthePitoawirelessnetworkmediafiles,uploadingtoPi/UploadingmediafilestothePimediafiles,uploadingonWindows/Windowsmediafiles,uploadingonLinux/LinuxPi,shuttingdown/ShuttingdownthePi
outdoorweatherstationrequisites/WhatyouwillneedMaplinsensors,using/ReverseengineeringtheMaplinsensorssensors,settingup/Settinguptheremainingsensorsweatherstationwebapplication,creating/Theweatherstationwebapplicationassembling/Assemblingtheweatherstationusing/Usingthewebapplication
PPiPlay
URL/SettingupPiPlaysettingup/SettingupPiPlaybuttons,using/UsingthebuttonsandjoystickwithPiPlayjoystick,using/UsingthebuttonsandjoystickwithPiPlay
PirateRadiosettingup/SettingupthepirateradioMP3files,transferringtoRaspberryPi/TransferringMP3filestothePi
PIRmotionsensorsusing/ThePIRmotionsensors
Pisetup,forMagicMirrordisplay,rotating/Rotatingthedisplaywebapplication,deploying/DeployingthewebapplicationChromium,settingup/SettingupChromium
PortableSpeakerSystemrequisites/Whatyouwillneedrequiredtools/ToolsyouwillneedLogitechMediaServer,settingup/SettingupLogitechMediaServerRaspberryPi,settingasSqueezeboxclient/SettingupthePiasaSqueezeboxclientelectronics,building/Buildingtheelectronicsenclosure,building/BuildingtheenclosureforthespeakersystemLogitechMediaServer,runningonPi/RunningLogitechMediaServeronthePi
potentialdividerabout/Understandingthesensors
printedcircuitboard(PCB)about/Understandingthesensors
prototypingboardabout/SettinguptheLCD
pull-upresistorabout/Understandingthesensors
PulseWidthModulation(PWM)about/Driveelectronics
push-to-make(PTM)buttonsabout/Whatyouwillneed
PuTTYURL/ConnectingtothePiviaSSH
python-midilibraryURL/Configuration
PythonSMTPlibraryURL/Deployingourapplication
RRaspberryPi
settingup/SettingupthePiLinuxdistribution,selecting/ChoosingaLinuxdistributionURL,fordownloading/ChoosingaLinuxdistribution,WritinganSDcardSDcard,writing/WritinganSDcardbooting/BootingthePiforthefirsttimenetworkscanning,withNmaputility/Networkscanningconnecting,viaSSH/ConnectingtothePiviaSSH,CommonLinuxcommandsinitialsetup/TheinitialsetupMP3files,transferring/TransferringMP3filestothePisettingup,forRFnetwork/SettinguptheRaspberryPi
RaspberryPi,asSqueezeboxclientsettingup/SettingupthePiasaSqueezeboxclientWi-Fi,settingup/SettingupWi-FionthePisqueezelite,runningasdaemon/Runningsqueezeliteasadaemon
remotecontrolfunctionsInput.Up/SettinguptheswitchesInput.Down/SettinguptheswitchesInput.Left/SettinguptheswitchesInput.Right/SettinguptheswitchesInput.Select/SettinguptheswitchesInput.Back/SettinguptheswitchesInput.Home/SettinguptheswitchesPlayer.PlayPause/SettinguptheswitchesPlayer.Stop/SettinguptheswitchesPlayer.GoPrevious/SettinguptheswitchesPlayer.GoNext/Settinguptheswitches
residualcurrentdevice(RCD)about/Buildingtheenclosureforthespeakersystem,Buildingthecabinet,Enclosureconstruction
revolutionsperminute(RPM)about/Understandingthesensors
RF24NetworklibraryURL/TheRFnetwork
RFnetworkusing/TheRFnetworkRaspberryPi,settingup/SettinguptheRaspberryPiArduino,settingup/SettingupArduino
RH(relativehumidity)about/Whatyouwillneed
roboticarmrequisites/Whatyouwillneed
driveelectronics,configuring/Driveelectronicscamera,settingup/Settingupthecamerawebapplication,deploying/Deployingwebapplicationsarm,constructing/Thearmandchassisconstructionchassis,constructing/Thearmandchassisconstructioncalibrating/Calibrationtroubleshooting/Troubleshooting
Sscheduledoperatingsystem
about/UnderstandingthesensorsSDcard
writing/WritinganSDcardwriting,onWindows/Windowswriting,onLinux/LinuxandMacOSwriting,onMacOS/LinuxandMacOSbackupimage,creating/CreatingabackupimageofanSDcard
SecureFileTransferProtocol(SFTP)about/TransferringMP3filestothePi
sensorssettingup/SettinguptheremainingsensorsDHT11/22,settingup/DHT11/22BMP180,settingup/BMP180readings,recording/Takingreadingsfromthesensors
sensors,homesecuritysysteminterfacing/InterfacingsensorsPIRmotionsensors,using/ThePIRmotionsensorsmagneticdoorsensors,using/Magneticdoorsensors
servicesetidentifier(SSID)about/SettingupWi-FionthePi
squeezeliteURL/SettingupthePiasaSqueezeboxclientrunning,asdaemon/Runningsqueezeliteasadaemon
SSHRaspberryPi,connecting/ConnectingtothePiviaSSH,CommonLinuxcommands
SupervisorapplicationURL/DeployingtheapponthePi
switchessettingup,forhometheatrePC/Settinguptheswitches
Ttroubleshooting,bottlexylophone
missednotes/Notesaremissedservosmovement/Servosdonotmovecorrectly
troubleshooting,MagicMirrorissues,withwebapplication/Thewebapplicationfailswiththe500InternalServerErrordisplayissue/Thedisplaydoesnotwork
troubleshooting,roboticarmvideostream/Thevideostreamhasasubstantialdelayservos/Theservosmakealoudhummingnoiserobotcontrol/Controloftherobotislostarmsmovement/Thearmjumpstonewpositions
Uultracabs
about/SettinguptheinputelectronicsURL/Settinguptheinputelectronics
USBstoragedeviceautomounting/AutomountingaUSBstoragedevice
VVideoforLinux2(V4L2)driver
about/Settingupthecamerareferencelink/Settingupthecamera
Wweatherstationwebapplication
creating/Theweatherstationwebapplicationdeploying/DeployingtheapponthePi
webapplication,homesecuritysystemcreating/Webapplicationsdeploying/Deployingourapplicationsensors,configuring/Configuringsensorsandalarmsalarms,configuring/Configuringsensorsandalarms
webapplication,MagicMirrordeveloping/Thewebapplicationwidget,developing/Developinganewwidget
Wi-Fisettingup,onRaspberryPi/SettingupWi-FionthePireferencelink/SettingupWi-FionthePi
widget,MagicMirrorPythoncode/ThePythoncodeJinjapagetemplate/TheJinjapagetemplateJavaScriptcode/TheJavaScriptcodeconfigurationfiles/Widgets,Exampleconfigurationsconfigurationoptions/Includedwidgets
widgetconfiguration,MagicMirrorbbc_ticker.conffile/bbc_ticker.confclock.conffile/clock.conf
Win32DiskImagerURL/Windows
WindowsSDcard,writing/Windows
XXBMCmediacentersoftware
URL/SettingupOpenELEC
Z7-Zip
URL/SettingupOpenELEC