Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi...

453

Transcript of Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi...

Page 1: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 2: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 3: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

RaspberryPiBlueprints

Page 4: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 5: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 6: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 7: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 8: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 9: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 10: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 11: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

RaspberryPiBlueprints

Page 12: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 13: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 14: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 15: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 16: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 17: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

AbouttheAuthorDanNixonlivesinEnglandandisa20-yearoldsoftwareengineeringstudentwhoiscurrentlystudyingatNewcastleUniversityandisinhisthirdyear.Hehaslonghadaninterestinelectronicsandembeddedcomputingprojects.

Previously,Danhasworkedona360-degreecamerasystemfortheRaspberryPiandthisiswherehisinterestintheplatformstarted.

Currently,heisonayear-longworkplacementandisworkingonneutrondataanalysissoftwareattheRutherfordAppletonLaboratoryinOxford,UK.

Iwouldliketothankmymotherandfatherfortheirsupportwhilewritingthisbook.IwouldalsoliketothankthemembersofMakerSpace,Newcastle,forprovidingthefacilitiestoprototypetheprojectsandallowingmetousesomeoftheirprojectsinthisbook.

Page 18: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 19: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 20: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 21: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

www.PacktPub.com

Page 22: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 23: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser

Page 24: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.

Page 25: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 26: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

PrefaceTheRaspberryPiisasmallformfactor,singleboard,ARM-basedcomputer.ItiscapableofrunningonmanydesktopapplicationsthatcanberunonastandardLinuxcomputer.WhilethePiisonlyslightlylargerthanacreditcard,itusesverylittlepower.Assuch,ithasbecomeverypopularamongthehackerandmakercommunity,whichusesthePitointegratemorecomputingpowerintheirprojects.

ThePiisveryeasytosetupandinlessthan20minutes,youcanrunitonamodifiedversionofpopular,Linux-basedoperatingsystems.ItwillfunctionjustlikeyouwouldexpectadesktopPCto.Thankstoitssmallformfactor,manypeoplehaveuseditasanalternativetoatraditionalPCforfastaccesstoapplicationsandtheInternet.SincethePidrawsverylittlepower,itcanbeleftrunning.

WherethePireallyexcelsisthatitbringsmorecomputingpowertohardwareandelectronicsprojects.ThisismadepossiblebyawiderangeofinterfacesonthePithataretypicallynotfoundonconventionalcomputers.

ThishasledtoariseinnewprojectsthataremadeusingthePi,whichotherwisewouldhavebeenconsiderablymoredifficultorexpensivetomake.

Page 27: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 28: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 29: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

WhatyouneedforthisbookThisbookassumesthatyouarefamiliarwiththebasicsoftheRaspberryPiandLinux.MostofthecodeinthisbookisinPythonwithsomeC++.However,thesourcecodeforeachoftheprojectsisavailablealongsidethebookthatcanbeusedstraightonthePi.

Severaloftheprojectswillalsodealwithsomebasicelectronics,andassuch,somebasictoolswillbeneededforthecompletionofsomeprojects.However,notethatatthestartofeachchapter,theproceduretobuildtheelectronicssideoftheprojectisexplainedstepbystep.

Someprojectswillalsorequireaccesstowoodworkingtoolsinordertoconstructcasesandenclosures.Usually,youwillrequirejustthecommon“gardenshed”tools.However,thereisinformationintherelevantchaptersonwhatyoucandoifnothavingthecorrecttoolscausesanissueintherelevantchapters.

Page 30: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 31: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

WhothisbookisforThisbookisaimedatthosearejustgettingstartedwiththeRaspberryPi,alreadyhaveafewsmallprojectsundertheirbelt,andarelookingtogetintotheworldofhardwareandphysicalcomputingprojects.

Page 32: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 33: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 34: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 35: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.

Tosendusgeneralfeedback,simplye-mail<[email protected]>,andmentionthebook’stitleinthesubjectofyourmessage.

Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.

Page 36: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 37: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.

Page 38: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.comforallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.

Page 39: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

DownloadingthecolorimagesofthisbookWealsoprovideyouwithaPDFfilethathascolorimagesofthescreenshots/diagramsusedinthisbook.Thecolorimageswillhelpyoubetterunderstandthechangesintheoutput.Youcandownloadthisfilefromhttps://www.packtpub.com/sites/default/files/downloads/2901OS_ColoredImages.pdf.

Page 40: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 41: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

PiracyPiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.

Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.

Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.

Page 42: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

QuestionsIfyouhaveaproblemwithanyaspectofthisbook,youcancontactusat<[email protected]>,andwewilldoourbesttoaddresstheproblem.

Page 43: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 44: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Chapter1.RaspberryPiPirateRadioInthischapter,wewilltakeaquicklookattheRaspberryPihardwareandsomeofthesoftwarethatwillbeusedbothinthisprojectandthemajorityofothersthroughoutthisbook.

AsthePiwasbasedonhardwarethatwastobeincludedinembeddedorportableelectronics(suchassmartphonesandtablets),ithasafewextrahardwarefeaturesthatarenotfoundonatypicaldesktoporlaptopPC,oneofwhichistheGeneralPurposeInputandOutput(GPIO)header.Thisisasetofpins(26onthemodelAandB,and40onthemodelB+)thatallowsyoutocommunicatewithexternalhardwaresuchasGPSsensors,accelerometers,andmotorsthroughprogramminglanguagessuchasPython,C,andC++.Whenwegetfurtherinthischapter,wewilltakealookatalittletrickthatcanbedonetoturnoneofthesepinsintoanFMradiotransmitter.

Page 45: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

WhatyouwillneedYouwillneedthefollowing:

TheRaspberryPiandpowersupplyAnSDcardwithatleast4GBmemory(16GBisrecommendedasitholdsagoodamountofmusic)AthickwireorFMradioantennaMaletomale0.1inchpinjumperwires

Page 46: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 47: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 48: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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?

Page 49: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

WritinganSDcardWhenyouhavealltherelevanthardware,headovertohttp://www.raspberrypi.org/downloadsanddownloadtheZIParchiveforRaspbianandextractit.

Thenextstepsvarydependingonyouroperatingsystem.

WindowsWindowsdoesnotnativelyincludeatoolusedtowritediskimages,therefore,theWin32DiskImager(http://sourceforge.net/projects/win32diskimager)applicationisusedtowriteimagestoanSDcard.

First,gotothedownloadlinkmentionedintheprecedingparagraph,download,andinstallWin32DiskImager.Aswritingimagestodrivesrequiresadministratorpermissions,youwillneedtorunWin32DiskImagerbyright-clickingonitsentryintheStartmenu,andselectingRunasadministrator:

Page 50: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Next,selectthe.imgfilethatwasextractedfromtheRaspbianZIPfileusingthefoldericonunderImageFileandthedriveletteroftheSDcardfromthedrop-downbox:

Page 51: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 52: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 53: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 54: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 55: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

onlyservicethatisstarted,soitisusuallygivenawayasthedevicethatonlyprovidesSSH.

Page 56: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 57: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 58: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

moreabout:

mancommand

Page 59: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 60: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 61: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 62: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

radiosthatdoautomatictuningalsotendtopreferfrequenciesthatareamultipleof0.1MHz(forexample,99.9,101.3,andsoon).

Onceyouhavechosenyourfrequency,tuneyourradiointoit,andrunthefollowingcommandonthePi,wherefreqisthefrequencyyouwishtobroadcaston:

sudo./pifmleft_right.wavfreq22050stereo

Youshouldnowhearasampleautoclipdemonstratingtheabilitytobroadcaststereoaudio.

Page 63: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 64: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

outputofffmpegtoPiFM:

ffmpeg-ifile.mp3-fs16le-ar22.05k-ac2-|sudo./pifm-freq22050

stereo

Here,fileistheMP3filetobebroadcastedandfreqisthefrequencytobroadcastiton.Sincewearetellingffmpegtoprovideoutputfortwoaudiochannels(-ac2)andgivingthestereooptiontoPiFM,thisshouldgiveastereoaudiobroadcast.

Page 65: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 66: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ScriptingamediaplayerNowthattheFMtransmitterisworking,wecanmakeitdosomethingalittlemoreuseful;inthiscase,wewilluseittobroadcastapersonalizedradiostationwithacollectionofyourownmusic.

Todothis,wewillwriteaPythonscriptthatmanagestosearchforMP3filesandcallsPiFMtobroadcastthem.

Page 67: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 68: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 69: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 70: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 71: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 72: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 73: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SummaryInthischapter,wecoveredthebasicsetupofthePihardwareandRaspbianOS.YoulearnedhowtodiscovertheIPaddressofthePiinordertoallowremoteaccesstoitoverSSH;thisprocesswillbeusedinthemajorityoftheprojectslaterinthisbook.

WealsotookaquicklookattheGPIOexpansionheader,andhowitistypicallyusedtointerfacewithexternalhardware.WealsousedthisasacrudeFMtransmitterthroughwhichwewroteasinglePythonscripttobroadcastmusic.

Inthenextchapter,wewillgointofurtherdetailsregardinghowtosetupvarioussoftwarepackagesinordertorunthemonthePi,aswellasyouwilllearnthevariouswaystoconfigurenetworkingwhenwemakeaportablespeakersystemthatrunstheLogitechMediaServer.

Page 74: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 75: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Chapter2.PortableSpeakerSystemInthischapter,wewillbuildawireless,battery-poweredspeakersystemthatcanbecontrolledusingawebbrowserorsmartphone.

Toprovidethemusicforthespeakersystem,wewillusetheLogitechMediaServersoftware,whichisapieceofsoftwarethatcanbeusedtostreammusic,videos,andphotosfromonecomputeronanetworktomultipleotherdevices.Italsoallowsustocontroltheplaybackfromanycomputerorsmartphoneonthesamenetwork.

Initially,wewillsetupthePitoconnectittoanexistingserver(theonerunningonalaptopforinstance),whichissuitableforusearoundyourhomeorgarden.Later,wewilllookathowtomakethesystemtrulyportablebyremovingtheneedforanexistingserverandnetwork.

ThesystemwillbeselfcontainedwithinastandardflightcasewiththespeakersexposedwhenthelidisopenedasitispossibletorunLogitechMediaServeronthePiitself.Itisnotnecessarythatyouhaveanycontrolsonthesystemitselfotherthanapowerswitch.

ThisprojectisbasedonasimilarprojectmadebyIainYarnallatMakerSpace,Newcastle.

Page 76: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 77: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 78: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ToolsyouwillneedThisisalistoftoolsthatyouwillneedforthischapter;theycanallbepurchasedfromeitheranelectronicscomponentsstoreoratool/hardwarestore:

Drillanddrillbitsrangingfrom3mmto10mmAjigsawAtrysquare(optional)AsolderingironandsolderAmultimeterAsmall,flatscrewdriverAsmallPosidrivescrewdriver

Page 79: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 80: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 81: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Next,selectBrowseonthefolderthathasMusicticked;thiswillopenadirectorytreethatwillallowyoutobrowsethedirectoryyourmusicisstoredin.Onceyoudothis,clickonClose,andunderRescanMediaLibrary,clickonRescan.Thiswilllookintheconfigureddirectoriesformediafilesandaddthemtothelibrary,whichmaytakeafewminutesdependingonthesizeofyourmediacollection;theprogressofthisprocesscanbeviewedintheInformationtab.ClickonApplyinthebottom-rightcornerofthescreentoreturntothelibraryview.

Oncebacktothelibraryview,youmayhavetorefreshthepageinordertodisplayyournewmedia;thiscanbedonebyclickingontheLogitechMediaServertextinthetop-leftcornerofthepage.

SincethisisallLogitechMediaServercanwithoutaplayer,wewillnowsetupthePiasaSqueezeboxclient.

Page 82: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 83: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 84: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 85: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 86: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

OncethePihasbooted,SSHbackintoitandmakesurethatthePihasaWi-Ficonnection,usingthefollowingcommand:

ifconfig

Iftheconfigurationissuccessful,youwillseeoutputsimilartothis,whichshowsanactiveEthernet(on192.168.0.2)andaWi-Fi(on192.168.0.18)connection:

Afterthis,youshouldbeabletoSSHinthePiviaitsWi-FiIPaddressanddisconnecttheEthernetcable.

Page 87: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

;;

*)

Page 88: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

;;

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.

Page 89: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 90: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 91: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

TheamplifiercircuitFirstly,wewillwirethetwomonoamplifiermodulestoastripofterminalblockstomakeastereoamplifiermodule.Thisisdonebyconnectingthecommonconnectionsfromeachamplifiertogetherandkeepingthesignalandoutputconnectionsseparate,asshowninthefollowingdiagram:

Next,takethevolumecontrolandsolderthewiresontoitintheconfiguration,asshowninthefollowingdiagram:

Page 92: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Theaudioinputwiresshouldberelativelyshort(around50mm)andconnectedtoastripofthreeterminalblocks;theoutputshouldhaveenoughwiretoreachtheamplifiermodule(around150-200mm).Thisvolumecontrolisessentiallycomprisedoftwopotentialdividerswiththeirwipersfixedtogethersuchthateachpotentialdividerisalwaysatthesameposition.

Now,wecansolderwirestothe3.5mmaudiojack;sincethisisabitsmalleranditwillonlycarrytheunamplifiedaudiosignal,wecanusea32AWGwireforthis:

Page 93: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Theaudioconnectorcannowbeconnectedtotheterminalblockonthevolumecontrol;atthisstage,theorientationoftheleftandrightchannelsisnotimportant.

Then,connecttheoutputfromthevolumecontroltothefirstthreeconnectionsontheamplifierterminalblocks;again,theorientationisnotimportantatthisstage.

Sincethepowergroundconnectionontheamplifierwillhavetobeconnectedtoboththespeakers,thebatteryandtheDC-DCconvertertopowerthePiwillbebesttoextendthespeakersconnectionstotheirownstripofterminalblocks.Thiswillreducethenumberofconnectsthathavetobemadeinthesameconnection.

Thisissimplyacaseofaddingashortlengthofwire(around50-100mm)tothetwospeakeroutputsandpowergroundfromtheamplifierterminalblocksandconnectingthemtoastripofthreeterminalblocks:

Page 94: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Next,weneedtosolderawire(around300mm)tothetwospeakers.Notethatthespeakerwillhavemarkingsthatshowthecorrectpolarityitistobewiredin:

Now,connecteachspeakertothestripofthreeterminalblockscomingfromtheamplifiermodules.Onceagain,thecorrectspeakerorientationisnotimportantatthisstage.

Thisisallwithrespecttothewiringfortheaudiosectionofthespeakersystem.

Page 95: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 96: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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,

Page 97: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 98: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 99: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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).

Page 100: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Oncethisisdone,wecantakeajigsawandcutalongthelinestogetthepanel,whichshouldbeabletosnuglyfitintheopeningoftheflightcase.

Nowthatwehavethebasicpanelfortheenclosure,wewillcutthetwospeakerholes.Sincedifferentspeakersaremountedindifferentways,Iassumethatyouareusingthesamespeakersthatarelistedonthepartslisthere.

Mountingthespeakerswillfirstinvolvecuttingalargeholeintothesheettosetthespeakersinandthendrillingfoursmallerholesthatareusedtoboltthespeakertothepanel.Fortunately,forthespeakers,thelargeholecanbemarkedouteasilybytracingaroundaCD.

Onceyouhavetheoutlineofthespeakerpositionedcorrectly,drilla10mmholeneartheedgeofeachcircle,asshowninthefollowingimage.Thiswillallowustogetinsidethecirclewiththejigsawinordertocutalargeholeinthepanel.

Page 101: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Oncethisisdone,insertthebladeofthejigsawintotheholeandcutaroundtheoutlineofthecircleforeachspeaker.Itisn’tvitalthattheholesarecutneatlyoraccurately,sincethespeakerwillcoverthisedgewheninstalled;however,itisimportantthatthespeakersitsflatwhenitismountedonthecutout.

Next,weneedtodrillthemountingholesthatwillbeusedtoboltthespeakerstotheMDFpanel;inthiscase,wewilldrill4mmholesanduseM3screwsandnutstomountthespeakers.

First,markthepositionsofeachholebyplacingthespeakerintotheholeandmakingamarkontheMDFthroughtheholeinthespeakerfascia(withapencil,forexample).

Next,drilla4mmholeineachmarkedposition.Itwouldbeagoodideatocheckwhethertheholeslineupwiththespeakercorrectlybytrialfittingitwithjustthescrews;however,wewillmountthespeakersproperlylater.

Page 102: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 103: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

AllthatislefttodonowismounttheDC-DCconverterandamplifierstothebackofthepanel,reconnect,andtidyupthewiring.

Sincetheamplifiermoduleshavemountingholes,Iusedthesetothreadsomelargecabletiesthroughandfastenedthemtothetwospeakers.ThisallowsasecuremountingoftheamplifiersthatdoesnotneedadditionalholestobedrilledintheMDFpanel.

TheDC-DCconvertercanbemountedanywhereontheMDFpanelusinganysuitableadhesive.Iwouldrecommendhotglueasitallowsfairlyeasyremovalwithoutriskingdamagetotheconverter,butyoucanalsousedouble-sidedtape.

Thenextstepistoreconnectallthewiringthatiscurrentlydisconnected.Whiledoingso,itisagoodideatotrimanywiresthatareexcessivelylongsothateachwireisjustlongenoughtoreachwhereitshouldconnectto.Thisismainlydonejusttomakethewiringtidier.

Bynow,thebackshouldlookasshowninthefollowingimage:

Page 104: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

AssumingthatyouareusingthesameflightcasethatIused,therearetwodividersincludedthatmakeaperfectspacertokeeptheMDFpanelagooddistancefromthebottomoftheflightcase,thespacersshouldbeplacedaround40mmfromeachsideofthecase.

AllthatislefttodonowisreconnectthePiandbatteryandgivethesystematest.

Page 105: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 106: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

RunningLogitechMediaServeronthePiOurcurrentsolutionisallwellandgoodifyouonlywanttousethesystemaroundthehomeandgarden.However,tomakethesystemtrulyportable,weneedtomovethemediacollection,LogitechMediaServer,andwirelessnetworktothePi.

Page 107: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 108: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 109: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThisshouldshowyouthefilesanddirectoriesattherootofthepartitionontheUSBstoragedevice.

Page 110: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 111: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

sudoreboot

OncethePihasbooted,navigatetoPI_IP:9000(wherePI_IPistheIPaddressofyourPi)toaccesstheLMSwebinterface.Here,youcanfollowthesamestepsdescribedearliertosetupyourmedialibrary.KeepinmindthatthewebinterfaceandmediascanningmayseemslightlyslowerthanonastandardPC.ThisismainlyduetothelowersystemresourcesofthePi.

Page 112: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 113: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 114: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

sudochmod755/usr/sbin/hostapd

Oncethecommandshavefinishedexecuting,rebootthePiandyoushouldbeabletopickuptheWi-Finetwork.

Page 115: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 116: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SummaryInthischapter,wetookalookatsomebasicelectronicsthatweretobeusedtopowerthePiandexternaldevicesandtoamplifytheaudiofromtheaudiooutputonthePi.

Wealsotookthefirststepstodesignandmanufacturecustomenclosuresandfittingsforhardwareprojectsbyadaptinganexistingcasefortheenclosureofthespeakersystem.Inlaterprojectsinthisbook,wewillusetheseskillstomanufactureenclosuresfromscratch.

Inthenextchapter,wewilllookfurtherintodesigningandmanufacturingcustomizedenclosures,aswebuildaminitabletoparcademachine.

Page 117: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 118: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Chapter3.MiniRetroArcadeCabinetInthischapter,wewillbuildaminiretro-stylearcadecabinet,whichrunsaselectionofemulatorsthatcanplaygamesfromawidevarietyofgameconsolesandarcademachines.ThiswillbedoneusinganoperatingsystemcalledPiPlay(formallyknownasPiMAME).

Anarcadecabinetisessentiallyastandardcomputerandmonitorinacustom-builtcabinetusedtomimicthestyleandshapeofretroarcademachines.

Thisprojectwillalsobethefirstthatinvolvesasignificantamountofwoodworkandcarpentryinthemakingofthecabinetforthearcadesystem.Althoughitseemslikeadauntingtaskforanyonewhohasnotundertakenaprojectlikethisinthepast,theconstructionisrelativelysimpleandcanbedonewithcommonhouseholdtools.

Tocontrolthegames,wewilluseaselectionofarcadecontrolsthatarereadilyavailableonline.WewillinterfacethemtothePiusingtheGPIOportandsomesoftwarewrittenbyAdafruit.

ThisprojectisbasedonasimilarprojectbuiltbyTonyDixonatMakerSpace,Newcastle.

Page 119: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

RequirementsForthisproject,youwillneedthehardwareandtools.Hereisthelistofthehardwarerequired:

TheRaspberryPiAUSBkeyboard(forsetuponly)ArcadebuttonsandajoystickAmonitor(andanHDMIadapterifneeded)Asheetof6mmplywood(seetheBuildingthecabinetsectionforthesizerequired)Asheetof12mmplywood(seetheBuildingthecabinetsectionforthesizerequired)Female-to-female0.1inchpinjumpers

Toolsrequiredforthisprojectarelistedasfollows:

AsolderingironandsolderWirecuttersAPozidrivscrewdriverAdrillmachineA30mmForstnerdrillbitSandpaper(80,120,and240grit)Ajigsaw

Page 120: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 121: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 122: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

joystick.

Next,aswiththebuttons,soldera0.1inchjumperwiretoeachswitchcontactandasinglejumperwiretooneofthecommonconnections:

Oncethisisdone,theelectronicspartofthisprojectisprettymuchcomplete.WewillconnectthebuttonsandjoysticktothePilater,oncetheyaremountedonthecabinet.

Page 123: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 124: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

BuildingthecabinetFirstly,itisimportanttohaveagoodideaofthedimensionthatweneedforeachpartofthecabinet.ThefollowingdiagramshowsthedimensionofthecabinetImadewiththeheightandwidthofthemonitor.Whileyouarefreetoadaptthedesigntowhateverstyleyoulike,beawareofthedimensionsthatarelikelytochangethroughoutthedesign.Inthefollowingdiagram,notethatallthesizesareinmm:

Notethattheanglebetweenthemonitorandjoystickpanelisnotfixed,asitwilldependonthesizeofthemonitorandjoystick/buttonpanel.Thedimensionslistedinthediagramareonlyaroughguideandyouareencouragedtodrawasidepaneloutinascaleof1:1tocheckthedimensionsbeforedecidingonthem.

NoteWhenusingpowertools,propersafetyprecautionsshouldbeundertaken.Eyeprotectionshouldalwaysbewornandmains-poweredtoolsshouldbeprotectedusingaresidualcurrentdevice(RCD).

Page 125: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 126: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 127: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 128: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 129: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 130: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 131: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 132: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Notethatintheprecedingimage,Iused12mmplywoodforthefrontpanel.Whileitispossibletodothis,itisnotrequired.Drillingthe30mmholetakesmuchlonger.

Next,wewanttomarkthepositionofthebuttonsandjoystickonthefrontpanel.Thebestwaytodothisistoplacethepanelinpositiontoseewhichpositionwillfeelmostcomfortableorintuitivetoplay.Onceyouhavedonethis,markthepositionofthecenterofeachbuttonandthejoystick,asshowninthefollowingimage:

Nowthatwehavethepositionsofeachparttobemountedonthispanel,wecanstartdrillingtheholesforthem,startingwiththejoystick.

Withthejoystick,Irecommendthatyoudrillone30mmholefortheshaftofthejoystickandfour4mmholesforthemountingscrews.Startbydrillingthe30mmholecenteredonthemarkyoumadeforthecenterofthejoystick.Thisholewillbecutusingthe30mmForstnerbitinthesamewayastheholeforthebuttononthefrontpanel.

Oncethisisdone,insertthejoystickintotheholewiththeswitchsideonthebacksideofthepanel(youwillneedtounscrewtheredballfromthetopofthejoystickfirst)andmarkthepositionofthefourholesinthecornerofthemetalplate.Thisiswherewewilldrilltheholesthatwillbeusedtomountthejoystick.

Page 133: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Aftertheholeshavebeendrilled,thepanelshouldlooksomethinglikewhat’sshowninthefollowingimage:

Wewillmountthejoysticklateron.Now,itistimetodrilltheholesforourarcadebuttons.Thisisdoneinthesamewayaswasdoneforthesingle-playerbuttononthefrontpanel.

Eachofthebuttonscannowbemountedonthepanel.Whilenonessential,mountingthemsothatallofthemicroswitcheslineupparalleltoeachothermakescablemanagementeasier,asshownintheupcomingimage.

Next,wecanfastenthejoystickinpositionwithfourM3machinescrewsbyusingawasherforboththesidesofthemetalplateonthejoystick.Finally,placetheround,blackdiscthatcamewiththejoystickoverthejoystickshaftandreattachtheredball.

Bythispoint,thebackofthefrontpanelshouldlooksomethinglikewhat’sshowninthefollowingimage:

Page 134: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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/

Page 135: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 136: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 137: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SettingupPiPlayFirst,youshouldheadtothePiPlaywebsite(http://pimame.org),downloadthelatestversionoftheOS,andwritetheimagetoanSDcard.ThisisthesameprocedurethatwefollowedwithRaspbianinthetwopreviousprojects.

OncetheimageiswrittentotheSDcard,connectanetworkcable,USBkeyboard,andmonitortothePiandpoweritup.Afterafewminutes,youshouldseethePiPlaymainscreen,asshowninthefollowingscreenshot:

Thisshowsalistofalltheinstalledemulatorsandacountofhowmanygamesareinstalledforeachoneinthesmallredsquares(obviously,foracleaninstall,therewillnotbeanygamesinstalled).

PiPlayhasawebinterfacethatcanbeusedtouploadgamestothearcadesystem.ThisisaccessedusingtheIPaddressofthePi,asshowninthefollowingscreenshot:

Page 138: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThisinterfacecanalsobeusedtoshutdownandrebootthePiusingtheToolsmenu.Fornow,wewilluseROMUploadertoaddanewgametotheGameboyemulator.Thelistofalltheinstalledemulatorsisshowninthefollowingscreenshot:

Page 139: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

NoteTherearemanywebsiteswhereROMscanbedownloaded.Ifyou’relookingforaparticulargame,thebestoptionistouseasearchenginewithaquerycontainingthenameofthegameandtheplatformyouwanttoemulateiton.

Here,wewillselecttheGameboyemulator.ThisshowsapagewhereyoucandraganddropanyROMfilesfromyourPCthataretobeuploadedtothePi:

Page 140: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Oncetheuploadiscomplete,thenewgamewillbeavailableinthemenuforthatemulator.

Whenanewgamehasbeenaddedforacertainemulator,PiPlaywillaskwhetheryouwanttodownloaditsinformationfromanonlinedatabase,asshowninthefollowingscreenshot.Thiswillautomaticallycorrectthenameofthegameanddownloadacoverimageifitisavailable;itisnotrequiredthatyoudothistoplayagame.

Page 141: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Whenanemulatorisselected,amenusimilartotheoneshowninthefollowingscreenshotisshown,whichlistsallthegamesuploadedtothePiforthecurrentemulator.Tostartone,selectitusingthearrowkeysandpressEnter.ToreturntothemainPiPlaymenu,pressEsc.

Page 142: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 143: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 144: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Oncethisisdone,recompilethecodeusingthefollowingcommand:

make

Thismaytakeacoupleofminutesandwilloutputamessagesimilartothefollowing:

Ifthisisthecase,thenallisgoodandyoucanmoveontothenextstep.IfyougetamessagewiththewordErrorinitanywhere,thenyouwilllikelyhaveerrorsinthesyntax

Page 145: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 146: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThisscriptisrunattheendoftheLinuxbootsequence,soitisagoodplacetoaddcodethatshouldbeexecutedaftertheoperatingsystemhasfinishedbooting.

Finally,rebootthePiandmoveontoconfigurethebuttonswithinPiPlay:

sudoreboot

ThenextstepistowireupthebuttonsandjoysticktotheGPIOport.Thismustbedone,asshowninthefollowingdiagram,toensurethatthebuttonmappingisasexpectedandbasedonthecodechangedinretrogame.c.ItwouldbeworthdoingthiswiringwiththepowertothePiturnedofftoreducethechancesofmistakesandpermanentdamagetothePi.

Page 147: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

NotethatPLR1isthebuttononthefrontpanel,B1-3isthebottomrowofbuttonsfromlefttoright,andT1-3isthetoprowofbuttonsfromlefttoright.

Oncealltheconnectionshavebeenmade,theinsideofthefrontofthecabinetshouldlooksomethinglikewhat’sshowninthefollowingimage.AlsonotethatthewhiteHDMItoVGAconverterallowsyoutouseanoldPCmonitorforthisproject.

Page 148: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Intheprecedingimage,youmaynoticethatIampoweringthePifroma5Vpowersupply,whichisconnecteddirectlytothe5VandgroundpinsontheGPIOport.Thisisnotessential,butifyoufindthatthePibecomesunstableorhasproblemswithUSBdevicesorinmaintaininganetworkconnection,thenthismaybethecasebecausethepowersupplycannotsupplyenoughcurrent.Thiscanhappenespeciallyifyou’reusingaHDMItoVGAconverter,whichrequiresacertainamountofpowertooperate.

Oncethisisdone,repowerthePi.WhenthePibootsbackintoPiPlay,youwillnoticethatthejoystickandbutton1willalreadybeabletomovethecursorandselectemulators.However,youwillneedtoconfigurethekeymappingfortheadditionalbuttonsusedbyeachemulator.

Toconfigurethejoystickandbuttonsforacertainemulator,presstheTabkeyonthekeyboard.Thisshouldbringupamenusimilartotheoneshowninthefollowingimage.UsethearrowkeystoscrolldowntoControllerSetupandpressEnter.

Page 149: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThiswillshowanothermenuthatshowsalltheemulatorsthatPiPlaycancontrolthekeymappingof.Here,itisbesttoselectasingleemulatorandassignitskeymappingindividually,forinstance,selectarcadefromthismenu.

Thiswillthenshowapreviewofthecontrollerasshowninthefollowingimageandyouwillbepromptedtopresscertainbuttonstoconfigurethekeymapping.Certainemulatorsmayhavemorebuttonsthanwhatareavailableonthecabinet.Inthiscase,theywillhavetobemappedtokeysontheUSBkeyboard.(Ihaveonlyfoundthistobethecasewithacoupleofemulators,forexample,thepauseandcreditbuttonsofMAMEemulatorshavetobemappedtokeysonthekeyboard.)

Page 150: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Oncethisisdone,youwillbetakenbacktothemainmenuandcanthenselectanyoftheemulatorsusingthejoystickandarcadebuttons.Notethatthetop-leftarcadebuttonisusedtoselectamenuoptionandthefront,single-playerbuttonisusedtoreturntothePiPlaymainmenu.

Page 151: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 152: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SummaryInthischapter,wehadagoodlookattheprocessofdesigningandbuildingacustomenclosureforaprojectbasedontherequirementsofspecificpartsthataretobeusedintheproject.

WealsomademoreuseoftheGPIOportonthePibyusingitasanadditionalinputdevicetocontrolavarietyofgamesmadeavailableonthePiPlayoperatingsystem.

Inthenextchapter,wewillusetheRaspberryPicameramoduletocreatealocation-awaretime-lapserecorderthatcanbeusedtorecordaseriesofstillimagesoveralongperiodoftime.

Page 153: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 154: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Chapter4.GPS-enabledTime-lapseRecorderOneofthepossibleusesoftheRaspberryPicameramoduleistherecordingoftime-lapsecaptures,whichtakesastillimageatasetintervaloveralongperiodoftime.Thiscanthenbeusedtocreateanacceleratedvideoofalong-termeventthattakesplace(forexample,abuildingbeingconstructed).

Onealterationtothisistohavethecameramountedonamovingvehicle.Usethetimelapsetorecordajourney;withtheadditionofGPSdata,thiscanprovideaninterestingrecordofareasonablylongjourney.

Inthischapter,wewillusetheRaspberryPicameramoduleboardtocreatealocation-awaretime-lapserecorderthatwillstoretheGPSpositionwitheachimageintheEXIFmetadata.

Todothis,wewilluseaGPSmodulethatconnectstothePiovertheserialconnectionontheGPIOportandacustomPythonprogramthatlistensfornewGPSdataduringthetimelapse.

Forthisproject,wewillusetheRaspbiandistribution.InstructionsonhowthisisinstalledcanbefoundinChapter1,RaspberryPiPirateRadio.

Page 155: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

WhatyouwillneedThisisalistofthingsthatyouwillneedtocompletethisproject.Alloftheseareavailableatmostelectroniccomponentsstoresandonlineretailers:

TheRaspberryPiArelativelylargeSDcard(atleast8GBisrecommended)ThePicameraboardAGPSmodule(http://www.adafruit.com/product/746)0.1inchfemaletofemalepinjumperwiresAUSBpowerbank(thisisoptionalandisusedtopowerthePiwhennootherpowerisavailable)

Page 156: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 157: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SettingupthehardwareThefirstthingwewilldoissetupthetwopiecesofhardwareandverifythattheyareworkingcorrectlybeforemovingontothesoftware.

Page 158: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThecameraboardThefirst(andthemostimportant)pieceofhardwareweneedisthecameraboard.Firstly,startbyconnectingthecameraboardtothePi.

ConnectingthecameramoduletothePiThecameraisconnectedtothePiviaa15-pinflat,flexribboncable,whichcanbephysicallyconnectedtotwoconnectorsonthePi.However,theconnectoritshouldbeconnectedtoistheonenearesttotheEthernetjack;theotherconnectorisfordisplay.

1. Toconnectthecablefirst,liftthetopretentionclipontheconnector,asshowninthefollowingimage:

2. Inserttheflat,flexcablewiththesilvercontactsfacingtheHDMIportandtherigid,blueplasticpartoftheribbonconnectorfacingtheEthernetportonthePi:

Page 159: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

3. Finally,pressdownthecableretentioncliptosecurethecableintotheconnector.Ifthisisdonecorrectly,thecableshouldbeperpendiculartotheprintedcircuitboard(PCB)andshouldremainseatedintheconnectorifyoutrytousealittleforcetopullitout:

Page 160: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

4. Next,wewillmoveontosetupthecameradriver,libraries,andsoftwarewithinRaspbian.

SettinguptheRaspberryPicameraFirstly,weneedtoenablesupportforthecameraintheoperatingsystemitselfbyperformingthefollowingsteps:

1. Thisisdonebytheraspi-configutilityfromaterminal(eitherlocallyoroverSSH).Enterthefollowingcommand:

sudoraspi-config

Thiscommandwillopenthefollowingconfigurationpage:

Thiswillloadtheconfigurationutility.ScrolldowntotheEnableCameraoptionusingthearrowkeysandselectitusingEnter.

2. Next,highlightEnableandselectitusingEnter:

Page 161: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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()

Page 162: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 163: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 164: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

5. Afterboththefilesarechanged,powerdownthePiusingthefollowingcommand:

sudoshutdown-hnow

Next,weneedtoconnecttheGPSmoduletothePiGPIOport.OneimportantthingtonotewhenyoudothisisthattheGPSmodulemustbeabletorunon3.3Voratleastbeabletousea3.3Vlogiclevel(suchastheAdafruitmoduleIamusinghere).

NoteAswithanydevicethatconnectstothePiGPIOheader,usinga5VlogicdevicecancauseirreparabledamagetothePi.

Page 165: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Next,connecttheGPSmoduletothePi,asshowninthefollowingdiagram.IfyouareusingtheAdafruitmodule,thenallthepinsarelabeledonthePCBitself.Forothermodules,youmayneedtocheckthedatasheettofindwhichpinstoconnect:

Oncethisiscompleted,thewiringtotheGPSmoduleshouldlooksimilartowhatisshowninthefollowingimage:

Page 166: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 167: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 168: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

applications)and-GtellsgpsdtoacceptconnectionsfromdevicesotherthenthePiitself(thisisnotreallyrequired,butisagooddebuggingtool):

NoteWhenyoustartgpsdwiththe-Goption,youcanthenusecgpstoviewtheGPSdatafromanydevicebyusingthecommandwhere[IP]istheIPaddressofthePi:

cgps[IP]

7. Finally,youwillbeaskedforthelocationofthecontrolsocket.ThedefaultvalueshouldbekeptheresojustselectOk:

8. Aftertheconfigurationisdone,rebootthePiandusethefollowingcommandtotesttheconfiguration:

cgps-s

Thisshouldgiveoutputsimilartowhatisshowninthefollowingscreenshot,ifeverythingworks:

Page 169: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

IfthestatusindicationreadsNOFIX,thenyoumayneedtomovetheGPSmoduleintoanareawithaclearviewoftheskyfortesting.Ifcgpstimesoutandexits,thengpsdhasfailedtocommunicatewithyourGPSmodule.Gobackanddouble-checktheconfigurationandwiring.

Page 170: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 171: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 172: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 173: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 174: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Now,youcanrebootthePiandtestouttherecorder.AgoodindicationthatthecaptureisworkingistheredLEDonthecameraboardthatlightsupconstantly.Thisshowsthatthecamerapreviewisopen,whichshouldalwaysbethecasewiththisapplication.

Alsonotethat,thecapturewillnotbeginuntiltheGPSmodulehasafix.OntheAdafruitmodule,thisisindicatedbyaquickblinkevery15secondsonthefixLED(nofixisindicatedbyasteadyblinkoncepersecond).

OneissueyoumayhavewiththisprojectistheamountofpowerrequiredtopowerthecameraandGPSmoduleontopofthePi.Topowerthiswhileonthemove,IrecommendthatyouuseoneoftheUSBpowerbanksthathavea2Aoutput(suchpowerbanksarereadilyavailableonAmazon).

Page 175: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 176: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

UsingthecapturesNowthatwehaveasetofrecordedtime-lapseframes,whereeachhasaGPSpositionattached,thereareanumberofthingsthatcanbedonewiththisdata.Here,wewillhaveaquicklookatacoupleofinstancesforwhichwecanusethecapturedframes.

Page 177: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 178: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 179: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 180: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 181: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SummaryInthischapter,wehadalookathowtousetheserialinterfaceontheGPIOportinordertointerfacewithsomeexternalhardware.TheknowledgeofhowtodothiswillallowyoutointerfacethePiwithamuchwiderrangeofhardwareinfutureprojects.

WealsotookalookatthecameraboardandhowitcanbeusedfromwithinPython.Thiscameraisaveryversatiledeviceandhasaverywiderangeofusesinportableprojectsandubiquitouscomputing.

Youareencouragedtotakeadeeperlookatthesourcecodeforthetime-lapserecorderapplication.ThiswillgetyouonyourwaytounderstandthestructureofmoderatelycomplexPythonprogramsandthewaytheycanbepackagedanddistributed.

Inthefollowingchapter,wewilltakeamoreintricatelookathowtointerfacewithexternalhardwareaswebuildahometheaterPC.

Page 182: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 183: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Chapter5.HomeTheaterPCInthischapter,wewillcreatealow-powerhometheaterPCcapableofplayingavarietyoflocalmediafilesfromaUSBmemorystickorharddriveaswellasthecontentstoredonyourlocalnetworkandcloudservices,suchasYouTube.

Todothis,wewillusetheOpenELEC(http://openelec.tv)operatingsystem,whichisanoperatingsystemdesignedspecificallyforhometheaterPCsrunningonthePi.

WewillalsocreateacustomenclosureforthemediaPCthatwillhousea20columnby4row(20x4)LCD,whichcanbeusedbyXBMCtodisplayinformationofthecurrentlyplayingmediaorinformationrelatedtothecursorpositionintheonscreenmenu.WewillalsoincludeasetofbuttonsthatcanbeusedtocontrolXBMCwithoutaUSBkeyboardoranyotherremote;boththeseandtheLCDwillbeinterfaceddirectlytotheGPIOportonthePi.

Page 184: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 185: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 186: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 187: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

USBkeyboardconnectedtoit.IwillalsoconnectaUSBWi-Fiadapter,butyoucaneasilyjustuseanEthernetconnectioninsteadofWi-Fi.

Fornow,wecanpowerthePifromaUSBconnection,asweareyettoconnectanyadditionalperipheralstoit.However,lateron,weneedtopowerthePiusingamoresubstantial5VpowersupplytoprovideenoughpowerforthePiandtheLCD.

Page 188: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThefirstbootandinitialsetupWhenyoufirstbootOpenELEC,itwillshowascreensomethingsimilartothefollowingscreenshot.Itmaydisplaythisforsometime,asitiscurrentlyresizingthemediastoragepartitionoftheSDcard.

WhenOpenELECboots,itwillbootstraightintoXBMC.Sincethisisthefirsttimeithasbeenbooted,youwillalsobegreetedwiththeOpenELECfirst-timesetupwizard.ThisoftentakesawhiletobedisplayedafterXBMChasstarted.

Tonavigatethemenus,simplyusethearrowkeystomovethecursorandEntertoselectamenuoption;performthefollowingsteps:

1. First,youareaskedbyOpenELECtoselecttheappropriateregionalsettings.SelectthebuttonthatdefaultstoEnglishtochangethesettingsandselectNexttocontinue.

Page 189: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

2. Next,youareaskedtoenteranewhostnameforthemediacenter.Itisnotrequiredthatyouchangeit.However,ifyouintendtohavemultiplemediacenters,thenitwouldbeessentialasnotwodevicesshouldshareahostname.ThiswillmakeidentificationofthePionthenetworkeasier.

3. Thenextoptionasksyoutoconfigurenetworkinterfaces.AsweareusingWi-Fi,wecannotdoanythinghereyet,aswirelessadaptersaredisabledbydefaultandwiredconnectionsdonotrequireconfiguration.JustselectNexttocontinue.

Page 190: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

4. Next,youwillbeaskedwhatserversyouwanttoenableonthePi.Bydefault,SSHisdisabledandSambaisenabled.Iwouldrecommendyoutoenableboth,asyouwillneedSSHtoconfiguretheLCDandbuttonsandSambatouploadmediatothePi.

5. Afterthisstep,theinitialconfigurationiscomplete.SelectNexttoreturntotheXBMChomescreen.

Page 191: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

6. Fornow,thereisoneadditionalsettingthatweneedtochange.Todothis,navigatetotheSettingsoptionundertheSYSTEMmenuusingthearrowkeysandtheEnterkey.

7. Next,navigatetotheSystemmenuandselectitusingEnter.

Page 192: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

8. Next,navigatetoInputdevicesanddisabletheEnablemouseandtouchscreensupportoption,asneitherofthesedeviceswillbeusedwithXBMCthewaywewillbeusingthem.

9. Onthismenu,settingsareautomaticallysavedwhentheyarechanged,soyoucannowuseEsctogobackuntilyoureturntothemainmenu.

Page 193: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ConnectingthePitoawirelessnetworkIfyouplantouseWi-Fitoconnecttoyournetwork,thenyouwillneedtofirstenableitinordertojoinyourwirelessnetwork.UsingWi-FiasopposedtoEthernetallowsyoutoinstallthemediaPCwithouthavingtoworryaboutrunninganEthernetcabletoit.However,yournetworkperformancewillbelower,soitisonlyrecommendedifitisessential.Toconnecttothewirelessnetwork,performthefollowingsteps:

1. SelecttheOpenELECoptionundertheSYSTEMmenu:

2. Fromhere,navigatetoNetworkandselecttheActiveoptionunderWirelessNetworks.ThiswillenabletheWi-Fiadapterandstartsearchingforwirelessnetworksinrange.

Page 194: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

3. Toconnecttoanetwork,navigatetotheConnectionsmenu.Here,youshouldseealistoftheWi-Finetworksthathavebeenfoundinyourrange.Toconnecttooneofthem,navigatetoit,pressEnter,andselecttheoptionJoin.

4. Youwillthenbeaskedforthepasswordforthenetwork.TypeitinandpressEnter.Oncedone,thiswillreturntotheConnectionsmenu;youshouldnowseethatthenetworkyouselectedhasanIPaddresslistedalongsideit.Thisshowsthatthe

Page 195: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

connectionwassuccessful.

Page 196: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 197: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 198: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

followingcommand:

sudoumount/media/openelec

Page 199: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ShuttingdownthePiToshutdownthePi,youcanusethepowermenuinXBMC,whichcanbefoundinthebottom-leftcornerofthehomescreenintheformofapowersymbol.

ThiswillgiveyoutheoptiontoshutdownandrebootthePiaswellastheabilitytosetashutdowntimer,whichwillshutdownthePiafteragivenamountoftimehaselapsed.

Page 200: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 201: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 202: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Vsupplyisneededherethatisconnectedtothe+5VandGNDconnectionstothefarrightoftheboardwehavejustsoldered.

Thisconnectorshouldbesoldered,asshownintheprecedingphotograph,wheretheredwireis+5Vandthewhitewireisground.Ifindoubtaboutthepinoutoftheconnector,youcanverifyitbytestingthepairsofthepinsusingamultimeter,whenthereisapoweradapterconnected.

ThefollowingtwodiagramsprovidedetailsforthewiringofthehometheaterPC.Notethatallconnectionsshouldbemadedirectlytotheotherpinwiththesamelabel,withtheexceptionofthosethatareusedforbuttons(thatis,allstartingwithB_),inwhichthepush-to-makebuttonshouldbewiredinserieswiththisconnection.

Page 203: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 204: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 205: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThissearchshouldfindtheXBMCLCDprocadd-on.Ifnoresultswerefound,tryrebootingthePi,asIfoundproblemswiththelistofadd-onsnotbeingupdatedifthenetworkconnectionwasjustsetup.

4. SelecttheLCDprocadd-onusingEnterandselecttheInstalloption.Thiswillnowdownloadandinstalltheadd-on.Whentheprocessiscomplete,youwillseeanotificationinthebottomrightofthescreen,andtheentryinthesearchresultswillhaveanEnabledindicatornexttoit.

Page 206: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

5. Whenthisisdone,selecttheadd-onfromthesearchresultsagain,andselecttheConfigureoption.

Thishassomeoptionsthatcontrolhowcertaintextisdisplayed.Someoptionsyoumaywishtochangehereare:

Navigationdisplayduration:Thisisthedurationofhowlongthedisplaywill

Page 207: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 208: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 209: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 210: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 211: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 212: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 213: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 214: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

2. Next,mounteachofthepushbuttonsinthetoppanelusingthewashersandnutsthatcamewiththebuttons,asshowninthefollowingimage:

3. Next,wecanassemblethetop,bottom,back,andsidepanelsthatwillincludethecutoutforthevideoconnector,thatis,ifyouarebuildingthecompositevideoversionoftheenclosure,youwillhavetheoppositesideattachedtowhatisshowninthefollowingimage:

Page 215: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

4. Aroundtheedge,themiddlepanelsconnecttothesidepanels.Here,youwillseeaseriesoffittingssimilartothoseshowninthefollowingimage.TheserequireanM4nuttobeinsertedintotheslotandanM4machinescrewtobeinsertedthroughtheholeinthesidepanel,asshowninthefollowingimage:

Page 216: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Thescrewfitting—beforebeingtightened(left)andafterbeingtightened(right)

NoteItisimportantnottoovertightenthesescrewfittings,astheloadistakenentirelybytheapproximately2mmofMDFthatisincontactwitheachnut.

5. Next,mountthePiintotheenclosureusingtwoM4machinescrewsthroughthebottompanel.Here,itisusefultouseastackofwatcherstospacethePCBapartfromthebottompaneltohelpremovestraininthePCB.Beforedoingthis,itisimportanttoverifythatthewashersyouintendtousearesmallenoughtopreventcausingashortwithanyexposedcomponentsatthebottomofthePi.

ThisisalsoagoodpointtostartrewiringthePi,LCD,andthesmallboardwemadetocontroltheLCDbrightnessandcontrast.

6. Next,wewillrewirethebuttonstothePiasbeforeandattachthetoppanelinthesamewayastheotherthree.

Bythispoint,themediacenterwiringshouldbecomplete.Now,youcanmounttheDCbarreljackthatwillbeusedtopowerthePiexternallytothebackpanelusingthenutandwasherthatwassuppliedwithit.

Page 217: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

7. Atthispoint,youarereadytoattachtheremainingsidepanelandgivethemediacenteratestbeforefasteningtheremainingscrewfixings.

8. IfallseemstobegoodandboththeLCDandbuttonsworkasintended,youcangoaheadandfastentheremainingsidepanelusingthesamescrewfixingsthatwereusedfortheotherside.

Page 218: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Here,itisimportanttokeeptheenclosuretiltedsothatifoneofthenutsfallsoutoftheslot,itwillfalloutsideoftheenclosureratherthaninsideit.

Page 219: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 220: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SummaryInthischapter,welookedatyetmorehardwarethatcanbeusedwiththeGPIOportonthePiandadditionalwaysinwhichitcanbecontrolledbysoftware.

Wealsotookalookatanotherapplication-specificoperatingsystemavailableforthePi,howtheycanbeverydifferenttothegeneralRaspbianOS,andhowtheapproachtosolveaproblem(suchasthebuttonsinthisproject)hastobechangedbasedontheenvironmentinwhichitwillbeimplemented.

Wealsotookaquicklookathowtouselasercuttingtomanufactureprofessionalqualityenclosuresquicklyandeasily.Thisisaveryversatilemanufacturingprocessandcanbeusedtocreatesomeveryimpressiveproducts.Iwouldhighlyrecommendyoutoconsideritinanyprojectsyoumayundertakeinthefuture.

Inthenextchapter,wewilllookathowtointerfacetheRaspberryPiwithavarietyofsensorsusingtheArduinoprototypingplatformtocreateanoutdoorweatherstation.

Page 221: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 222: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Chapter6.OutdoorWeatherStationInthischapter,wewillmakeanoutdoorweatherstationthatisaccessibleovertheInternet,whichwillallowremotemonitoringandrecordingoftheweatherconditions.

Todothis,wewillhavealookatanewskillthatwillallowustotakesomeexistingsensorsandadaptthemforuseinourproject—reverseengineering.Thisisessentiallytheprocessoftakingapartofanexistingproductandderivingthecommunicationmethodbetweenitandtherestoftheproduct,sothatyoucanreplaceeitheraspecificpartorawholeproduct.

WewillalsotakeaquicklookathowtousethePiasawebserverandthemethodusedtodevelopanddeployaPythonwebapplication.

Page 223: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 224: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

NotethatwewillnotusethefullpackofresistorsIprovidedalinkto.However,theyareveryhandytohaveashavingtoorderpartslikeresistorsasandwhentheyareneededslowsdownthistypeofelectronicsproject.

Page 225: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 226: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ReverseengineeringtheMaplinsensorsBeforewestartcreatingourownelectronicstotakereadingsfromthesesensors,weneedtostartwithalittletheoryandtestingtogetagoodunderstandingofhowthesesensorsworkandhowwewillbeabletointeractwiththem.

Page 227: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

UnderstandingthesensorsTostartwith,let’stakealookatthemechanicsandelectronicsusedinthedevicestoknowhowtheofficialdevicewouldhavetakenmeasurementsfromthem(notethatyoudonothavetodisassembleyoursensorshere).

Wewillstartwithprobablythesimplestofallthree—theraingauge.Ifweunclipthetopsection,wewillbeabletonoticeaseesaw-likemechanismthatcarrieswaterfromthespoutofthefunnelinthetopcoveredsectiontoeithertheleft-handsideorright-handsideofthesensor,dependingonthepositionoftheseesaw.

Witheachmovement,theseesawtriggersareedswitch,asmallswitchthatisactivatedusingamagnetinthecenteroftheseesawthatcompletesacircuit,whichcanbemonitoredbythemeasurementdevice.

Page 228: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Whilethismethodisquiteeffectiveatmeasuringwhenthereisrainfall,itcannotaccuratelydeterminehowmuchrainfalltherehasbeen,asthiswillpartiallydependontherateofrainfall.Sincethisrelationshipisnotlinear,itwouldtakemoreeffortthanwhatitisworthtoderive.Simplyrepresentingthenumberoftimestheswitchistriggeredoveragivensampletimewillbesufficientforourweatherstation.

Let’smoveontotheanemometernow.Thisisthedevicethatwillbeusedtodeterminehowfastthewindisblowing.Ifyouremovethethreescrewsatthebottomofthesensor,wecannoticethatithasasimilarreedswitch.Byattachingamultimeterinresistancemode,wecantellthattheswitchpulsesclosedcircuitandthenopencircuittwiceperrevolutionofthesensor.

Page 229: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Giventhatweareabletomeasuretimerelativelyaccurately(uptomillisecondprecision)usingArduino,wecanusethesignalfromthisreedswitchtomeasuretherevolutionsperminute(RPM)travelledbytheanemometer.Then,wecanmultiplythisbythecircumferenceoftheanemometermeasuredfromthecenterofthecupstofindthedistancetravelledbyasinglecupinoneminute.Finally,convertthisresulttoastandardunit(inourweatherstationthiswillbeinmilesperhour(MPH))togetthewindspeed.

Thefinal(andmostinteresting)sensoristhewinddirectionsensor.Thisisessentiallyavanethatpointsinagivendirectionifforceisexertedonthesideofthevanebythewind.Ifweopenthebottomofthissensor,wecanseeaprintedcircuitboard(PCB)thatcontainseightreedswitchesandasocket,whichisusedtoconnecttheanemometer.

Page 230: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

IfyouremovethisPCB,youcanseethatthetwomiddleconnectionsofthesocketareconnecteddirectlytothemiddletwoconnectionsofthecablerunningfromthewinddirectionsensor,leavingjusttheoutertwowiresofthecableforthedirectionsensor.

OnthereversesideofthePCB,youwillalsonoticeeightresistorsmarkedwithagivenuniqueresistanceonthePCB.Here,everyreedswitchhasitsownresistance(asshowninthefollowingcircuitdiagram),andbecauseofthespacingoftheswitches,onlyonecanbeactivatedatonce.Therefore,bymeasuringtheresistanceacrossthecircuit,youcansetthepositionofthedirectionsensoraccurateto45degrees.

Page 231: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 232: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 233: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Next,wewillpreparetheLDR:

1. TakeastripofthreeterminalblocksandconnecttheLDRtothecenterandtheleftmostterminal.

2. Onthesameside,connecta4.7kΩresistortotherightmostterminalandthecenterterminal.

3. Ontheothersideoftheterminalblock,connectamale-to-malepinjumperwiretoeachterminal.

Now,theterminalblockwiththeLDRshouldlooksimilartothefollowingimage:

Page 234: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Nowthatwehavethecircuitsrequiredforoursensorsbuilt,wecanconnectthemtotheArduino,asshowninthefollowingdiagram.ThissamewiringdiagramwillworkforthemajorityofArduinoboards,includingtheUno,Mega,Leonardo,andDuemilanove:

Page 235: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SettingupyourArduinoThefinalsteptobetakenforthesensorstoworkisuploadingthesoftwarethatwillmonitorthesensorsandreportinformationbacktothePiviayourArduino.Todothis,weneedtofirstdownloadandinstallversion1.0.6oftheArduinoIDEfromhttp://arduino.cc/en/main/software.Whenitisinstalled,followtheseinstructionstocompileanduploadthecodetoyourArduinoandperformthefollowingsteps:

1. ConnectyourArduinotoyourcomputerandopentheArduinoIDE.2. SelectFileandOpenandbrowsetotheMaplinWeatherInstrumentDriverfolderin

theprojectfiles.OpentheArduinosketchinsidethatfolder.Whenloaded,itshouldlooksomethinglikethefollowingscreenshot:

Page 236: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

3. SelectthetypeofArduinoonwhichyouwillbeuploadingtheprogrambynavigatingtoTools|Board.

4. SelecttheserialportyourArduinoisattachedtobynavigatingtoTools|SerialPort.5. Now,clickontheuploadbuttoninthetop-leftcorneroftheArduinoIDE.Thisisthe

roundbuttonwithanarrowpointingtotheright.TheArduinoIDEwillthengiveamessagethatitisuploadingthesketchtotheboard,asinthefollowingscreenshot:

Assumingthattheuploadiscompletedsuccessfully,youshouldseethemessageDoneuploadingintheIDE,asshowninthefollowingscreenshot:

Page 237: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Ifyougetanerrorhere,thencheckwhetheryourboardandserialportoptionsarecorrect.Iftheerrorstillpersists,thendisconnectyourArduinoandrestarttheArduinoIDEandtryagain.Thisusuallyfixesanyproblemsthatoccurhere.

Oncetheuploadiscomplete,youcanopentheserialmonitorusingthebuttoninthetop-rightcorneroftheArduinoIDEthathasthemagnifyingglasssymboltocheckwhetherthesensorsareworkingcorrectly.Here,youshouldbeabletomanuallymovethesensorsandseetheoutputprintedtotheserialconsole.

Note

Page 238: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Inregardstowinddirection,thedirectionisrepresentedbyavalueof0to7,where0isnorth.Thevalueincreasesin45degreeincrements,so1isnortheast,2iseast,andsoon.Thisgoesonupto7,whichisnorthwest.

Thefollowingscreenshotdisplaystheoutputprintedintheserialconsole:

Page 239: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 240: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SettinguptheremainingsensorsNowthatwehavetheMaplinsensorsandtheLDRworkingproperly,usingtheArduinoboard,wecanturnourfocustotheremainingsensorsthatwillmeasuretemperature,humidity,andthebarometricpressure.

Forthis,wewilluseDHT11orDHT22tomeasurethetemperatureandhumidityandBMP180tomeasurethebarometricpressure.ThesedevicescanbeinterfaceddirectlytoandpoweredfromtheGPIOportonthePi.

Page 241: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

DHT11/22DHT11andDHT22useaone-wirecommunicationprotocoltosenddatabacktothePi,whichrequiresanadditional10K(brown,black,andorange)resistortobeaddedbetweenthedataand3.3Vpinsonthesensor.TheeasiestwaytodothisisbymountingtheDHTsensor,resistor,andarowofmalepinheadersonasmallsectionofastripboard,asshowninthefollowingdiagram:

Oncethisiscomplete,theboardshouldlooksimilartothefollowingimage:

Page 242: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Thecoppertracksrunverticallyfromthetopoftheprecedingimagetothebottom.Asthisissimplyataskofaddingaresistoracrosstwotracks,thereisnoneedtocreateanybreaksinthecoppertracks.

NowthatwehaveaboardfortheDHT11/22sensor,wecanmakethefollowingconnectionstothePiGPIOportbyusingfemale-to-femalepinjumperwires:

Pin1(theleftmostpinintheprecedingimage)tothePipin6(GND)Pin2shouldnotbeconnectedPin3tothePipin7(GPIO4)Pin4(therightmostpinintheprecedingimage)tothePipin1(3.3V)

Oncethewiringiscomplete,wecannowconfigurethesoftwarefortheDHT11/22sensorwiththefollowingsteps:

Page 243: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 244: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 245: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 246: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 247: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Thisshouldgiveanoutputsimilartothefollowingscreenshotwiththereadingstakenfromthesensor:

Ifyoudidnotgetthisoutput,thenyoumayneedtodouble-checkthewiringbetweenthesensorandPi.IfthatlooksOK,thenitisworthrebootingthePiandtryingagain.

Page 248: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 249: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 250: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 251: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 252: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 253: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 254: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 255: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

updateafterthesubmitintervalhaselapsed.

Page 256: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 257: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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).

Page 258: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Thenextthingwewillneedisawaytoruncablesinsidethebox.Thiscanbedonebyremovingthelipononesideofthebox,sothatwhenthelidisreplaced,thereisagaplargeenoughtorunthewiresthrough.Thelipcanberemovedbyusingapairofwire/sidecutterstocreateagapwideenoughforthecablesfromtheraingauge,winddirectionsensor,andamicroUSBcable,asshowninthefollowingimage:

Page 259: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

NoteBeverycarefulwhilecuttingawaythelipoftheboxlikethis.Usingtoomuchforceortryingtocutawaytoomuchatoncecancausepartsoftheboxtochipawayathighspeed.Eyeprotectiongearshouldbewornwhiledoingthis.

Next,weneedtoassembletheelectronicsandsensorsinthebox.TheonlyrequirementhereisthattheLCDfacesdirectlyupwardsandthattheDHT11/22andBMP180sensorsareclosetothepathofairwhichgoesthroughthecorneroftheboxwheretheholesweredrilled.

Youshoulduseanadhesiveorgluetokeeptheelectronicsfrommoving.Youcanuseanythingfromatemporaryfixing,suchasBlu-Tack,toamorepermanent(butstillremovable)adhesive,suchashotglue.Whicheveryoudecidetouse,itisimportanttokeepadhesivesawayfromsensitiveareasoftheelectronics,suchasthemetallicsensorchipontheBMP180PCBorthesurfacemountcomponentsonthebackofthePi.

Thefollowingimageshowstheassembledelectronicsandsensorsinthebox:

Finally,allthatislefttodoistoreplacetheboxlid,setuptheweatherstationoutside,andapplypower.Wecannowmoveontotesttheweatherstationandlookatsomedatafromit.

Page 260: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Notethatwhileinstallingthewinddirectionsensor,itisimportanttoalightitproperlywiththenorthdirection.Itmustbeinstalledsuchthatwhenthearmisinposition,asshowninthefollowingimage,thevanemustpointtonorthandtheroundpointoppositethevanemustpointtosouth:

Page 261: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 262: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

UsingthewebapplicationWhenyoufirstbrowsetotheIPaddressofthePi,youaregreetedbyapagethatwilllooksimilartothefollowingscreenshot.Thisshowsthecurrentweatherconditionsthathavebeenrecordedoverthelastmeasurementperiod(thatis,theperiodspecifiedbythe--submit-intervalparametertothesensor_manager.pyscript).

ByclickingontheHistorylinkinthetop-rightcornerofthepage,youareabletobrowsethroughalltherecordingsthathavebeentakenbytheweatherstation.

Bydefault,itdisplaysthehistoryforthepreviousweek.Thiscanbechangedbyusingthetwooptionsatthetopofthepage(notethattheseoptionsmayonlyrendercorrectlyinChrome,Opera,orSafariwebbrowsers).

Youcanalsochangewhichrecordedvaluesaretobedisplayedonthegraphbyusingtheselectionofcheckboxesatthetopofthepage.Notethatsomemeasurementsmaynotbesuitedtobedisplayedatthesametimeastheyhavedifferentranges,forexample,rainfallandthelightlevel.

Page 263: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Ifyoueverwanttotakeabackupoftheweatherdata,youcandosobytakingacopyoftheweather.dbfileinthe/home/pi/weather_station_webapp/directory.Ifyouwanttoerasealltherecordeddata,youcansimplyruntheinitializedatabasecommandagain.

Page 264: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Notetheunitsforthemeasurements:

Windspeed:Thisismeasuredinmilesperhour(MPH)Temperature:ThisismeasuredindegreesCelsiusHumidity:ThisismeasuredinpercentageRH(relativehumidity)Pressure:kPa(kilopascal),where1kPa=10mb(millibar)Lightlevelandrain:Arbitraryunits

Page 265: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 266: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SummaryInthischapter,welookedatthestepsneededtodesignanddeployaPython-basedwebapplicationonthePiusingtheFlaskframework.Thisisatechniquewewillbeusinginacoupleofchapterslaterinthebook,wherewewillcreateweb-basedcontrolpanelsandinformationdisplays.

WealsolookedatyetmorewaystointerfacedevicestothePi,bothdirectlyviatheGPIOportandbyusinganintermediatedevice;inourcase,anArduino.Wealsolookedattheadvantagesthiscanbringwithcertaintypesofsensor.

Inthenextchapter,wewillfurtherexploretheuseofsensors,aswecreateahomesecuritysystemthatconnectsseveralsensorsusingawirelessnetwork.

Page 267: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 268: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Chapter7.HomeSecuritySystemInthischapter,wewilllookathowtocreateasimplisticsecuritysystemthatwillbeabletomonitorbasicsecuritysensors,suchasdoorpositionsensorsandpassiveinfrared(PIR)sensors.Thesearecommonforstandardhomesecuritysystemsandsende-mailalertswhencertaincombinationsofsensorsaretriggered.

Page 269: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 270: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 271: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThesecuritysystemstructureThesecuritysystemwillbedividedintofivemainparts:theArduinosensornodes,theRFnetworkthatconnectseachnodetotheRaspberryPi,theMQTTbrokerthatconnectstheRFnetworktothewebapplication,thewebapplicationthatmanagesthesenoreventsandalerts,andthedatabasethatstorestheconfigurationofthesensorsandalarmsandthehistoryofeachsensor.

EachsensornodeiscomprisedofanRFmodulethatallowscommunicationbetweenthenetworkofsensornodesandseveralsecuritysensors,suchasPIRmotiondetectorsandreedswitchdoorsorwindowsensors,andboththestandardsensorsusedonthestandardhomesecuritysystems.Whilethesenodescanbebatterypoweredforbetterreliability,wewillpoweroursbyusingaUSBportandUSBpowersupply.

TheRaspberryPiwillserveasboththehostserverforthewebapplicationanddatabaseandthebasenodeintheRFnetwork.ThiswillusethesameRFmodulesandsoftwarelibrariesastheArduinosensornodes.

Oursecuritysystemwillnotuseabellorsounder,suchasaconventionalsecuritysystem;instead,itwillsende-mailalertstoanaddressconfiguredviathewebinterface.Itwillalsoallowalarmstobeconfiguredmuchmorefreelythanaconventionalsystem,allowingyoutosetseveralalarmsforeachdifferentareainahouse.Itwillalsoallowthealarmstoactindependentofeachother.

Page 272: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

DesigningyoursecuritysystemFortherestofthechapter,wewillassumethatthesecuritysystemhasthreesensornodes;here,allthreehavemagneticdoorsensorsandonlytwooutofthreehavePIRmotionsensors.

Atthisstage,youneedtothinkaboutwhereeachnodewillbelocated,astheRFmodulescanonlytransmitoveracertaindistancebeforethesignaleitherbecomestooweaktoensurereliablecommunicationorislostcompletely.Frommyowntesting,Ihavefoundthatthelinkbetweentwonodescanrarelytravelmorethanonewallorfloor.

Therefore,inordertohavealongerdistancebetweenthebasenodeandsensornode,thesensornodemustcommunicatethroughanodethatactsasarepeater.Thisishandledbythenetworkprotocollibraryusedonthesensor’snodesandthePi.Wewilllookatthisinmoredetaillaterinthischapter,butfornow,provisioningatleastonesensornodeineachroomyouwanttohaveasensorinaswellasanyroombetweennodeswillbesufficient.

Thefollowingdiagramroughlyshowsthestructureofthesystemwewillusefortherestofthechapter:

Ifyouareusingyourownsystemdesign,thenithelpstomakeyourowndiagramsimilartothis.Makesuretonotethesensornodeaddress,location,andMQTTtopicofeachsensortohelpmaketheprogrammingofeachofthesesensornodesandtheadditionofthesensorstothewebapplicationeasier.

Page 273: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 274: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

WebapplicationsThesecuritysystemwillbebasedonawebapplicationthatwillbeusedtorecordandvieweventsfromthesensorsandwillallowaconfigurationofsensorsandalarms.

Forthis,wewillusetheFlaskframeworkforPython,whichwasusedinthepreviouschapter,andtheMQTTprotocoltoestablishcommunicationbetweenthesensorsandwebapplication.Thisprotocolisapublisherandsubscribermodel,whereclientscansubscribetoinformation(topics)theyareinterestedinandreceivenewdataasitismadeavailable(published)byotherclients.

Anoverviewofthestructureofthewebapplicationisshowninthefollowingdiagram.Aswedidinthepreviouschapter,wewillusetheSQLitedatabaseengine:

Page 275: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 276: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 277: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 278: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 279: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ConfiguringsensorsandalarmsNowthatthewebapplicationisdeployedcorrectly,itistimetologintoitandconfigurethesensorsandalarmswewilluseforthesystem:

1. StartbybrowsingtotheIPaddressofyourPiandenterthelogindetailsinthepageyouaretakento.Theselogincredentialsaretheonesthatwereconfiguredintheconfigurationfileintheprevioussection.

2. Onceloggedin,youwillbegreetedwiththeSensorspage.Thisshowsalistofallthesensorsthatarecurrentlyconfiguredonthesecuritysystem.WewillstartbyfirstaddinganewsensorbyclickingontheAddNewSensorlinkatthetopofthepage.

Page 280: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

3. Here,wearegivenoptionsforthenameandidentificationofthesensor,bothinrelationtothepositioninthehouseandtheMQTTtopicthatitmapsto.Wewillsetthissensortobethedoorsensoronthefirstsensornode.Forallthesensorswewilluse,thevalueofTriggeredtextshouldbe1.

4. Oncethisiscomplete,clickonAddandyouwillseeamessagesayingthatthesensorhasbeenadded.Atthebottomofthisscreen,youwillseeasectionthatdisplaysthelastrecordedeventforthissensor.Sinceithasjustbeenadded,noeventshavebeenrecordedyet.

Page 281: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

5. Followthisprocedurefortheremainingsensorsinyoursetup,followingthesystemstructurediagramyoumadeearlierinthischapter.Oncethisiscomplete,youwillhaveafairfewsensorsaddedtothesystem,asdepictedinthefollowingscreenshot:

6. Next,wewillmoveontoaddanalarmforsomeofthesensors.Thiswillcontrolhow

Page 282: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 283: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 284: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 285: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 286: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 287: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

supply.

WithintheArduinocode,aPIRsensorshouldbeaddedwiththevalueofACTIVE_LOWandPULL_UPsetto0.

Page 288: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

MagneticdoorsensorsThissensorcanbeusedtodeterminewhentwoobjects,commonlyadooranditsframe,moveapart.Thisissimplyareedswitchandmagnet,thereforeallthatisrequiredtousethissensoristodetectwhenadigitalinputsignallevelchanges.

Althoughtherearefourwirescomingfromthesensor,onlytwoareneededforourusage.Thesetwohavetheendsofthewirestripped,revealingasectionoftheconductor,andareslightlylongerthantheothertwo.Thetwounnecessarywirescanbecutoffifdesired.

WithintheArduinocode,amagneticdoorsensorshouldbeaddedwiththevalueofACTIVE_LOWsetto0andPULL_UPsetto1.

Page 289: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 290: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

TheRFnetworkTheRFnetworkthatwillbeusedforthesensornodesisprovidedbytheRF24Networklibrary(https://github.com/TMRh20/RF24Network).ThisallowsRNnodestobenetworkedinatreestructureinwhicheachnodecanhaveuptofivechildnodes,sinceeachindividualnodecanlistentouptosixothernodesatonce.

Assuch,theaddressesforthenodesareoctalandfollowthestructure,asshowninthefollowingdiagram,where000isalwaysthebasenode,001isachildofthebasenode,021isachildnodeof001,andsoon:

Thisallowsamessagetobepassedtoanynodeonthenetworkbyfirsttransmittingitupwardsthroughthetreeuntilitreachesthefirstnodethatisacommonpathforboththesendingandreceivingnode.

Page 291: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 292: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 293: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Oncethisiscomplete,rebootthePitorunthebasenodeandwebapplicationonboot.ThiscompletestheconfigurationthatneedstobedoneonthePi.

Page 294: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 295: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Next,usingthefollowingsteps,programeachArduinobyusingthesensornodecodebasedonthesystemstructurediagramgivenearlierinthischapter:

1. ConnecttheArduinotoyourPCandopenanunmodifiedversionoftheSensorNode_Arduino.inocodeintheArduinoIDE.

2. ChangetheTHIS_NODE_ADDRvariabletotheaddressofthenodeyouhaveconnected.Notethathaving0atthestartoftheaddressisrequired,thatis,iftheaddressis23,youmustuse023asthevalue.

3. SettheNUM_SENSORSandsensorsvariablesasdescribedintheInterfacingsensorssection.

Page 296: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

4. Ifyouprogramthenodesinorderoftheirpositionawayfromthebasenode(forexample,002,012,and003),youwillbeabletotesteachnodeasyouprogramit.Thisisassimpleasopeningtheeventspageonthewebapplicationandverifyingthatneweventsshowupforthesensorwhenitischanged.Ifthisdoesnothappen,refertotheTroubleshootingsection.

5. Assumingthatthesensornodeworksasintended,youcannowdisconnectthenodefromyourPC.Although,ifyouwishtokeeptestingadditionalnodes,youwillneedtopowerthenodeexternally.

Onceallthesensornodesareprogrammedandtested,theycanbeinstalledintheirintendedpositions.IfoundthatBlu-Tackisagoodtemporaryfixforthenodesthatareto

Page 297: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

beplacedabovethedoors.

ThesensornodewithadoorswitchandPIRsensorinstalledaboveadoorframeusingBlu-Tack

Page 298: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 299: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

TroubleshootingIfyoufindthatasensornodeisnotupdatingthesecuritywebapplicationwhenthesensorsaretriggered,youmayneedtofirstcheckthewiringandconfigurationofthesensornode.Dothistocheckwhetherthesensornodehasavalidaddressandthatitistryingtoconnecttoaparentnodethatexistsonyournetwork(refertothestartofTheRFnetworksection).

Ifthisdoesnotseemtobetheissue,thenyoumaysimplybeoutofrangeofthesensorsorhaveasignalintegrityissuecausedbyotherdevicesusingthesamefrequencyrange.Ifyoususpectthistobethecase,youcantrychangingthevalueoftheCHANNELvariablesintheBaseNode_rPi.pyandSensorNode_Arduino.inocodefiles.ThisvaluesetsthefrequencythattheRFmoduleoperateson.Thefrequencycanbederivedbyf=2400+CHANNELMHz.

Hence,thedefaultvalueof90givesafrequencyof2.49GHz.TheRFmodulecanoperateanywherebetween2.4GHzand2.525GHz.

Page 300: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 301: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SummaryInthischapter,wegainedmoreexperiencewithexpandingthePi’shardwarecapabilitybyaddingadditionalmeansofcommunicationtoitandaddinghardwareusinganewprotocol,thatis,SPI.

ArduinoalsoplayedalargepartinthischapterandhashelpedtoprovideanexampleofawiderangeofhardwarethatcouldpossiblybeusedwiththePi.Evenifasensor,motor,orotherdevicecannotbecontrolleddirectlyfromthePi,itisalmostguaranteedthatthereisanadditionalpieceofhardwarethatcansitbetweenthePiandthedeviceandallowcontrolofthedevicefromthePi.

Wealsohadamorein-depthlookatthetypeofwebapplicationsthatcanbecreatedusingPythonandFlaskandintroducedquiteafewnewfeaturesintothesecuritywebapplicationovertheapplicationmadeinthepreviouschapter.

WewillcontinuetoexplorethewaywebapplicationscanbeusedasaninputmethodforthePiandcontrolphysicalhardwareinthelaterchaptersinthisbookbyusingseveralnewwaysofinterfacingcustomelectronics.

Page 302: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 303: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Chapter8.Remote-operatedRoboticArmInthischapter,wewillusetheRaspberryPitocreateasimpleroboticarmactuatedwithseveralmicroservosmountedonamovablebaseusingtwomotors.AllofthesewillbecontrolledthroughawebinterfaceviathePiGPIOport.

Wewillalsomountthecameramoduleatthefrontofthebaseandstreamittothewebinterface,enablingafullremoteoperation.

Page 304: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 305: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 306: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

DriveelectronicsThefirststepistowireupandconfigurethedriveelectronicsandmotorsthatwillmovethevariouspartsoftherobotarm;thiswillconsistoffourmicroservosthatwillmovethearm,andtwogearedmotorsthatwillprovidedrivetothechassis.

Theservosarepoweredbya5Vpowersupplyandcanbedrivenusingapulseddigitalsignal(throughPulseWidthModulation(PWM))fromthePiGPIOports,whichdefinethepositionthatthearmoftheservoistobekeptin.

Themotorswillbedrivenusingarelayboard,whichallowsthePiGPIOporttoswitchthehighercurrentsneededtopowerthemotor.Thisisjustoneofthemanywaysthiscanbedone.AnotherpossibilityistouseaMOSFETH-bridge,whichwillalsoallowcontrolofthespeedofthemotors.However,therelaysolutionissimplerinbothcodeandelectronicconstruction,soitwillbeusedhere.

Thewiringforthedriveelectronicsisshowninthefollowingdiagram:

ThewiringofthePiGPIOheaderisshowningreaterdetailinthefollowingdiagram:

Page 307: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Wewillstartbyconstructingthepowerboard;thisissimplytwosetsof0.1inchpinheadersonasmallsectionofthestripboardthatwilldistributethe5Vandgroundpowerrails.Wewillneedatleastsevenheadersforboththe5Vandgroundrails;however,addingmoreheaderswillallowpossibleexpansionlater.

Theboardshouldbelaidoutasshowninthefollowingdiagram:

Nowthatwehaveallthepartsneededforthedriveelectronics,wecanstartassemblingthemtotestwiththewebapplication,laterinthechapter:

1. Soldera18AWGwireontoeachterminalofbothmotors,asshowninthefollowing

Page 308: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

image:

2. Takesomemore18AWGwiresandwireuptherelayboard,asshowninthediagramearlierinthechapter.

3. ConnectthemotorsandPP3batterycliptotherelayboard.Bynow,theboardwiringshouldlooksomethinglikewhatisshowninthefollowingimage:

4. Removethesmallorangepinjumperonthethree-pinconnectionontherelayboard;itcanbestoredbyconnectingonesideofittothemiddlepinofthisheader,asshowninthefollowingimage:

Page 309: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

5. Now,takethepowerboardandconnectthefourservostoit,asshowninthefollowingimage,toprovidethemwithpowerandleavethesignalpinaccessiblefromthesideoftheboard:

6. Next,takefourmale-to-femalepinjumpercablesandconnecttheservostotheGPIOheader,asshownintheprecedingdiagram.

Page 310: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

7. TaketheUSBcableandcutthecable10cmawayfromtheUSBAconnector.8. Striptheouterinsulationandshieldingtorevealfourwires.9. Striptheredandblackwires.Thesearethe5Vandgroundpowerconnectionsthat

wewillusetopowertherobotarmfromtheUSBpowerbank.10. Connectthewirestothetwomale-to-femalepinjumpersusingastripoftwo

terminalblocks,asshowninthefollowingimage:

11. Finishoffanyremainingwiringbyfollowingthewiringdiagramshownearlier.

Nowthatthewiringiscomplete,attachtheUSBpowerbanktotheUSBcabletoprovidepowertothePiandservos.Ensurethatyouusethehigheroutputcurrentportonthebank(usuallymarkedaseither2.1Aorusedfortabletcharging)andconnecta9VPP3batterytothebatteryclipattachedtotherelayboard.

Page 311: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 312: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 313: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 314: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 315: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Althoughwewillbeabletoviewastreamstraightaway,wewillgotothesettingspagefirst(showninthefollowingscreenshot)inordertochangethecaptureresolutiontoincreasetheframerateofthevideostream.

Page 316: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Here,wewillchangetheimagewidthandheightoptionsatthetopofthepage.Theoptimalvalueswilldependonthenetworkconnectionbeingused.However,Ihavefoundthat600x400isareasonablestartingpoint,asthisstreamswellonmostconnectionsandgivesanimageofsufficientqualityforwhichwewillusethecamera.

Tosetthis,enterthecorrespondingoptionsintheheightandwidthfieldsatthetopofthepageandclickontheApplybuttontowardstheendofthepageasshowninthefollowingscreenshot.Oncethisisapplied,youwillberedirectedbacktothesettingspage.Togetbacktothemainpage,eitherusethehomelinkatthebottomofthepageornavigatetothepagemanuallybyusingthesameaddressweusedpreviously.

Page 317: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Onceyou’rebackonthemainpage,selectthevideostreamlinktoviewthelivefeedfromthePicamera.Thefollowingscreenshotdisplaysthemainpageonwhichthevideoisstreamed:

Page 318: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Youwillnoticesomedelaybetweenthemovementinthefrontofthecameraanditbeingdisplayedonthewebpage.ThisiscausedbyoverheadsinthestreamingprotocolandthenetworkthePiandcomputerareconnectedto.Unfortunately,thereislittlethatcanbedoneaboutthis,however,Ihaveonlyevermanagedtomeasureatmostthreesecondsofdelay.

Page 319: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 320: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 321: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

sudosupervisorctlupdate

sudosupervisorctlstartrobot_arm_webappp

Nowthatthewebapplicationhasbeendeployed,wecantesttheelectronicsandcamerastreamingthroughthewebapplication.

ThemainpageofthewebapplicationshowsthemovementcontrolsforthechassisandpiArm:

7. First,testthemovementcontrolsandensurethatboththemotorsrotateinthesamedirectionwhenyouselectForwardandintheoppositedirectionwhenyouselectReverse.

8. Next,ensurethatthearmcontrolsmovetheservoscorrectly.ForJoint2andHand,asingleservoshouldmoveandforJoint1,twoservosshouldmoveintheoppositedirection.

Thevideopage(accessedusingtheVideolinkinthetop-rightcornerofthewebapplication)showsthelivevideostreamfromthePicameramodule.Belowthestream,thereisalinktothecamerasettingspageprovidedbythestreamingserver.Notethatthereisnolinkbacktothewebapplicationfromthecamerasettingspage,soyoumustnavigatebacktoitmanuallyafterfollowingthislink.

Page 322: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThereisalsoapagethatshowsboththevideostreamandcontrolsaccessedusingtheControl&Videolinkinthetop-rightcornerofthewebapplication.

Page 323: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 324: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 325: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 326: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

14. Next,thetwolowerarmpanelsmustbeattachedtothetwoservos.ThisisdonebypressingtheshaftintotheholesinthelowerendofthearmpanelsandfasteningtheshaftwithM3washersandthescrewssuppliedwiththeservos.

15. Now,thelowerarmassemblycanbeassembledinthesimilarwaytotheupper-armsectionbyfasteningthetwopanelstogetherusingtwooftheM4threadedbarsectionsandelevenoftheMDFspacers.

16. TheupperandlowerarmsectionscannowbejoinedusingasectionoftheM4threadedbar,asshowninthefollowingimage.Notethatthisshouldbeafairlyloosefasteningtoreducethefrictioninthisjointandthereforereducetheloadontheservo.

Page 327: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

17. Now,wecanattachtheentirearmassemblytothechassisbasebyusinganM3screwoneachoftheservobrackets,asshowninthefollowingimage:

18. Now,wecanconnecttheservomountedinthelower-armsectiontothebaracrosstheupper-armsectionusingapieceofrigidcopperwire.Thisshouldbeattachedtogetthedesiredfieldofmovementontheupper-armsection,whichcanbemeasuredbymanuallymovingtheservoarm.

Page 328: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

19. Thefinalstepoftheassemblyistoattachthecameratothemountingbracket;thecamerashouldfirstbedisconnectedtofeedtheflat,flexcablethroughtheslotatthebottomofthebracket,asshowninthefollowingimage:

20. Next,attachthecameratothebracketbyusingsmallsectionsofBlu-Tack(thisallowsustoadjusttheangleofthecameratotheoptimalangle)andplacethecameraattachmentintotheslotinthechassisbase.

Oncefullyassembled,therobotshouldlooksomethinglikewhatisshowninthefollowingimage:

Page 329: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 330: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

CalibrationNowthatthearmandchassisarebuilt,weneedtocalibratethemotorsandservostoensurethattheyreactinthecorrectwaytothecommandsfromthewebapplication.Inthecaseoftheservos,donotattempttomovethemtoofarasthiswillcausedamagetothemorotherpartsoftheroboticarm.

Page 331: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ChassismotorsFirstly,wewillensurethatthechassismotorsbehavecorrectly.Thisissimplyacaseofrunningthemotorsineachoftheirdirectionstoensurethatthechassismovesinthedirectionintended.

Whenrunninginforwardorreversemotion,ifonemotorisrunninginthewrongdirection,thiscanbecorrectedbyswappingthepolarityofthemotor.Youcanswapthepolaritybyswappingtheconnectionsonthetwowiresleadingtoitfromtherelayboard.

Whenthemotorrunsintheclockwiseorcounterclockwiserotation,ifthebaserotatesinthewrongdirection,thenbothmotorsneedtohavetheirpolarityswapped.

Page 332: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 333: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 334: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 335: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 336: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

TroubleshootingThefollowingareafewissuesyoumaycomeacrosswhilebuildingandusingtheroboticarm,wherethecausesoftheissuesandinformationonhowtheproblemcanbefixed.

Page 337: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThevideostreamhasasubstantialdelayThisdelaycanbecausedifyouattempttostreamattoohighofaresolution.Thefirstthingtodoistotryandreducetheresolutionyouarestreamingat(notethatthishastobedoneeverytimethePiisrebooted).

Iftheissueisstillthere,thenyoumaywanttotryreducingtheJPEGqualityandframerateoptionsonthestreamingserverconfigurationpage(whichisaccessibleviathelinkonthevideostreampageofthewebapplication).

Page 338: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

TheservosmakealoudhummingnoiseTheservoscanoftenmakealoudhummingsoundwhentheyareundersubstantialload.Usually,thisisthecasewhenthearmisfullyextendedorisattemptingtoliftaload.Ifthiscontinues,anextendedlengthoftimewillconsumemorebatterypowerandcouldlowertheexpectedlifetimeoftheservos;however,inthisproject,thisbehaviorisnormaloperation.

Page 339: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ControloftherobotislostIfthecontroloftherobotislost,themostlikelycauseisthelossoftheWi-Fisignal.However,othercausescanincludelowpowerintheUSBbatterybankoradditionalloadontheservosthatcausesthemtodrawmorepowerthanusual(however,thisshouldonlyevercauseanissuewhenthebatterybankisrunninglow).

Page 340: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThearmjumpstonewpositionsThiscanbecausedbytoomanyrequeststomoveanaxisofthearminagivendirectionbeingsentinaperiodoftime.Ifyoufindthatittakestoolongtomovethearm,thenconsiderincreasingthevalueofSERVO_DELTAinthewebapplicationconfigurationfile.

Page 341: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 342: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SummaryInthischapter,wehadalookatyetmorewaystointerfacewithhardwareovertheGPIOportthatincludesusingpulsewidthmodulation,whichcanbeusedtodrivedevicessuchastheservosusedinthischapter.Wealsotookalookathowtoemulateananalogsignal,whichcanthenbeused,forexample,tocontrolthebrightnessofanLED.

WealsotookalookatthewaysinwhichtheRaspberryPicameracanbeaccessedremotelyusingtheV4Lstreamingserver.Intheserver,thesamecontrolandstreamingoptionsthatareavailabletothelocalapplicationsaremadeavailabletothedevicesonthesamenetwork.

Inthenextchapter,wewilllookathowtousethePiforatrueubiquitouscomputingproject,whichwillcombineaninformationdisplayintoafairlystandardmirror.

Page 343: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 344: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Chapter9.MagicMirrorInthischapter,wewillcreateamirrorthatiscapableofbeingbothareflectivesurfaceandaninformationdisplaythatcanbeusedtoshowcustomizedinformation.

Thiswillbedonebytakingadvantageofthepropertiesofatwo-waymirror(commonlyusedforshopsecurity),whichwillallowlighttopassthroughitasifitwasaglasswhentheothersideisdarkerandbehavelikearegularmirrorotherwise.

ThisprojectisbasedontheMagicMirrorprojectbyMichaelTeeuw.Moreinformationabouthisoriginalversioncanbefoundathttp://michaelteeuw.nl/tagged/magicmirror.

Page 345: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

WhatyouwillneedThefollowingisalistofthingsthatyou’dneedforthisproject:

TheRaspberryPiAUSBkeyboard(forsetuponly)AVGAmonitorA6mmplywoodA12mmplywoodAsheetoftwo-waymirroredacrylic(www.cutplasticsheeting.co.uk/mirrored-sheeting/two-way-acrylic-mirror)M4machinescrewsandwashers

Page 346: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 347: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 348: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 349: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 350: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 351: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThewebapplicationThewebapplicationwewilluseforthemirrorisessentiallyaframeworkbuiltusingFlask,whichprovidesacommoninterfaceforindividualwidgetsdisplayedonthemirror.Inordertogetthedesiredeffectwherethewidgetsarevisiblethroughthemirror,thepagemusthaveablackbackgroundwithwhitetextandgraphics.Forbestresults,thetextshouldbeaslargeaspossiblesothatitallowsmaximumlighttopassthroughthemirror’ssurface.

Page 352: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 353: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 354: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 355: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 356: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThePisetupTheinitialstepstosetupthePiaretogetacopyofRaspbianinstalledonanSDcardofatleast4GB(although8GBorlargerispreferable),asdescribedinChapter1,RaspberryPiPirateRadio,andifdesired,connectthePitoyourWi-Finetwork.ThisprojectwillkeepthePioutsidethedisplayenclosuresothatWi-Fiisonlyreallyneededifawiredconnectionisnotavailable.

Page 357: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

RotatingthedisplayYoumaywishtorotatethedisplaytousethemirrorinaportraitorientation,inwhichcasethevideooutputofthePiwillalsoneedtoberotated.Fortunately,thisisdonebyasimplechangetoaconfigurationfile:

1. Openthebootconfigurationfileusing:

sudonano/boot/config.txt

2. AddthefollowinglineandreplaceNwithoneoftheoptionsdescribedinthenextscreenshot:

display_rotate=N

Theconfigurationfilelookssimilartothefollowingscreenshot:

Page 358: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

3. SavethefileandrebootthePitoseethechanges:

sudoreboot

ThepossibleoptionsthatcanbegivenforNare:

0:Normaldisplay1:Rotate90degreesclockwise2:Rotate180degreesclockwise3:Rotate270degreesclockwise

Page 359: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 360: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Oncethishasbeendone,youshouldbeabletobrowsethewebapplicationusingtheIPaddressofthePifromanyPConthesamenetwork.Ondoingso,youshouldbegreetedwithapagesimilartothatshowninthefollowingscreenshot:

Don’tworryifthepagelooksbadlyrendered,asthedefaultwidgetconfigurationisdesignedtobeshownonaportraitmonitorandthefontsizesaresetrelativetothewidthofthescreen.WhendisplayedonthePi,thislooksalotbetter.

Page 361: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SettingupChromiumNowthatwehavethewebapplicationsetup,wecanmoveontoinstalltheChromiumbrowser.WewillusethebrowserinthekioskmodetodisplaythewebapplicationonthePIautomatically,whenitboots.TosetupChromium,performthefollowingsteps:

1. Firstly,wemustconfigurethePitobootstraightintoLXDE(thedefaultwindowmanagerusedonRaspbian)insteadofaconsole.ThiscanbedoneusingthePiconfigurationutility:

sudoraspi-config

2. Next,selecttheEnableBoottoDesktop/ScratchoptionandhitEnter.

3. Now,selecttheDesktopLoginasuser‘pi’atthegraphicaldesktopoptionandhitEnter.

Page 362: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 363: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

9. Finally,rebootthePitotestthesetup:

sudoreboot

Allbeingwell,youshouldseethePibootintoLXDE(indicatedbytheRaspberryPilogoshownonawhitebackground)andshortlyafterthat,Chromiumshouldstartandbrowsetothewebapplication.

Page 364: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 365: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

EnclosureconstructionNowthattheelectronicsandsoftwareinstallationiscomplete,wecanmoveontobuildtheplywoodenclosureforthemirror.Ifyoudonothaveaccesstoarouterandtableforthisproject,thenrefertotheBuildingthemirrorwithoutanenclosuresectiondescribedlaterinthechapterforinstructionsonhowtoconstructthedisplaywithouttheplywoodenclosure.

NoteWhenusingpowertools,propersafetyprecautionsshouldbetaken.Eyeandearprotectionshouldalwaysbewornandmains-poweredtoolsshouldbeprotectedbyusingaresidualcurrentdevice(RCD).

First,weneedtomeasurethemonitortodetermineboththesizeofthemirroredacrylicsheetthatneedstobeorderedandthesizestowhichthepanelsfortheenclosureshouldbecut.

Theupcomingdiagramshowsthepanelsthatmustbecutouttomaketheplywoodenclosure.Eachofthedimensionsaregivenbythefollowingcalculations:

W=monitorwidth+24H=monitorheightWb=W+10Hb=H+10T=monitorthickness+9

NoteNotethatallthesizesareinmm.

Page 366: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Toconstructtheenclosure,performthefollowingsteps:

1. Whiletakingthemeasurementsoftheheightandwidth,itisadvisabletoleavearound2mmoneachsideofthemonitor,whichwillallowustorectifyanyerrorsinthemeasurementwhilemanufacturing.

2. Inordertotakethenextmeasurement,wemustfirstremovethefrontplasticbezelfromthemonitor.Thisisusuallyheldonwithaseriesofsmallplasticclipsaroundtheedgeofthemonitor,asshowninthefollowingimage.Toremovethem,useasmall,flatscrewdrivertoprizeopenthegapbetweenthebackofthemonitorcaseandthefrontbezel.Gradually,workaroundthemonitoruntilalltheclipsarereleased.Thefrontbezelshouldnowliftoffwithease.

3. IfthemonitorhasanybuttonsorLEDsonthefrontpanel,thereislikelyanadditionalPCBthatmustberemovedfromthefrontbezel.Thisusuallyrequiresustounscrewtheboard.

Page 367: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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).

Page 368: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

7. Oncetherouterandtablearesetup,itisagoodideatomakeafewtestcutsonascrappieceofmaterialtoensurethattherouterissetupcorrectly.Aimtogetaslotthatisaround5-6mmdeepintotheplywoodandaround4mmawayfromoneedge,asshowninthefollowingimage:

8. Onceyouarehappythatthesetupiscorrect,youcanmachinetheactualpanelstoendupwithasetofpanels,asshowninthefollowingphotograph.Atthisstage,itisagoodideatosandthepanelswithsomecoarsegritsandpapertoremoveanyraggededgesleftbytherouterorjigsaw.

Page 369: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

9. Thenextstepistoassemblethefoursidepanelsthatformtheoutsideoftheenclosure.Thisisdoneusingtwoscrewsateachendofthelongpanelsthatarescrewedintotheendsofthetwoshortpanels.Forthis,wewillusescrewsthatareatleast1inchinlength,butnomorethan2inch.Performthefollowingsteps:

1. First,wemustdrillclearanceholesintotheendsofthetwolongsidestoallowthescrewshafttopassthrougheasily.Thisholeshouldbejustlargerthantheshaftofthescrew,butsmallerthanthehead.

Page 370: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

2. Next,alignoneofthelongpanelsagainstashortone,asshowninthefollowingfigure,andusetheclearanceholeasguidancetodrillapilotholeintheendoftheshortsidepanel.Thisholeshouldbearound0.5-1mmsmallerthantheshaftofthescrew.

3. Repeatthepreviousstepuntilallthejointshavebeenfastened,ensuringthattheslotforthemirrorrunsallthewayaroundtheinsideedge,asshowninthefollowingphotograph:

Page 371: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 372: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

12. ThenextstepistomarkthepositionoftheVESAmountsonthebackpanelinordertodrilltherequiredholesinthebackpanel.Theeasiestwaytodothisistocarefullyremovethedisplayassemblyfromtherearplastichousing,usingthefollowingstepsasaguide:

1. Thedisplayassemblyisrarelyfixedintotheplastichousingbyanythingotherthanthefactthatitisenclosedby.So,ifwegiveenoughforce,thedisplaypanelandelectronicsenclosurebehindthedisplaypanelwillberemoved.

NoteBecarefulwhenremovingthedisplayassemblyasthedisplaypanelandelectronicsenclosureareusuallynotfixedtoeachotherandexcessstresscoulddamagethecablesrunningbetweenthetwo.

Itisalsonotadvisedthatyouapplypowertoamonitorwiththebackcoverremovedastherearepotentiallydangerousvoltagesintherearelectronicscabinet.

2. Oncethisisdone,youshouldbeabletoplacetherearplasticcaseintotheenclosureandeasilymarkthepositionsofthefourVESAmountingholes.

Page 373: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

3. Atthisstage,itwouldalsobeusefultomarkthepositionoftheholethatwillallowpowerandvideocablestoreachthemonitor.Thisholeshouldbeatleast25mmindiametersothatitaccommodatesanIECpowerconnector.

4. Oncetheholesaremarked,youcannowputthedisplayassemblybackintotherearplasticcase.

13. Oncetheholesinthebackpanelaremarked,thepanelcanberemovedandtheholesdrilledwiththefollowingsteps:

1. ThefourholesfortheVESAmountcanbedrilledusinga4.5mmdrillbit.2. The25mmholewillhavetobedrilledwitheitherafairlypowerfulmainshand

drillor,better,adrillpressusingaForstnerdrillbit.

Page 374: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

14. Oncethebackpanelhastherequiredholesdrilledinit,itisworthgivingitaquicksandoverbyusingacoarsegritsandpaper,justtotidytheedgeleftbytherouterandForstnerdrillbit.

15. Next,reattachthebackpanelontotherestoftheenclosureusingthescrewholesmadepreviously.

16. Atthispoint,itisworthpoweringupthemonitorandensuringthatthedisplayissettofairlyhighcontrastandbrightnesssettingsinordertogetthebestimagequalitythroughthemirroredacrylic.

17. Oncethisisdone,feedthecablesthroughtheholepreviouslymadeforthem.LineuptheVESAmountwiththeholesdrilledforthemandscrewthemonitorintoposition.

Ifyourmonitorhasbuttonsmountedonthefrontpanel,youcansimplyplacethePCBtheyaremountedonbehindthemonitorwithintherangeofthecablethroughwhichtheyareconnectedtothemonitor.

Notethatifthemonitoristoofarbackintheenclosure(thatis,thedisplaysurfaceismorethan1mmawayfromtheslotforthemirror),thenyoumayneedtoaddsomewashersandspacerstothescrewstomovethemonitorslightlyforward,asshowninthefollowingimage:

Page 375: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Bythispointtheenclosureshouldlooksomethinglikethefollowingimage:

18. Thefinalstepistoinsertthemirroredacrylicpanelintotheslotcutforit.Thiscanbeeasilydonebyremovingoneoftheshortsidepanelswiththefollowingsteps:

1. Firstly,removethescrewsthatholdtheshortpanelinplaceonboththelongsidepanelsandthebackpanelandremovethepanel.

Page 376: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

2. Youshouldnowbeabletoslidethemirroredacrylicpanelintotheenclosureeasily.

3. Atthispoint,youmaywishtopoweronthemonitoroncemoretocheckwhetherthedisplaysettingsleakanylightthroughthemirrorpanelwhenthedisplayisblack.Ifso,turnthebrightnessdownslightly.

4. Thefinalstepistoreattachtheshortsidepanelandtheenclosureiscomplete.

Page 377: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Sincethebuttonsonthemonitorarenolongereasilyaccessiblefromoutsidetheenclosure,itisimportanttoensurethatthemonitorwillautomaticallyturnonwhenpowerisappliedtoit.Thiswillbethemethodusedtoenableanddisabletheinformationdisplayonthemirror.

NoteAstheenclosureisalmostfullyenclosed,itisdiscouragedthatyouleavethemonitoronforalongperiodoftimetoavoidexcessivebuildupofheatinsidetheenclosure.Instead,itisrecommendedthatyouonlyapplypowertothemonitorwhentheinformationdisplayisdesired.

Ifdesired,hardwarefittingscanbeusedtomakethemirrorwallmountable.However,fornow,wewilluseoursasadeskmountedmirroronly.Itisrecommendedthatyouplacethemirroragainstawalltoensuregoodstability,asitshighcenterofgravitydoesmakeitmoreliabletofalloverevenifverylittleforceisappliedtoit.Ifthisisanissue,thenyoucoulduseitinthelandscapemodebychangingthedisplayrotation.

Page 378: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

BuildingthemirrorwithoutanenclosureIfyoudonothaveaccesstothetoolsrequiredtobuildtheplywoodenclosure(orwouldsimplypreferamoremodern-stylemirror)thenyoucanadaptanexistingmonitorintoamirrorrelativelysimplywithoutanytools.Allthatisrequirednowisanadhesive.

Youmaywishtouseatemporaryadhesive,suchasacleartapeorhotglueforthistoensurethatthemonitorcanbereusedifyoudecidetoremovethemirrormaterial.Althoughnothingisstoppingyouusingsomethinglikeacontactadhesive,suchasAraldite,foramorepermanentfitting.

1. Thefirststeptoconstructthedisplayistomeasurethesizeofthemirrormaterialthatwillbeneeded.Theseareessentiallythedimensionsofthescreenthatisexposedontheinsideoftheplasticbezelaroundthesideofthemonitor(refertothefollowingimage).Orderthemirrormaterialtobecutafewmillimeterssmallertoensurethatitwilldefinitelyfitwithintheinsideofthebezel.

2. Onceyouhavethemirrormaterial,youshouldfindthatitsimplydropsintothebezelwitharound1mmsparedoneachside.

Page 379: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

3. Next,usingyouradhesiveofchoice,fixthemirrormaterialintothebezelofthemonitor.Itisimportantheretoavoidgettingadhesiveofanytypeonthedisplaysurface,asthiscandamagethemonitor.

Page 380: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThePienclosureSincethePiisnotpartoftheenclosurewehavebuilt,youmaywishtokeepthePiinanexternalenclosure.Therearemanyoftheseavailableatonlineretailers.OneofmypersonalfavoritesisthePibowrangebyPimoroni(http://shop.pimoroni.com/products/pibow-raspberry-pi-case).

Page 381: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 382: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ConfigurationNowthatthewebapplicationhasbeendeployedtothePiandthedisplayenclosureisconstructed,itistimetoconfigurewhatinformationisshownandhowitisshownonthemirror.

Notethatwhenchangingthestylesheet,simplyreloadthepageinChromiumbypressingF5onaconnectedkeyboardtoshowthechange.Changestowidgetconfigurationswillrequireyoutorestartthewebapplicationbyusingthefollowingcommands:

sudosupervisordstopmirror_webapp

sudosupervisordstartmirror_webapp

Page 383: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 384: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

IncludedwidgetsHereisalistofthewidgetsthatcomewiththemirrorwebapplicationandalistoftheirconfigurationoptions:

Digitalclock(class:DigitalClock)

timezone:Thetimezoneforwhichthetimeisdisplayed(forexample,US/Eastern)

Analogclock(class:AnalogClock)

Page 385: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 386: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 387: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 388: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 389: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 390: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

TroubleshootingThissectiondetailssomeofthecommonissuesyoumayencounterwhilebuildingthisprojectandthestepstobetakentoresolvethem.

Forissuesnotlistedhere,checkeitherthelogfilesinthe/home/pidirectory(anditssubdirectories)ortheChromium(orGoogleChrome)developerconsole.

Page 391: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Thewebapplicationfailswiththe500InternalServerErrorThiscanbecausedbyavarietyofreasons.Moreinformationastothecauseoftheproblemwillbeavailableinthe/home/pi/mirror_webapp/mirror_app.loglogfile.

Someofthecommonissuesthatarelikelytocausethisare:

ThelackofInternetconnectionmaycausefailuretoupdatewidgets,suchasweatherandRSSTickerErrorsinwidgetconfigurationfilescancausefailureoftheserver-sidePythonscriptingErrorsinthewidgetcodeitselfwillalsocausethisissue;althoughthisislesslikely

Page 392: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ThedisplaydoesnotworkTherecanbeissueswiththeusageofcertainHDMItoVGAadapterswiththePi.Editthe/boot/config.txtfileanduncommentthefollowingline:

hdmi_force_hotplug=1

ThisforcesthePitooutputthevideoontheHDMIoutputevenifitfailstodetectadeviceconnectedtoit.

Ifyoustillhaveproblemsafterthis,thenthereislikelyanissuewiththepowersupplyyouareusingtopowerthePi.SinceHDMItoVGAadaptersalsodrawpower,alargerUSBpowersupply(preferablycapableofoutputtingupto2A)isneededtoperformstableoperations.

Page 393: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 394: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SummaryInthischapter,welookedathowtorunawebapplicationonthePiusingFlaskandPythontocreateaframeworkthatprovidesaneasywaytoaddnewinformationdisplaystothemirrordisplay.

Wealsohadalookatsomemoreadvancedtechniquestomanufactureanenclosure,whichcanbeappliedtoawiderangeofprojectsyoumaywishtopursueafterthisbook.

Inthenextchapter,wewilllookatyetanotherexampleofhowthePicanbeusedtocontrolelectronicdevicesinrealtime,whenwewillbuildanelectronicxylophonethatplaysmusicfromMIDIfiles.

Page 395: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 396: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Chapter10.BottleXylophoneInthischapter,wewillbuildaconfigurableMIDI-controlledxylophone-likeinstrumentmadewithemptyglassbottlesandasetofservos.ThiswillmakeuseofalmostallofthePi’sGPIOheaderstodrivetheservos.

TheservosarecontrolledusingawebapplicationthatallowsyoutouploadaMIDIfile,setatemp,andallowsthePitoplaythefileonthebottlesusingaconfigurationfiletotellitwhichbottleistunedtowhichnote.Thetuningitselfisdonebyvaryingthelevelofwaterineachbottle.

SincethisprojectrequiresalotofGPIOpins,youmaywishtooptforaB+model,whichhasanadditionalnineGPIOpinsonits40-pinconnector.

Page 397: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 398: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 399: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

AssemblinganotebottleThebottlemountsarecomprisedoftwolasercutsectionsof3mmmaterial.Thiscanbeanyrigidmaterial,suchasMDF,plywood,oracrylic.IwouldrecommendyouuseMDF,asitislesspronetodamageunderforceandcanbesandedeasilyifthejointsaretootight.

Thebasedesignhastwolayers,oneforthesectionthatistobecutandasectionthatshowstheroughplacementofthebottles.Thiscanbeengravedifyouwouldlikeitaspartofthe“notebottle”assembly;however,thisisnotrequired.

Thepartsrequiredtoassembleonenotebottle

Theservoarmsthatactuallyhitthebottleswillbemadeusingashortsectionofmetalbar.Thiscanreallybeanymetalbaraslongasalltheservosusethesametypeinordertomaketuningeasier.Todothis,performthefollowingsteps:

1. Thefirststepistocut15lengthsofthemetalbar.Todothis,useapieceofkitchenrolltotightlygripthebarattheedgeofatableandcutasectionaround10cmlongusingahacksaw.

Page 400: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

2. Oncethisisdone,youcanthenattachthebarstotheplasticservoarmsthatcamewitheachservo.Todothis,wewillusethearmwithtwolargeservoarmsoppositeeachother(asshowninthefollowingimage)toattachthemetalbartotheservousingtwocableties.

3. Thenextstepistoattachthesmallservomounttothelargermountbase.Youcanattachthemountoneitherofthesetsofthemountingholes;however,youonlyneedtoattachoneservomountperbase.

Page 401: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

4. Ifthejointisslack,thenyoucanuseanM3nutandmachinescrewstotightenthejoint.Whetherthisisneededornotdependsontheresolutionofthelasercutterusedtomachinetheparts.Ifthejointfeelsfairlytightonitsown,thenyoucanskipthisstep.

5. Now,allthatisleftistoattachtheservototheservomount.Thiscanbedoneusingeitherthesmallscrewsthatcamewiththeservoorusinganadhesive,suchashotglueorAraldite.

Page 402: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Oncethisisdone,youshouldhaveanotebottleassemblythatlookssimilartotheoneshowninthefollowingimage:

Page 403: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 404: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 405: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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:

Page 406: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Oncethisiscomplete,youshouldhaveaboardthatlookssimilartothis:

2. Ifyourpowersupplyisratedfor3Aorless,youwillmostlikelyneedtoincludeacapacitorbanktoensurethatthereisaconstantreliablepowersupplyforthemotors.Thiscanbebuiltbysimplyconnectingthecapacitorsalongwithoneofthepowerrailsofabreadboard.Usingtwomale-to-femalejumperwires,connectthistotheservopowerdistributionboard.

NoteWhilebuildingthecapacitorbank,ensurethatallthecapacitorsarewiredinthecorrectway.Therewillbealightstripwithseveralnegative(-)symbolsnexttothelegthatmustbeconnectedtotheground.Thislegisalsoshorterthanthepositiveleg.

Ifthistypeofcapacitorisconnectedintheincorrectwayinthecircuit,thenitcanswell,leak,orexplode.

Page 407: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

3. Next,wewillconnecteachoftheservostothepowerdistributionboardsuchthatthesignalpinisoverhangingontheedge.Notethatbecauseofthewidthoftheservoheaders,youarebetteroffifyouconnecttheminsetsoffive,asshowninthefollowingimage:

4. Finally,wecanconnecttheservosignalwirestothePi.Thefollowingdiagram

Page 408: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

showsthepinsthatareavailableonboththePimodelB(justthepinsabovetheblueline)andthemodelB+(theentireconnector).Inordertousethedefaultconfigurationsuppliedwiththecode,youmusthaveanotebottleonthesepins:4,17,18,27,22,23,24,10,9,25,11,8,7,and5.ThefollowingdiagramshowstheGPIOpinsavailabletoconnecttheservostoandthecommongroundpin:

Oncethisiscompleteandallthebottlesareinplace,thefinishedsetupshouldlooksomethinglikethis:

Page 409: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Ifyoufindthatyoucannotlayouteachofthenotebottlesinaverysuitablewayduetotheshortcablesontheservos,youcanusesomeextensioncablesthatgivearoundanother30cmofcablelength.Suchcablescanbefoundatwww.amazon.co.uk/Remote-Control-Servo-Extension-Cable/dp/B007SUKUXM.

Page 410: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 411: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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~

Page 412: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

7. Finally,wewillupdatethesupervisorandstartthewebapplication:

sudosupervisorctlupdate

sudosupervisorctlstartbottle_xylophone_webappp

Nowthatthewebapplicationhasbeendeployed,youshouldbeabletobrowsetotheapplicationusingtheIPaddressofthePifromaPConthesamenetworkasthePi.Whenyoudoso,youshouldseeapagesimilartothefollowing:

Page 413: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 414: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 415: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 416: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 417: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 418: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 419: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

TestingNowthatwehavefinishedbuildingthebottlexylophone,itistimetogiveitatestusingaMIDIfile.First,browsetotheIPaddressofthePiandyoushouldbegreetedwithapagesimilartothefollowing:

Towardthebottomofthepage,youwillhavetheoptiontobrowseforaMIDIfile(withthe.midfileextension)andtouploadit.Onceyouhavedoneso,youwillseethefilelistedintheMIDIFilessectionofthepageaswellasaconfirmationmessagethatthefilewassuccessfullyuploaded,asshowninthefollowingscreenshot:

Page 420: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Ifrequired,thetempoatwhichthefilewillbeplayedcanbemodifiedusingthetemposettingatthetopofthepage.ThismustbesetbeforeyouselectafiletobeplayedbychangingthevalueinthefieldandbyclickingonSubmit.Oncethetempohasbeenchanged,youwillseeanotification,asshowninthefollowingscreenshot:

Page 421: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Onceyouarereadytoplayafile,simplyclickonthe[play]linknexttothefilename.Youshouldseeanotification,asshowninthefollowingscreenshot,andtheservosshouldstarttomove.Ifyouhaveanyissueshere,refertotheTroubleshootingsectionlaterinthischapter.

Page 422: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Playbackcanthenbestoppedusingthe[stop]linknearthetopofthepage.

Page 423: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 424: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

TroubleshootingThissectiondetailssomeofthecommonissuesyoumayencounterwhilebuildingthisprojectandstepsyoucanusetoresolvethem.

Page 425: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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.

Page 426: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

ServosdonotmovecorrectlyIftheservosseemtobebehavingerratically,thenthereisalmostcertainlyanissueregardingalackofsufficientpowersupplyforalltheservos.Thiscanbeconfirmedbymeasuringthevoltageacross5Vandgroundconnectionsontheservopowerdistributionboard.

Page 427: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,
Page 428: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

SummaryInthischapter,wecontinuedtolookatthepossibilitiestocontrolhardwareusingtheGPIOportsandhadaquicklookattheadditionalfeaturesofthePimodelB+.

Wealsolookedatsomeoftheissuescausedbydrivinglargenumbersofelectronicdevicesthatrequirealargeamountofpowerduringtheiroperations.Wealsolookedathowtheseissuescanbeovercome.

Nowthatyouhavecompletedalltheprojectsinthisbook,itistimeforyoutoembarkonyourownprojectsusingtheRaspberryPiandthevastrangeofdevicesthatcanbeusedwithittocreatesomeimpressiveprojectsthatcaninteractwiththeworldaroundyou.

Page 429: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

IndexA

AdafruitURL/UsingthebuttonsandjoystickwithPiPlay

AllThingsPiURL/InstallingLogitechMediaServer

Arduinosettingup,forMaplinsensors/SettingupyourArduinosettingup,forRFnetwork/SettingupArduino

ArduinoIDEURL/SettingupyourArduino

AudacityURL/Tuning

Page 430: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Bbottlexylophone

requisites/Whatyouwillneednotebottle,assembling/Assemblinganotebottleelectronics,configuring/Electronicswebapplication,creating/Thewebapplicationconfiguration/Configurationtuning/Tuningtesting/Testingtroubleshooting/Troubleshooting

Page 431: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 432: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

DDocumentObjectModel(DOM)

about/TheJavaScriptcodedriveelectronics

configuring,forroboticarm/Driveelectronics

Page 433: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Eelectronics,PortableSpeakerSystem

building/Buildingtheelectronicsamplifiercircuit,connecting/Theamplifiercircuitbattery,using/Runningthespeakersystemonbatterypower

enclosureconstruction,MagicMirrorinstructions/Enclosureconstructionwithoutplywoodenclosure/BuildingthemirrorwithoutanenclosurePienclosure/ThePienclosureURL,forPienclosure/ThePienclosure

extensioncablesreferencelink/Electronics

Page 434: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

FFileZilla

URL/TransferringMP3filestothePiFlask

URL/Theweatherstationwebapplication

Page 435: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

GGoogleChartsAPI

URL/TheweatherstationwebapplicationGoogleFonts

URL/StylesGPS-enabledTimelapseRecorder

requisites/Whatyouwillneedhardware,settingup/Settingupthehardwarecapturesoftware,settingup/Settingupthecapturesoftwarecaptures,using/Usingthecaptures

GunicornURL/Theweatherstationwebapplication

Page 436: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 437: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Iinstallation,LogitechMediaServer

about/InstallingLogitechMediaServer

Page 438: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

JJavaScriptdevelopment

referencelink/TheJavaScriptcodeJavaScriptObjectNotation(JSON)

about/ThePythoncodeJinjatemplatelanguage

referencelink/TheJinjapagetemplate

Page 439: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 440: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 441: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

cabinet,building/Buildingthecabinetreferencelink/BuildingthecabinetPiPlay,settingup/SettingupPiPlaybuttons,usingwithPiPlay/UsingthebuttonsandjoystickwithPiPlayjoystick,usingwithPiPlay/UsingthebuttonsandjoystickwithPiPlay

miniretro-stylearcadecabinet,requisiteshardware/Requirementstools/Requirements

mountpointabout/Linux

MP3filestransferring,toRaspberryPi/TransferringMP3filestothePi

Page 442: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Nnetwork

scanning,withNmaputility/NetworkscanningNginx

URL/TheweatherstationwebapplicationNmaputility

URL/Networkscanningused,forscanningnetwork/Networkscanning

Page 443: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 444: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 445: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 446: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

driveelectronics,configuring/Driveelectronicscamera,settingup/Settingupthecamerawebapplication,deploying/Deployingwebapplicationsarm,constructing/Thearmandchassisconstructionchassis,constructing/Thearmandchassisconstructioncalibrating/Calibrationtroubleshooting/Troubleshooting

Page 447: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 448: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Ttroubleshooting,bottlexylophone

missednotes/Notesaremissedservosmovement/Servosdonotmovecorrectly

troubleshooting,MagicMirrorissues,withwebapplication/Thewebapplicationfailswiththe500InternalServerErrordisplayissue/Thedisplaydoesnotwork

troubleshooting,roboticarmvideostream/Thevideostreamhasasubstantialdelayservos/Theservosmakealoudhummingnoiserobotcontrol/Controloftherobotislostarmsmovement/Thearmjumpstonewpositions

Page 449: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Uultracabs

about/SettinguptheinputelectronicsURL/Settinguptheinputelectronics

USBstoragedeviceautomounting/AutomountingaUSBstoragedevice

Page 450: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

VVideoforLinux2(V4L2)driver

about/Settingupthecamerareferencelink/Settingupthecamera

Page 451: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

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

Page 452: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

XXBMCmediacentersoftware

URL/SettingupOpenELEC

Page 453: Raspberry Pi Blueprintsprophet/raspberrypi/Raspberry... · Table of Contents Raspberry Pi Blueprints Credits About the Author About the Reviewers Support files, eBooks, discount offers,

Z7-Zip

URL/SettingupOpenELEC