Tải bản đầy đủ (.pdf) (234 trang)

buiding smart homes wwith raspberry pi zero

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.22 MB, 234 trang )


BuildingSmartHomeswithRaspberryPiZero


TableofContents
BuildingSmartHomeswithRaspberryPiZero
Credits
AbouttheAuthor
AbouttheReviewer
www.PacktPub.com
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Errata
Piracy
Questions
1.ConfiguringYourRaspberryPiZeroBoard
IntroducingtheRaspberryPiZeroboard
RequiredcomponentsfortheZeroboard
Assemblingthedifferentcomponents
InstallingRaspbian
Configuringtheboardforremoteaccess
InstallingNode.js
Summary
2.MeasureDataUsingYourRaspberryPiZeroBoard
Hardwareandsoftwarerequirements


Hardwareconfiguration
Softwareconfiguration
Readingdatafromthesensor
Storingsensordata
Accessingthedataremotely
Plottingthestoreddata
Summary
3.BuildingaSmartHomeThermostat
Hardwareandsoftwarerequirements
Hardwareconfiguration
Testingindividualcomponents
Buildingthethermostat
Controllingthethermostatremotely
Summary
4.ControllingAppliancesfromtheRaspberryPiZero


Hardwareandsoftwarerequirements
ControllingLEDs
ControllingthespeedofaDCmotor
Controllinghomeappliances
Summary
5.MakingaSmartPlugwiththeRaspberryPiZero
Hardwareandsoftwarerequirements
Hardwareconfiguration
Configuringthesmartplug
Creatinganinterfaceforthesmartplug
Loggingyourenergyconsumptionovertime
Summary
6.SendingNotificationsusingRaspberryPiZero

Hardwareandsoftwarerequirements
Makingamotionsensorthatsendstextmessages
Sendingtemperaturealertsthroughemail
ReceivingmeasurementSATAthroughpushnotifications
Summary
7.UsetheRaspberryPiZerotoBuildaSecuritySystem
Hardwareandsoftwarerequirements
BuildingamotionsensorwiththePiZero
Makingasimplealarmmodule
Buildingawirelesssecuritycamera
Creatingasecuritysystem
Summary
8.MonitorYourHomefromtheCloud
Hardwareandsoftwarerequirements
Monitoringdatafromaclouddashboard
Creatingaclouddashboardforyourdevices
Accessingyoursecuritycamerafromanywhere
Summary
9.ControlAppliancesfromAnywhere
Hardwareandsoftwarerequirements
ControlaLEDfromanywhereintheworld
Creatingseverallampsfromthecloud
Makeamotion-activatedlampusingIFTTT
Buildanautomatedcloudthermostat
Summary
10.BuildingaHomeAutomationSystemwithRaspberryPiZeroBoards
Hardwareandsoftwarerequirements
Buildingallthemodules
Configuringthemodules
Integratingthemodulesintoasingleinterface

Automatingyourhome


Accessingyourhomeautomationsystemfromanywhere
Summary
Index


BuildingSmartHomeswithRaspberryPiZero


BuildingSmartHomeswithRaspberryPiZero
Copyright©2016PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,or
transmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthe
publisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyofthe
informationpresented.However,theinformationcontainedinthisbookissoldwithout
warranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealers
anddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyor
indirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthe
companiesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,
PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:October2016
Productionreference:1241016
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.

ISBN978-1-78646-695-2
www.packtpub.com


Credits
Author
MarcoSchwartz
Reviewer
VasilisTzivaras
CommissioningEditor
KartikeyPandey
AcquisitionEditor
PrachiBisht
ContentDevelopmentEditor
TrushaShriyan
TechnicalEditors
NirantCarvalho
NaveenkumarJain
CopyEditors
SafisEditing
SnehaSingh
ProjectCoordinator
KinjalBari
Proofreader
SafisEditing
Indexer
PratikShirodkar


Graphics

KirkD'Penha
ProductionCoordinator
ShantanuNZagade
CoverWork
ShantanuN.Zagade


AbouttheAuthor
MarcoSchwartzisanelectricalengineer,entrepreneur,andblogger.Hehasamaster's
degreeinelectricalengineeringandcomputersciencefromSupélec,France,andamaster's
degreeinmicroengineeringfromtheEcolePolytechniqueFédéraledeLausanne(EPFL),
Switzerland.
Hehasmorethanfiveyearsofexperienceworkinginthedomainofelectricalengineering.
Marco'sinterestsgravitatearoundelectronics,homeautomation,theArduinoandRaspberry
Piplatforms,opensourcehardwareprojects,and3Dprinting.
HehasseveralwebsitesaboutArduino,includingtheOpenHomeAutomationwebsite,which
isdedicatedtobuildinghomeautomationsystemsusingopensourcehardware.
MarcohaswrittenanotherbookonhomeautomationandArduino,calledHomeAutomation
WithArduino:AutomateYourHomeUsingOpen-sourceHardware.Hehasalsowrittenabook
onhowtobuildInternetofThingsprojectswithArduino,calledInternetofThingswiththe
ArduinoYun,byPacktPublishing.


AbouttheReviewer
VasilisTzivarasisasoftwaredeveloperandhardwareengineerwholivesinIoannina,
Greece.Heiscurrentlyanundergraduatestudentofthedepartmentofcomputerscienceand
engineeringatIoannina.Alongwithhisstudies,heisworkingonmanyprojectsrelevantto
robotics,suchasdrones,homeautomation,andsmarthomesystemsusingArduinoandthe
RaspberryPi.Heisalsoenthusiasticaboutcleanenergysolutionsandculturalinnovation
ideas.

HehasworkedfortheUniversityHospitalofIoanninaasanassistantforvariouscomputer
issuesandhasbeenapartofthesupportteamofhisCSEdepartmentforoverayear.Hehas
participatedinIEEEUOIStudentBranchandotherbigorganizations,suchasFOSSCOMM,
withpersonalpresentationsforwebsitedesigning,programming,Linuxsystems,anddrones.
HeisthechairofIEEEUniversityofIoanninaStudentBranchandhasproposedmany
projectsandsolutionstoautomatehomesandmanyotherlifeproblemsbyreducingthetime
ofeverydayroutines.Inadditiontothis,hehascomeupwithideastoentertainkidswith
funnyandmagicalprojectsusingArduino-likehardwareandopensourcesoftware.Manyof
theprojectscanbefoundonhisGitHubaccountunderthenameofBillyTziv.
ApartfromBuildingSmartHomeswithRaspberryPiZeroandInternetofThingswithArduino
Cookbook,hehasalsopublishedabooknamedBuildingaQuadcopterwithArduino.Hehas
alsoworkedonanotherbookProgramminginC,whichisnotyetpublished.Inadditionto
this,hehaswrittenforblogs,forums,guides,andsmallchapters,explainingandsharinghis
knowledgeofcomputers,networks,andprogramming.


www.PacktPub.com
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePub
filesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprint
bookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat
<>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupfora
rangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksand
eBooks.

/>Getthemostin-demandsoftwareskillswithMapt.MaptgivesyoufullaccesstoallPackt
booksandvideocourses,aswellasindustry-leadingtoolstohelpyouplanyourpersonal
developmentandadvanceyourcareer.
FullysearchableacrosseverybookpublishedbyPackt
Copyandpaste,print,andbookmarkcontent

Ondemandandaccessibleviaawebbrowser


Preface
TheRaspberryPiisanamazingdevelopmentplatformthatwasintroducedbackin2012,
alongwiththereleaseofthefirstboard.However,duetoitsprice,itwasnotconvenientfor
peopletouseitforsmarthomeapplications,whereyouneedtodeployseveralmodulesat
differentplacesofyourhome.Usually,peoplebuildingsmarthomeswiththisboarduseditas
acentralhub.
However,in2016theRaspberryPifoundationreleasedtheZeroboard,whichisasmaller
andmuchcheaperversionoftheRaspberryPiboard,andthischangedeverythingforthe
homeautomationfield.Now,youcanactuallyuseseveraloftheseboardsinahome
automationsystemandenjoyallthepowerandflexibilityoftheRaspberryPiforallyour
projects.
ThisisexactlywhatIwillteachyoutodointhisbook.Youwilllearnhowtousethe
RaspberryPiZeroboardinseveralhomeautomationprojects,inorderforyoutobuilda
smarthomethatisreallytailoredtoyourneeds.


Whatthisbookcovers
Chapter1,ConfiguringYourRaspberryPiZeroBoard,teachesyouhowtogetstartedwith
yourRaspberryPiZeroboardandalsoinstalleverythingthatyouneedtocarryoutallthe
projectsthatyouwillfindinthisbook.
Chapter2,MeasureDataUsingYourRaspberryPiZeroBoard,teachesyouhowtomeasure
datafromasensorusingtheRaspberryPiZeroboard.Youwillalsolearnhowtomeasure
datafromthesensor,storethisdataonthePi,andplotitgraphically.
Chapter3,BuildingaSmartHomeThermostat,getsyourightintothecoretopicofthisbook,
thatis,buildingyourfirsthomeautomationsystem.Inthischapter,wewillbuildasimple
thermostatthatwillallowyoutoregulatethetemperatureinyourhome.
Chapter4,ControlAppliancesfromtheRaspberryPiZero,showsyouhowtousethe

RaspberryPiZeroboardtoeasilycontrolhomeappliances.Asanexample,we'llseehowto
controlaDCmotorandswitchon/offappliances,suchaslamps.
Chapter5,MakingaSmartPlugwiththeRaspberryPiZero,teachesyouhowtobuildyour
ownversionofasmartwirelessplugthatyoucanbuyinashop.We'llseehowtobuildthe
sameusingtheRaspberryPiZeroboardandhowtocustomizeitforyourownneeds.
Chapter6,SendingNotificationsusingRaspberryPiZero,showsyouhowtosendautomated
notificationsfromyourPi,forexampletoindicatethatthetemperatureinyourhomeis
gettinglow.Asexamples,we'llseehowtosendtext,email,andpushnotifications.
Chapter7,UsetheRaspberryPiZerotoBuildaSecuritySystem,showsyouhowtostart
integratingeverythingwesawsofarinthebookandbuildasecuritysystemusingwhatwe
havelearnedsofar.You'll,forexample,learnhowtotransformyourRaspberryPiZero
boardintoawirelesssecuritycamera.
Chapter8,MonitorYourHomefromtheCloud,guidesyouthroughanamazingfield:the
InternetofThings.YouwilllearnhowtousetheInternetofThingsforyoursmarthomeand
monitoritfromanywhereintheworld.
Chapter9,ControlAppliancesfromAnywhere,guidesyouintothefieldoftheInternetof
Things,thistimebyteachingyouhowtocontrolhomeappliancesfromoutsideofyourWi-Fi
network.
Chapter10,BuildingaHomeAutomationSystemwithRaspberryPiZeroBoards,uses
everythingyoulearnedinthebooktobuildacompletehomeautomationsystemforyour
entirehome.


Whatyouneedforthisbook
Forthisbook,themaincomponentyouwillneedis,ofcourse,aRaspberryPiZeroboard.In
thefirstchapterofthebook,Iwillshowyouhowtocompletelyconfiguretheboard,soyou
canuseitfortheprojectsofthisbook.Wewillusesomebasiccomponentsatthestart,suchas
sensors,andthenmoveontousingmorecomplexcomponents.Foreveryproject,Iwillof
courseguideyoustep-by-stepintobuildingthehardwarepartsothatyouarenotleftbehind.
Onthesoftwareside,itisgoodifyouactuallyhavesomeexistingprogrammingskills,

especiallyinJavaScriptandintheNode.jsframework.However,Iwillexplainallthepartsof
eachsoftwarepieceofthisbook;soevenifyoudon'thavegoodprogrammingskillsin
JavaScriptyouwillbeabletofollowalong.


Whothisbookisfor
Thisbookisforallthepeoplewhowanttoautomatetheirhomesandmakeitsmarter,while
atthesametimehavingcompletecontrolonwhattheyaredoing.Ifthat'syourcase,youwill
learneverythingthereistolearninthisbook,onhowtousetheamazingRaspberryPiZero
boardtoautomateyourhome.
Thisbookisalsoformakerswhohaveplayedinthepastwithotherdevelopmentboards,
suchasArduino.Ifthat'syourcase,youwilllearnhowtousethepoweroftheRaspberryPi
platformtobuildsmarthomes.Youwillalsolearntocreateprojectsthatcan'teasilybedone
withotherplatforms,suchascreatingawirelesssecuritycamerawiththePiZero.


Conventions
Inthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsof
information.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,
dummyURLs,userinput,andTwitterhandlesareshownasfollows:"Youcannowsimply
navigatetotheIPaddressofthecomputerorPionwhichtheapplicationisrunning,followed
byport3000."
Ablockofcodeissetasfollows:
varrequest=require('request');
varsensorLib=require('node-dht-sensor');

Anycommand-lineinputoroutputiswrittenasfollows:
sudonpminstallexpressrequest


Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,for
example,inmenusordialogboxes,appearinthetextlikethis:"Youcannowjustclickon
Streamtoaccessthelivestreamfromthecamera."

Note
Warningsorimportantnotesappearinaboxlikethis.

Tip
Tipsandtricksappearlikethis.


Readerfeedback
Feedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—
whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitles
thatyouwillreallygetthemostoutof.
Tosendusgeneralfeedback,simplye-mail<>,andmentionthe
book'stitleinthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingor
contributingtoabook,seeourauthorguideatwww.packtpub.com/authors.


Customersupport
NowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyouto
getthemostfromyourpurchase.


Downloadingtheexamplecode
Youcandownloadtheexamplecodefilesforthisbookfromyouraccountat
.Ifyoupurchasedthisbookelsewhere,youcanvisit
andregistertohavethefilese-maileddirectlytoyou.

Youcandownloadthecodefilesbyfollowingthesesteps:
1.
2.
3.
4.
5.
6.
7.

Loginorregistertoourwebsiteusingyoure-mailaddressandpassword.
HoverthemousepointerontheSUPPORTtabatthetop.
ClickonCodeDownloads&Errata.
EnterthenameofthebookintheSearchbox.
Selectthebookforwhichyou'relookingtodownloadthecodefiles.
Choosefromthedrop-downmenuwhereyoupurchasedthisbookfrom.
ClickonCodeDownload.

YoucanalsodownloadthecodefilesbyclickingontheCodeFilesbuttononthebook's
webpageatthePacktPublishingwebsite.Thispagecanbeaccessedbyenteringthebook's
nameintheSearchbox.PleasenotethatyouneedtobeloggedintoyourPacktaccount.
Oncethefileisdownloaded,pleasemakesurethatyouunziporextractthefolderusingthe
latestversionof:
WinRAR/7-ZipforWindows
Zipeg/iZip/UnRarXforMac
7-Zip/PeaZipforLinux
ThecodebundleforthebookisalsohostedonGitHubat
Wealso
haveothercodebundlesfromourrichcatalogofbooksandvideosavailableat
Checkthemout!



Errata
Althoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.
Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—we
wouldbegratefulifyoucouldreportthistous.Bydoingso,youcansaveotherreadersfrom
frustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,
pleasereportthembyvisitingselectingyourbook,
clickingontheErrataSubmissionFormlink,andenteringthedetailsofyourerrata.Once
yourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedto
ourwebsiteoraddedtoanylistofexistingerrataundertheErratasectionofthattitle.
Toviewthepreviouslysubmittederrata,goto
andenterthenameofthebookinthesearch
field.TherequiredinformationwillappearundertheErratasection.


Piracy
PiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.At
Packt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucomeacross
anyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththe
locationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
leasecontactusat<>withalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluable
content.


Questions
Ifyouhaveaproblemwithanyaspectofthisbook,youcancontactusat
<>,andwewilldoourbesttoaddresstheproblem.



Chapter1.ConfiguringYourRaspberryPiZero
Board
Inthefirstchapterofthisbook,wearegoingtogothroughallthestepsthatarerequiredto
configureyourRaspberryPiZeroboardsoyoucanuseitforalltheprojectswewillseein
thisbook.
Firstwewilllookatthelistofcomponentsthatarerequiredtousetheboard.Then,wewill
installtheRaspbiandistribution,whichwillbetheoperatingsystemwewillusethroughout
thisbook,ontheboard.Finally,we'llseehowtoconfiguretheboardforremote,andhowto
installtheNode.jsframeworkthatwewilluseinnearlyalltheprojectsofthebook.Let'sstart!


IntroducingtheRaspberryPiZeroboard
TheRaspberryPiZeroisaboardthatwasintroducedin2015,andthegoalwastomakea
low-cost($5),small-formatboardwithmostofthefunctionalitiesoftheoriginalRaspberry
Piboard.
ThefollowingisanimageoftheZeroboard:

Inthecenteroftheboard,youwillfindthesameSystem-on-a-Chip(SoC)astheoriginal
RaspberryPiboard,witha1-GHzsingle-coreprocessor,512MBofRAM,andagraphical
processingunit.
Theboardhasseveralinputsandoutputs,likethe40-pinGPIOconnectorthatwewilluse
throughthiswholebooktoconnecttheboardtosensorsandothercomponents.
TherearealsotwoUSBports(oneforpower,oneforcommunication),onemini-HDMIport,
andoneSDcardslottoputtheoperatingsystemandotherfilesin.


×