Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your...
Transcript of Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your...
![Page 1: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/1.jpg)
![Page 2: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/2.jpg)
![Page 3: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/3.jpg)
BuildingaHomeSecuritySystemwithRaspberryPi
![Page 4: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/4.jpg)
TableofContents
BuildingaHomeSecuritySystemwithRaspberryPi
Credits
AbouttheAuthor
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Errata
Piracy
Questions
1.SettingUpYourRaspberryPi
WhichflavorofPi?
RaspberryPiModelA
RaspberryPiModelB
RaspberryPiModelB+andModel2
Modelcomparisontable
Sowhichone?
PreparingtheSDcard
DownloadingtheRaspbianimage
UsingMicrosoftWindows
![Page 5: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/5.jpg)
UsingLinux
BootingyourPi
Expandingthefilesystem
Usingtheraspi-configutility
SettingupyourPi
Gettinguptodate
Gettingtherighttime
fake-hwclock
ntp
Talkingofsecurity…
Whatisthissudothinganyway?
ConnectingviaWi-Fi
Summary
2.ConnectingThingstoYourPiwithGPIO
Prerequisites
SayhellototheGPIO
DigitalI/Opins
TheI2Cbus
TheSPIbus
TheUARTserialbus
USBports
Powerconnections
GettingacquaintedwiththeGPIO
Lettherebelight
Gettingflashy…
Addingaswitch
Pullingyourselftogether
Thedetectionscript
Themostelaboratelightswitchintheworld
Theilluminatingscript
Summary
![Page 6: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/6.jpg)
3.ExtendingYourPitoConnectMoreThings
Prerequisites
TheI2Cbus
Just2wires
What’syouraddress?
Thereisaparalleluniverse
Serial-to-parallelconversion
Givemepower
BuildinganI2Cexpander
TheI2Cportexpandercircuit
Let’swalkthroughthecircuit
Buildingyourexpansionboard
Usingready-madeexpansionboards
HobbytronicsMCP23017expanderportkit
PiFaceDigitalI/Oexpansionboard
Gertboard
Summary
4.AddingaMagneticContactSensor
Prerequisites
Theworkingofmagneticcontactsensors
SettinguptheI2Cportexpander
EnablingtheI2CBus
InstallingtheI2Ctoolspackage
Findingourdevices
Settinguptheportexpander
Connectingourmagneticcontactsensor
Monitoringthesensor
Anti-tampercircuits
Gettingintothezone
Summary
5.AddingaPassiveInfraredMotionSensor
![Page 7: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/7.jpg)
Prerequisites
Passiveinfraredsensorsexplained
SettingupyourPIRsensor
Givemepower(again)
ConnectingourPIRmotionsensor
12Valarmzonecircuits
Alarmcircuitprotection
Howitworks
WirelessPIRmotionsensors
433-MHzwirelessalarmsystems
Connectinga433-MHzreceiver
Thealternativeapproach(becausewehavenochoice)
Thereceiverwiringdiagram
Loggingdetectiondata
Summary
6.AddingCamerastoOurSecuritySystem
Prerequisites
TheRaspberryPicameramodule
Connectingthecameramodule
Settingupthecameramodule
Testingthecameramodule
Beavideostar
Caughtoncamera
Youhavenewmail
Settingupthee-mailsenderclient
Sendingattachments
Wherewasthattaken?
Nightvision
Anilluminatingexperience
TheElaboratelightswitchre-visited
Isthatabadger?
![Page 8: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/8.jpg)
UsingUSBcameras
Installingthewebcam
Takingasnap
Snapsnapsnap
Themulticamerasetup
TheSlavedriver
Summary
7.BuildingaWeb-BasedControlPanel
Installingthewebserver
TestingthePHP5installation
Beingincontrol
Armingyourself
Themasterconfigurationfile
Creatingthewebpage
ThecontrolpanelHTMLtemplate
Givingitsomestyle
Makingitdynamic
Gettingabitofhelpfirst
ThemainPHPcode
I’msomeoneelse
Remoteaccesstoourcontrolpanel
SettingupadynamicDNSaccount
TheRaspberryPidynamicDNSclient
SettingupastaticIPonyourRaspberryPi
Port-forwarding
Summary
8.AMiscellanyofThings
Arminganddisarmingthesystem
Drivinginductiveloads
Beyondintrusion
Asimplewaterdetector
![Page 9: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/9.jpg)
Howitworks
Asimpletemperaturesensor
Howitworks
Acarbonmonoxidedetector
RemoteadministrationforourRaspberryPi
GettingWebmin
Updatingtherepositorysources
Importingthesigningkey
AccessingWebminlocally
RemotelyaccessingWebmin
Summary
9.PuttingItAllTogether
Alarmsystemdiagram
Overviewofthesystemelements
A+12Vpowersupply
A+3.3Vpowersupply
Theopto-isolatorinputmodule
Theportexpander
Anarm/disarmswitch
Alarmoutputs
Designingthecontrolscripts
Buildingthecontrolscript
Exploringthescriptcode
Declarations
Updatingconfigsettings
SettinguptheGPIO
SettinguptheI2Cportexpander
Decodingthezoneinputsstatus
Initialization
Thesystemmonitoringloop
Armingthesystem
![Page 10: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/10.jpg)
Monitoringthezones
Entrydelay
Soundingthemainalarm
Disarmingandresettingthesystem
We’redone(almost)…
Automaticallystartingthesystem
PreservingtheSDcard
CreatingaRAM-basedfilesystem
Conclusion
Tipsforbuildingsystems
Summary
Index
![Page 11: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/11.jpg)
![Page 12: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/12.jpg)
BuildingaHomeSecuritySystemwithRaspberryPi
![Page 13: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/13.jpg)
![Page 14: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/14.jpg)
BuildingaHomeSecuritySystemwithRaspberryPiCopyright©2015PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:December2015
Productionreference:1161215
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78217-527-8
www.packtpub.com
![Page 15: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/15.jpg)
![Page 16: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/16.jpg)
CreditsAuthor
MatthewPoole
Reviewers
LihangLi
CédricVerstraeten
CommissioningEditor
EdwardBowkett
AcquisitionEditors
VivekAnantharaman
VinayArgekar
ContentDevelopmentEditor
SumeetSawant
TechnicalEditor
NamrataPatil
CopyEditor
AngadSingh
ProjectCoordinator
ShwetaH.Birwatkar
Proofreader
SafisEditing
Indexer
RekhaNair
ProductionCoordinator
ManuJoseph
CoverWork
ManuJoseph
![Page 17: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/17.jpg)
![Page 18: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/18.jpg)
AbouttheAuthorMatthewPooleisasystemsengineerbasednearSouthamptononthesouthcoastofEnglandwithover20yearsofindustryexperience.Aftergraduatinginelectronicsandcommunicationsengineering,hewentontotrainasandtobecomeanairtrafficengineerfortheUKCivilAviationAuthority,workingonmicroprocessor-basedcontrolandcommunicationssystems.
Later,hebecameasoftwarearchitectandmobiletechnologyspecialist,andworkedforseveralconsultanciesandglobalorganizations.HeisnowapartneratUKMobileMedia,aboutiquesystemsconsultancyfocusedondesigningBluetoothandotherwirelesssystems,takingideasfromconcepttoprototype.HeisalsothedirectoroftechnologyforMobileOnboard,aleadingUK-basedtransporttechnologycompanythatspecializesinon-busconnectivityandmobileticketing.
![Page 19: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/19.jpg)
![Page 20: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/20.jpg)
AbouttheReviewersLihangLireceivedhisMSdegreeincomputervisionfromNationalLaboratoryofPatternRecognition(NLPR)atInstituteofAutomationoftheChineseAcademyofSciences(CAS).HisinterestsincludeLinux,opensource,cloudcomputing,virtualization,computervisionalgorithms,machinelearninganddatamining,andavarietyofprogramminglanguages.
Youcanfindhimathispersonalwebsiteathttp://hustcalm.me.
Ithasbeenagreatopportunitybeingapartofthisbook.Ihavealwaysbeenafanofembeddeddevicesandsystems.Thanksgotoourauthorandcoordinator.Hopethereaderswillfindthisbookhelpful.
CédricVerstraetenhasanMScinengineeringandisprimarilyactiveintheC++community.Heworksasasoftwareengineerandisahugeopensourceenthusiast.Hespendsmostofhistimeonsideprojects.He’sthefounderofKerberos.io,anopensourcevideosurveillancesystembuiltfortheRaspberryPi,andistheorganizeroftheRaspberryPiBelgiummeetupgroup.
IwouldliketothankPacktPublishingformakingmeareviewerofthisbook.Ireallythinktheirbookscangivepeopleanin-depthoverviewofaparticulartopic.
![Page 21: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/21.jpg)
![Page 22: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/22.jpg)
www.PacktPub.com
![Page 23: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/23.jpg)
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 24: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/24.jpg)
Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser
![Page 25: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/25.jpg)
FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.
![Page 26: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/26.jpg)
![Page 27: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/27.jpg)
PrefaceTheRaspberryPiisapowerful,low-cost,credit-cardsizedcomputer,whichlendsitselfperfectlyasthecontrollerofasophisticatedhomesecuritysystem.Usingtheavailableon-boardinterfaces,theRaspberryPicanbeexpandedtoallowtheconnectionofavirtuallyinfinitenumberofsecuritysensorsanddevices.TheRaspberryPihastheprocessingpowerandinterfacesavailabletobuildasophisticatedhomesecuritysystembutatafractionofthecostofcommerciallyavailablesystems.
BuildingaHomeSecuritySystemwithRaspberryPistartsoffbyshowingyoutheRaspberryPiandhowtosetuptheLinux-basedoperatingsystem.ThebookthenguidesyouthroughconnectingswitchsensorsandLEDstothenativeGPIOconnectorsafely,anditalsoshowsyouhowtoaccesstheseusingsimpleBashscripts.Asyoudivefurtherin,you’lllearnhowtobuildaninput/outputexpansionboardusingtheI2Cinterfaceandpowersupply,allowingtheconnectionofthelargenumberofsensorsneededforatypicalhomesecuritysetup.
Thebookfeaturescleardiagramsandcodelistingeverystepofthewaytoallowyoutobuildatrulysophisticatedandmodularhomesecuritysystem.
![Page 28: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/28.jpg)
WhatthisbookcoversChapter1,SettingUpYourRaspberryPi,startsoutbytakingourRaspberryPioutofitsboxandpreparingitforbeingthecenterpieceofourhomesecuritysystem.Alongtheway,wewillinstallandsetuptheoperatingsystem,connectourPitothenetwork,andaccessitremotely.We’llalsosecureourPiandmakesureitcankeeptherighttime.
Chapter2,ConnectingThingstoYourPiwithGPIO,explorestheGPIOportandthevariousinterfacesitfeatures.We’lllookatthevariousthingswecanconnecttotheRaspberryPiusingtheGPIOincludingswitchesandsensorsaswestarttobuildourhomesecuritysystem.
Chapter3,ExtendingYourPitoConnectMoreThings,looksatwaysofexpandingthenumberofthingswecanconnecttoourRaspberryPi,overcomingthelimitationofhavingjusttheeightdigitalpinsavailabletousontheGPIObytappingintootherinterfacesontheGPIOandbuildingourowninput/outputexpansionboard.
Chapter4,AddingaMagneticContactSensor,startstoactuallyconnectthingstoourhomesecuritysystem,suchasmagneticsensorsandothertypesofcontactdevices.YouwilllearnhowtoprogramourI2CexpansionportusingBashscriptssothatwecanreadthestateofoursensorsandswitchonwarningLEDs.We’llalsostarttodevelopthecontrolscriptsforoursystemthatwillallowustoarmanddisarmthesystemandadddelaytimers.
Chapter5,AddingaPassiveInfraredMotionSensor,looksatpassiveinfra-redmotiondetectors,howtheywork,andhowwecanconnectwiredandwirelesstypestoourhomesecuritysystem.We’llalsolearnhowtocreatelogfilesbasedoneventsusingBashscriptssothatwecanmaintainahistoryofdetectorstatesastheychange.
Chapter6,AddingCamerastoOurSecuritySystem,teachesyouhowtoconnectbothRaspberryPicameramodulesandUSBcamerastoourPiboardinordertotakeimageandvideocaptureswhenrequiredbyourhomesecuritysystem.We’llalsolearnhowtooverlayourimageswithinformativetextandhavethefilesimmediatelyemailedtous.
Chapter7,BuildingaWeb-BasedControlPanel,getsdowntothebusinessofstartingtoputtogethermodulesbybuildingamobile-optimizedweb-basedcontrolpanelforourhomesecuritysystem.You’lllearnhowtosetupawebserveronourRaspberryPiandmanipulatefilesusingourwebcontrolpanel,meaningwe’llstarttoexplorehowalloftheelementssofarwillcometogetheraspartofourfinalsystem.
Chapter8,AMiscellanyofThings,looksafewotherbitsandpieces,suchasaddingothersensorstoourhomesecuritysystemthatarenotnecessarilyrelatedtointruderdetection.We’llalsolookathowwecanadministerourentireRaspberryPisystemremotelyusingawebbrowserinadditiontoaccessingourhomesecuritycontrolpanel.
Chapter9,PuttingItAllTogether,isthemomentwe’veallbeenwaitingfor;we’regoingtotakealloftheelementsandconceptsfromthepreviouschaptersandputtogetherourfullsystemcomprisingtheelementswewanttofeature.Thestaroftheshowwillbeour
![Page 29: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/29.jpg)
Bashscripts,whichwillgluetogetheralloftheseelementsandprovidethecontrollogicfortheentiresystem.
![Page 30: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/30.jpg)
![Page 31: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/31.jpg)
WhatyouneedforthisbookYou’llneedthefollowingsoftware:
Gpartedddfake-hwclockWin32DiskImager0.9.5PuTTYi2c-tools
![Page 32: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/32.jpg)
![Page 33: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/33.jpg)
WhothisbookisforThisbookisforanyonewhoisinterestedinbuildingamodularhomesecuritysystemfromscratchusingaRaspberryPiboard,basicelectronics,sensors,andsimplescripts.Thisbookisidealforenthusiasticnoviceprogrammers,electronicshobbyists,andengineeringprofessionals.Itwouldbegreatifyouhavesomebasicsolderingskillsinordertobuildsomeoftheinterfacemodules.
![Page 34: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/34.jpg)
![Page 35: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/35.jpg)
ConventionsInthisbook,youwillfindanumberofstylesoftextthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestyles,andanexplanationoftheirmeaning.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Extract2015-09-24-raspbian-jessie.imgtoyourHomefolder.”
Ablockofcodeissetasfollows:
#passwd
root@raspberrypi:/home/pi#passwd
EnternewUNIXpassword:
RetypenewUNIXpassword:
passwd:passwordupdatedsuccessfully
root@raspberrypi:/home/pi#
Anycommand-lineinputoroutputiswrittenasfollows:
$sudoapt-getinstallfake-hwclock
Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,inmenusordialogboxesforexample,appearinthetextlikethis:“TypetheIPaddressoftheRaspberryPiintotheHostNameboxandclickonOpen.”
NoteWarningsorimportantnotesappearinaboxlikethis.
TipTipsandtricksappearlikethis.
![Page 36: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/36.jpg)
![Page 37: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/37.jpg)
ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedormayhavedisliked.Readerfeedbackisimportantforustodeveloptitlesthatyoureallygetthemostoutof.
Tosendusgeneralfeedback,simplysendane-mailto<[email protected]>,andmentionthebooktitleviathesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideonwww.packtpub.com/authors.
![Page 38: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/38.jpg)
![Page 39: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/39.jpg)
CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.
![Page 40: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/40.jpg)
DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
![Page 41: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/41.jpg)
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 42: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/42.jpg)
PiracyPiracyofcopyrightmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucomeacrossanyillegalcopiesofourworks,inanyform,ontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluablecontent.
![Page 43: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/43.jpg)
QuestionsYoucancontactusat<[email protected]>ifyouarehavingaproblemwithanyaspectofthebook,andwewilldoourbesttoaddressit.
![Page 44: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/44.jpg)
![Page 45: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/45.jpg)
Chapter1.SettingUpYourRaspberryPiBeforewecangetintotherealmsofbuildingourhomesecuritysystem,there’sabitofpreparationworkneededtogetourRaspberryPiupandrunning.So,we’regoingtogothroughtheinitialstepsneededtogetourPireadytobeworkedon.
Inthischapter,wewillcoverthefollowingtopics:
ExploringthedifferentversionsoftheRaspberryPithatareavailableChoosingtherightRaspberryPiversionforyoursystemPreparingtheSDCardwiththeRaspbianOperatingSystemLearninghowtoremotelyaccesstheRaspberryPioveryourhomenetworkUpdatingouroperatingsystemwiththelatestpackagesExploringthetime-keepingoptionsontheRaspberryPiSettingtheuserandrootpasswordstosecureourRaspberryPi
![Page 46: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/46.jpg)
WhichflavorofPi?SincetheRaspberryPiwasreleasedin2012,therehavebeenseveralversionsofthemini-PCboardreleased.I’llgothougheachoftheversionsreleasedwiththeirrespectivefeaturessothatyoucanchoosewhichoneissuitableforyourparticularproject.
Thegoodnewsisthatitdoesn’treallymatterwhichversionyouuseintermsofpower,asourhomesecuritysystemdoesn’tnecessarilyneedloadsofprocessingpower,dependingonwhatyouwantyoursystemtodo,ofcourse).Youmighthaveanolderboardkickingaboutthatwillworkforyou.
TheotherpieceofgoodnewsisthattheGPIOinterfacepinlayoutsarethesameacrossalltheversions.Thelaterversionshavemorepins,buttheoriginal26pinsstillremaininthesameplace.
ThelatestRaspberryPiVersion2
![Page 47: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/47.jpg)
RaspberryPiModelAThebabyofthefamilyistheModelA;itwasreleasedasalower-costversionoftheModelB,showninthefollowingsection.ItsmaindifferencesfromtheModelBarethatitfeaturesjust256MbofmemoryandhasnoEthernetport;soifyouwanttoconnectthisboardtoanetwork,youarelimitedtousingaUSBWi-Fidongle.
TheRaspberryPiModelABoardLayout
![Page 48: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/48.jpg)
RaspberryPiModelBThiswasthefirstversionofRaspberryPitobereleased;anupdatedrevision,whichimprovedthepowersystemandUSBportprotection,camelater.Itfeatures512MbofmemoryandhasanEthernetportforconnectingtoyournetwork.Thisisprobablythemostcommonversionused,andhavingtheEthernetportisincrediblyuseful,especiallytogetupandrunquicklyinordertosetupandconfigureyourPiwithouttheneedforakeyboardandmonitor.
TheRaspberryPiModelBLayout
![Page 49: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/49.jpg)
RaspberryPiModelB+andModel2In2014,theRaspberryPiFoundationreleasedanewversionoftheboardthathadsomefundamentalchangesascomparedtothepreviousversion.Themostfundamentalchangesweretheboardlayout,formfactor,andmountingpoints—muchtothedismayofthemanyenclosureandaccessorymanufacturersoutthere.
Infact,wewereinthemiddleofprototypinganenclosureforacommercialproductthatweweredevelopingbasedontheRaspberryPi—fortunatelywecaughtwindoftheboardchangeinthenickoftimeandwereabletochangeourenclosuretosupporttheupcomingmodelB+.
Themainelectronicchangestothisboardaretheadditionof2moreUSBportsthatcandelivermorepowertoperipherals,anexpandedGPIOinterface,andtheremovalofthecompositevideoportthatisnowconsolidatedintotheaudiojack.ItalsonowusesamicroSDcardwithabettercardslot.
InFebruary2015,amorepowerfulRaspberryPiwasreleased:theRaspberryPiModel2.It’ssimilartotheModelB+intermsofform-factorandinterfaces,butisnowreportedly6-timesfasterthantheModelB/B+withitsupgradedARMprocessorand1Gbofmemory.
Atthesamelowcostoflessthan£30,it’safantasticlittleboardandagreatpower-houseforembeddedsystems.
![Page 50: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/50.jpg)
TheRaspberryPiModelB+andModel2Layout
![Page 51: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/51.jpg)
Modelcomparisontable ModelA ModelB ModelB+ Version2
ProcessorARM1176JZF-S700MHzprocessor,
VideoCoreIVGPU
Quad-coreARMCortex-A7CPUandaVideoCoreIV
dual-coreGPU
Memory 256Kb 512Kb 512Kb 1Gb
USBPorts 2 2 4 4
Ethernet No Yes Yes Yes
No.GPIO
Pins26 26 40 40
Storage SDCard SDCard MicroSDCard MicroSDCard
![Page 52: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/52.jpg)
Sowhichone?Essentially,anyversionoftheRaspberryPiwillworkwiththemodulespresentedinthisbook,butifyouwanttoexploitfeaturessuchasthecamera,whichmayrequiremoreprocessingpowerandmemory,orwanttohaveanEthernetconnection,you’llneedtousetheModelB.
IfyouwanttostartpluggingadditionalstuffintotheUSBport,suchasaGSMmodem,thenIrecommendthatyouusetheModelB+asitdeliversmorepowertothosekindsofdeviceswithouttheneedforadditionalUSBhubs.
Ifyouwanttodomoreprocessingwithvideoandimagesfromanattachedcamera,orwanttoconnectlotsofthings,thengoforthelatestModel2board.I’mgoingtoassumethat’stheoneyouhavechosenforthisproject,andthat’stheoneI’llbeusingthroughoutthisbook;justbeawareofanylimitationsifyouchoosetouseanearliermodel.
NoteTheRaspberryPiFoundationsitehasmoredetailedinformationabouteachmodel.Youcanvisititathttps://www.raspberrypi.org/products.
![Page 53: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/53.jpg)
![Page 54: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/54.jpg)
PreparingtheSDcardTheRaspberryPionlybootsfromanSDcard(ormicroSDcardfortheB+andv2models),andcannotbootfromanexternaldriveorUSBstick(wellthat’snotstrictlytrue,butisbeyondthescopeofthisbook).
It’srecommendedthatyouuseaClass10SDcardforperformance,butaClass4or6cardwillbefineforthisproject.You’llneedtohaveaminimumcardsizeof4Gb.
NowthatwehaveourRaspberryPiboardandSDcardtohand,weneedtopreparetheSDCardspecificallyforourhomesecuritysystem.We’regoingtousethestandardRaspbianoperatingsystemastherereallyisnoreasontouseanyotherdistribution;it’sthedefactochoicefortheRaspberryPi.
![Page 55: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/55.jpg)
DownloadingtheRaspbianimageYou’llneedtograbthelatestRaspbianOSimagefromtheRaspberryPisiteathttps://www.raspberrypi.org/downloads.
DownloadtheRaspbianOSZIPfilecontainingtheimagetoyourPC.
NoteAtthetimeofwriting,thelatestversionwasRaspbianJessieversion4.1(2015-09-24-raspbian-jessie.zip).
Oncedownloaded,unzipthefileandyou’llhavethefile,2015-09-24-raspbian-jessie.img.
ThenextthingtodoisburnthisimagetoyourSDcard…
![Page 56: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/56.jpg)
UsingMicrosoftWindowsOnaWindowsPC,thebestwaytoburntheimagetoyourSDcardistousetheWin32DiskImagerutility.Thiscanbedownloadedfromhttp://sourceforge.net/projects/win32diskimager.
NoteThecurrentversion,atthetimeofwriting,is0.9.5.
Itdoesn’thaveaninstaller,andlaunchesdirectlyfromtheEXEfile.
Now,it’stimetocreateyourSDcardimage:
1. InsertyourSDcardintothePCandlaunchtheWin32DiskImager.2. SelecttheSDcarddevicedriveletter(makesureit’sright!).3. ChoosetheRaspbianimagefileyou’vejustdownloaded.4. ClickontheWritebuttontocreatetheSDcardimage.
![Page 57: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/57.jpg)
UsingLinuxOnaLinuxPC,you’llneedtousethegpartedandddutilitiestoburntheimageonyourSDcard.
CarryoutthefollowingstepstocreateyourSDcardimage:
1. Extract2015-09-24-raspbian-jessie.imgtoyourHomefolder.2. InsertyourSDcardintothePC.3. Ifyou’renotalreadyinashellterminalwindow,openone(youcanuseCtrl+Alt+T
onmostgraphical-baseddesktopsystems).4. Typethefollowingcommandintheshellterminal:
$sudofdisk-l
Inthelistcheck,yourSDcardappearsasadrivedevice(forexample,/dev/sdb).It’scrucialthatyouensureyouusetherightdeviceinthenextstep.We’llassumethatyourdeviceis/sdb.
5. ToburntheimagetotheSDcard,typethefollowingcommand:
$sudoddif=2015-09-24-raspbian-jessie.imgof=/dev/sdb
6. HitEnterandgomakeacupofteaorcoffeeasthiswilltakeawhile.You’llknowthatit’sfinishedwhenthecommand($)promptre-appears.
7. Whenthecommandpromptdoesre-appear,typethefollowingcommand:
$sudosync
8. Oncethatcommandhasfinished,youcanremovetheSDcardfromthePC.
![Page 58: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/58.jpg)
BootingyourPiYou’renowreadytobootupyourRaspberryPi.PopyourshinynewSDcardintoitandpluginthepower.
AssumingthatyouhaveamonitorattachedtoyourPi,youshouldseeyoursystembootingupnicely.Althoughyoucouldwaitforittobootupandconnecttoitviaaterminalsession(we’lllookatthatlater),Irecommendthatyouconnectamonitortoit,atleastinthefirstinstance,justtomakesureeverythingisworkingcorrectly.
InthenewJessieversionofRaspbian,you’llbootstraightintoadesktopGUI,whichisamajorchangefrompreviousversions,whereyou’dbetakentotheraspi-configutility,thefirsttimethesystemisrun,whereyou’dsetupyourPi,andimportantly,expandthefilesystemtousetheentirespaceavailableonyourSDcard.
DebianJessiebootsintotheGUIbydefault
![Page 59: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/59.jpg)
ExpandingthefilesystemWhenyoufirstcreateyourRaspbianSDcard,you’llonlybeleftwithabout200Mbofspaceinthefilesystem,regardlessofthesizeofyourSDcard.Thisisnotmuchuse,sowewanttoexpandthefilesystemsothatitusesalloftheavailablespaceonthecard.
Fortunately,thisisveryeasyontheRaspberryPinow,asthisfunctionisavailableintheRaspberryPiConfigurationToolonthedesktop.
Toaccessthenewconfigurationtool,gotoMenuandselectPreferences|RaspberryPiConfiguration.
ThenewRaspberryPiConfigurationTool
TipGoodbyeGUI
Mostofourworkisgoingtobedoneinthecommand-lineinterface(CLI).Therefore,beforewerebootthesysteminaminute,let’schangetheBootoptionbyselectingToCLI,asshowninthepreviousscreenshot,sobootintothecommandlinegoingforward.
Anyway,nowweclickontheExpandFilesystembutton,andinacoupleofseconds,you’llseeaconfirmationmessage.Thefilesystemwillbeexpandedwhenthesystemnextreboots.
Usingtheraspi-configutilityIfyouhaveanolderversionofRaspbian,oryou’renotusingthedesktopGUI,thenyou’llneedtousetheraspi-configutility(whichisstillbetterthantheolddayswhenwehadtodothismanuallyintheshell).Thefirsttimeyoubootup,you’llbetakenstraighttothe
![Page 60: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/60.jpg)
raspi-configutility.
ThefirstoptionistheExpandFilesystemoption;selectthisandyou’llseevariouscommandsscrollingupthescreen.Onceit’sfinished,you’llseethefollowingmessage:
Rootpartitionhasbeenresized.
Thefilesystemwillbeenlargeduponthenextreboot
ClickonOK.
SelectFinishontheconfigscreenandrebootyourPiwhenprompted.
AfteryourPirebootswithitsfullerfilesystem,you’llbetakenstraighttotheshellpromptwhereyoucanloginwiththedefaultuserandpassword.
Login:pi
Password:raspberry
![Page 61: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/61.jpg)
![Page 62: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/62.jpg)
SettingupyourPiWhenyoubootintotheshellandhavetheEthernetconnected,hopefullythePiwillhaveconnectedtoyourhomenetworkandacquiredanIPaddressfromyourrouter.Ifthisisthecase,youshouldseetheIPaddressthathasbeenissuedjustbeforetheloginprompt,asshowninthefollowingscreenshot:
Asyoucanseefrommyscreenshot,it’sgivenmetheIPaddress,192.168.0.118.ThisisgoodbecauseIcannowaccessthePiremotely,usingasecureshell(SSH)clienttoconnecttoitfromthecomfortofmylaptop.ThisisparticularlyusefulwhenmyPiisintheofficeandIwanttositonmysofainfrontofthetellybutstillworkonit,whichIoftendowhenI’mfeelinglazy.
TipDownloadingtheexamplecode
Youcandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.comforallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
![Page 63: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/63.jpg)
Todothis,downloadPuTTY:autilitythatallowsyoutoconnecttoshellterminalsremotelyoverthenetwork.Youcandownloaditfromhttp://www.putty.org.
InstallandlaunchPuTTYandyou’rereadytoconnecttoyourPiremotelyfromthecomfortofyoursofa.
TypetheIPaddressoftheRaspberryPiintotheHostNameboxandclickonOpen.You’llbeconnectedtoyourPiinaremoteterminalwindow.Onceyou’veloggedin,youcandoprettymucheverythingonyourPi,asifyouweresittinginfrontofit.
![Page 64: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/64.jpg)
We’llassumefromnowonthatmostoftheworkwedowillbethrougharemoteshellsession,unlesshighlightedotherwise.
IfyouwanttousethecommandlinetolaunchtheRaspberryPiremoteshell—forexample,fromanotherLinuxsystem—usethefollowingcommandfromyourterminalwindow:
You’llthenbepromptedforthePi’spasswordandtakenintoashellsession.
ThePishellsessionlaunchedfromaDebiandesktopterminalwindow
![Page 65: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/65.jpg)
GettinguptodateSomethingthatyoushouldgetintothehabitofdoingisupdatingtheoperatingsystemregularly;eventhoughyoumayhavethelatestimageinstalled,it’sverylikelythatthereareupdatedpackagesavailable.ToupdateyourOS,enterthefollowingcommand:
$sudoapt-getupdate
Afterthis,enterthefollowingone:
$sudoapt-getdist-upgrade
Thismaytakeawhile,dependingonthenumberofupdatesrequired.
![Page 66: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/66.jpg)
GettingtherighttimeTheRaspberryPidoesn’thaveon-boardreal-timeclockhardware.Thisisoneofthedeliberateomissionstokeepthecostoftheboarddown.Instead,thePigetsitstimewhenitbootsupfromtimeserversontheInternetusingtheNetworkTimeProtocol(NTP).However,ifthereisnoInternetconnectionatthetimeofbootingup,thenthetimewillbewrong.
NoteInoursecuritysystem,it’simportantthatthetimeiskeptaccuratesothattimestampsonlogfilesandimagesarecorrect.
fake-hwclockThefake-hwclockpackageisincludedinthelatestRaspbiandistributions,butinotherpastversionsitwasn’t.Ifyouneedtoinstallit,usethecommandthatfollows:
$sudoapt-getinstallfake-hwclock
fake-hwclockisusedbytheRaspberryPitotryandkeeptimewhenthereisnonetworkconnection.Itwillregularlysavethecurrenttimeandrestoreitatboot-up.TheobviousproblemwiththisisthatifthePihasbeenswitchedoffafewdays,thenthetimewillbesettothelasttimethatitwason,usingfake-hwclock.
Ifyouwanttoseewhattimeitlastlogged,typethefollowingcommand:
$cat/etc/fake-hwclock.data
ntpTheNetworkTimeProtocol(NTP)isusedwhenthereisanInternetconnectionavailableanditcanrequestthelatestmostaccuratetimefromoneormoretimeserversontheInternet.
Bydefault,thentpserviceisenabledonthelatestRaspbiandistribution,butitwillinitiallygetitstimeatboot-upfromfake-hwclockifthereisnoInternetconnection.Theremaybetimeswhenit’snecessarytoforcethentpservicetoupdatefromtheInternet—forexample,iftheInternetconnectionisrestoredsometimeafterboot-up.
ToforcethentpservicetoupdatefromtheInternet,usethefollowingcommands:
$servicentpstop
$ntpd–gq
$servicentpstart
![Page 67: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/67.jpg)
Talkingofsecurity…There’snopointinhavingasecuritysystemifthesystemitselfisnotsecure.So,nowwe’llchangethedefaultpasswordforthepiuser.
Fromtheprompt,typethefollowingcommand:
$sudopasswdpi
pi@raspberrypi~$sudopasswdpi
EnternewUNIXpassword:
RetypenewUNIXpassword:
passwd:passwordupdatedsuccessfully
Whatisthissudothinganyway?You’dhavenoticedthatwe’vebeenputtingsudoatthestartofeachcommandthatwerunintheterminalwindow.Thisissothatcommandsarerunastherootuser—thehighestsecuritylevel.Thiselevatedsecurityisrequiredtoperformmanyoperations.sudoactuallymeanssuperdo.
Ifyoucan’tbebotheredtotypesudoeverytime,thenyoucanswitchtothesuperuserbytypingthefollowing:
$sudosu
You’llseethatthepromptchangedfroma$toa#,whichindicatesthatyouarenowrunningastherootuser.
So,thismightbeagoodtimetochangetherootuserpasswordtoo!Todothis,typethefollowing:
#passwd
root@raspberrypi:/home/pi#passwd
EnternewUNIXpassword:
RetypenewUNIXpassword:
passwd:passwordupdatedsuccessfully
root@raspberrypi:/home/pi#
![Page 68: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/68.jpg)
ConnectingviaWi-FiYoucanalsoconnectyourRaspberryPitoyournetworkusingWi-FibypluggingaUSBdongleintoit.Thereareadditionalconfigurationstepsrequiredtomakethiswork,whicharebeyondthescopeofthischapter,buttherearemanyresourcesavailablecoveringthissubject.
NoteYoucanfindrecipesforconnectingyourRaspberryPiusingWi-FiintheRaspberryPiNetworkingCookbookbyRickGolden,publishedbyPacktPublishing(https://www.packtpub.com/hardware-and-creative/raspberry-pi-networking-cookbook).
![Page 69: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/69.jpg)
![Page 70: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/70.jpg)
SummaryInthischapter,wetookourRaspberryPioutofitsboxandpreparedittobethecenterpieceofourhomesecuritysystem.Alongtheway,weinstalledandsetuptheoperatingsystem,connectedourPitothenetwork,andaccesseditremotely.WealsosecuredourPiandmadesureitcouldkeeptherighttime.
Inthenextchapter,we’regoingtoexploretheGPIOportandthevariousinterfacesitfeatures.We’lllookatthevariousthingswecanconnecttotheRaspberryPiusingtheGPIOport,includingswitchesandsensors,aswestarttobuildourhomesecuritysystem.
![Page 71: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/71.jpg)
![Page 72: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/72.jpg)
Chapter2.ConnectingThingstoYourPiwithGPIOTheRaspberryPihaslotsofwaystoconnectthingstoit,suchaspluggingthingsintotheUSBports,connectingdevicestotheon-boardcameraanddisplayports,andconnectingthingstothevariousinterfacesthatmakeuptheGPIOconnector.Aspartofourhomesecurityproject,we’llbefocusingmainlyonconnectingthingstotheGPIOconnector.
Inthischapter,wewillcoverthefollowingtopics:
ExaminingtheGPIOconnectorandwhateachofthepinsdoesLearningabouttheI2CandSPIbusesthatwillbeusedinlaterchaptersConnectinganLEDandaswitchsafelytothedatapins,andaccessingthesedatapinsusingsimplescriptsUnderstandingtheUSBportsandtheirlimitations
![Page 73: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/73.jpg)
PrerequisitesAlongwithyourRaspberryPi,you’llneedthefollowingpartsfortheprojectsinthischapter:
AbreadboardAnLEDA220ohmresistor(red,red,black)A10Kohmresistor(brown,black,orange)ApushbuttonortoggleswitchAhook-upwire:
Ourlittlecollectionofparts
![Page 74: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/74.jpg)
![Page 75: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/75.jpg)
SayhellototheGPIOTheGPIOconnectoristhelargegroupofpinsontheedgeofyourRaspberryPiboard.Onearliermodels,therewere26pinsthatmadeupthisconnector.But,eversincetheModelB+,therehavebeen40pins,althoughthefirst26pinsareidenticaltothepreviousmodels,andit’sthese26pinswe’llbeworkingwith.Youwon’tneedtoworryabouttherestofthepins.
Essentially,theGPIOconnectorprovidesaccesstofollowing:
PowersuppliesDigitalI/OpinsI2CbusSPIbusUARTSerialbus
SomeofthepinsontheGPIOhavemorethanonepurpose,dependingonhowtheyareprogrammed.ThefollowingdiagramisareferenceguidetoallofthepinsontheGPIO.TheGPIOnumbersontheyellowlabelsrelatedirectlytothoseontheBroadcomchip,andarenumbersgenerallyusedwithinthescripts.
![Page 76: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/76.jpg)
DigitalI/OpinsTheGPIOhas8digitalinput/outputpinsavailableforuse.Thesecanbeusedtoswitchthingsonandoff(inoutputmode),andalsotodetectwhenexternalthingsareswitchedonandoff(inputmode).Eachpincanbeconfiguredindependentlyforinputoroutputoperation,andIhavelabelledthemD0toD7intheprecedingdiagram.
Obviously,ifweweretouseeachofthesepinstodriveorsenseanindividualdevice,wewouldbelimitedtoamaximumof8devicesthatcouldbeconnectedtoourhomesecuritysystem.Inmanyscenarios,thisisprobablynotenough,sointhenextchapterwe’lllearnhowtousetheGPIOtoconnectmanymorethingstoourRaspberryPi.
![Page 77: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/77.jpg)
TheI2CbusTheInter-IntegratedCircuit(I2C)busisalow-speedinterfacethatcanconnectmultipledevicesandsimplesensorsusinga2-wireinterfacewithouttheneedforaseparateclockordeviceselectline.Typically,thisbuscanoperateatspeedsupto100kbit/s.We’llbecoveringthisinthenextchaptertohelpusexpandourdigitalI/Oandconnectmorethings.
![Page 78: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/78.jpg)
TheSPIbusTheSerialPeripheralInterface(SPI)busisasynchronoustwo-wayserialconnectionbetweenamasterandaslavedevice.Itcanbeusedtoaccessmorecomplexsensorsordrivedisplays.
Themasterdeviceprovidesthesynchronization,andeachtransmissionissynchronizedbyaclockpulseonSCLK(GPIO11/pin23).DataistransmittedontheMOSI(master-out-slave-in)andMISO(master-in-slave-out)(pins19and21respectively).
![Page 79: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/79.jpg)
TheUARTserialbusTheUniversalAsynchronousReceiverandTransmitter(UART)busisawaytocommunicatewithexternaldevicesoveraserialdataconnection,andisacommonwayfortheRaspberryPitoaccessdatafromdevicessuchasGPSmodules,whichoftencomewithserialconnections.ItcanbealittlebitfiddlygettingthePisetuptocommunicatewithUART-connecteddevices,asit’salsotiedinwiththeoperatingsystem’sserialconsole.
![Page 80: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/80.jpg)
USBportsWe’reprobablyallfamiliarwithUniversalSerialBus(USB)portsasweusethemtoconnectallsortsofthingstoourPCs,suchaskeyboards,mouses,andharddisks.OntheRaspberryPi,it’sjustthesame;wecanconnectkeyboards,mouses,anddonglestogiveusWi-FiandBluetoothconnectivity.
OfficialRaspberryPiUSBWi-FiDongle
OnearlierRaspberryPimodels,theamountofcurrentthattheportsdeliveredwasprettylowandcausedallsortsofproblemsiftoomuchcurrentwasdrawnbytheconnecteddevices.ThiswassignificantlyimprovedfromthemodelB+onwards,andit’snowpossibletoconnectGSM/LTEdongleswithoutanyproblems.
Therearestilllimitations,however,ifyouwanttoconnectthingssuchasharddiskdrives;thesecanstilldrawmorecurrentthanwhatcanbesuppliedbytheRaspberryPiUSBports,soit’srecommendedthatapoweredUSBhuborUSBpowerinjectorbeusedwhenconnectingthesetypesofdevicestoyourPi.
![Page 81: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/81.jpg)
PowerconnectionsTheGPIOconnectoralsoprovidesaccesstotheon-boardpowersupplies.The+5Vconnection(pins2and4)isessentiallythe+5Vinputfromtheexternalpowersupplyconnectedtothemicro-USBpowerport.Thiscanbeusedtopowersmallexternalcircuitsifnecessary,althoughitisrecommendedthatanadditionalexternal+5Vsupplybeusedifsignificantcurrentisrequired.
The+3.3Vsupply(pins1and17)istheoutputfromtheon-board3.3Vregulatorandprovidesasmallamountofcurrentupto50mA.Ifyouneedtodrawmorethan50mAforyourexternalcircuits,thenyoushoulduseanexternalpowersupply.I’llshowyouhowtobuildonelaterinthisbook.
NoteTheI/OpinsontheRaspberryPioperateat3.3Vlevels.ConnectingvoltageshigherthanthistothepinscouldirreversiblydamageyourPi.Ifyoufollowtheinstructionsinthisbook,theneverythingshouldbefine,butrandomlyconnectingthingstoyourPithatuselotsofpowerwillbreakit!
![Page 82: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/82.jpg)
![Page 83: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/83.jpg)
GettingacquaintedwiththeGPIOBeforeweembarkonconnectinglotsofthingstoourPiboard,itmightbeagoodideatojustgetacquaintedwiththeGPIOthroughacoupleofsimpleprojectsthatwillhelpusunderstandhowtointeractwiththedigitalI/Opinsusingshellscripts.
![Page 84: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/84.jpg)
LettherebelightThissimplelittleprojectshowshowtoconnectaGPIOoutputtoanLED,andswitchitonandoffusingshellcommands.
Thefollowingdiagramshowshowtoconnectupthecircuitusingabreadboard:
NoteTheprettydiagramthatyoujustsawwasproducedusingafreesoftwaretoolfromfritzing,whichisanopen-sourcehardwareinitiativetomakeelectronicsaccessibleascreativematerialforanyone.Downloaditfromfritzing.org.
TheLEDanode(thepositiveside)isconnectedtotheD0digitalI/O(pin11oftheconnectororGPIO17).Whenthispinisswitchedon,itwillprovidea3.3VsupplytotheLED.
TheLEDisconnectedtotheGroundpinviaa220Rresistoronthecathode(negativeside).TheresistorlimitsthevoltagetotheLEDandthecurrentthroughit,otherwiseitwouldburnout,asyoucanonlysupplyuptoabout2VtoLEDs.Withacurrentofaround10mAbeingdrawnbytheLEDona3.3Vsupply,a220RresistorworkswelltoprotectbothitandtheGPIO.
![Page 85: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/85.jpg)
Here’sthecircuitdiagramforit:
NoteCalculatingLEDResistorValues…
Whilethisbookisnotreallyacourseonelectronicstheory,IthoughtitwouldbehandytoshowyouhowtoworkouttheresistorvaluesforLEDsusingOhmsLaw,aswe’llbecoveringthisagainlater.
AsImentioned,atypicalLEDwilldropabout2Vacrossit,althoughthisvariesaccordingtocolorandtype.ThisiscalledtheforwardvoltageofthedeviceorVLED.
ThecurrentrequiredbyanLEDisaround10mA,againdependingonitsspecification.We’llcallthiscurrentflowingthroughtheLED,ILED.
Essentially,thevoltageacrosstheresistorwillbethesupplyvoltageminusthevoltagedropacrosstheLED(forexample,.2V).So,ifwehavea12Vsupply(VS),thevoltageacrosstheresistorwillbe10V(VS–VLED).
AccordingtoOhmsLaw,theresistanceRisthevoltageacrossitdividedbythecurrentflowingthroughit:R=V/I.Aswerequire10mAflowingthroughit,withavoltageof10Vacrossit,theresistancerequiredis10Vdividedby0.01A,whichis1,000ohmsor1K.
Insummary,R=(VS-VLED)/ILED.
Now,toturntheLEDonandoff:theGPIOpinsareactuallymappedasdevicesintheLinuxfilesystem,sousingshellcommandsiseasy,althoughtherearemanylibrariesavailableouttherethatallowyoutocontroltheGPIOusingPython,forexample.However,sothatyoudon’thavetolearnanewlanguage,we’regoingtodoeverythingusingshellcommands.
![Page 86: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/86.jpg)
TheD0pinthatweareconnectedtoisactuallyGPIO17asfarastheRaspberryPiisconcerned(takealookatthepreviousdiagramforreference).ThefirstthingweneedtodoiscreatefileaccesstothisGPIOpin.Wedothiswiththefollowingcommand:
$sudoecho17>/sys/class/gpio/export
Wethenhavetosetthepin’sdirectiontoout:
$sudoechoout>/sys/class/gpio/gpio17/direction
NextwecanswitchthepinontoturntheLEDon:
$sudoecho1>/sys/class/gpio/gpio17/value
ToswitchtheLEDoff,weusethiscommand:
$sudoecho0>/sys/class/gpio/gpio17/value
Oncewe’vefinishedwithaGPIOportwecanremoveitsfileaccess:
$sudoecho17>/sys/class/gpio/unexport
Gettingflashy…WecanputthesecommandstogetherinasingleBashscripttocreateaflashingLED.Tocreatetheflashyscript,createanewtextfileinnanoorsomeothertexteditor.Or,asIusuallydo(don’tforgetthatI’mquitelazy),createthetextfileonyourlaptop,andthencopyittotheremotePiusingWinSCP(although,readmynoteintheboxthatfollowsifyouwanttopreventsomeheartache).
Thefollowingisthecodelistingforled-flash.sh:
#!/bin/bash
sudoecho17>/sys/class/gpio/export
sudoechoout>/sys/class/gpio/gpio17/direction
#loopforever
whiletrue
do
sudoecho1>/sys/class/gpio/gpio17/value
sleep0.5
sudoecho0>/sys/class/gpio/gpio17/value
sleep0.5
done
NoteIfyouuseWindowstocreateyourfiles,remembertosaveyourfileswiththeend-of-lineformatbeingLinux(asingle0x0aorLineFeedcharacter)ratherthanWindows(0x0a+0x0dorLineFeed+CarriageReturncharacters),otherwiseyoumightfindthatyourBashscriptdoesnotrunproperlyontheRaspberryPi.TexteditorsonWindows,suchastheexcellentNotepad++,willconvertyourscriptlineendsforyou.
Runthescriptbycallingled-flash.sh(assumingthat’swhatyou’vecalledit).Ifyou’reinthesamedirectoryasthescript,thiscanbedonebytypingthefollowing:
$sudobash./led-flash.sh
![Page 87: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/87.jpg)
SincethisisanendlessloopwiththeLEDflashingonandoffathalfsecondintervals,you’llneedtobreakoutofitbyusingCTRL+Ctostopthescript.
Don’tforgettoremovetheGPIOpinfromfileaccessbyusingthefollowingcommand:
$sudoecho17>/sys/class/gpio/unexport
Otherwise,you’llseetheerror,echo:writeerror:Deviceorresourcebusy,ifyoure-runthescript,asthefirstlinetriestosetGPIO17forfileaccessagain.
![Page 88: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/88.jpg)
AddingaswitchInthisproject,we’llseehowtoconnectaswitchtoaGPIOinputandwriteashellscripttoreadthestateoftheswitch—thatis,whetherit’sswitchedonoroff.
ConnectaswitchtoyourPi’sGPIO27pin,asshowninthefollowingdiagram:
PullingyourselftogetherAreallyimportantthingtorealizeaboutGPIOinputsisthattheyareinwhat’scalledafloatingstate.Thismeansthat,asfarastheoperatingsystemisconcerned,itdoesn’tknowwhatitsreferencestateisunlessitispresentedwithaknownvoltage.
Thisiswhereourresistorcomesintoplay—itpullsuptheGPIOpintoaknownvoltageof3.3V,whichgivesitadefaultstateofHIGH(orbinary1).
Whenthepushbuttonswitchispressed,thistakestheGPIOpinto0V,whichisaLOWstate(orbinary0).
Here’sthecircuitdiagramforourGPIOswitch:
![Page 89: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/89.jpg)
ThedetectionscriptNowthatwe’veconnectedtheswitchtoourRaspberryPi,weneedtowritealittlescriptthatwilldetectwhentheswitchhasbeenpushed.
It’ssimilartothepreviousLEDscriptshown,butthistimewe’llsettheGPIOpinasaninputandreaditslogiclevel.
Inthisproject,we’veconnectedourswitchtoD2,whichisGPIO27(again,refertotheearlierGPIOpin-outdiagram).Asbefore,weneedtocreatefileaccessforthepinbyenteringthefollowingcommand:
$sudoecho27>/sys/class/gpio/export
Andnow,setitsdirectiontoin:
$sudoechoin>/sys/class/gpio/gpio27/direction
We’renowreadytoreaditsvalue,andwecandothiswiththefollowingcommand:
![Page 90: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/90.jpg)
$sudocat/sys/class/gpio/gpio17/value
You’llnoticethatitwillhavereturned1,orahighstate.Thisisbecauseofthepull-upresistorweweretalkingaboutearlier.Thismeansthatitsdefaultstate,whentheswitchisn’tpushed,ishigh.
Whentheswitchispushed,thevalueshouldbereadas0orlow.Ifyouhavemorethantwohands,youcantrythisbypushingthebuttonandre-runningthecommand.Or,wecanjustcreateascripttopolltheswitchstate.
Thecodelistingforpoll-switch.shisasfollows:
#!/bin/bash
sudoecho27>/sys/class/gpio/export
sudoechoin>/sys/class/gpio/gpio27/direction
#loopforever
whiletrue
do
#readtheswitchstate
SWITCH=$(sudocat/sys/class/gpio/gpio27/value)
if[$SWITCH==1];then
#switchnotpushedsowaitforasecond
sleep1
else
#switchwaspushed
echo"You'vepushedmybutton"
fi
done
Whenyourunthescriptandthenpushthebutton,youshouldseeYou'vepushedmybuttonscrollinguptheconsolescreenuntilyoustoppressingit.
Don’tforgetthat,oncewe’vefinishedwiththeGPIOport,wecanremoveitsfileaccess:
$sudoecho27>/sys/class/gpio/unexport
We’venowseenhowtoeasilyreadaswitchinput,andthesamecircuitandscriptcanbeusedtoreadothersensors,suchasdoorcontactswitches,reedswitches,oranythingelsethathasanonandoffstate.
![Page 91: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/91.jpg)
![Page 92: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/92.jpg)
ThemostelaboratelightswitchintheworldBycombiningthetwolittleprojectsearlier,wecannowcreateasystemthatwilldosomethingusefulwhenthepushbuttonswitchispushed—forexample,switchingontheLEDthatwealsohaveconnected.Granted,wecouldjustconnecttheLEDdirectlytotheswitchandabattery,butnotonlywouldthatbeboring,itwoulddefeatthepointofwhatwe’retryingtodo,whichisprogrammaticallysensingandcontrollingthings.
Here’sthebreadboardlayoutforourelaboratelightswitch:
Andhere’sthecircuitdiagram:
![Page 93: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/93.jpg)
![Page 94: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/94.jpg)
TheilluminatingscriptOurfullBashscriptforourelaboratelightswitchisdemonstratednext.Thiswillloopendlessly,detectingthestateoftheswitchGPIOpin,andwillturnontheLEDGPIOpinwhentheswitchispushed.
Thecodelistingforlight-switch.shisasfollows:
#!/bin/bash
#setuptheLEDGPIOpin
sudoecho17>/sys/class/gpio/export
sudoechoout>/sys/class/gpio/gpio17/direction
#setuptheswitchGPIOpin
sudoecho27>/sys/class/gpio/export
sudoechoin>/sys/class/gpio/gpio27/direction
#loopforever
whiletrue
do
#readtheswitchstate
SWITCH=$(sudocat/sys/class/gpio/gpio27/value)
#0=Pushed1=NotPushed
if[$SWITCH="1"]
then
#switchnotpushedsoturnoffLEDpin
sudoecho0>/sys/class/gpio/gpio17/value
else
#switchwaspushedsoturnonLEDpin
sudoecho1>/sys/class/gpio/gpio17/value
fi
#shortdelay
sleep0.5
done
So,hereweare—wehaveascriptthatwilldetectaninputstateanddosomethinginresponse;inthiscase,itwillswitchonanLED.We’renowformingthebasisofhowwearegoingtoputtogetherourhomesecuritysystem.
NoteRemember,don’tconnectanythingtoyourRaspberryPiinplaceoftheLED,suchasabuzzeroranyotherdevicethatconsumeslotsofcurrent.Thisislikelytoirreversiblyrenderyourboarddead.We’lllookatways,lateroninthisbook,tocontroldeviceswithhigherpowerrequirements.
![Page 95: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/95.jpg)
![Page 96: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/96.jpg)
SummaryInthischapter,weintroducedvariouswaystoconnectyourRaspberryPitotheoutsideworldbylookingatthevariousinterfacesavailableontheGPIO.We’veunderstoodhowtoconnectthingstothedigitalpinsonyourRaspberryPi’sGPIOconnector,andcontrolandreadthemusingsimpleBashscripts.Inparticular,we’vesafelyandproperlyconnectedaswitchtoadigitalinputpin,whichwillformthefoundationforourhomesecuritydetectioncircuits.
Inthenextchapter,we’lllookatwaystoexpandthenumberofthingswecanconnecttoourRaspberryPi,overcomingthelimitationofhavingjustthe8digitalpinsavailabletousontheGPIObytappingintootherinterfacesontheGPIOandbuildingourowninput/outputexpansionboard.
![Page 97: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/97.jpg)
![Page 98: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/98.jpg)
Chapter3.ExtendingYourPitoConnectMoreThingsWe’renowgoingtolookatwaystoexpandthenumberofthingswecanconnecttoourRaspberryPi,overcomingthelimitationofhavingjustthe8digitalpinsavailable.We’regoingtodothisbybuildingourownexpansionboardtogiveuswhatcouldintheorybeanunlimitednumberofdigitalinputsandoutputs.
We’realsogoingtoovercomethelimitationsofthe+3.3Vpoweravailabletousbybuildingourown+3.3VpowersupplythattapsofftheRaspberryPi’s+5Vsupply.
Inthischapter,wewillcoverthefollowing:
LookingattheI2CbusindetailLearningaboutserial-to-parallelandparallel-to-serialconversionsBuildinga+3.3VpowersupplyBuildinganI2C-basedportexpandertogiveusmoreinputsandoutputsLookingatalternativeready-madeexpansionboards
![Page 99: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/99.jpg)
PrerequisitesAlongwithyourRaspberryPi,you’llneedthefollowingpartsfortheprojectsinthischapter:
Acopperstripboard(orVeroboard®)AnLD1117V33voltageregulatorA2x100nF,16VceramiccapacitorA10uF,16VelectrolyticcapacitorA1xMCP2301716-bitportexpanderICA4x10K-ohmresistorAhook-upwire
![Page 100: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/100.jpg)
![Page 101: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/101.jpg)
TheI2CbusInthepreviouschapter,webrieflytouchedontheI2Cbus(orInter-IntegratedCircuitbus),whichisawaytoconnectmultipledevicestogetherusingjusttwowires.I2Cwasinventedintheearly1980sbyPhilipsasawaytolinkcomputerperipheralstogetherusingacommonprotocol.YoucanthinkofI2CasakindofearlyformofUSB.
I2Ctypicallyoperatesatrelativelylowspeedsofupto100kbit/s,comparedtomuchfasterinterfacessuchasEthernet,whichtypicallyoperatesatupto1Gbit/s,orUSB,whichcanoperateatupto480Mbit/s.However,thisisfastenoughtoconnectbasicsensors,displaydevices,orotherperipheralssuchasreal-timeclocks—infact;therearefasterversionsoftheprotocolthatsomedeviceswillsupport.
![Page 102: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/102.jpg)
Just2wiresI2Cisabi-directionalserialcommunicationprotocolthatoperatesovertwowires:
TheSerialDataLine(SDA)wiretransmitsthedatatoandfromthemasterdevice.ReferringbacktotheGPIOreferenceinChapter2,ConnectingThingstoYourPiwithGPIO,thisispin3oftheGPIOconnector.TheSerialClockLine(SCL)wirehandlesalltimingandflowcontrolforthedataonthebus.Thisispin5oftheGPIOconnector.
You’llrememberthatwespokeaboutpull-upresistors,inthepreviouschapter,whichensurethattheGPIOdigitalinputsarepulledtoaknownstate.Well,thisisrequiredforthetwolinesontheI2Cbus,andbydefaultthelinesshouldbepulledhighwithresistors.However,ontheRaspberryPi,thishasalreadybeendoneforus,sowedon’tneedtoworryaboutitinourcase.
![Page 103: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/103.jpg)
What’syouraddress?So,ifwecanusejusttwowirestocommunicatewithmultipledevices,howdoesourRaspberryPiknowwhichdevicetotalkto?ThisiswheretheI2Cprotocolcomesintoitsown.EachdeviceconnectedtothebushasitsownuniqueID,oraddress,madeupof7-bitsor10-bits.Somedeviceswillallowyoutosettheaddresstoensurethatit’suniquewithinyoursystem,butotherdeviceshavetheiraddresseshardcodedbythemanufacturer.
Thetwoaddressingmethods(7-and10-bit)areinteroperableandyoucanhavedevicesonthesamebusthatuseeithermethod,sincetheRaspberryPiitselfsupportsbothmethods.So,witha10-bitaddressingscheme,youcanseethatwecanconnectalotofthingstoourRaspberryPiusingtheI2Cbus,ascomparedtothelimitednumberofdigitalpinsontheGPIO!
![Page 104: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/104.jpg)
ThereisaparalleluniverseDataisnormallytransmittedinserialmodeorparallelmode,dependingonthingssuchastherequireddataspeed,cabledistance,andfunctionality.Mostdatacommunicationbetweensystemsistransmittedinserialmodeoveracoupleofwires,suchastheI2Cbusmentionedearlier,butthisalsoincludesthingssuchastheEthernet,RS232/422,andUSB.
Withinacomputersystem,dataistransmittedinparallelmodeusingbuseswhosewidthmatchesthewordsizeofthedigitalsystemcommunicatingbetweenchips.Inparallelmode,allbitsofthedatawordaretransmittedsimultaneouslyovertheirrespectivedatalineswithinthebus,ratherthanassequentialbitsalongasingleline.
ThedigitalI/Opinswe’vebeentalkingabout(includingtheonesontheRaspberryPi’sGPIOconnector)areusuallygroupedtogetherasaparallelbus.Onoursystem,we’llbeusingparallelbuses(groupsofdigitalI/Opins)thatare8-bitswide.Thatis,thebushas8wiresthatcanbesetorreadusing8-bitbinaryvalues(ourwordsize).
Arepresentationofan8-bitdatabus
So,intheprecedingdiagramwehavethe8digitalI/Owiresonourbus.Ifwewantedtomakethebits(orwires)0,1,and4highoron,withtherestloworoff,thenwe’daddressthebusandsetittothefollowingvalues:
Inbinary,thiswouldbe00010011Inhex,thiswouldbe0x13Indecimal,thiswouldbe19(representedby16+2+1)
So,inotherwords,toswitchondatalines0,1,and4,wesendthebytevalue,19,tothebus’saddress.
Serial-to-parallelconversion
![Page 105: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/105.jpg)
So,nowthatweknowwhatnumberstosendtoourbustoswitchonorswitchoffcertaindigitaloutputs,orreadcertaindigitalinputs,howdowedothisusingourI2Cbus,whichisaserialinterface?
Fortunately,therearemanyintegratedcircuits(ICs)availablethatallowustodothissimplyandeasily.TheseICsarecalledshiftregistersandperformserial-to-parallelconversions,takingthedatafromtheserialI2Cbusandconvertingtheincomingbitstoaparallelrepresentationbysettingeachoftheparallelbusoutputs.
Whenreadingtheparallelbusdatalinesasinputs,thereversehappens,convertingthebitsintoaserialformontheI2Cbus;thisisknownasparallel-to-serialconversion.
Thisisquiteasimplisticoverviewandtherearemanyresourcesavailablethatexplaintheseoperations;we’llseethisinactionlaterinthechapter,butfirst…
![Page 106: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/106.jpg)
![Page 107: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/107.jpg)
GivemepowerYou’llrememberfromthepreviouschapterthatmostthingstodowiththeGPIOoperateona+3.3Vlevel,ratherthanthe+5Vlevelthatisoftenassociatedwithdigitalcircuits.ThisisthesamewithourI2C-basedshiftregisters—theyneedtooperateon+3.3Vlevelsaswell,inordertoworkwiththeRaspberryPi.
You’llalsorecall,however,thatthere’snotmuch+3.3VjuiceavailabledirectlyfromtheRaspberryPi—infact,just50mA.Thisisreallynotenoughforourinterface.So,beforewegoanyfurther,we’regoingtobuildourown+3.3Vpowersupply,whichissufficientforoursystem.
Forourpowersupply,we’regoingtouseabasic3.3Vvoltageregulator(typeLD1117V33)thatwilltakeourslightlymoreplentiful+5VsupplyfromtheRaspberryPiandregulateittoanicesmooth+3.3Vsupply.Weshouldbeabletodrawafewhundredmilliampsfromthissupply—enoughfortheI/Ocircuitryonoursecuritysystem.
Thepartsrequiredforourpowersupplyareasfollows:
ALD1117V33voltageregulatorA100nF,16VceramiccapacitorA10uF,16Velectrolyticcapacitor
Here’sthecircuitdiagramforour+3.3Vpowersupply:
Aswithallourcomponents,theLD1117V33regulatoriswidelyavailablefrommanyelectroniccomponentsuppliers.
![Page 108: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/108.jpg)
Ourpowersupplycanbeeasilybuiltonasmallpieceofstripboardlikethis:
NoteThestripboardisshownfromthetopintheprecedinglayout.Thatis,thecoppertracksareontheundersideoftheboardandthecomponentsareinsertedfromtheplaintop-sideandsolderedtothestripsunderneath.Inthislayout,it’snotnecessarytocutanyofthetracksonthestripboard.
![Page 109: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/109.jpg)
![Page 110: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/110.jpg)
BuildinganI2CexpanderRight,nowthatwe’veworkedoutwhatweneedtodotogiveusmoredigitalI/Opins,andbuiltourpowersupplyforit,wecanbuildourexpansionport.
Todothis,we’regoingtouseachipdesignedexactlyforthejob:theMCP23017,manufacturedbyMicrochipandwidelyavailablefromelectronicsuppliers.
TheMCP23017isanintegratedcircuitthatconnectsdirectlytotheI2Cbus(theSDAandSCLpinswetalkedaboutearlier)andgivesus16bi-directionalinputandoutputpins.Ifrequired,wecanconnectupto8ofthesechipstothesamebus,givingusupto128inputsandoutputs(yes,IknowthatIsaid“virtuallyunlimited”previously,butI’llexplainlater).
AnMCP23017integratedcircuitpinout
NoteThefulldatasheetfortheMCP23017isavailableonMicrochip’ssite,whichcanbefoundatwww.microchip.com/MCP23017.
![Page 111: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/111.jpg)
TheI2CportexpandercircuitThebasicpartsyouwillneedtobuildyourportexpanderareasfollows:
A1xMCP2301716-bitportexpanderICA4x10K-ohmresistorA1x100nF,16VceramiccapacitorAcopperstripboard(orVeroboard®)Ahook-upwire
Here’sthecircuitdiagramforourI2Cportexpandercircuit.Itlookscomplicated,butactuallymostofthelinesareforconnectionstotheoutsideworld:
Let’swalkthroughthecircuitOntheright-handside,theconnector,CN1,isourRaspberryPiGPIOconnector—notethatwe’reonlyusingfourofthepins:
The+5VOutput(Pin2)TheI2CSDA(Pin3)TheI2CSCL(Pin5)The0V/GND(Pin6)
You’llseemyfriend,the+3.3Vregulator(U1,C1,andC2),discussedearlier.Thistakesthe+5VoutputfromtheRaspberryPiandgivesusour+3.3Vforusebytherestofthecircuit.
ThemaincomponentisU2—ourMCP23017portexpanderchip.Pins9and10onthe
![Page 112: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/112.jpg)
chipareconnectedtothe+3.3VsupplyandtheGND,respectively,andC3isusedasadiscouplingcapacitorclosetothechiptoreduceanynoiseonthepowersupply.
TheMCP23017canbeusedasa16-bitexpander,oras2x8-bitexpanders.Inourcircuit,wehavesplitthedevicetogiveus2x8-bitbusses:I/OBusAandI/OBusB.Eachpinonthebussescanbeprogrammedtoworkasaninputoroutput.
TipConnectingthingstotheinput/outputpins
Theinputandoutputpinsonourbussescan’tusuallybeconnectedtothingsdirectly—theyprovidelimitedcurrentandneedtobeinterfacedcorrectlytothingssuchasbuzzersandlights;theymustalsobeprotectedagainstdamaginginputsignals.Inthenextchapter,we’lllearnhowtoconnectsafelytoourI/Oports.
TheI2CSDA/SCLlinesfromtheRaspberryPiareconnectedtopins12and13ofthechip.You’llseethattherearealsoadditionalI2Coutputs(PL1toPL3)toillustratethatwecanconnectotherdevicestotheI2Cbus,suchasanotherMCP23017chiptogiveusafurther16digitalI/Os.
ResistorR1isusedtoholdtheRESETpin(18)high.Bybringingthispinlow,youcanresetthechip.
ResistorsR2toR4areusedtoholdtheaddresspinsA0toA2(pins15-17)low.
Highsandlows
Whenweusethetermshighandlowinrespecttodigitalpinsorinputs,wearesimplydescribingwhetherthelogiclevelofthepinisatabinary1or0,respectively.Digitalpinsdon’tliketobeleftfloating—wherebytheyareneitherhighnorlow—asthiscancauseunpredictableoperations.Therefore,wealwaysmakesuretheyareheldatadeterminedlogiclevel.Ingeneral,connectingthepinto0V(orground)ensuresthatit’sheldatlogiclevel0,andconnectingtothepositivesupply(e.g.3.3V)ensuresthatit’sheldatlogiclevel1.
RememberImentionedearlierthatyoucanconnectalargenumberofdevicestotheI2CbusinordertogiveusavirtuallyunlimitednumberofI/Opins?Well,actuallyinmanycases,thisisnotstrictlytrue.ThisisbecauseoftheaddressingschemeforI2Cdevices,whichmakesalldevicesidentifiablewhentheyareallconnectedtothesametwowires(theiruniqueaddress).Theaddressofeachdeviceisagreeduponinadvancebymanufacturerstomakesurethateveryone’sdeviceswillworktogetheronthesamebuswithoutcreatingconflicts.Assuch,theaddressispre-programmedintothedevice.
TheMCP23017hasbeengivenitsuniquebaseaddress,butcanbemodifiedbychangingtheaddresspinsA0-A2highorlow;thus,ineffect,itcanbeconfiguredtobeoneof8addresses.Thisiswhyyoucanonlyhaveamaximumof8ofthesechipsonthesameI2Cbus,givingusatheoreticalmaximumof128I/Opins(thatis,16I/Osx8chips).
![Page 113: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/113.jpg)
BuildingyourexpansionboardThiscircuitcaneasilybebuiltonasmallpieceofstripboard.Thefollowingimageshowsanexampleofthelayout,whichlooksabitsimplerthanthecircuitdiagram.Inthenextchapter,we’lllearnhowtoconnectupourboardandprogramitsowecancheckthatitworks.
TipWhenusingstripboard,makesurethatyoucutthetracksbetweenthetworowsofpinsontheMCP23017sothattheyaren’tshortedtogether.Youcanbuytrackcutters,whichmakethistaskeasy,frommanyelectronicsuppliers.Again,ontheprecedinglayout,thecopperstripsareunderneaththeboardwiththecomponentsontheplainside.
Youmightwanttoaddthe+3.3Vpowersupplycircuittothesamepieceofstripboardtoo,tokeepeverythingcontainedtogether.
NoteInthenextchapter,wewilllearnhowtoprogramthedevicesothatwecanuseitinourhomesecuritysystem.
![Page 114: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/114.jpg)
![Page 115: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/115.jpg)
Usingready-madeexpansionboardsWhileit’smuchmoresatisfyingtobuildyourownstuff,youmightwanttolookatbuyingsomereadilyavailableexpansionboardsforyourhomesecuritysystemifyou’renotyetconfidentwithyoursolderingiron,orifyoujustsimplydon’thavethetime.
Followingaresomeready-madeexpansionboardsthatyoucanobtain;theyshouldworkaspartofourhomesecuritysystemwithabitofmodificationtoourscriptstosupportthelibrariesthatarerequiredbythehardware.
![Page 116: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/116.jpg)
HobbytronicsMCP23017expanderportkitThiskitisalmostidenticaltoourowncircuitintheprevioussectionofthischapter.ThekitcomeswithanMCP23017,aPCB,andvariousconnectors.Theboardsaredesignedtobedaisy-chainedtogethersothatyoucanhavemultipleexpanderstogiveyoumoreinput/outputports.Notethatthiskitisnotpre-builtandrequiressoldering,butIthoughtI’dincludeitbecauseit’stheboardthatIusetobuildsuchsystemswhenprototyping.YoucangetitdirectlyfromHobbytronicsathttp://bit.ly/mcp23017.
![Page 117: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/117.jpg)
PiFaceDigitalI/OexpansionboardThePiFaceDigitalI/Oexpansionboardisapre-builtversionofourboard,butitusestheMSP23S17chipvariantthatoperatesovertheSPIbusinsteadoftheI2Cbus.Theboardisdesignedwith8inputsand8outputs,aswellasseveraladditionalpiecesofhardwareincludingacoupleofrelays,someLEDs,andsomeswitches.Notethatthecodeinthisbookforoursystemwillneedtobemodifiedtoworkwiththisboard,sinceitusesadifferentinterfaceanddifferentlibraries.It’savailablefromFarnellelement14athttp://bit.ly/2434230.
ThePiFaceDigitalI/OExpansionBoard
![Page 118: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/118.jpg)
GertboardTheGertboardisaRaspberryPiadd-onboarddesignedbyGertvanLoo—oneofthehardwareengineersinvolvedintheoriginaldesignoftheRaspberryPi.
It’saverycapableandreasonably-pricedboardthatcomesfullyassembledandfeatures12bufferedinput/outputlines,opencollectordriversforswitchingondevicesthatneedafairbitofcurrent(suchassoundersandlights),plusadigital-to-analogconverter.
YoucanonlyconnectoneoftheseboardstoyourRaspberryPi,soifyouneedmoreI/Olinesyou’llneedtousesomethingelseaswell.Butit’sagreatboardtoexperimentwith.Interestingly,itfeaturesanATmegamicrocontroller,whichisthesameastheonethattheArduinouses,andyoucan,infact,usetheArduinodevelopmentenvironmentforthedevice.
Onceagain,thecodeinthisbookforoursystemwillneedtobemodifiedtoworkwiththisboard.
TheGertboardisavailablefromFarnellelement14athttp://bit.ly/2250034.
AssembledGertboard
![Page 119: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/119.jpg)
![Page 120: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/120.jpg)
SummaryWe’venowlookedattheI2Cbusindetail,andlearnedhowtobuildanexpansionportusingthisinterfacesothatwecanconnectmanymorethingstoourRaspberryPi,ratherthanbeingrestrictedtojustthe8digitalI/OpinsofferedbytheRaspberryPi’sGPIOport.Inadditiontothat,weexploredotherready-madeboardsthatcanbeusedtoconnectlotsofthingstoourRaspberryPi.Wehavealsobuiltapowersupplythatwillgiveusmore+3.3VpowerthanwecanobtainfromtheRaspberryPidirectly.
Inthenextchapter,we’llstarttoactuallyconnectthingstoourhomesecuritysystem,suchasmagneticsensorsandothertypesofcontactdevices,andlearnhowtoprogramourI2CexpansionportusingBashscriptssothatwecanreadthestateofoursensorsandswitchonwarningLEDs.We’llalsostartdevelopingthecontrolscriptsforoursystem,whichwillallowustoarmanddisarmthesystemandadddelaytimers.
![Page 121: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/121.jpg)
![Page 122: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/122.jpg)
Chapter4.AddingaMagneticContactSensorNowthatwehavebuiltourportexpanderhardware,weneedtolearnhowtoprogramitsothatourRaspberryPicandetectthethingsthatweconnecttoitaspartofourhomesecuritysystem.Wewillbeginbyconnectingswitchestooursystemintheformofmagneticsensors—themostcommoncomponentusedinhomesecuritysystemstodetectintrusionsthroughdoorsandwindows.
Inthischapterwewillcoverthefollowingtopics:
LearningaboutreedswitchesandhowtheyworkasdoorsensorsEnablingandsettinguptheI2CbusontheRaspberryPiConnectingoursensortoaninputonourportexpanderLearninghowtoaccessourI2CportexpanderfromaBashscriptWritingascriptthatwilldetectthestateofourdoorsensorLookingatothertypesofcontactsensorsthatcanbeconnectedandprogrammedinthesameway
![Page 123: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/123.jpg)
PrerequisitesYou’llneedthefollowingpartsfortheexercisesinthischapter:
OurRaspberryPiandPortExpanderboard8x10KohmresistorsAmagneticdoorsensorandmagnetAhook-upwireA4-corealarmwire
![Page 124: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/124.jpg)
![Page 125: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/125.jpg)
TheworkingofmagneticcontactsensorsAreedswitchisessentiallywhatmakesupourmagneticcontactsensor.Areedswitchcomprisestwometalcontactsmadeofmagneticmaterial(calledreeds)placedinsideaglassenvelope.Whenthecontactstouch,theswitchison,andwhentheyspringapart,theswitchisoffandthecircuitisbroken.Thewaytocontrolthesecontactsisbymeansofamagneticfieldthatmakesorbreaksthecircuitwhenitisneartotheswitch.
Anormallyopen(NO)typeofreedswitchisnormallyswitchedoffuntilamagnetcomesclosetotheswitch,whichthenpullsthecontactstogether.
Anormallyclosed(NC)varietyworkstheotherwaywiththeswitchbeingnormallyonuntilthemagnetcomesclosetotheswitch,pullingthetwocontactsapart.
Atypicaltypeofreedswitch
Youcannowseehowamagneticreedswitchcanbeausefulsensorinsecurityapplications,andinparticularforourhomesecuritysystem,todetectwhendoorsandwindowsareopenedandclosed.Wesimplyputareedswitchonthedoorframeandconnectittooursecuritysystem,withthemagnetplacedoppositetheswitchontheactualdoor.Whenthedooropensandcloses,itmakesorbreaksthecontactsinourreedswitch.
Reedswitchesandtheirmagnets,whicharedesignedforsecuritysystems,usuallycomeenclosedinlittleplastichousings,makingthemeasytoscrewontothedoorandframe.
![Page 126: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/126.jpg)
Adoor-frame-mountedmagneticsensorcontainingareedswitch(Type:CherryMP201801)
Themagneticsensorismountedonthedoorframe(obviously,soitcanconnecttothealarmcircuitwires),whiletherespectivemagnetwillbeattachedtothedoor,closeenoughtotheedgesuchthatthesensorcontactsconnect(orbreak,dependingonthetype)whenthemagnetisdirectlyoppositeit.
Arespectivedoor-mountedmagneticactuator(Type:CherryAS201801)
![Page 127: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/127.jpg)
![Page 128: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/128.jpg)
SettinguptheI2CportexpanderNowthatwehavebuiltourportexpander,weneedtogetitreadytoconnectoursensorsto.First,weneedtoinstallthetoolsontheRaspberryPitoallowustousetheI2Cbusandprogramdevicesconnectedtoit,includingtheMCP23017chipthatmakesupourportexpander.
NoteDon’tconnectyourportexpandertotheRaspberryPiuntilafteryou’vesetuptheI2Cbusonyoursystem.
![Page 129: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/129.jpg)
EnablingtheI2CBusIt’shighlylikelythatthemoduleforusingtheI2Cbushasn’tbeenloadedbydefault.Fortunately,doingthisisfairlystraightforwardandcanbedoneusingtheRaspberryPiconfigurationtool.Performthefollowingsteps:
1. LaunchtheRaspberryPiconfigurationtoolwiththefollowingcommand:
$sudoraspi-config
2. Selectoption8:AdvancedOptions.
![Page 130: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/130.jpg)
3. SelectOptionA7:I2C.
4. Select<Yes>.5. RebootyourRaspberryPiforthesettingtotakeeffect.
NowthattheI2Cbushasbeenenabled,weneedtosetuptheoperatingsystemsothattherequiredmodulesareloadedeachtimethesystemboots.Todothis,performthefollowingsteps:
1. EdittheModulesfileusingthefollowingline:
$sudonano/etc/modules
2. Addthefollowinglinestothefile:
i2c-bcm2708
i2c-dev
3. SavethefileandexitNano.
![Page 131: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/131.jpg)
InstallingtheI2CtoolspackageSothatwecaneasilyaccesstheI2CbususingBashscripts,weneedtoinstallthei2c-toolspackage:
$sudoapt-getinstalli2c-tools
Onceinstalled,weshouldshutdownoursystem:
sudoshutdown–hnow
Afteractivityhasstopped,switchoffyourRaspberryPi,connectyourportexpandertotheGPIOport,andpoweritbackupsothatwecanstartusingit.
Asaquicksanitycheck,youcanseeifI2Csupporthasbeenloadedbytyping:
$ls/dev/i2c-*
Thisshouldgiveyoualistofatleastonebus—forexample,/dev/i2c-1—ifthemoduleisloaded.Ifit’snot,you’llprobablygetthefollowingresponse:
ls:cannotaccess/dev/i2c-*:Nosuchfileordirectory
Inthiscase,you’llneedtocheckbackthroughthepreviousstepsassomethinghasn’thappenedproperly.
![Page 132: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/132.jpg)
FindingourdevicesThei2c-toolspackageinstallsseveraldifferenttoolstohelpususeourportexpanderattachedtothebus.Thei2cdetecttoolallowsustofindI2Cbusesanddevicesattachedtothebusses.
TogetalistofI2Cbussesonoursystem,typethefollowing:
$sudoi2cdetect-l
Youshouldgetthefollowingresponse:
pi@raspberrypi~$sudoi2cdetect-l
i2c-1i2c20804000.i2cI2Cadapter
TheprecedingoutputshowsthatwehaveoneI2Cbus,andthiswillbetheoneconnectedtoourGPIO.NotethatearliermodelsoftheRaspberryPimayreturnthedeviceIDasbeingi2c-0.
Wecannowusethetooltoscanforallofthedevicesattachedtoourbus.WedothisbyspecifyingthebusID,asinthefollowingcommand:
$sudoi2cdetect1
WithnothingattachedtotheI2Cbus(thatis,withoutourportexpanderattached)we’dexpecttoseethefollowingoutput:
pi@raspberrypi~$sudoi2cdetect1
WARNING!ThisprogramcanconfuseyourI2Cbus,causedatalossandworse!
Iwillprobefile/dev/i2c-1.
Iwillprobeaddressrange0x03-0x77.
Continue?[Y/n]Y
0123456789abcdef
00:—--—--—--—--—--—----
10:—--—--—--—--—--—--—--—--
20:—--—--—--—--—--—--—--—--
30:—--—--—--—--—--—--—--—--
40:—--—--—--—--—--—--—--—--
50:—--—--—--—--—--—--—--—--
60:—--—--—--—--—--—--—--—--
70:—--—--—--—--
pi@raspberrypi~$
NothingfoundontheI2Cbus
Withourportexpanderattached,weshouldseethefollowingoutput:
pi@raspberrypi~$i2cdetect1
WARNING!ThisprogramcanconfuseyourI2Cbus,causedatalossandworse!
Iwillprobefile/dev/i2c-1.
Iwillprobeaddressrange0x03-0x77.
Continue?[Y/n]Y
0123456789abcdef
00:—--—--—--—--—--—----
10:—--—--—--—--—--—--—--—--
![Page 133: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/133.jpg)
20:20—--—--—--—--—--—--—----
30:—--—--—--—--—--—--—--—--
40:—--—--—--—--—--—--—--—--
50:—--—--—--—--—--—--—--—--
60:—--—--—--—--—--—--—--—--
70:—--—--—--—--
pi@raspberrypi~$
OurI2Cportexpanderslavedevicecanbefoundattheaddress,0x20(32decimal).
NoteTheprecedingaddressisthelocationofourMCP23017chipconnectedtotheI2Cbus.Ifyoudon’tseethis,thenthere’sprobablyawiringissueandyou’llneedtogobackandcheck.
You’llrecallthatwecanaddupto8ofthesedevicestotheI2CbusbysettingtheA0-A2pinstoauniqueaddress.IfA0issettohigh,thentheaddressofthedevicewillbeshownas0x21(33decimal)—andupto0x27(39decimal),ifallpinsarehigh.
![Page 134: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/134.jpg)
SettinguptheportexpanderAsdiscussedinthepreviouschapter,wecanhave2x8-bitbussesonourportexpander,witheachpinbeingdefinedasaninputoroutput.Ontheexpanderboardwebuilt,wecalledthemI/OBUSAandI/OBUSB.
ToconfiguretheMCP23017chipontheI2Cbus,wecansendittheappropriatecommandsusingthei2csettoolweinstalledearlier.
Onourhomesecuritysystem,wearegoingtoassignallofthepinsonBUSAasinputsforconnectingoursensorstoit.Todothis,weusethefollowingcommand:
$sudoi2cset–y10x200x000xFF
NoteWhatdoesthiscommandmean?
-y:Thisrunsthecommandwithoutuserinteraction.1:ThisistheIDofthebus(forexample,i2c-1).0x20:Thisistheaddressofthechip.0x00:Thisisthedataregisteronthechip(inthiscase,thePORTApinassignment).0xFF:ThisistheValueloadedintothedataregister(inthiscase,allpinsasinputs—binary%11111111).
Youcancheckthatthedataregisterhasbeensetcorrectlybyreadingitusingthefollowing:
$sudoi2cget–y10x200x00
Thisshouldreturnavalueof0xFF,whichisthevaluewesetearlier.
![Page 135: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/135.jpg)
![Page 136: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/136.jpg)
ConnectingourmagneticcontactsensorNowthatwe’vegotourportexpanderworkingwiththeRaspberryPi,wecanstartconnectingthingstoitandcreatethescriptsthatwillmonitorthesensorsontheinputpins.
Let’sgobacktoourportexpanderstripboardthatwasbuiltinthepreviouschapterandconnectourmagneticsensor.Butfirst,weneedtoensurethatallofourinputsarepulledlowbydefaultusing10Kohmresistors.Thispreventsthemfrombeinginafloatingstateandgivingusspuriousdatawhenwereadtheport’sdata.
NoteInthefollowingdiagram,I’veconnectedthepull-downresistorsexternally,butyoumaywanttoincludethemdirectlyonthestripboard.Towardtheendofthisbook,we’llhaveanewboardlayoutthatbringseverythingthatwe’vebeenprototypingsofartogetherinasinglesolution.
Tochecktheport’sinputvalue,weusethei2cgetcommand:
$sudoi2cget–y10x200x12
Thisshouldreturn0x00,whichmeansallinputsareoff(binary%00000000).
NoteWhatdoesthiscommandmean?
-y:Thisrunsthecommandwithoutuserinteraction.1:ThisistheIDofthebus(forexamplei2c-1).0x20:Thisistheaddressofthechip.0x12:Thisisthedataregisteronthechip(inthiscase,thePORTAreadvalue).
Nowlet’sconnectonesideofourmagneticsensor’sreedswitchtodatapin0ofBUSA(whichwe’llcallGPA0forreference),andtheothersidetoour+3.3Vline.Bydefault,theswitchisnormallyopen(NO),whichmeansthattheinputisstillpulledlowbytheresistor.
Butwhenyoumovetheaccompanyingmagnetneartothesensorswitch(forexample,ifthedoorisclosed),theswitchwillclose,pullingtheinputhightothe+3.3Vline.Ifyoureadtheport’sinputvaluenow,byrunningthesamecommand,youshouldseethatitreturns0x01,indicatingthatthefirstbitishigh(binary%00000001).
![Page 137: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/137.jpg)
![Page 138: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/138.jpg)
![Page 139: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/139.jpg)
MonitoringthesensorNowthatwehaveeverythinginplaceandourmagneticsensorisdetectingwhetherthedoorisclosed,wecanmonitorthissensorwithasimpleBashscriptthatusestheI2Ctoolcommandsthatweinstalledearlier.
Thecodelistingforpoll-magnetic-switch.shisasfollows:
#!/bin/bash
sudoi2cset–y10x200x000xFF
#loopforever
whiletrue
do
#readthesensorstate
SWITCH=$(sudoi2cget–y10x200x12)
if[$SWITCH=="0x01"]
then
#contactclosedsowaitforasecond
echo"Thedoorisclosed!"
sleep1
else
#contactwasopened
echo"Thedoorisopen!"
fi
done
Whenyourunthescriptandthenpushthebutton,youshouldsee“Thedoorisopen!”scrollinguptheconsolescreenuntilyoustoppressingit.
Bycombiningthiswithourelaboratelightswitchprojectinchapter2,wecanswitchontheLEDconnectedtoGPIO17whenthedoorisopened:
#!/bin/bash
#setuptheLEDGPIOpin
sudoecho17>/sys/class/gpio/export
sudoechoout>/sys/class/gpio/gpio17/direction
#setupportexpander
sudoi2cset–y10x200x000xFF
#loopforever
whiletrue
do
#readthesensorstate
SWITCH=$(sudoi2cget–y10x200x12)
if[$SWITCH=="0x01"]
then
#switchnotpushedsoturnoffLEDpin
sudoecho0>/sys/class/gpio/gpio17/value
else
![Page 140: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/140.jpg)
#switchwaspushedsoturnonLEDpin
sudoecho1>/sys/class/gpio/gpio17/value
fi
#shortdelay
sleep0.5
done
NoteLater,asweaddmoresensorstodifferentinputpins,wewillneedtobeabletodetectwhichonehasbeentriggered.We’lllookatwritingaBashfunctionlaterinthebook,whichwillparsethereturnedhexvaluefromthei2cgetcommand,andtellusexactlywhichofthe8inputsishigh.
![Page 141: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/141.jpg)
![Page 142: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/142.jpg)
Anti-tampercircuitsIfyoutakeacloserlookatoursystem,youmightrealizethatdependingonwhetheryouaredetectingnormallyopenornormallyclosedsensorswitches,itispossibletotamperwiththesensorchannelbysimplycuttingthewire.So,inthecaseofanormallyopenswitch,itwouldn’tactivatethemonitoringsystemifthewireswerecut,asitwouldalwaysappeartobeopen,eveniftheswitchwasclosed.
Tomitigatethis,mostalarmsystemsfeaturea4-corewiringsystemtoconnectthesensordevicestothemaincontrolboard—twocoresareusedtoconnectthesensorandtwoareusedtocreateananti-tamperloop,whichthenitselfformsasensorinputformonitoring.
4-corealarmcable
TakealookatthefollowingcircuitsothatyouseewhatImean:
![Page 143: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/143.jpg)
Inthiscircuit,wehavetwosensors:oneformonitoringawindowandoneformonitoringadoor.TheseareconnectedtotheI/OBUSAinputs,0and1(orGPA0andGPA1,asweliketocallthem).Asbefore,theyarepulleddownto0Vbyresistorsbut,whenswitchesareclosed,thepositivevoltagerailtakestheinputshigh.
However,we’vealsoaddedananti-tamperloopthroughoutthewholesystem,whichisconnectedtoGPA7formonitoring.Theloopisdaisy-chainedthrougheachofthecablesconnectingthesensorstothecontrollerboard.Allthetimetheloopisintact,theinputGPA7iskepthigh,butifthecableiscutanywhere,thecurrentwillstopflowingthroughitandtheresistor,R3,willpulltheinputlow.Thiswillthenbedetectedbythemonitoringscript.
Manysecuritysensorproductsprovideafacilitytoterminateanti-tamperloopwireswithinthem.
So,inourhomesecuritysystem,we’regoingtoassignGPA7asouranti-tamperloop.
![Page 144: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/144.jpg)
![Page 145: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/145.jpg)
GettingintothezoneItmayhaveoccurredtoyoubynowthatevenamodest-sizedpropertycouldrequireplentyofdoorandwindowsensors;thus,ifweusedoneinputforeachsensor,we’dsoonrunoutunlessweputmoreandmoreportexpandersontothesystem.Thesameistrueforcommerciallyavailablesecuritysystems.
So,thewaythisisdealtwithisbycreatingzones,witheachzonecontainingagroupofsensors.Abedroom,forexample,maybedefinedasonezonewithawindowsensor,adoorsensor,andmovementdetectorformingthatzone.Inthisscenario,eachsensorisconnectedtothenextinaseries(ordaisy-chained);ifoneofthemtriggers,itwillalertthemonitoringsystemthattherewasatriggerinthezone.Obviously,though,itmaynotnecessarilybetheactualdetector,whichinmostapplicationsisn’treallyanissue.
However,thiscanintroducesomechallengeswhenwe’reconsideringmixingnormallyopenandnormallyclosedtypesensorswithinazone,butthisissomethingwewillexplorelateroninthisbook.
Theothersensorsyoucanusearelistedasfollows:
HallEffectSensor:Hall-effectsensorsaresimpleelectronicchipsthatareusedtodetectmagneticfieldsplacednearthem.Theyarenotdissimilartothereedswitchwe’vebeenusing;however,becausetheyareelectronicdevices,theyareabletomeasurethedegreeofproximityinrelationtothemagnet(orthestrengthofmagnetism),ratherthanbeingjustonoroff,asisthecasewiththereedswitch.Also,becausetheyaresolid-state,theycouldbeseenasbeingmorereliablethanmechanicalswitches.
Alow-costhalleffectsensor—AllegroMicrosystemsA1302KUA-T
PressureMatSensors:Pressurematsareusedtodetectapersonstandingorwalkingonthem,andcanbeplacedunderafloormattohidethemfromsight.Theycanevenbeusedinachairtodetectpeoplesittingonit.Essentially,theyareswitches,justlikethereedswitch,exceptthattheyareactivatedbythepressureofwalkingonthem,andso,canbewiredandusedinexactlythesamewayasforourmagneticsensorcircuits.
![Page 146: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/146.jpg)
Apressureswitchcanbeusedunderafront-doormat
![Page 147: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/147.jpg)
![Page 148: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/148.jpg)
SummaryInthischapter,wegotourI2C-basedportexpanderconfiguredandworking,andweexperimentedwithitbyconnectingamagneticsensor—oneofthemostcommonlyusedsensorsinsecuritysystems.We’vealsolearnedhowtointeractwithI2CdevicesusingBashscripts,andhowtoreadandwritedatatoandfromthesedevices.
Inaddition,weshouldnowbebeginningtounderstandthevariouselementsandbuildingblocksofasecuritysystem,includinganti-tamperloopsandzones.Theseareconceptsthatwillprepareusforlateroninthebook,whenwestarttopieceallofthistogetherandbuildourfinal,all-encompassingsystem.
Inthenextchapter,wewilllookatpassiveinfra-redmotiondetectors,howtheywork,andhowwecanconnectthewiredandwirelesstypestoourhomesecuritysystem.We’llalsolearnhowtocreatelogfilesbasedoneventsusingBashscriptssothatwecanmaintainahistoryofdetectorstatesastheychange.
![Page 149: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/149.jpg)
![Page 150: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/150.jpg)
Chapter5.AddingaPassiveInfraredMotionSensorInthepreviouschapter,westartedaddingbasicbutcommonlyusedmagneticswitchsensorstoourhomesecuritysystemandreadingtheirstatustoprotectdoorsandwindowsfromintrusion.Wealsolookedathowwecandivideourhomeintozones,suchasbyindividualrooms,sothatwecangroupoursensorsintologicalcircuits,whichcanthenbeidentifiedaspartofthesezonesratherthanasindividualsensorinputs.
WewillnowaddmotionsensorstooursystemintheformofPassiveInfra-Red(PIR)detectors.Thesedetectorscomeinavarietyoftypes,andyoumayhaveseenthemlurkinginthecornersofrooms.Fundamentally,theyallworkinthesameway,whichisdetectingthepresenceofbodyheatwithinacertainrange;so,theyarecommonlyusedtotriggeralarmsystemswhensomebody(orsomething,suchasapetcat)entersaroom.
AtypicalPIRmotionsensor(typeGardScanQX-PIR)
Inthischapter,wewill:
LearnhowPIRdetectorsworkandhowtheyaresetupConnectawiredPIRdetectortoaninputonourportexpanderStartusinga12Vpowersupplyinsteadof3.3VinourzonecircuitsLearnhowtointerface12VcircuitssafelywithourGPIOportsLearnhowtoconnecta433MHzwirelessreceivertoourRaspberryPiConnectaremote-controlledswitchtooursystemusing433MHzradiosignalsWriteascriptthatwilldetectandlogthestateofourdetectorinputswhenitchanges
![Page 151: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/151.jpg)
PrerequisitesYou’llneedthefollowingpartsforthischapter(apartfromthecomponentsusedinthepreviouschapter):
Apassiveinfrareddetector,thewiredtype(thisisavailablefromanyDIYstore)A4N25/4N35opto-isolatorA1N4148diodeA1-KohmresistorA10-KohmresistorA433MHzreceivermoduleandremotetransmitter(thisisoptional)A12VpowersupplyAhook-upwireA6corealarmwire
![Page 152: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/152.jpg)
![Page 153: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/153.jpg)
PassiveinfraredsensorsexplainedYoumightnotrealizeit,butallobjectsradiateheatenergy(includingyourcoffeetable);it’sjustthatyoucan’tseeitbecauseheatconsistsessentiallyofinfraredwaves,whichareinvisibletothehumaneye(exactlythesameasyourTVremotecontrol).Thesewavescan,however,bedetectedbyelectronicdevicesdesignedforsuchapurpose,suchastheinfraredreceiverinyourTVthatdetectstheenergyemittedbyyourremotecontrolwhenthebuttonsarepressed.
Youprobablydorealize,however,thatlivingthingssuchasus,ourcat,andthemouseunderthefloorboardsgeneratequiteabitofheat.Passiveinfraredmotionsensorsusedinsecuritysystemsandautomaticlightsaredesignedtodetectthislevelofheat.Thetermpassiveisusedbecausethesensorsthemselvesdonotradiateanyenergyfordetectionpurposes—instead,theyjustdetecttheinfraredradiationemittedbyobjects.Thisisnotablydifferentfromdevicessuchasultrasonicsensorsandradars,whichrelyondetectingreflectionsfromobjectsofthepulsesofenergythatthesensorssendout.
PIRsensorsneedtobealittlesmartbecausetheyeffectivelyhavetocopewithconstantlyvaryingtemperaturesintheroom.Theysettleonthebackgroundtemperatureoftheroomtheyarein,suchasthatofawallorfloorthattheypointto.Whenanobject,suchasoneofusorourcat,movesbetweenthedetectorunitandthebackgroundobject,thetemperatureinfrontofthesensorrisestothebodytemperaturequickly,andthisinturntriggersthesystem.
![Page 154: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/154.jpg)
SettingupyourPIRsensorPIRsensordevicescomeinmanyformats,includingdifferentmaterialsinsensorchipsandthelensinfrontofthesensorviewwindowthatcanwidelyaffecttherange,fieldofview,andsensitivityofthedevice.Therefore,yourbestguidetosettingupasensorwillusuallybeinthatlittlebitofinstructionpaperthatcomeswithit.
However,regardlessofthetypeofPIRsensoryouhave,herearesomegeneralguidelineswhenconsideringwhereyoumountyoursensorinordertoavoidfalsetriggers:
EnsurethatthedeviceismountedonasolidfoundationandnotaffectedbyvibrationNevermountitinalocationwheredirectorreflectedsunlightcanbepickedupbythelensSimilarly,nevermountthedevicefacingoraboveheatsourcesDon’tmounttheunitindraughtylocationsasthiswillaffectitsbackgroundtemperaturecalibration
Thelocationoftheunitalsodependsontheareayouwanttoprotect.Youmaywanttodetectpeopleenteringyourlivingroomfromthehallway,soyourcoverageareacouldbedefinedasbeingfromthecorneroftheroomwherethedeviceismountedtothelivingroomdoor.
PIRsensorsusuallyofferafixedfieldofview(forexample90or110degrees)buthaveavaryingrange,dependingontheangleatwhichtheyarepointingdownandtheheightatwhichtheyarelocated.
Inmysystem,IwilluseaGardscanQXPIRDetectorformywiredunits,whichisaprettygood,low-costunitavailablefromRSComponents(theordercodeis493-1289).Thisunithasafieldviewof110degreesandarangeofupto12meters,dependingontheconfigurabledownanglethatit’smountedat.Thecoveragepatternsforthisparticularunit,astakenfromitsdatasheet,areshowninthefollowingfigure.Notethatfromthesepatternsnoteverypartoftheareainfrontofthedeviceiscovered,whichispossiblynotquitewhatyouexpect.Thisiswhypositioningtheunitsinaccordancewiththedevice’sdatasheetissoimportant.
![Page 155: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/155.jpg)
GardScanQX-PIRcoveragepatternforits110degreefieldview(top/planview)
Hereisadiagramofthesideviewaswell:
![Page 156: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/156.jpg)
GardScanQX-PIRcoveragepatterndependingontheangleconfiguredplusa“look-down”window(sideview)
![Page 157: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/157.jpg)
![Page 158: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/158.jpg)
Givemepower(again)Beforewecangoontoconnectoff-the-shelfsecuritydevicestoouralarmsystem,weneedtohaveapowersupplythat’scompatiblewithsuchdevices.Typically,alarmcircuitsandtheirdevicesusea12Vsupplywithenoughcurrenttodriveallthedevicesandthealarmcontrolsystemitself.
Fortunately,thisisnottoodifficulttosortout,butitissomethingweneedtodonow;otherwise,wewon’tbeabletoconnectandpowerourPIRsensors.Theeasiestwaytodothisistobuyahigh-quality12Vmainsadapterthatprovidesaniceregulatedsupply.Thesearereadilyavailablefromonlinestoresorelectronicssuppliers.Alternatively,youcanbuildyourown12VregulatedsupplyandaddittothepowersupplystripboardthatwebuiltinChapter3,ExtendingYourPitoConnectMoreThings.
NoteAnotheroptionistousebattery-poweredPIRsensors,whichmeansthatyouwouldn’thavetopowertheunitfromthesecuritysystem’spanelitself;however,itobviouslyalsomeansthatthebatterieswouldneedreplacingfromtimetotime.ThewirelessPIRwewilllookatlaterinthischapterisbattery-powered.
We’lltakealookathandlinghigher-voltagesensorcircuitslateroninthischaptersothatwedon’tblowupourhomesecuritycontrolcircuitsortheRaspberryPi.
![Page 159: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/159.jpg)
![Page 160: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/160.jpg)
ConnectingourPIRmotionsensorCommerciallyavailablealarmsystemsconnecttotheirdevicesusinga4coreor6corealarmcable.Inthepreviouschapter,weuseda4corecablebecausewewereconnectingaswitchthatneededtwowiresplusanantitamperloop,whichneededanothertwowires.
ForourPIRsensorcircuit,weneedthesamefourwires;however,wealsoneedtosendpowertothedevicefromthecontrolpanel,soanadditionaltwowiresareneededforthis—hencetherequirementfora6corecable.
ThefollowingdiagramshowsthewiringconnectionsformyGardScanPIRsensor,butthisisinfacttypicalformostoff-the-shelfsecuritysystemdevices:
Typicalconnectionsforsecuritysystemsensordevices
Similartothemagneticcontactsensorsthatwelookedatinthepreviouschapter,devicescancomewitheitheranormallyclosed(NC)oranormallyopen(NO)alarm.Thisparticulardevicehasanormallyclosedoutput,whichmeansthatthealarmcircuitwillbebrokenwhenthedetectoristriggered.Thisisthepreferredconfigurationforoursensordevicesasthismeansthattheycanbewiredinaserieswithineachofourzones.
Wecannowaddthissensordeviceintothealarmcircuitthatwestartedputtingtogetherinthepreviouschapter.Thefollowingdiagramshowsthecircuitforalloursensorssofarwiredintoasinglezone:
![Page 161: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/161.jpg)
Aschematicforourzonewithallthreesensorsplustamperloopinthesamezone
Upuntilnow,weusedthe+3.3Vpowersupplytopassthroughthesensorswitchesandalarmcircuit.Infact,thisisnotagoodidea,andwe’vebeendoingthisonlyforconveniencetotestoutourGPIOinputs.
Inreality,andinourfinalsystem,wereallyshouldusea12Vsupplytopassthroughthesensorandantitampercircuits.Thisisbecauseahighervoltagetravelsbetterthroughthesystemandislesssusceptibletonoise,whichcouldpreventtriggeringorcausefalsetriggering.Thisalsomakesitcompatiblewithcommerciallyavailablesystemsandaccessories.
![Page 162: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/162.jpg)
![Page 163: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/163.jpg)
12ValarmzonecircuitsMakingourzonecircuitsuse12Vinsteadof3.3Visassimpleaschangingthepowersupply,andinfactallofsensorsweusedsofarcanhandle12Vpowerpassedthroughtheirswitches.
However,ifweweretopresentthe12VcircuittotheinputsonourGPIOportontheRaspberryPiorourportexpander,wewouldexpecttoseesomemagicsmokeandsmellsomethingburning.So,weneedtoaddsomecircuitrythatallowsustouse12Valarmcircuitsaswellasprotectourcontrolboardinputs.
![Page 164: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/164.jpg)
AlarmcircuitprotectionAneffectivewaytoprotectourzoneinputsfrom12Valarminputsistousealittlelow-costdevicecalledanopto-isolator.Asthenamesuggests,thisisolatesthealarmcircuitfromthedigitalinputsofthecontrolboardusinglight.
Insideanopto-isolator(alsocalledanopto-coupler)isaninfraredLED,whichtransmitslighttoaphoto-transistorwhenacurrentispassedthroughit,thusswitchingiton.Thecircuitsareelectricallyisolatedastheyarecontrolledonlybylight.
The4N25(shownintheprecedingimage)and4N35arelow-cost,6-pinopto-couplerdevices,andmostmanufacturestendtousethepinlayoutshowninthefollowingdiagram:
![Page 165: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/165.jpg)
Nowthatweknowhowwewillcoupleour12Valarmcircuitwiththeinputsonourcontrolpanel,let’sbuildtheentirecircuit,whichwe’lluseforeachofthezonesthatweaddtooursystem.
A12VzonecircuitopticallyisolatedfromtheGPIOinput
![Page 166: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/166.jpg)
HowitworksAtthistime,we’reassumingthatourzonecircuitsarenormallyclosed—thatis,thealarmtriggerswhenthecircuitisbroken.
The12VsupplyispassedthroughtheLEDoftheopto-isolatorwiththecurrentbeinglimitedbythe1-Kohmresistor.The1N4148diode,inreverse,istheretoprotecttheopto-couplerfromreverse-polarityvoltages.
NoteThe1-Kohmresistoriscalculatedfromthefactthatwehavea12Vsupplyandaforwardvoltagedrop(Vf)of1.2VacrosstheLEDwithacurrent(If)ofabout10mA.
Whilethealarmcircuitisclosed,thecurrentflows,andtheLEDison.ThiskeepsthetransistoronandtheinputtotheGPIOportisheldlow.Ifthealarmcircuitisbroken,theopto-couplerLEDswitchesoff,andthisinturnswitchesoffthetransistor.TheGPIOinputisthenpulledhighbythe10-Kohmresistor.
Thisisquitesimplebuteffective,eh?
Theotheradvantageofthiscircuitisthatitshouldfailpositive—thatis,iftheopto-couplershouldfailforanyreason,thealarminputontheGPIOportshouldbepulledhigh,thustriggeringitratherthanitjustfailingsilently.
![Page 167: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/167.jpg)
![Page 168: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/168.jpg)
WirelessPIRmotionsensorsWirelessmotionsensorsarenowcommonlyavailableatalowcost,allowingthemtobeinstalledpracticallyanywherewithoutanywiringfromthealarmcontrolpanel.Someofthemstillrequireanexternalpowersupply,butmanyoperateonbatteries.Thealarmsystemmustcontainawirelessreceivercompatiblewiththewirelesssensor.
Inthissection,we’lltakealookathowwecanuseourRaspberryPi-basedsecuritysystemwithwirelessreceiverdevices.
![Page 169: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/169.jpg)
433-MHzwirelessalarmsystemsWirelesssystemsuseanunlicensedradiofrequencytocommunicatebetweenthevariouscomponentsofanalarmsystem.IntheUK,thetwomostpopularfrequenciesusedare433MHzand868MHz.Whilethemorerecentsystemsnowusethe868-MHzfrequency,433MHzisstillinwidespreaduseasithasaslightlylongerrangethanan868-MHzsystem.However,the433-MHzbandisalsousedbymanyotherdevices,whichmakesitcongested,whereas868MHzisgenerallyusedonlyforalarmsystems.
Whilewirelesssecuritysystemscanbeconvenient,it’simportanttounderstandtheadvantagesanddisadvantagesofusingwirelessratherthanwiredsystems.
Theadvantagesareasfollows:
TheireaseandspeedofinstallationTheireaseofremoval,whichmeansthatyoucantakethemanywherewithyouExpandingthesysteminthefuturecanbeeasier,withmostsystemsautomaticallydetectingnewunits
Thedisadvantagesareasfollows:
Theyaremoreexpensivethanwiredsystems,sometimesthreeorfourtimesthecostTheyarenotassecureaswiredsystemsandcannotachieveasecuritygradinggreaterthantwoinaccordancewithEuropeanStandardBSEN50131(although,thisgradeissuitablefordomesticproperties)WirelessdevicesneedtohavetheirbatteriesreplacedatregularintervalsWirelesssystemsarelessreliableandsusceptibletointerferenceandevenradiojamming
![Page 170: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/170.jpg)
Connectinga433-MHzreceiverInthepast,itwaspossibletorolloutyourown433-MHzreceiverfortheRaspberryPiusinganinexpensivereceiver,suchastheXY-MV-5Vmodulealongwiththe433-UtillibrarythatwasputtogetherbyaguycalledMarkWolfe,acontributoronGitHub.Essentially,hegatheredtogethercoderelatingto433-MHzcommunicationsandputitallintothislibrary.OriginallydevelopedforArduino,thishasnowbeenportedtotheRaspberryPi.
Youcanthenuseareadilyavailabletransmitter,suchasakeyfoboranyother433-MHztransmitter,andtakealookattheincomingcodeasyoupresseachbuttononthetransmitter.
AXY-MK-5VGeneric433-MHzreceivermodule
Findingasuitable433-MHzreceivershouldbeeasyaswebsitessuchasAmazonandeBayareawashwiththem,andtheycostaslittleasacoupleofpounds.
NoteNotethatthe433-MHzbandisafreeformanytypesofdevices.Assuch,therearevariousdifferenttypesofreceiver,andalthoughtheymayallstatethattheyare433-MHzreceivers,theycanoperateusingAMorFM,andsomeonlydetectcertaintypesofdata.Some,suchastheQuasarQAMrange,mayalsorequirespecialdecoderchipsinordertoreadtransmitteddataandmayonlyworkwithpairedtransmitters.
Thereceivermodulecanpickupsignalsfromakeyfobremotecontrol,suchastheoneshowninthefollowingimage(thiscanbepickedupfromthehomesecuritysectionofanylocalDIYstore),whichgetsanoutputasaseriesofsquarewaves.Thesesquarewavesarethendecodedbythe433-Utilsoftware.
![Page 171: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/171.jpg)
ANovar/Blyss433MHzwirelessremotecontrol
IlikedthisparticularremotecontrolbecauseIthoughtitwouldbegoodasthearmanddisarmdeviceforourhomesecuritysystem.IwilltalkaboutarminganddisarminginChapter8,AMiscellanyofThings,wherewewilllookatthewaystoachievethis.
Thealternativeapproach(becausewehavenochoice)Istartedofftheprevioussectionwiththewords“Inthepast…”.Thisisbecauseinrecenttimes,I’venotbeenabletogetthe433-Utilsoftwareworkingwithreceivermodules,whichusedtoworkinthepast).I’mnotentirelysurewhythisisso;however,Icanonlyguessthatbecausethesoftwareuses“bitbanging”todecodeincomingdatasignals,thetimingisnolongercorrect,perhapsbecauselaterRaspberryPiboardsarefasterandthereforemessuptheroutines.
NoteWhatisbitbanging?
Bitbangingisawayofusingsoftwareforserialcommunicationinsteadofdedicatedhardware.Thesoftwareisresponsibleforalltheparametersofthesignal,includingtiming,levels,andsynchronization.Bitbangingcanbeseenasabitofahack,butitdoesallowtheimplementationofdifferentprotocolsataverylowcostwithoutanyhardwarechanges.
So,inordertomakeourliveseasier(andactuallymakethedeviceworkonallflavorsofPi),wewillresorttousingadedicatedreceivermodulethatyoucanpickupforlessthan
![Page 172: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/172.jpg)
£5onAmazonanddoesn’trequireallthissoftwarebitbangingnonsense.You’llnoticefromthefollowingimagethatitstillusesasimilarXY-MK-5Vradioreceiver;it’sjustthatthehostboarddecodesthesignalsforusandswitchesarelayonoroffinresponsetoacommandfromtheremotecontrol.
NoteIfyou’restillinterestedinthe433-Utilsoftwareprojectandwanttotryandrolloutyourownreceiver,youcanfindtheoriginalprojectathttps://github.com/ninjablocks/433Utils.
AHielectransmitterfobandreceivermodule,availableonAmazon
Thefactthatitjustswitchesarelayonandoffmeansthatwecaneasilyimplementthisinourhomesecuritysystembecauseitsimplyactsasaswitch.Whenyoupressthebuttononthetransmitter,therelayswitchesthecontactson;pressitagain,andtherelayswitchesoff.Thescrewterminalsontheboardprovideuswithaccesstotherelayterminals.
![Page 173: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/173.jpg)
ThereceiverwiringdiagramAswearejustdealingwithaswitchinput,wecanusethesamecircuitaswedidwiththezonecircuitearlierbutconnectedtoourarm/disarmGPIOinput,whichwe’lldetermineinChapter9,PuttingItAllTogether.
CircuittointerfacethereceivermodulewithaGPIOinput
Whenthereceivermoduleswitchestherelayon,thiswillcompletethe12Vcircuitthroughtheopto-coupler’sLEDbyturningiton.ThiswillmakethetransistorpulltheGPIOpindowntoground,givingitalowinput.
Youcanusethistypeofcircuitforanypairedreceiverforthewirelesssecuritydevicesthatyouwanttouseinyoursystem.
![Page 174: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/174.jpg)
![Page 175: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/175.jpg)
LoggingdetectiondataWithanysystem,it’susefultobeabletologdatawhensomethinghappens.Wecandothiswithourdetectorstoobywritingtoalogfileeverytimeadetectorinazoneistriggered.Thisway,youcankeepalogofeverytimesomeoneentersaroom,whichyoucanreviewatalaterdateevenifthesystemisn’tarmed.Youcanalsokeepalogofwhenthesystemisarmedanddisarmed.
Here’sasimplescriptthatshowsyouhowtodothiswheneveraneventhappensonourzonesconnectedtotheGPIOinputs:
#!/bin/bash
#setuptheI2Cexpansionport
sudoi2cset–y10x200x000xFF
#resetstatus
CURR_STATE="0x00"
LAST_STATE="0x00"
#pathtothelogfile
LOG_FILE="/etc/pi-alarm/zones.log"
#loopforever
whiletrue
do
#readthegpioinputs
CURR_STATE=$(sudoi2cget–y10x200x12)
#checkifstatehaschanged
if["$CURR_STATE"!="$LAST_STATE"]
then
#writechangetologfile
TIMESTAMP=`date"+%Y-%m-%d%H:%M:%S"`
echo"$TIMESTAMPZoneStatusChangedfrom$LAST_STATEto$CURR_STATE"
>$LOG_FILE
fi
$LAST_STATE=$CURR_STATE
sleep1
done
Theprecedingexampleisquitesimple,butitcanbemademoreusefulbyactuallywritingoutthezoneorzonesthatchangebydecodingthehexvaluethat’sreturnedbythei2cgetcommandintheconstituentzones.
NoteInChapter9,PuttingItAllTogether,you’lllearnhowthisisdoneinordertodisplaytheindividualstatusofeachzoneonawebpage.Youcanuseexactlythesametechniquetodothisforyourlogfilesand,infact,outputtothelogfilebyexpandingonthesamescript.
![Page 176: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/176.jpg)
![Page 177: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/177.jpg)
SummaryInthischapter,westartedoffbylearninghowpassiveinfraredsensorsareusedtodetectmotiontoprotectapredefinedcoverageareafromintrusion.Wethenlookedatconnectingthesetotheinputsonourportexpanderviaopto-couplersaswewillnowuse12Vtopowerthealarmzonecircuits.
Wethenlookedatwirelessalarmsystemsthatoperateontheopen433-MHzband,whichiscommonlyusedforsecuritydevices.Afterexploringthepossibilityofusingthelegacy433-Utilbit-bangingsoftwareonourRaspberryPitodecodethesignalstransmittedbydevicesusingasimplereceiver,weoptedtouseapairedreceiverdevicethatwillinterfaceeasilywithouralarmcircuitinputs.
Finally,wecreatedasimplescriptthatwilllogthechangesinouralarminputstoatextfile,whichcanlaterbeexpandedtologexactlywhat’sgoingonwiththesystemindetail.
![Page 178: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/178.jpg)
![Page 179: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/179.jpg)
Chapter6.AddingCamerastoOurSecuritySystemUntilnow,we’vebeenputtingtogethertheelementsthatwillallowustoconnectsensorstoouralarmsystemtodetectintrusionsusingeitherswitchesorpassiveinfra-redmotiondetectors,whichinturnwilltellourRaspberryPithatsomethinghashappenedinaparticularzone.Theseelementswillallcometogetherasawholesystemlaterinthisbook.
Oursystemisnowgoingtobecomeawholelotmoresophisticatedwiththeadditionofcamerastotakepicturesandvideoclips,ande-mailthemtousstraightawaywhenitdetectssomething.
We’llalsousee-mailtosendusalertsonoursmartphonewhenwe’reoutandaboutwhenanyofthesensorsinthesystemaretriggered.
Inthischapterwewillcoverthefollowingtopics:
SettinguptheRaspberryPicameramoduleandlearninghowtocapturestillsandvideoimagesLearninghowtooverlaycapturedimageswithtextandtime-stampsTriggeringimagecaptureswithamotiondetectorE-mailingtheimageandvideofilestousinrealtimeUnderstandingthedifferencesbetweencapturingimagesduringthedayandduringthenightSwitchingonandoffsecuritylightingandotherhigh-currentdeviceswhenrequiredConnectingaUSBwebcaminsteadofthenativecameramodule
![Page 180: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/180.jpg)
PrerequisitesYou’llneedthefollowingpartsforthischapter,ontopofthecomponentsusedinthepreviouschapter:
ARaspberryPistandardcameramoduleARaspberryPiNoIRcameramoduleAnInfra-RedLEDarrayand/orvisibleLEDarrayAUSBwebcam
![Page 181: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/181.jpg)
![Page 182: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/182.jpg)
TheRaspberryPicameramoduleTheRaspberryPiCameraModuleisanofficialRaspberryPiaccessorythatworkswithallmodelsofthePi,andcanbeusedtotakehigh-definitionstillsandvideoimages.ItconnectsdirectlytothePiboard’scameraserialinterface(CSI)port,whichisdedicatedtothesemodulestoenablehigh-speedoperation.
Thecameraitselfisa5megapixelfixed-focussensorsupporting1080p,720p,andVGAvideomodesandstillcaptures.
TheofficialRaspberryPiCameraModule
Youcanalsoobtainhousingsforthecameramodules,which,unlessyou’regoingtobuildyourownenclosureforthecamerasystem,Irecommendyouuse.
![Page 183: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/183.jpg)
RaspberryPicamerahousingscomeinvariouscolorsandstyles
![Page 184: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/184.jpg)
ConnectingthecameramoduleAspreviouslymentioned,themoduleconnectsdirectlytotheRaspberryPiboardviaitsdedicatedcamerainterfaces,asshowninthefollowingimage.Whenconnectingthecamera,thecontactsideoftheribboncableistowardtheHDMIconnectorandthebluesideofthecableistowardthenetworkconnector.
![Page 185: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/185.jpg)
![Page 186: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/186.jpg)
Connectthecameramoduletothededicatedinterface
Asyoucanseeinthefollowingimage,theribbonconnectorisnotthatlong,sothecameraneedstobelocatedclosetotheRaspberryPi.Byusingacameraenclosure,youcouldactuallymountthecameradirectlyontopoftheRaspberryPicaseitself,ifthatworksforyou.
Thecameramodule,housedwithinanenclosure
![Page 187: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/187.jpg)
SettingupthecameramoduleBeforewecanusethecameramodule,weneedtoenablecamerasupportontheRaspberryPi.Todothis,weusetheraspi-configtool,aswedidwiththeI2Cbusearlierinourjourney.
1. ConnecttoyourRaspberryPithelazywayfromyoursofausingSSH,ordirectlyusingakeyboardandmonitor.
2. Onceyou’veloggedin,launchtheconfigtoolwiththefollowingcommand:
$sudoraspi-config
3. Andthen,select5EnableCamera.
4. You’llthenbeaskedtoconfirmwhetheryouwanttoenablecamerasupport.
![Page 188: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/188.jpg)
5. Select<Enable>.6. Then,selectFinishandrebootyourPitoenablethecamerasettings.
TestingthecameramoduleOnceyourRaspberryPihasrebooted,yourcamerashouldbeenabled.Wecantestthisbytakingastillimageusingtheraspistillutility:
$raspistill–v-otest.img
Thiswilldelayfor5secondsthentakeapicture,whiledisplayingvariouspiecesofinformation,suchasthatshowninthefollowingscreenshot:
![Page 189: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/189.jpg)
NoteThecameramoduleneedsatleast128MBofGPUmemorytooperateproperlyonRaspian.Ifyouexperienceanyissues,firstensurethatthethegpu_memsettinginthe/boot/config.txtconfigurationfileissettoatleast128.
Andifallgoeswell,youshouldfindthefile,test.jpg,inyourhomefolder.Asyou’reconnectedviatheshell,youwouldn’thaveseenthe5secondpreviewimagedisplayedwhenthecommandwasrunning.
IfyoudownloadtheimagefiletoyourPC,youshouldseeanicequalitysnaptakenbythecameramodule.
![Page 190: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/190.jpg)
ThetestphototakenbytheRaspberryPiCameraModule
TipIfyoufindthatraspistilloutputserrorswhenyourunit,ensurethatitisconnectedproperlyatbothendsoftheribboncable.Oneothercatchisthatsometimestheribbonthatconnectstheactualcameralenscomponenttothetinyconnectoronthecameraboardcancomeloose.Justensurethatthisissecurelyconnectedtoo.I’vehadthisissueacoupletimesafterthecameramoduleshavebeentakenoutofmyboxofrandomtestbitstobeused.
Theraspistillutilityhasloadsofoptionsformanipulatingtheimagesitcaptures,andwe’llusesomeofthemabitlaterinourcapturescript.Inthemeantime,toseetheavailableoptions,runraspistillwithoutanyoptionsandtheywillbelisted:
$raspistill
![Page 191: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/191.jpg)
![Page 192: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/192.jpg)
BeavideostarNowthatweknowourcameramoduleisworking,wecantryandcapturesomevideo.Todothis,we’llusetheraspividutility.Thefollowingcommandwilltake5secondsofhigh-definitionvideoandsavethefiletoyourRaspberryPi:
$raspivid–otest.h264–t5000
You’llnoticethatfileiscalledtest.h264—thisisbecausethevideoiscapturedasarawH.264videostream.Unfortunately,notmanymediaplayerswillhandlethesefiles(althoughVLCplayerwill—itrocksandhandlespracticallyanythingyouthrowatit—getitonyourPCatwww.videolan.org).
Ifyouwanttoplaythefileonsmartphonesandconventionalmediaplayers,thenwewillneedtowrapitinacontainerformat,suchasMPEG-4,andgivethefilea.mp4extension.
Todothis,we’llusetheGPACpackage,whichisanopensourcemultimediaframework.ItcomeswithautilitycalledMP4Box,whichisatoolwe’llusetocreateanMP4containerforourvideofile:
1. First,installtheGPACpackage:
$sudoapt-getinstallgpac
2. Onceit’sinstalled,runthecommandtoconvertthetestvideowecreated:
$MP4Box-fps30-addtest.h264test.mp4
Youshouldnowhavethefile,test.mp4,whichyoucandownloadandplayonyourPCorsmartphone.
TipAnotherpopularconversiontoolisffmpeg,whichIusealotonWindowstoconvertvideofiles;however,itcanbequitecomplexandalthoughthereisapackagefortheRaspberryPi,Iactuallycouldn’tgetittoconvertproperlyonthePi.MP4Boxismuchmorestraightforwardandfittingforourneeds.
![Page 193: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/193.jpg)
CaughtoncameraSo,wenowhaveamethodofcapturingstillimagesandvideo,whichwecanputtouseinoursecuritysystem.Ifwewanttohavethisrunningconstantly,wecouldwriteascripttotakevideoconstantly,butthiswouldsoonfillupourmemorycardandwouldn’tbeparticularlyefficient.So,we’llcombineourcamerasystemwiththemotiondetectorsweconnectedearlier.
Inthelastchapter,wecreatedanalarmzonewhichhadacoupleofsensorsandamotiondetectorconnectedtooursystemontheinputGPA0.So,let’swriteascriptthatwilltakeavideoclipwheneverthemotiondetectoristriggered:
#!/bin/bash
#setupportexpander
sudoi2cset–y10x200x000xFF
#loopforever
whiletrue
do
#readtheGPAinputs
GPA=$(sudoi2cget–y10x200x12)
#detectthezoneoninput0
if[$GPA=="0x01"]
then
#circuitnormallyclosedsozoneisOK
#shortdelay
sleep0.5
else
#zoneisactivatedsotakea20secvideoclip
#filenamewillbebasedoncurrenttimestamp
sDate='date+%d%m%y'
sTime='date+%T'
echo"Zone1Activateat$sDate$sTime"
#takevideoclip
raspivid–o$sDate$sTime.h264–t20000
#converttoMP4
MP4Box-fps30-add$sDate$sTime.h264$sDate$sTime.mp4
fi
done
![Page 194: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/194.jpg)
![Page 195: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/195.jpg)
YouhavenewmailHavingtheimagesstoredonyourRaspberryPiisnotreallymuchuse—ideally,youwouldwanttheimagessenttoyoustraightaway,assoonastheyarecaptured,sothatyoucanviewthemonyoursmartphone.
Aneasy,quick,andreliablewaytodothisistosimplyhavetheme-mailedtoyou.Hencewe’regoingtoaddane-mailingfunctionalitytoourhomesecuritysystemsothatimagecapturesareattachedtoamessageandsenttoyoure-mailaddressstraightaway,whichyoucanaccessfromyoursmartphone.TheimagescanthenberemovedfromyourRaspberryPitopreventtheSDcardspacefrombeingcloggedupwiththesereasonablylargefiles.
![Page 196: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/196.jpg)
Settingupthee-mailsenderclientFortunately,therearesomegoodpackagesavailablethatwillhelpuswiththis.Carryoutthefollowingstepstoinstalltheemailpackagesweneed:
1. Updatethepackageinstallerwiththefollowingcommand:
$sudoapt-getupdate
2. InstallandsetuptheSMTPclientwiththefollowingcommand:
$sudoapt-getinstallssmtp
You’llnowneedtosetuptheclienttosendemailsthroughyouremailaccount.Inthefollowingconfigurationfile,I’veassumedthatyouhaveaGmailaccount.Thesettingsmaybedifferentifyouuseanotheremailprovider.
3. OpenthessmtpconfigurationfileusingNanooranothertexteditor:
$sudonano/etc/ssmtp/ssmtp.conf
4. Replacetheentrieswiththefollowingconfiguration:
root=<your-username>@gmail.com
mailhub=smtp.gmail.com:587
rewriteDomain=gmail.com
AuthUser=<your-username>@gmail.com
AuthPass=<your-password>
FromLineOverride=YES
UseSTARTTLS=YES
5. ssmtpcanbeusedonitsownbutcanbeabitofafaffwhileautomaticallysendingemails(bydefault,youmanuallytypetheemailinwiththecommandline,orcreateatextfile),sowe’realsogoingtoinstallthemailutilspackage:
$sudoapt-getinstallmailutils
6. Onceit’sinstalled,wecanusethemailcommandtosendemailsmoreeasily.Sendatestemailthroughthe(G)mailaccountthatwesetupearlier,usingthefollowingcommandtomakesureyoursettingsareworking:
$echo"TestEmail"|mail–s"TestPi-Mail"[email protected]
Ifallgoeswell,youshouldreceivethetestemailinyourmailboxwithinafewsecondsorso.
![Page 197: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/197.jpg)
SendingattachmentsNowthatwecansendbasicemailsfromourhomesecuritysystem,let’strysendingthestillimagetakenfromourcameraearlier.Butfirst,weneedtoinstallyetanotherpackagetohelpuswiththis:
$sudoapt-getinstallmpack
Oncethat’sinstalled,youcansendthetestimagefilewetookpreviouslybyusingthefollowingcommand:
$sudompack–s"SecurityPhoto"[email protected]
Wenowhavealloftheelementsneededtosendalertsandimagesfromourhomesecuritysystemdirectlytooursmartphoneusingemail.
![Page 198: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/198.jpg)
Wherewasthattaken?Ordinarily,youcouldjustannotatetheemailmessagewithwhereandwhentheattachedimagewastaken,butthatwouldn’tbeascoolasactuallyoverlayingtheimagewithsometext,wouldit?Solet’sdosomemagicwiththehelpofimagemagick,whichisapopularcommand-lineimagemanipulationtool.Installitwiththefollowingline:
$sudoapt-getinstallimagemagick
We’llnowusethecommandlinetotakethetestphotothatwetookearlier,overlaysometextusingoneoftheimagemagickutilities,andsaveittoanotherfile:
$converttest.jpg–fillred–pointsize48annotate+20+60'Camera1'
annotated.jpg
Afterafewseconds,thiswillhavegeneratedafilecalledannotated.jpgcontainingourimagewithCamera1writteninredinthetopcorner.Whenweputallofthistogetherinourfinalsystem,we’llalsooverlaytheimagewithatimestamp.
NoteAtthemoment,theimagesgeneratedbytheraspistilltoolareprettylarge,beinghighresolutionphotos.Thismakesmanipulatingandsendingthemabittime-consumingasfarasprocessingtimeisconcerned,sowhenwebuildourfinalsystem,we’llbeusingtheraspistilloptions,–w,–hand,–q,toreducethesizeandqualityoftheimagestomakethesystemmoreefficient.
![Page 199: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/199.jpg)
Tocapturesmallerimagefiles,tryusingthefollowingcommand:
$raspistill-otest.img–h768–w1024–q25
![Page 200: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/200.jpg)
![Page 201: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/201.jpg)
NightvisionThestandardRaspberryPicameraisgreatfortakingdaytimesnapsofpeoplewalkingupthegardenpath,butwhenitcomestonighttimeshots,it’snotreallysuitable.Therearetwowaysofdealingwiththis:thefirstistoilluminatethecaptureareawithabrightlightwhenthePIRdetectoristriggered,andthesecondistousetheRaspberryPiNoIRcameramoduleandaninfra-redLEDarraytoletthecameraseeinthedark.Moreaboutthatinaminute.
TheRaspberryPiNoIRcameramodule;itlookssimilartothestandardmodel
![Page 202: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/202.jpg)
AnilluminatingexperienceInordertoswitchonalightorLEDarrayfromtheRaspberryPiGPIOorourportexpandercircuit,weneedsomethingthatwillallowustodrivehighercurrentsandvoltagesthancanbeprovidedbytheGPIOportsalone.
AgoodcandidateforthisistheTIP120Darlingtontransistor,whichwillallowustoswitchonandoffloadsofupto80Vand5AfromourGPIOpins.Inourfullsystemlateron,we’regoingtousePortBofourMCP23017portexpandertocontroloutputs,buttheprinciplestandsforanyoftheGPIOoutputsavailabletous.
TIP120transistorscanbeboughtcheaplybutcandrivelargeloads
ThefollowingcircuitshowshowwecandrivebigloadsfromourGPIOportoutputs.
![Page 203: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/203.jpg)
Inourexamplecircuit,we’reusingaGPIOoutputpintocontrolthebaseofourtransistorviaa220ohmresistor.WhentheGPIOpingoeshigh,thetransistorisswitchedonandallowsthe12VcircuittoflowthroughtheLEDarray.
Intheprecedingcircuit,thereisnocurrentlimitingfortheLEDsbecausetheyareconnectedinseries,andsowithnineofthem,eachdroppingabout1.5Vacross,thisisaboutrightfora12Vsupply(yesIknowI’veonlyincludedsixLEDsherebutit’sjustforillustration).Remembertoadjustforyourparticularneeds.Thiscircuitcouldeasilydriveotherloads,suchasbulbsorsounders.
NoteIfyouintendtodrivehighpowerloads,youwillprobablyneedtoattachtheTIP120toaheatsinkthatwilldissipateanyheatandpreventitfromover-heatingandburningout.Inourcircuitthatwasdemonstratedpreviously,however,youprobablywon’tneedoneaswe’reonlydrivingacoupleofhundredmilliwattsatmost.
![Page 204: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/204.jpg)
TheElaboratelightswitchre-visitedExpandingonceagainonourelaboratelightswitchfrompreviouschapters,wecanonceagainwriteaBashscriptthatwillswitchonourcameralight,takeasnapwiththecamera,ande-mailittouswhenaPIRdetectoristriggered.
Forthefollowingscript,we’reassumingthattheoutputcontrollingtheTIP120transistoristheRaspberryPIGPIO17pin(D0orpin11ofourconnector),whichreplacestheLEDinourearlierset-up.TheinputfromthePIRtriggeris,again,connectedtotheGPA0(portA,datapin0)ofourMCP23017portexpander.Alltheotherinputsaretiedlow,asbefore,using10Kresistors:
#!/bin/bash
#setuptheHighLoadGPIOpin
sudoecho17>/sys/class/gpio/export
sudoechoout>/sys/class/gpio/gpio17/direction
#setupportexpanderPortAforinputs
sudoi2cset–y10x200x000xFF
#cleartheoutputbydefaulttoswitchlightoff
sudoecho0>/sys/class/gpio/gpio17/value
#loopforever
whiletrue
do
#readthesensorstate
SWITCH=$(sudoi2cget–y10x200x12)
#PIRisnormallyclosedsopinisheldhigh
if[$SWITCH!="0x01"]
then
#PIRwastriggered–pintakenlow
#switchonlampdriver
sudoecho1>/sys/class/gpio/gpio17/value
sleep0.5
#takeastillimage
sudoraspistill–o–image.jpg–h768–w1024–q25
#emailtheimage
mpack–s"SecurityAlertPhoto"[email protected]
#switchoffthelampdriver
sudoecho0>/sys/class/gpio/gpio17/value
fi
#shortdelay
sleep0.5
done
![Page 205: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/205.jpg)
pir-camera-trigger.sh
You’llnowseethatwe’vestarteddevelopingthefoundationsofthesoftwarethatwillcontrolourhomesecuritysystem.
![Page 206: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/206.jpg)
Isthatabadger?Ifyoudon’twanttoilluminateanareabeforecapturinganimage,youcanuseinfra-redlightinginconjunctionwithacompatiblecamera.ThestandardRaspberryPicameramodulewon’tworkwithinfra-redlightingbecauseitcontainsaninfra-redfilter,butwecanusetheNoIRversionofthecameramoduleinstead.
TheRaspberryPiNoIRcameramoduleisexactlythesameasthestandardone,exceptthatitdoesn’thaveaninfra-redfilterbuiltin,whichmeansitwillseeinthedarkwiththeaidofinfra-redlighting.Thismakesitgoodforwatchingbadgersatnightaswellasforuseinourhomesecuritysystem.
Youwillneedaninfra-redLEDarrayorclustertoinvisiblyilluminatetheareayouwanttocapturewiththecamera.Thesearereadilyavailableinvariousformfactorsandintensities,oryoucanbuildyourownusingindividualinfra-redLEDspurchasedfromanelectronicsstore.
TheKingbrightinfra-redLEDclusterrunsfroma6Vsupply,whichmeansyoucanconnecttwoinseries—oneoneithersideofthecamera.
ConnectinganddrivingtheLEDclustermodulesworksexactlythesameasourilluminatinglightabove,usingtheTIP120drivercircuit.Theonlydifferenceisthatwehumanscan’tseewhentheLEDsareon.
![Page 207: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/207.jpg)
![Page 208: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/208.jpg)
UsingUSBcamerasInsteadofusingtheRaspberryPiCameraModule,it’salsopossibletouseastandardUSBwebcamtotakestillimages.YoushouldbeawarethoughthatthededicatedcameramoduleisfarsuperiortoaUSBwebcamintermsofimagequality.Although,youmayalreadyhaveawebcamknockingaboutinyourboxofbits,sowhynottryit?
![Page 209: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/209.jpg)
InstallingthewebcamAfteryou’veconnectedyourwebcamtoaUSBportonyourPi,youcancheckwhetherit’sbeenrecognizedusingthelsusbcommand:
$lsusb
I’musingaLogitechwebcamthatgetsreportedasfollowswithlsusb(Device006):
pi@raspberrypi~$lsusb
Bus001Device002:ID0424:9514StandardMicrosystemsCorp.
Bus001Device001:ID1d6b:0002LinuxFoundation2.0roothub
Bus001Device003:ID0424:ec00StandardMicrosystemsCorp.
Bus001Device006:ID046d:08d8Logitech,Inc.QuickCamforNotebook
Deluxe
NoteNotallwebcamswillworkwiththeRaspberryPi.EventhoughitmayberecognizedasaUSBdevice,itmightnotactuallyworkproperlywiththeoperatingsystemandcreateavideodevice(forexample,/dev/video0).Forexample,anoldcheapTrustwebcamIhadappearedasaUSBdevicebutwouldn’tcaptureanyimages.
YoucancheckwhetheryourwebcamislikelytoworkwiththePibycheckingyourmakeandmodelathttp://elinux.org/RPi_USB_Webcams.
So,nowthatthePiknowsthatwehaveawebcamdeviceattached,wecanusethefswebcamutilitytocaptureimageframes.Youcanfindoutmoreaboutfswebcamfromthedeveloper’ssiteathttp://www.sanslogic.co.uk/fswebcam.
Installfswebcamwiththefollowing:
$sudoapt-getinstallfswebcam
![Page 210: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/210.jpg)
TakingasnapYoucannowtestthewebcambycapturingastillimage,whichcanbedonebyrunningthefollowingcommand:
$fswebcamtest.jpg
Youshouldexpecttoseeoutputsimilartothefollowing:
Notefswebcamhaslotsofoptionsforthingsliketheresolutionandqualityoftheimage.Usethecommandfswebcam-?togetalistofalloptions.
Snapsnapsnapfswebcamdoesn’ttakevideostreams,butyoucansetituptotakeaseriesofframesatregularintervals.Forexample,totakeasnapevery10seconds,youcanusethefollowingcommand:
$fswebcamframe.jpg-l10
Anexampleofhowthiswouldbeusefulcanbedemonstratedbysettingthewebcamtotakeasnapeveryfewsecondsinthebackground(the–qswitchrunsfswebcaminthebackground).Whenoursecuritysystemistriggered,wecouldthentakethelatestimagesnappedwiththewebcamwhichcouldbelookingdownyourpathway.
Forthepurposeofputtingtogetherourentiresystemlaterinthisbook,we’llbefocusingontheRaspberryPiCameraModule,butyoucanalwaysreplacethecodewiththepreviousexamplesifyouwanttouseUSBwebcamsinstead.
You’llnoticethatfswebcam,unlikeraspistill,hastheabilitytooverlaytheimageswithtimestampinformation,soyoudon’tneedtoworryaboutoverlayingtextaswedidpreviously.Lookatthefswebcamcommandlineoptionsformoreinformation.
![Page 211: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/211.jpg)
![Page 212: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/212.jpg)
ThemulticamerasetupItmayhaveoccurredtoyouthattheRaspberryPihasonlyonecameramoduleinput.Now,thisisobviouslylimitingifyouwanttohavemultiplecamerasaroundyourpropertythataretriggeredbymotiondetectors.
However,thereisnothingstoppingusfrombuildingstandaloneunitsthathaveaseparateRaspberryPiboardwithaPIRdetector,CameraModule,andnetworkconnection,eitherusingaWi-FidongleorEthernet.
BecauseyouonlyneedasingleinputtotheRaspberryPitodetectwhenthePIRmotionsensoristriggered,youcanusetheon-boardGPIOporttoconnectthesensor,ratherthanusingaportexpander.TheRaspberryPiwillemailthealertoverthenetwork,andcouldalertthemaincontrollerPiifrequired—makingitaslavesensordevice.
YoucanreadilyobtainsmallPIRdetectors,suchastheParallaxoneshownnext,whichyoucanmountontoaRaspberryPiCasealongwiththecameramodule,creatingaself-containedunit.
AParallaxPIRmotionsensor(type555-28027)
![Page 213: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/213.jpg)
![Page 214: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/214.jpg)
TheSlavedriverWhileitmayseemquiteelaboratetohaveaRaspberryPiforeachcamera—thinkaboutit—youcanactuallybuildeachcameraunitwithallofthecomponentsforaround£50,whichissignificantlycheaperthanbuyingawirelesssmartcamera.Ifyoureallywanttobeclever,youcouldalsousethisasaslavedevicetoacceptfurthersensorinputslocaltotheunit.
ThereisnothingtostopyoufromconnectingaGPIOoutputpinontheslaveunittodriveaninputonthemaincontrollerandcontrolthepindependingonthestateofitslocalsensors.Byrunninga6-corecablebetweentheunits,youcouldevenpowertheslaveunitifyourpowersupplyismanenough(you’dneedtohaveasupplyof5V@1AfortheslavePirunningalongthewire).
I’mnotgoingtogointoanymoredetailaboutthisconfigurationatthistime,butyoucouldsetyourselfachallengetocreateafullydistributedhomesecuritysystemusingmultipleRaspberryPisandthebuildingblocksandconceptslearnedinthisbook.
![Page 215: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/215.jpg)
![Page 216: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/216.jpg)
SummaryInthischapter,welearnedhowtoconnectbothRaspberryPicameramodulesandUSBcamerastoourPiboardinordertotakeimageandvideocaptureswhenrequiredbyourhomesecuritysystem.Wealsolearnedhowtooverlayourimageswithinformativetextandhavethefilesimmediatelyemailedtous.
Inordertocaptureimagesfromourcameraatnight,wealsolookedatwaystoilluminatethecaptureareausingbothvisibleandinfra-redlighting,withtheabilitytoswitchthelightingonandoffasrequiredbyusingahigh-currentDarlingtontransistordriver.
Inthenextchapter,we’regoingtogetdowntothebusinessofputtingtogethermodulesbybuildingamobile-optimizedweb-basedcontrolpanelforourhomesecuritysystem.We’lllearnhowtosetupaWebserveronourRaspberryPiandmanipulatefilesusingourWebcontrolpanel,whichmeansthatwe’llstarttoexplorehowalloftheelementswe’veencounteredsofarcancometogetheraspartofourfinalsystem.
![Page 217: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/217.jpg)
![Page 218: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/218.jpg)
Chapter7.BuildingaWeb-BasedControlPanelWe’venowgotallofourhardwareelementstogetherforustocreateacompletehome-securitysystemfeaturingcontactswitchesforourdoorsandwindows,andmotiondetectorsandcamerastotakehappysnapsofwannabeintruders!I’vedeliberatelyguidedyouthroughthisinamodularfashionsothatyoucanpickandchooseandexpandonthehardwaresensorelementsthatsuityourrequirements.InChapter9,PuttingItAllTogetherwewillbewiringallofthistogethertoformthecompletesystembasedonzonesthatwelookedatearlier.
Onethingthatallhomesecuritysystemsrequireisacontrolpanelthatallowsustoarmanddisarmthesystemandmonitorthestatusofthezoneswithinoursystem.Wemightalsowanttodothingssuchasonlyarmcertainzones,orhavethesystemautomaticallyarmanddisarmatcertaintimesoftheday.
Thehardwarerequiredforthis,suchasswitches,LEDs,andLCDdisplays,canbequiteexpensiveandtime-consumingtoputtogether;theycanalsomakethesystemlessconfigurableandflexible.So,inoursystem,we’regoingtobuildaWeb-basedcontrolpanelthatwecanaccessfromourmobilephonebrowser.Thisalsomeansthatwecancontrolthesystemremotely,whenweareoutofthehouse.
Inthischapter,wewillcoverthefollowing:
DefiningthescopeofourhomesecurityintermsofthenumberofzoneswewillbemonitoringandtheI/OportswewilluseLearninghowtoinstallandconfigureawebserveronourRaspberryPiDevelopingabasicHTML5webpageforouralarmcontrolpanelLearninghowtousePHPscriptstodynamicallyconfigureoursystemfromthewebpage
![Page 219: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/219.jpg)
InstallingthewebserverThereareseveralwebserversreadilyavailablethatwecouldinstallonourRaspberryPi,andtheywouldallbesuitableforoursystem.ButIlikethelighttpdwebserverasit’seasytouseandlightweight.lighttpdisoftenreferredto,andaffectionatelyknownas,“Lighty”—whichtobehonestislessofamouthfulthanlighttpd.
AswellastheWebserveritself,we’realsogoingtoinstallPHPsupport,whichwillallowustowritedynamicwebpagestointeractwiththeLinuxsystem.Now,tobehonest,I’mnotamassivefanofPHPforcommercialWeb-baseddeploymentsformanyreasons,butforasmallembedded-Linuxsystemsuchasourhomesecuritysystem,it’sperfectandworksreallywell.It’salsoquitestraightforwardtogetintoifyou’veneverdoneserver-sideWeb-scriptingaswell.
Toperformthefollowingsteps,you’llneedtobeloggedintoyourRaspberryPiviatheterminalconsole(forexample,PuTTY):
1. Updatethepackageinstaller:
$sudoapt-getupdate
2. InstallthelighttpdWebserver:
$sudoapt-getinstalllighttpd
Onceinstalled,itwillautomaticallystartupasabackgroundservice,andwilldosoeachtimeyourRaspberryPistartsup.
3. InstallPHP5support:
$sudoapt-getinstallphp5-cgi
4. Now,weneedtoenablethePHPFastCGImoduleinourwebserver:
$sudolighty-enable-modfastcgi-php
5. Andfinally,weneedtorestarttheWebserver:
$sudo/etc/init.d/lighttpd
That’sit!YoushouldnowhaveyourPHPWebserverinstalled.Bydefault,thewebcontentfilesgetinstalledinthelocation,/var/www,andLightyinstallsatestplaceholderpageinthislocation,whichyoucanaccessfromyourbrowserbysimplyenteringtheIPaddressofyourRaspberryPi,asshowninthefollowingscreenshot:
![Page 220: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/220.jpg)
TheLighttpdplaceholderpage
![Page 221: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/221.jpg)
TestingthePHP5installationWhilewe’reatit,weshouldalsotestourPHPinstallation,asthisisfundamentaltobuildingourconsole.ThiscanbedonebywritingasimplePHPscriptpagethat,ifPHPisinstalledcorrectly,willreturninformationaboutitsenvironmentandconfiguration:
1. First,gotothewebcontentfolder:
$cd/var/www
2. InNano,createafilecalledphpinfo.php:
$sudonanophpinfo.php
3. Intheeditor,enterjustthefollowingsingleline,thensaveandexitfromNano:
<?phpphpinfo();?>
Now,inyourbrowser,entertheIPaddressofyourRaspberryPifollowedby/phpinfo.php,forexample,http://192.168.0.110/phpinfo.php,andyoushouldbepresentedwiththefollowingpage:
![Page 222: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/222.jpg)
ThePHPinfopagegeneratedbytheWebserver
Nowthatweknowourwebserverisworkingproperly,wecanstartcreatingourconsolewebpage.
![Page 223: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/223.jpg)
![Page 224: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/224.jpg)
BeingincontrolSothatweknowwhatcontrolswewantonouralarmcontrolpanel,weneedtomapoutoursystemwiththenumberofzoneinputsandcontrolinputsandoutputs.Asyou’llrememberfromChapter3,ExtendingYourPitoConnectMoreThingswecanessentiallyhaveupto16zonesinoursystemusingthetwoI/Oportsonourportexpander.WealsohavetheeightGPIOpinsatourdisposalontheRaspberryPiboarditself.So,let’snowallocatetheseoutputsanddocumenttheminthetablethatfollows.
I’mgoingtosetupan8-zonesystemformyalarminputsusingportAontheI/Oexpanderboard,usingthenativeGPIOpinsforthingssuchasbuttonsandalertoutputs.Onereasonfordoingitinthisconfigurationisthatthesystemcanalwaysfail-safe—soiftheexpanderboardfails,theRaspberryPicanstillcommunicatealertsandbuzzersconnectedtoit.
Port I/OPin Label/Purpose
ExpanderA 0(A0) Zone1Input(Entry/ExitChannel)
1(A1) Zone2Input
2(A2) Zone3Input
3(A3) Zone4Input
4(A4) Zone5Input
5(A5) Zone6Input
6(A6) Zone7Input
7(A7) Zone8–Anti-TamperLoopInput
ExpanderB 0(B0)
1(B1)
2(B2)
3(B3)
4(B4)
5(B5)
6(B6)
7(B7)
R-PiGPIO 0(GP0) Arm/DisarmSwitch(Input)
![Page 225: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/225.jpg)
1(GP1)
2(GP2)
3(GP3)
4(GP4) ArmedLED(Output)
5(GP5) Arm/DisarmBuzzer(Output)
6(GP6) AlarmLED(Output)
7(GP7) AlarmBell(Output)
![Page 226: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/226.jpg)
ArmingyourselfThetermsarmanddisarmarealarmsystem-speakforswitchingthealarmmonitoringon(armingthesystem)andoff(disarmingthesystem).Zone1ofoursystemisgoingtobelinkedtothearminganddisarmingpartofthesystemasitwillbeconnectedtothesensorsonthedoorthatweleaveorenterfrom;thiswillbeaspecialzoneforentryorexitpurposes.
Whenwesetthealarm,weneedabitoftimetogetoutofthehouse.Thewaythatthesystemknowswe’veleftthepropertyisbymonitoringtheexitzonetoseeifwe’veopenedandthenclosedthefrontdoorbehinduswithinthetimeallowed.
Similarly,whenwereturn,wewillopenthefrontdoor,butwedon’twantthealarmtogooffstraightaway—weneedachancetodisarmthesystemwithinagivenamountoftime.Wewillarmanddisarmthesystemviaourweb-basedcontrolpanel,orbyusingaswitchofsomesortontheinputGP0.
![Page 227: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/227.jpg)
![Page 228: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/228.jpg)
ThemasterconfigurationfileOursystemwilluseamasterconfigurationfilethatwilltellithoweverythingissetupandconnected.Thisconfigurationfilewillbeusedbyboththewebcontrolpanelandthemainalarmcontrolscriptssothatthetwosub-systemscan“talk”toeachother.Let’screatethefilewithourinitialsettings.
ThesettingsfilewillbestoredinthesamelocationaswherewewillcreateourcontrolscriptsinChapter9,PuttingItAllTogether,whichisinthefolder./etc/pi-alarm.So,let’screatethisfolder,andgiveitexecuterightssothatourscriptscanberun:
$cd/etc
$sudomkdirpi-alarm
$sudochmod777pi-alarm
We’llnowcreatethemasterconfigurationfile,tobeusedbyoursystem,inthisfolder:
$cdpi-alarm
$sudonanoalarm.cfg
TipAsbefore,youdon’thavetocreateyourfilesinNanoontheRaspberryPi—youcancreatethemonyourdesktopcomputer,andthentransferthemtoyourPiusingSCP.
#ALARMMASTERCONFIGFILE#
#Numberofzonesinthesystem
NUM_ZONES=8
#Displaylabelsforeachzone
ZONE_LABEL_1="Zone1-Entry/Exit"
ZONE_LABEL_2="Zone2"
ZONE_LABEL_3="Zone3"
ZONE_LABEL_4="Zone4"
ZONE_LABEL_5="Zone5"
ZONE_LABEL_6="Zone6"
ZONE_LABEL_7="Zone7"
ZONE_LABEL_8="Zone8"
#Zonesthatareenabled
#Setto0toDisableor1toEnable
ZONE_ENABLE_1=1
ZONE_ENABLE_2=1
ZONE_ENABLE_3=1
ZONE_ENABLE_4=1
ZONE_ENABLE_5=1
ZONE_ENABLE_6=1
ZONE_ENABLE_7=1
ZONE_ENABLE_8=1
SYSTEM_ARMED=0
#Zonestatus
![Page 229: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/229.jpg)
#Setto1ifzoneistriggered
ZONE_STATUS_1=0
ZONE_STATUS_2=0
ZONE_STATUS_3=0
ZONE_STATUS_4=0
ZONE_STATUS_5=0
ZONE_STATUS_6=0
ZONE_STATUS_7=0
ZONE_STATUS_8=0
alarm.cfgfile
![Page 230: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/230.jpg)
![Page 231: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/231.jpg)
CreatingthewebpageOurWeb-basedcontrolpanelisgoingtobeasinglePHP-drivenHTML5webpagewhichwillbemobileoptimized.HTML5isthelatestmark-upstandardforwebpagesandissupportedbymostmodernsmartphonesandbrowsers.Wewillalsocreateacascadingstyle-sheet(CSS)thatwillmakeourpagelookhalfreasonableonmobiledevices.
Tocreatethewebfiles,IrecommendthatyouusesomethingliketheexcellentNotepad++onyourdesktopcomputer,ratherthandoingitdirectlyontheRaspberryPi.Alternatively,ifyouareaseasonedwebdeveloper,youmayalreadyhaveyourIDEofchoice.
![Page 232: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/232.jpg)
ThecontrolpanelHTMLtemplateThefirstthingwe’lldoiscreateanHTMLfilethatwecanusetotestourlayoutbeforeweputtheHTMLintoaPHPfiletomakeitinteractwithoursystem.Thismakesiteasiertotweakthewaywewantittolookbeforehand,withoutthePHPscriptsgettingintheway.
NoteThisisnotatutorialonWebdevelopment—thereisaplethoraofbooksoutthereonthatsubject—butIhopethecodeisclearenoughforyoutoworkoutwhat’sgoingon.ThecodeI’mgoingtoshowyouisfullyfunctional,soyoucanjustusewhatIgiveyouwithouthavingtodoanymore.Hopefully,itmakesyourcontrolpanellookOKtoo!
Thefollowingmark-upgivesyouabasiccontrolpanelwithstatusforour8zones,amasterarmanddisarmswitch,andswitchestoenableordisableanyofourzones.
The<head>sectionofthecodecontainssome<meta>tagsthathelpmobiledevicesknowthatit’samobile-friendlysite.Inthemain<body>mark-up,wehaveasectionforeachzonethatcontainsthezone’snameandanon/offswitch.Eachzoneisinitscontainersothatwecanalsohighlightaparticularzonethatneedsourattention,forexample,ifit’striggered.
YoucanfindthefullHTML5markupforourcontrolpanelinthealarm-panel.htmlfilelocatedinsidethecodefolderofchapter7.
![Page 233: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/233.jpg)
GivingitsomestyleAtthemoment,thispagedoesn’tlookthatgreat(infact,itlooksawful,likesomethingfromthe1990s);itisn’tparticularlygoodformobiledevicesandwouldmostcertainlyfailthesausagetest.So,we’regoingtoapplysomestylingtomakeitlooknothalfbad.Althoughtheprecedingmark-upcontainsareferencetoaCSSfile—wehaven’tcreatedthatfile—sothisiswhatourpagecurrentlylookslike(asIsaid:itlooksawful):
Thewebcontrolpanelwithoutanystyling
ThefollowingCSS3mark-upisdesignedspecificallyforourcontrolpanel,anditmakesitlookquitenicewhilealsomakingitusableontouch-screenmobiledevices.TheCSSisquitelongandseemsoverwhelming,butyoudon’tneedtodoanythingwithit,orunderstandit,ifyoudon’twantto—theonlythingyouneedtoknowisthatit’sbeendesignedformodernbrowsersandsmartphones,sodon’texpectittoworkonInternetExplorer7,orprobablyevenIE9!
Inessence,itcontainsthestylingforthefollowing:
PreparingthebrowserforourmobilelayoutOurtextandzoneareasCreatingcoolswitchesinsteadofboringcheckboxesMakinganareaflashonandoffwhenweneeditto
![Page 234: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/234.jpg)
/*Clearbrowsermarginandpaddingdefaults*/
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,
fieldset,input,textarea,p{
margin:0;padding:0;-webkit-text-size-adjust:none;
}
body{
background:#ffffff;
color:#4A5651;
font-family:"TrebuchetMS",Helvetica,sans-serif;
font-size:10px;
height:100%;
padding:0;
margin:0auto;
max-width:320px;
min-width:240px;
text-align:left;
width:100%;
-webkit-box-shadow:0px20px40px0pxrgba(0,0,0,0.50);
-moz-box-shadow:0px20px40px0pxrgba(0,0,0,0.50);
box-shadow:0px20px40px0pxrgba(0,0,0,0.50);
}
p,.zoneLabel{
font-size:16px;
margin:5px;
line-height:1.4;
color:#4A5651;
}
#headerh1{
font-size:20px;
line-height:40px;
margin:0;
padding:00015px;
text-align:center;
text-overflow:ellipsis;
font-weight:bold;
}
.zoneControl,.masterControl{
border-bottom:1pxsolid#dddddd;
margin-top:5px;
margin-bottom:0px;
padding:5px;
display:block;
width:100%;
}
.zoneLabel{
font-weight:bold;
text-overflow:ellipsis;
}
input[type="submit"]{
border:none;
![Page 235: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/235.jpg)
background-color:#0b70cc;
color:white;
height:32px;
display:block;
padding:4px7px;
float:left;
border-radius:8px;
position:relative;
bottom:1px;
margin-left:4px;
text-align:center;
}
input[type="submit"]:hover{background-color:#b2ceec;color:
#0b70cc;border:none;border:1pxsolid#b2ceec;}
/*Flashinganimation*/
@-webkit-keyframesflash{0%,50%,100%{opacity:1;}25%,75%{opacity:
0;}}
@keyframesflash{0%,50%,100%{opacity:1;}25%,75%{opacity:0;}}
.flash{
-webkit-animation-name:
flash;animation-name:
flash;color:#f00000;
}
.animated{
-webkit-animation-duration:1s;
animation-duration:1s;
-webkit-animation-fill-mode:both;
animation-fill-mode:both;
animation-iteration-count:infinite;
-webkit-animation-iteration-count:infinite;
}
/*
ON/OFFSWITCHSTYLES
TherathercoolOn/Offswitchstylingwasgeneratedon
https://proto.io/freebies/onoff/
*/
.onoffswitch{
position:relative;
width:90px;
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
}
.onoffswitch-checkbox{
display:none;
}
.onoffswitch-label{
display:block;
overflow:hidden;
cursor:pointer;
border:2pxsolid#FFFFFF;
border-radius:20px;
![Page 236: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/236.jpg)
}
.onoffswitch-inner{
display:block;
width:200%;
margin-left:-100%;
transition:margin0.3sease-in0s;
}
.onoffswitch-inner:before,.onoffswitch-inner:after{
display:block;
float:left;
width:50%;
height:30px;
padding:0;
line-height:30px;
font-size:14px;
color:white;
font-family:Trebuchet,Arial,sans-serif;
font-weight:bold;
box-sizing:border-box;
}
.onoffswitch-inner:before{
content:"ON";
padding-left:10px;
background-color:#34C290;
color:#FFFFFF;
}
.onoffswitch-inner:after{
content:"OFF";
padding-right:10px;
background-color:#EEEEEE;
color:#999999;
text-align:right;
}
.onoffswitch-switch{
display:block;
width:18px;
margin:6px;
background:#FFFFFF;
position:absolute;
top:0;
bottom:0;
right:56px;
border:2pxsolid#FFFFFF;
border-radius:20px;
transition:all0.3sease-in0s;
}
.onoffswitch-checkbox:checked+.onoffswitch-label.onoffswitch-inner{
margin-left:0;
}
.onoffswitch-checkbox:checked+.onoffswitch-label.onoffswitch-switch{
![Page 237: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/237.jpg)
right:0px;
}
.masterswitch{
position:relative;
width:90px;
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
}
.masterswitch-checkbox{
display:none;
}
.masterswitch-label{
display:block;
overflow:hidden;
cursor:pointer;
border:2pxsolid#FFFFFF;
border-radius:20px;
}
.masterswitch-inner{
display:block;
width:200%;
margin-left:-100%;
transition:margin0.3sease-in0s;
}
.masterswitch-inner:before,.masterswitch-inner:after{
display:block;
float:left;
width:50%;
height:30px;
padding:0;
line-height:30px;
font-size:12px;
color:white;
font-family:Trebuchet,Arial,sans-serif;
font-weight:bold;
box-sizing:border-box;
}
.masterswitch-inner:before{
content:"ARMED";
padding-left:10px;
background-color:#F00000;
color:#FFFFFF;
}
.masterswitch-inner:after{
content:"OFF";
padding-right:10px;
background-color:#EEEEEE;
color:#999999;
![Page 238: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/238.jpg)
text-align:right;
}
.masterswitch-switch{
display:block;
width:18px;
margin:6px;
background:#FFFFFF;
position:absolute;
top:0;
bottom:0;
right:56px;
border:2pxsolid#FFFFFF;
border-radius:20px;
transition:all0.3sease-in0s;
}
.masterswitch-checkbox:checked+.masterswitch-label.masterswitch-inner{
margin-left:0;
}
.masterswitch-checkbox:checked+.masterswitch-label.masterswitch-switch{
right:0px;
}
/*ENDOFSWITCHSTYLES*/
Webcontrolpanelstylesheet–alarm-panel.css
Applythestylesheetandthisiswhatyouendupwith(alittlebitnicer,Ithinkyou’llagree):
![Page 239: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/239.jpg)
Thewebcontrolpanelwithstyling
![Page 240: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/240.jpg)
MakingitdynamicNowthatwehavethelayoutcodedefinedforourcontrolpanelpage,wecaninsertitinourPHPpagesothatitcanbemodifieddynamicallybythePHPscriptontheWebserver,dependingonthestatusofourhomesecuritysystem.
ThePHPscriptwillhelpusachievethefollowingbasicfunctions:
Updatingtheconfigurationfilewiththepositionoftheon/offswitchesforzonesArminganddisarmingthesystemTellinguswhichzonehasbeentriggeredwhenanintrusionhasbeendetected
Again,I’mnotgoingtogointodetailabouthowthePHPcodeworks,buthopefullythecommentswithinthecodewillhelpyoufollowwhat’sgoingon,andalsohelpyoumodifyitifyouwanttochangeitsbehavior.
GettingabitofhelpfirstUnlessyouchangesomeofthePHPconfiguration,itcanbeanightmaretryingtoworkoutwhat’sgonewrongifyouhaveasmallbuginyourcode,asbasicallyyouarepresentedwith…nothing!
So,beforewecreateandbuildourPHPpage,we’llchangeacoupleofsettingsinthePHPconfigurationfiletomakesureweknowifthereareanyissues:
1. OpentheconfigurationfilewithNano:
$sudonano/etc/php5/cgi/php.ini
2. Thefileisabitlargeandunwieldy,butbattleyourwaythroughit,findthesesettings,andchangethemasfollows:
error_reporting=E_ALL
display_errors=On
3. SavethefileandexitNano.4. Finally,restartLighty:
$sudo/etc/init.d/lighttpdrestart
ThemainPHPcodeAndhereitis…Butdon’trunityet—there’sstillabitmoretodo…
YoucanfindthefullmainPHPcodeintheindex.phpfilelocatedinsidethecodefolderofchapter7.InourWebservercontentfolder,weshouldnowhavethefollowingfiles:
pi@raspberrypi~$ls-1/var/www
alarm-panel.css
alarm-panel.html
index.lighttpd.html
index.php
phpinfo.php
![Page 241: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/241.jpg)
I’msomeoneelseNow,beforewecanactuallyopenthisPHPwebpagesuccessfully,weneedtobeawareofthefactthattheWebserver,bydefault,actuallyrunsasadifferentusercalledwww-data.Thismeansthatitdoesn’tordinarilyhavetherighttoperformcertainoperations;inparticular,thosethatinteractwiththefilesystem.
IfyouworkedthroughthepreviousPHPscript,you’llseethatitactuallyexecutessomeLinuxcommandstoreadandupdateouralarm.cfgfile.
Inthesamewaythatwehavetoputsudoinfrontofmanycommandsbecausewe’renottherootuser,itistrueforotherusersaswell,includingwww-data.So,togivetheWebserverrightstoexecutecertaincommands,weneedtoadditasasudoer,usingthevisudoutility.
Runtheutilitytoopenthesudoerconfigurationfile:
$sudovisudo
Atthebottomofthefile,addthefollowingline:
www-dataALL=(ALL)NOPASSWD:/bin/cat,/etc/pi-alarm/update-alarm-setting.sh
Thensavethefileandexit.
ThefinalthingwehavetodoiscreateasmallBashscriptthatwillhandlethetaskofupdatingsettingsinouralarm.cfgfile.Thereasonwhyweneedtodothisisbecausewe’regoingtousetheLinuxsedcommandtoupdatethefile.Thewaythatweareinvokingthesedcommandmeansthatitneedstocreateatemporaryfile.UnlesswedoabitofworkwithconfiguringtheWebserverbecauseofitsfilelocationcontext,itwon’twork.So,it’seasiertocreateastubBashscriptthatiscalledbythePHPscript.Inthisway,theBashenvironmentdealswiththetemporaryfilecontext.
So,we’llcreatethefollowingBashscriptandsaveitinour/etc/pi-alarmfolder:
#!/bin/bash
#/etc/pi-alarm/update-alarm-setting.sh
############################################
#Providesaccesstothesedcommandfrom#
#PHPasitneedswriteaccesstoatemp#
#folder.#
#$1-SettingName#
#$2-SettingValue#
############################################
sed-i"s/^\($1\s*=*\).*/\1$2/"/etc/pi-alarm/alarm.cfg
update-alarm-setting.sh
Andthenweneedtogivethescriptexecutionrights:
$sudochmod777/etc/pi-alarm/update-alarm-setting.sh
Thisiswhatweshouldseeinour/etc/pi-alarmfolderatthistime:
![Page 242: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/242.jpg)
pi@raspberrypi~$ls-1/etc/pi-alarm
alarm.cfg
update-alarm-setting.sh
Right,afterallthat,Ithinkwecannowlaunchthecontrolpanelpageinourbrowserat
http://<my-pi-ip>.
index.phpisconfiguredasadefaultpageinLighty’sconfig,soyoudon’tneedtoaddittotheendoftheURL;justtheIPaddresswillsuffice.
BychangingtheswitchpositionsandthenclickingontheUpdateSystembutton,youshouldfindthatthesettingvaluesgetupdatedaccordinglyinalarm.cfg.Youcannowseehowthisfilewillbethewayforthestatustobeexchangedbetweenourwebconsoleandthesecuritysystemscriptsthatwe’lldevelopinChapter9,PuttingItAllTogether.
![Page 243: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/243.jpg)
Thefinaloperationalcontrolpanel
![Page 244: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/244.jpg)
![Page 245: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/245.jpg)
RemoteaccesstoourcontrolpanelWhilewecansetupoursystemtoreceiveemailalertswhenoursystemdetectsanintrusion,itwouldbereallyusefultobeabletoaccessourWeb-basedcontrolpanelwhereverwearesothatwecanperhapsarmanddisarmthesystemorswitchoffcertainzoneswhenwe’renotthere.
However,inordertomakethispossibleweneedtodoafewthings:
![Page 246: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/246.jpg)
SettingupadynamicDNSaccountMostofuswon’thaveafixedIPaddressfortheInternetconnectioninourhome;itislikelytochangefromtimetotime,especiallywhenwerebootorunplugourrouter,wherebyourInternetserviceproviderassignsusanewonewhenwenextconnecttothem.Becauseofthis,wecan’trelyonusingtheIPaddresstogettoourhomenetworkwhenwe’reoutandabout.Tosolvethis,weneedtosetupadynamicDNSaccountthatwillallowustosetupadomainnameforourhomenetwork(forexample,myhomenetwork.com).
Itworksbyhavingaservicethatrunsinsideyournetwork,suchasonyourrouterorlaptop,thatupdatesthedynamicDNSservicehostingyourdomainnamewiththecurrentIPaddressofyourInternetconnection.Then,whenyouuseyourdomainnameinyourbrowser,itwilltakeyoutoaWebserveronyourhomenetwork.
PopulardynamicDNSprovidersoutthereincludeNo-IP(www.noip.com)andDynDNS(www.dyn.com).YoucanalsogetafreeDnsOMaticaccountwithOpenDNStomanageyourservices(www.dnsomatic.com).
MyNetgearNASdevicehasaDnsOMaticupdaterserviceadd-on
![Page 247: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/247.jpg)
MyNetgearRouterhastheoptionofupdatingaDynamicDNSservice
TheRaspberryPidynamicDNSclientSinceyourRaspberryPi-basedhomesecuritysystemislikelytoalwaysbeon,youmightwanttoinstalltheddclientupdaterserviceonthereinstead:
$sudoapt-getinstallddclient
Onceinstalled,youcansetitupforyourparticularserviceandaccountdetailsusingthefollowingconfigfile:
$sudonano/etc/ddclient.conf
![Page 248: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/248.jpg)
SettingupastaticIPonyourRaspberryPiSothatourhomenetworkalwaysknowswheretofindyourRaspberryPi,weneedtosetupastaticIPaddressonit,assumingthatitcurrentlyacquiresanIPaddressfromyourrouter’sDHCPservereachtimeitbootsup.
1. Todothis,weneedtoeditthenetworksettingsontheRaspberryPi.InNano,openthefollowingconfigurationfile:
$sudonano/etc/network/interfaces
2. You’llprobablyfindtheEthernetportconfigurationsettosomethinglikethis:
autoeth0
allow-hotplugeth0
ifaceeth0inetmanual
3. ChangethisconfigurationtobeanunusedstaticIPaddressonyournetwork.Inmycase,I’vesetitto192.168.0.99.ThegatewaysettingistheIPaddressofmyInternetrouter:
autoeth0
allow-hotplugeth0
ifaceeth0inetstatic
address192.168.0.99
netmask255.255.255.0
gateway192.168.0.1
4. Now,weneedtorestartthenetworkingservice—notethatyou’llbedisconnectedfromyourterminalsession.You’llneedtoreconnectusingthenewIPaddress:
$sudo/etc/init.d/networkingrestart
Ifyouhaveanyissues,simplyrestartthePiwithsudorebootandallshouldbegoodwhenitcomesbackup.
![Page 249: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/249.jpg)
Port-forwardingThefinalpieceofthispuzzleistomakesurethatourInternetrouterwilldirectincomingtrafficonagivenporttoourRaspberryPi’sWebserver.Forthepurposeofthisexample,I’mgoingtoassumethatwearegoingtosticktothedefault,port80,onourWebserver.
TipAwordaboutsecurity
GiventhatourWebserverwillnowbeaccessiblefromtheoutsideworld,weneedtobemindfulaboutsecuringoursystemproperly.ThetwomainwaystodothisaretochangetheWebserverporttoarandomnumberotherthan80(forexample,8799)andaddpasswordprotectiontoyoursitebyapplyingbasicauthentication.Bothofthesecanbedoneinthelighttpdconfigurationfile.
Mostrouterswillallowyoutosetupport-forwardingaspartoftheirfirewallconfiguration.Essentially,settingthismeansthatanyincomingtrafficfromtheInternetonagivenTCPportwillbeallowedtopassthroughtherouterandwillbedirectedtothedevicewiththespecifiedIPaddress.OnmyNetgearrouter,it’ssetupasshowninthefollowingscreenshot:
Settingupport-forwardingonaNetgearrouter
Now,whenyouenteryourpersonaldomainnameinyourbrowser,whenyou’reawayfromhomeyoushouldbetakentoyouralarmcontrolpanel.
TipYoumightalsowanttoconsideropeningupport22sothatyoucanaccesstheRaspberryPidirectlyusingPuTTyandSSHfromoutsideyournetwork.
![Page 250: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/250.jpg)
![Page 251: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/251.jpg)
SummaryWe’venowstartedbuildingthesoftwarethatwillcontrolourhomesecuritysystembydeterminingtheformatofthemainconfigurationfile.We’vealsoinstalledaWebserverandbuiltabasicsingle-pagecontrolpanelwithPHP,HTML5,andCSS3,whichcanbeaccessednicelyonourmobilephone,allowingustoconfigureoursystemandviewthestatus.
Inaddition,we’velearnedhowtoconfigureourhomenetworkandRaspberryPisothatwecanaccessourcontrolpanelwhenwe’reawayfromhome.
InChapter9,PuttingItAllTogether,we’llputalloftheelectronicelementstogetherandwritethemainscriptsthatwillrunthehomesecuritysystem.Butbeforethat,inthenextchapter,we’regoingtolookatafewotherbitsandpieces,suchasaddingothersensors,notnecessarilyrelatedtointruderdetection,toourhomesecuritysystem.We’llalsolookathowwecanadministerourentireRaspberryPisystemremotelyusingaWebbrowser,inadditiontoaccessingourhomesecuritycontrolpanel.
![Page 252: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/252.jpg)
![Page 253: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/253.jpg)
Chapter8.AMiscellanyofThingsThepreviouschaptershaveprovideduswiththefoundationandelementstodesignandputtogetherourentirehomesecuritysystem,whichwewilldointhenextchapter.IhopethatI’veguidedyouthroughthisjourneyinafairlystructuredandlogicalwaysothatyouarereadytodothat.
Beforehand,though,I’mincludingthischapterdubbedaMiscellanyofThings,asthat’sexactlywhatitis.Itcomprisesafewoptional,butuseful,extrasthatweshouldconsiderforoursystem,butthatdon’treallywarrantawholechapterintheirownright.Iguessyoucouldrefertothemasfootnotestopreviouschapters.
Assuch,wewilltakealookatthefollowingtopics:
Waystoarmanddisarmthesystemwithouttheweb-basedpanelDrivinginductiveloadssafelyfromourGPIOoutputsAddinganescapedwatersensorinputtooursystemAddingatemperaturesensorinputtooursystemHowcarbonmonoxidedetectorscouldbeaddedtooursystemRemotelymanagingourRaspberryPiusingWebmin
![Page 254: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/254.jpg)
ArminganddisarmingthesystemWe’veincludedaswitchonourWeb-basedcontrolpanelsothatyoucanarmanddisarmthesystemfromyoursmartphone.However,thisisprobablynotthemostconvenientwayofdoingit,especiallywhenyou’rerushingoutofthehouse,oryou’vereturnedhomewithaphonewhosebatteryisflat.So,weneedtofindanadditionalwayofarminganddisarmingoursystemattheentryandexitpointofourproperty.
Inthezonelisttableinthepreviouschapter,you’llnoticethatIassignedinputGP0ontheRaspberryPiGPIOasourarm/disarmswitchinput.Thisinputwillworkinconjunctionwithourcontrolpanelswitch.
Thisinputcanasbeasimpleasatoggleswitch,orabitmoresecure,suchasakeyswitchorelectronickeypad.Eitherway,itwillbewiredtogroundGP0(GPIO17)onourRaspberryPiwhenthesystemisarmed.
Thecircuitdiagramforourarm/disarmswitch
Ifyouhaveswitchesorothersuchdevicesthatwillbeoutsideandexposedtotheelements,you’llneedtoensurethattheyaresuitableforoutdoorusesothattheydon’tgetdamagedandcompromisetheintegrityofthesystem.
![Page 255: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/255.jpg)
TheIP67-ratedkeyswitch,suitableforoutdooruse(typeLorlinWRL-5-E-S-2-B)
Byusingastandalonesecuritykeypad,youcanalloweachusertohavetheirowncodetoarmanddisarmthesystem.Forexample,theCDVIECO100isalow-costkeypadthatallowsuptoa100users.Whenthecorrectcodeisentered,itwillarmthesystembyclosinganinternalswitch.Whenthecodeisenteredagain,thekeypadwilldisarmthesystembyopeningtheswitch.
![Page 256: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/256.jpg)
TheCDVIECO100programmablekeypad
![Page 257: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/257.jpg)
![Page 258: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/258.jpg)
DrivinginductiveloadsItalkedaboutdrivinglargeloadsinChapter6,AddingCamerastoOurSecuritySystem,butnowisprobablyagoodtimetoexpandonthisabitandtalkaboutdrivinginductiveloadssuchasbellsandincandescentlamps.Inthepreviouscircuitexample,IusedtheTIP120DarlingtontransistortodriveanLEDarraythatwasnotinductive.Withinductiveloads,youneedtoaddabitofdiodeprotectiontoprotectthecircuitagainstspikesgeneratedbythecoilswithinrelaysandbellsastheyswitchonandoff.
Here’sthemodifiedcircuitforourdigitalloaddriverwitha1N4007rectifierdiodeforprotection:
Thedigitalloaddriverwithdiodeprotection
![Page 259: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/259.jpg)
![Page 260: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/260.jpg)
BeyondintrusionHomesecurityisnotjustaboutprotectingourpropertyagainstintrusion,it’salsoaboutprotectingagainstotherriskstoo,suchasflood,fire,carbonmonoxideleaks,andsoon.So,itmakessensetoextendourhomesecuritysystemtodetecttheseotherriskstoo.
Youmaychoosetosetupthesystemsothatcertaintypesofalertsonlycometoyourphoneasemails,ratherthantriggeringalloftheoutsidebells,lights,andwhistles.Thiscanbedonebyadaptingthescriptsinthenextchaptersothattheyoperatehowyouwantthemto.
![Page 261: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/261.jpg)
AsimplewaterdetectorThere’snothingworsethanbeingawayforafewdaysandcominghometoafloodedkitchenbecausealeakhasdevelopedunderthesink.Oursimplecircuitwilldetectthepresenceofwaterandtriggeraninputonourhomesecuritysystem,whichcanthenalertyou.Youcanalsobuykitsandready-builtmodulestodothis,butthefollowingcircuitischeapandfeaturesouropto-isolatoraswe’regoingtohaveadifferentvoltageforouractualdetector.
Thecircuitforasimplewaterdetector,isolatedfromourGPIOinput
HowitworksWhenwaterisplacedacrosstheprobes,currentflowsthroughthewater,andso,throughtheR3/R4potentialdivideronthebaseoftransistorQ1.Whenthecurrentatthebaseishighenoughtosaturateit,thetransistorwillswitchonfully,allowingtheLEDinsidetheopto-couplertoswitchon.Thisinturnwillpulldowntheinputpintooursystemto
![Page 262: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/262.jpg)
groundviathephoto-transistorinsidetheoptocoupler.
Youcanusethetrimmer,R4,tocalibratethesensorbyadjustingitssensitivity.AnygenericNPNbipolartransistorshouldworkhere,butobviously,theyallhavedifferentoperatingparameters,sochooseasuitableone.
![Page 263: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/263.jpg)
AsimpletemperaturesensorIfwewanttobealertedwhentheambienttemperaturereachesacertainthreshold,thenwecanbuildacircuitusingthecommonlyusedLM34/LM35temperaturesensors.It’sasimpledevicewithjustthreepins:power,ground,andoutput,providingavoltageproportionaltothetemperature.ThedifferencebetweentheLM34andLM35isthattheLM34producesanoutputof10mV/°F,whereastheLM35produces10mV/°C.ThereisalsoanLM335variantthatproducesanoutputof100mV/°K.
PinouttakenfromtheTexasInstrumentsLM35DZdatasheet
Itmayhaveoccurredtoyouatthispointthatthisisananaloguedevice—sohowdoweinterfacethatwithourwhollydigitalsystem?Onewayistoincorporateananalogue-to-digitalinterfaceontoourinputcontrolboardandreadthedatacominginfromthatsothatweknowtheexacttemperature,butthat’sprobablyabitbeyondthescopeofthisbook.So,we’regoingtoimplementacircuitthatwillalertuswhenthetemperatureexceedsapre-definedthreshold,whichisprobablyallweneedinthecontextofourhomesecuritysystem.
NoteIfyou’reinterestedinbuildingananalogue-to-digitalmoduletoextendyourhomesecurity,thentakealookatsomethingsuchasthePCF8591chipfromNXP,whichisanI2C-basedanalogue-to-digitalconverter.ThiswillconnecttotheI2Cbusthatwe’realreadyusing,andsoitiseffectivelyjustanadd-on.
http://bit.ly/NXPPCF8591T
Forourtemperaturedetectorcircuit,wewilluseanoperationalamplifierconfiguredasacomparatorthatwilltriggerouropto-couplerinputwhenthepre-settemperatureisreached.So,forfiredetection,wemightwanttodetectwhentheambienttemperaturehasexceeded50°C.
![Page 264: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/264.jpg)
Thetemperaturethresholdsensortodriveourdigitalinput
HowitworksThereferencevoltageissetbythevariableresistor,R4,whichformsavoltagedividerbetweenthe12Vandtheground.Thisessentiallymeansthatthereferencevoltageonthe+veinputoftheop-ampcomparatorcanbebetween0and12V.Assumingthatwewanttodetectwhen50°isreached,wewillneedtheop-amptotriggerwhenthe–veis500mV(10mV/°C).
Inourcircuit,theoutputoftheop-ampishighinitsnormalstate,whichkeepstheopto-coupleron.However,whenthethresholdisreached,theoutputoftheop-ampisdrivenlow,switchingoffthetransistorQ1,andhence,theopto-coupler.ThispullsouralarminputhighviaresistorR2.
![Page 265: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/265.jpg)
AcarbonmonoxidedetectorIt’sentirelypossibletobuildsmokeandcarbon-monoxidedetectorsthatwecanconnecttoourhomesecuritysysteminasimilarwaytotheprevioussensors,althoughtheyarealittlebitmorecomplexastheycanrequirespecialhandling.TheSparkFunMQ-7CarbonMonoxide(CO)detector(whichisactuallymadebyWinsenElectronics)canbeimplementedinasimilarwaytoourtemperaturesensor,triggeringanalarminputwhenaparticularthresholdisreached.
TheWinsenMQ-7carbonmonoxidegasdetector,availablefromSparkFun.
NoteThemaximumsafecontinuousexposuretocarbonmonoxide(CO)is9ppm(parts-per-million)accordingtoASHRAE(www.ashrae.org),andyoushouldcertainlynotbeexposedtoCOhigherthanthisforprolongedperiodsoftime,with35ppmbeingtheabsolutemaximumforanormal8-hourworkingday.
TheMQ-7detectorhasasensitivityofbetween10and500ppm,soinmymind,I’dwant
![Page 266: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/266.jpg)
tobealertedassoonasitpicksupanything,thereforeweshouldsetourcomparator’sreferencevoltagetothelowerendofthescale,inaccordancewiththesensitivitycurvetakenfromthedatasheet,shownasfollows:
ThesensitivitycurvetakenfromtheWinsenMQ-7manufacturer’sdatasheet.
NoteWarning
I’veincludedthissectiononcarbonmonoxidedetectionmoreforinterestthananythingelse.It’snastystuff,andwhilerollingoutyourowndetectorisOKforinterest’ssake,pleasekeepitjustforthat.It’susefultohavethisinourhomesecuritysystemtoalertuswhenwe’reoutofthehouseasanaddition,butthisshouldnotbeareplacementforacommerciallyavailableonethatsitsnexttoyourboilerwithallofthecertifications,standards,andsoon,andmakesaveryloudnoisewhenwe’reinthehouse.
![Page 267: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/267.jpg)
![Page 268: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/268.jpg)
RemoteadministrationforourRaspberryPiInthepreviouschapter,welearnedhowtosetupoursystemandhomenetworksothatwecanremotelyaccessthealarmcontrolpanelfromwhereverweare.I’mnowgoingtoshowyouhowtoextendthistobeabletoadministerandmonitorourentireRaspberryPisystem.
![Page 269: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/269.jpg)
GettingWebminWebminisaratherfineandwellestablishedweb-basedinterfaceforadministeringUnix/Linuxsystems.YoucanfindeverythingaboutWebminonitswebsiteatwww.webmin.com.I’massuming,asthroughoutthisbook,thatyouareusingtheRaspbiandistributiononourPiwhenitcomestoinstallingWebmin.
ThereareacoupleofwaystoinstallWebmin:eitherbymanuallydownloadingandunpackingit,orbyupdatingourrepositorysourcessothatwecanuseapt-get.I’mgoingtooptforthelatter,soanydependenciesareautomaticallyinstalledandupdatescanbemanagedmoreeasilyinthefuture.Thereareafewsteps,butit’sprettystraightforward:
Updatingtherepositorysources1. ThefirstthingweneedtodoisupdateourrepositorysourcestoincludetheWebmin
repositories:
$sudonano/etc/apt/sources.list
2. Addthefollowingtwolinestotheendofthefile:
debhttp://download.webmin.com/download/repositorysargecontrib
debhttp://webmin.mirror.somersettechsolutions.co.uk/repositorysarge
contrib
3. SaveandexitNano.
Importingthesigningkey1. Next,weneedtodownloadandimporttherepository’ssigningkey:
$cd~
$sudowgethttp://www.webmin.com/jcameron-key.asc
$sudoapt-keyaddjcameron-key.asc
2. Nowthatwehaveeverythingweneed,wecanupdatethepackageinstallerandinstallWebmin.Itcantakeawhile,soyoumightwanttogoandmakeyourselfacupofteaorcoffee:
$sudoapt-getupdate
$sudoapt-getinstallwebmin
3. Onceit’sinstalled,youshouldseethefollowingmessageintheshellwindow:
![Page 270: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/270.jpg)
Webmininstallation
AccessingWebminlocallyWebmin,bydefault,runsonport10000andusesthesecureHTTPSprotocol;so,toaccessit,youneedtoenterthefollowingURLinyourbrowser:https://<my-ip>:10000
Where<my-ip>istheIPaddressofyourRaspberryPi.
Inthepreviouschapter,wesetupastaticIPaddressonoursystem;inmycase,Isetuptheaddressas192.168.0.99.So,toaccessWebminonmysystem,Iwoulduse:https://192.168.0.99:10000
NoteHTTPSPrivacyErrors
Insomebrowsers,suchasGoogleChrome,youmightseeaprivacyerrorasyoutrytoaccesstheWebminWebpage.ThisisbecausetheSSLcertificatebehindtheHTTPSconnectionisnotsignedbyaknownauthority.Thisisfine—justtellyourbrowserthatyouwanttoacceptthisandproceed(inChrome,youneedtoclickontheAdvancedlinkfirsttoaccessthatoption).
![Page 271: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/271.jpg)
YoucanlogintoWebminusingtherootorpiuseraccount,oranyotheraccountthathassudorights:
Webminlogin
![Page 272: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/272.jpg)
Onceloggedin,you’llbepresentedwiththemainsysteminformationpage.Haveagoodpokearoundinitbecausethere’slotsofusefulstuffyoucanseeanddo.
Webminsysteminformationview
Webmincomeswithalotofmodules,andnotallofthemareinstalled;therefore,youmightwanttoexploretheUn-usedModulessectionofthepaneltoseeifthereisanythingyouwanttoaddtoWebmin.
RemotelyaccessingWebminInthesamewaythatwesetupremoteaccessforouralarmcontrolpanelinthepreviouschapter,youcandoitwithWebmin—justsetupport-forwardingonyourrouterforport10000.YoucanthenaccessWebminfromanywhereusinghttps://<my-public-ip>:10000.
![Page 273: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/273.jpg)
![Page 274: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/274.jpg)
SummaryWell,thishasbeenabitofamix-and-matchofvarioustopicstoendonbeforeweputtogetherourhomesecuritysystemframework.Ihopeyouenjoyedthesevariousfootnotestopreviouschapters,andthatit’sgivenyousomeideasonhowfaryoucantakeyourhomesecuritysystem.
WestartedbylookingatwayswecanarmanddisarmoursystemwithouthavingtoaccesstheWeb-basedcontrolpanel,byaddingamechanicalordigitalswitchtoanarm/disarminput.
Wethenlookedataddinganalogue-typesensorstooursystem,whichcanalertuswhenathresholdhasbeenreachedbyusingoperationalamplifierssetupasvoltagecomparators.Theideabehindthesecomparatorcircuitscanbeimplementedfordifferenttypesofsensorswhereyouwanttoknowwhenacertainvoltagethresholdhasbeenreachedattheanaloguesensoroutput.
Finally,welearnedhowtoinstallWebminonourRaspberryPisothatwecanmonitorandconfiguremanyaspectsoftheLinuxoperatingsystem.
Thenextchapteristhemomentwe’veallbeenwaitingfor;we’regoingtotakealloftheelementsandconceptsfromthepreviouschaptersandputtogetherourfullsystemcomprisingtheelementswewanttofeature.ThestaroftheshowwillbeourBashscripts,whichwillgluetogetheralloftheseelementsandprovidethecontrollogicfortheentiresystem.
![Page 275: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/275.jpg)
![Page 276: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/276.jpg)
Chapter9.PuttingItAllTogetherOverthepasteightchapters,we’veexploredtheelementsandconceptsofafull-featuredhomesecuritysystemthatyou’dexpecttohaveinstalledinyourproperty.It’sbeenpresentedinamodularfashionsothatyoucanchoosewhichfeaturesyouwantforyoursystem,toallowyoutomakeitascompactandbasicorlargeandcomplexasyourequire.
Fundamentally,theideabehindahomesecuritysystemistodetectwhetherparticularzoneinputsaretriggeredhighorlowbyanexternalsensor,bethataswitch,motiondetector,orwaterdetector.Attheendoftheday,asfarasthecontrolsoftwareisconcerned,thetypeofsensorisirrelevantandthesystemsoftware’sjobistosimplycheckthestateofitsinputsandalertaccordingly.
Inthisfinalchapter,we’regoingtoputalloftheconceptstogethertocomeupwithasecuritysystemframeworkandwritethecontrolscriptsaroundit.Thisiswhatwewillcover:
Definingahigh-leveloverviewofoursystem,detailingtheconnectedelementsBuildingtheentiremodularsecuritysystemframeworkcontrolscript,exploringthecodeindetailDelvingintosomedetailedshellscriptingtechniquestoperformcertaintasksLearninghowtomakeoursystemautomaticallystartatboot-timePreventingtheburningoutofourSDcardbycreatingaRAM-basedfilesystem
![Page 277: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/277.jpg)
AlarmsystemdiagramSothatwedon’tgetlostinthisprocess,thefirstthingIrecommendistocomeupwithacompletesystemdiagramthatwecanfollow.IdothisforanysystemIdesignandputtogethersothatitcanbebuiltinastructuredway,andeasilydocumentedandmodified.
Forthehomesecuritysysteminthischapter,Ihavecomeupwiththefollowingsystemdiagramthatwewilllooktoasaframework.Thewholeconceptisdesignedtobemodular,soyoucancomeupwithyourownsystemtosuityourrequirementsandimplementitaccordingly,usingthescriptspresentedinthischapter.
![Page 278: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/278.jpg)
Thefinalhomesecuritysystemdiagram
![Page 279: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/279.jpg)
OverviewofthesystemelementsTheprecedingsystemdiagramcomprisestheelementsandmodulesthatwehavediscussedinpreviouschapters.Here’saquickrecapofthese:
A+12VpowersupplyThisistheprimarypowersupplytooursystem,whichwewillobtainfromanexternalmainsadapterthatcouldbebattery-backed.Thissupplyneedstobesmoothandregulatedtoensurethatitremainsstableforthesystemascurrentlydrawn.
Allofthealarmwiringandsensorswillbesuppliedwiththispower,aswillperipheralssuchassoundersandbells,whichusuallyoperatefroma12Vsupply.Chapter5,AddingaPassiveInfraredMotionSensordiscussedthemeritsofusinga12Vsupplyforthealarmcircuits.
A+3.3VpowersupplyThissupplyisaregulated+3.3Vsupplyforthedigitalportexpandercircuit;italsoprovidesthelogicalalarmzoneinputsviaanopto-coupler.The+3.3Vpowersupplycanbederivedfromeitherthe+12Vsupply(recommended),orthe+5VsupplyfromtheRaspberryPi’sGPIOconnector,usingavoltageregulatorchosenaccordingtohowmuchcurrentyouneed.
Chapter3,ExtendingYourPitoConnectMoreThings,showedyouhowtobuilda+3.3Vregulatedsupply.
Theopto-isolatorinputmoduleThiswillisolatethe+12VzoneinputpowerlinesfromtheportexpanderandGPIOdigitalinputs,whichshouldonlyhaveamaximumof+3.3Vpresentedtothemwhentriggeredhigh.
Thecircuitfortheseopto-isolatedinputmoduleswasdiscussedandshowninChapter5,AddingaPassiveInfraredMotionSensor.
TheportexpanderTheportexpanderisourmaindigitalinput/outputsystemthatwilltakethealarmzoneinputsandtransmitthemtotheRaspberryPiusingtheI2Cbus,orallowtheRaspberryPitoswitchoutputsonandoff.
WebuiltourMCP23017-basedportexpandercircuitinChapter3,ExtendingYourPitoConnectMoreThingsandconfiguredthesoftwareforitinChapter4,AddingaMagneticContactSensor.
Anarm/disarmswitchThearm/disarminputoverridesthearm/disarmsoft-switchfunctiononourweb-basedcontrolpanel,andisaswitch(key,digitalkeypad,orotherwise)connectedtoGP0directlyontheRaspberryPi’sGPIOconnector.
![Page 280: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/280.jpg)
RemembertoconnectanyswitchcircuitappropriatelytotheGPIOpintoavoiddamagetoyourRaspberryPi.ThiswasdiscussedinChapter2,ConnectingThingstoYourPiwithGPIO.
AlarmoutputsInoursystem,wehaveseveraloutputdevicesthatarecontrolledbyourRaspberryPiviaoutputdrivercircuits.Wehaveanoutputforanentry/exitbuzzer,anarmedstatusLED,analarmbell,andanalarmLEDindicator.
TheseareswitchedonandoffbyourRaspberryPiGPIOconnectorviadrivercircuitsthatallowustodrivehighcurrentandinductiveloadsusingtheGPIOpins.Thesedrivercircuits,basedaroundTIP120Darlingtontransistors,werediscussedinChapter6,AddingCamerastoOurSecuritySystemandChapter8,AMiscellanyofThings.
![Page 281: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/281.jpg)
![Page 282: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/282.jpg)
DesigningthecontrolscriptsBeforewestartwritingthescriptstocontrolouralarmsystems,itisprobablyagoodideatooutlinethehigh-levelprocessforthesystem.Thefollowingflow-charthelpsuspicturehowoursystemshouldwork,andthevariouslogicaldecisionsourscriptneedstomake.
Theflowchartmightlookabitcomplicatedwithallitslinesindifferentdirections,butit’sactuallyprettylinearandinadownwarddirection.Referringtotheflowchart,itshowsthefollowingtasksthatthecontrolscriptwillbedoing:
Sittingquietlyuntilthesystemisarmedeitherbythehardwarekeyswitchortheweb-basedpanel’ssoftswitch.Whenthesystemisfirstarmed,itwillsoundtheexitbuzzerforapre-determinedamountoftimebeforeactuallyarmingthesystem.Thisgivesyouachancetoleavethepropertyordisarmthesystemagain,beforeitstartsmonitoringtheinputs.Oncethesystemisarmed,thearmedLEDwillbeswitchedonandthesystemwillwaittoseeifanyofthealarmzoneinputsaretriggered.Itwillalsowaittoseeifthealarmisdisarmedonyourreturntotheproperty.Wecanoptionallyputanentrytimerinhereontheentryzonetodelaybeforetriggeringthealarm.Ifthealarmisultimatelytriggered,thenthemainalarmbellwillbeswitchedon,aswellastheexitbuzzer.Themainbellshouldonlysoundforawhile,dependingonenvironmentalrestrictionsinyourneighborhood,andso,thiswillbeswitchedoffafterapre-definedperiod,buttheinternalbuzzerwillstayon.Whentriggered,thesystemwillthenwaitforyoutodisarmit,beforeresettingit.
![Page 283: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/283.jpg)
![Page 284: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/284.jpg)
Thecontrolscriptflowchart
![Page 285: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/285.jpg)
![Page 286: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/286.jpg)
BuildingthecontrolscriptNowthatwehavedesignedoursystemthewaywewantittowork,wecanstartwritingourBashcontrolscript.Asbefore,we’lllocateourscriptsinthefolder,/etc/pi-alarm,which,you’llrememberfromChapter7,BuildingaWeb-BasedControlPanel,isalsowhereourWeb-basedcontrolpanelwritesitsconfigurationstatusfile,alarm.cfgto.We’llbereferringtothatfileinourscriptstoo.
Inthisscript,wearegoingtousethebctool(theBashcommand-linecalculator)toconverthexvaluestobinary.It’snotinstalledbydefault,soyou’llneedtogetthepackage:
$sudoapt-getupdate
$sudoapt-getinstallbc
TipOurscriptfileisquitelongso,asbefore,youmightwanttositonthesofaandwriteitonyourlaptopusingsomethingsuchasNotepad++.Remember,however,ifyou’reusingaPC,ensurethattheend-of-line(EOL)formatisconvertedtotheUnixformat,otherwisetheBashscriptwon’trunonthePiwhenyoucopyitacross.Notepad++willdothisforyou.
![Page 287: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/287.jpg)
ExploringthescriptcodeI’mnowgoingtowalkyouthroughthevarioussectionsofthecontrolscriptcodeI’vewritten,whichwillbeusedasaframeworkforoursystem.Isay“framework”because,whileitwillprovideyouwithafullyfunctionalcontrolscriptforthesystem,itcanbemodifiedandextendedtosuityourparticularrequirements.
Thefollowingcodelistingsareallpartofthesinglebashscript,alarm-control.sh,thatcanbedownloadedinfullwithcommentsfromthePacktPublishingwebsite.
DeclarationsWe’llstartoffbysettingupthevariouscontrolvariablesneededtotrackthesystem’sstate:
#!/bin/bash
#/etc/pi-alarm/alarm-control.sh
ALM_BELL_DURATION=600#durationinsecondsthealarmbellshouldsound
for
ALM_EXIT_DELAY=30#entry/exitzonedelayinseconds
ALM_KEY_ARMED=0#statusofthearm/disarmkeyswitch
ALM_SYS_ARMED=0#armedstatusofthesystem
ALM_ZONE_INPUT_READ=""#thiswillstorethevalueofthezoneinputs
read
ALM_ZONE_INPUT_STAT="00000000"#binaryrepresentationoftheinputs(b7-
b0)
ALM_ZONE_INPUT_PREV=""#previouszoneinputstatus
ALM_ZONE_TRIGGER=0#thiswillbesetto1ifoneormorezonesis
triggered
ALM_ZONES_STAT=(00000000)#dynamicarrayofnormalisedzone
status(z1toz8order)-1istriggered
STAT_RET_VAL=""#returnvaluefromfunctions
BecausewecouldfacethesituationwherebyaHIGHoraLOWinputcouldrepresentatriggeredzone,dependingonitsconfigurationandwiring,Ihaveintroducedanarrayofnormalizedstatusflagsinthevariable,ALM_ZONES_STAT,whichwillbethedefinitivestateasfarasthescriptisconcerned.We’lllookatthefunctionthatdealswiththislater.
UpdatingconfigsettingsInChapter7,BuildingaWeb-BasedControlPanel,weintroducedtheconfigurationfile,alarm.cfg,whichstoresthesystemstatusandconfigurationforthebenefitoftheWeb-basedcontrolpanel.Thisfilenotonlyneedstobereadbythemaincontrolscripttogetanysettingsmadeusingthecontrolpanel,butalsoneedstobeupdatedwithstatusvaluesfromthemaincontrolscriptsothattheycanbepresentedbacktothecontrolpanel,essentiallyexchangingdatabetweenthetwosub-systems.
Therefore,we’regoingtoincludeahelperfunctionthatcontainsthesamecodecalledbytheWebpagePHPscripttoupdatethisfilefromthecontrolpanel:
![Page 288: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/288.jpg)
#Thishelperfunctionwillupdatethealarmconfig
#filewiththespecifiedvalue(alarm.cfg)sothat
#theWebpanelcanknowthelateststatus
functionalmUpdateConfigSetting()
{
#$1-SettingName
#$2-SettingValue
sudosed-i"s/^\($1\s*=*\).*/\1$2/"/etc/pi-alarm/alarm.cfg
}
SettinguptheGPIOWenowneedtosetuptheRaspberryPi’sGPIOpinsforourpurposes,asoutlinedbytheearliersystemdiagram.ThefollowingcommandswerefirstdiscussedinChapter2,ConnectingThingstoYourPiwithGPIO:
#GPIOSETUP###################################
#SetuptheRaspberryPiGPIOpins
#RefertoChapter2forinfo
#D0(GPIO17)Arm/DisarmKeyInput
sudoecho17>/sys/class/gpio/export
sudoechoin>/sys/class/gpio/gpio17/direction
#D4(GPIO23)ArmedLEDOutput
sudoecho23>/sys/class/gpio/export
sudoechoout>/sys/class/gpio/gpio23/direction
sudoecho0>/sys/class/gpio/gpio23/value
#D5(GPIO24)ExitBuzzerOutput
sudoecho24>/sys/class/gpio/export
sudoechoout>/sys/class/gpio/gpio24/direction
sudoecho0>/sys/class/gpio/gpio24/value
#D6(GPIO25)AlarmLEDOutput
sudoecho25>/sys/class/gpio/export
sudoechoout>/sys/class/gpio/gpio25/direction
sudoecho0>/sys/class/gpio/gpio25/value
#D7(GPIO4)AlarmBellOutput
sudoecho4>/sys/class/gpio/export
sudoechoout>/sys/class/gpio/gpio4/direction
sudoecho0>/sys/class/gpio/gpio4/value
NoteNotethatyoucanonlyexportaGPIOpinonce,unlessithasbeensubsequentlyunexported.Therefore,youmightseetheerror,echo:writeerror:Deviceorresourcebusy,ifyoure-runthescriptwhenittriestoexportthepinagain.Youcansafelyignorethis.
We’llalsothrowinafewhelperfunctionsthatwilleasilyallowustoswitchonoroffvariousoutputstosimplifythemaincode.I’mabigfanofimplementingfunctions,howeversimple,astheykeepthecodemodular,reusable,andsimplertoreadinmostcases:
![Page 289: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/289.jpg)
#ThishelperfunctionwillswitchaspecifiedGPIOoutputonoroff
functionalmSetGPIOValue()
{
#$1-GPIOpinnumber
#$2-Value
sudoecho$2>/sys/class/gpio/gpio$1/value
}
#Helperfunctionstoswitchonandofftheoutputs
functionalmSetArmedLED()
{
#$1-0or1(OfforOn)
almSetGPIOValue23$1
echo"[ALM]ArmedLEDsetto$1"
}
functionalmSetExitBuzzer()
{
#$1-0or1(OfforOn)
almSetGPIOValue24$1
echo"[ALM]ExitBuzzersetto$1"
}
functionalmSetAlarmLED()
{
#$1-0or1(OfforOn)
almSetGPIOValue25$1
echo"[ALM]AlarmTriggerLEDsetto$1"
}
functionalmSetAlarmBell()
{
#$1-0or1(OfforOn)
almSetGPIOValue4$1
echo"[ALM]AlarmBellsetto$1"
}
And,we’lladdahelperfunctionthatwillreadtheARMswitchstatusfromtheD0(GPIO17)oftheRaspberryPiandfromtheweb-consoletoseeiftheARMsoftswitchhasbeenset:
#thisfunctionreturnswhetherthesystemisarmedvia
#eitherthewebconsoleorkeyswitch
functionalmGetArmedSwitchStatus()
{
STAT_RET_VAL="0"
#readarmkeyswitchinputfrom
localL_VAL=$(sudocat/sys/class/gpio/gpio17/value)
if[$L_VAL-eq1];then
#systemhasbeenarmedwithkeyswitch
echo"[ALM]SystemARMEDwithkeyswitch"
ALM_KEY_ARMED=1
almUpdateConfigSetting"SYSTEM_ARMED""1"#setsystemarmedconsole
flag
STAT_RET_VAL="1"
else
#readsystemarmedvaluefromwebconsoleconfigfile
if[$SYSTEM_ARMED==1];then
echo"[ALM]SystemARMEDwithwebconsole"
STAT_RET_VAL="1"
![Page 290: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/290.jpg)
fi
fi
}
SettinguptheI2CportexpanderThenextfewlinesofcodesetuptheI2Cportexpandertosetallofthepins,onbothPortAandPortB,asinputs.Inoursystemhere,we’reonlyusingPortA,butthisallowsustohaveanother8inputsifwewanttoexpandoursystem.WeoriginallylookedatthisinChapter4,AddingaMagneticContactSensor:
#PORTEXPANDERSETUP##########################
#RefertoChapter4formoreinformationabouttheI2Cbus
#WewillsetupI/OBUSAasallinputs
sudoi2cset-y10x200x000xFF
#Whilstwe'renotusingBUSBinoursystem,
#wecansetthatupasallinputstoo
sudoi2cset-y10x200x010xFF
NoteIfyoudon’thaveyourI2Cportexpanderattached,thenyou’llseethefollowingerrorwhenyoutrytorunthesecommands:Error:Writefailed
DecodingthezoneinputsstatusThenextfunctionisabigone—andkeytooursystem.ItwillreadthePortAvaluefromtheI2Cportexpander.It’llbereturnedasahexadecimalvalue,soweneedtoconvertthistoabinaryvaluewitha0or1flagrepresentingeachinputbit.We’llusethebctoolinstalledearliertodothis.
Oncewehavethestatusofeachinputbit,wethennormalizethestatusbydeterminingwhethera0ora1determinesapositivetrigger.Theresultingoutputisthearray,ALM_ZONES_STAT,whichcontainsthestatusofeachzone—witha1representingapositivetriggeredzonede-facto:
#Thisfunctionwillreadtheportinputsandsetthe
#statusofeachzone
functionalmReadZoneInputs()
{
#preservepreviouszonestatus
ALM_ZONE_INPUT_PREV=$ALM_ZONE_INPUT_STAT
#readthe8-bithexvalueofporta
ALM_ZONE_INPUT_READ=$(sudoi2cget-y10x200x12)
if[[$ALM_ZONE_INPUT_READ=*"Error"*]];then
#AnerroroccurredreadingtheI2Cbus-setdefaultvalue
ALM_ZONE_INPUT_READ="0x00"
fi
#removethe0xatthestartofthevaluetogetthehexvalue
localL_HEX=${ALM_ZONE_INPUT_READ:2}
#convertthehexvaluetobinary
![Page 291: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/291.jpg)
localL_BIN=$(echo"obase=2;ibase=16;$L_HEX"|bc)
#zeropadthebinarytorepresentall8bits(b7-b0)
ALM_ZONE_INPUT_STAT=$(printf"%08d"$L_BIN)
echo"[ALM]ZoneI/OStatus:$ALM_ZONE_INPUT_STAT($ALM_ZONE_INPUT_READ)"
#checkeachzoneinputtoseeifit'sinatriggeredstate
#atriggeredstatemaybeeither1or0dependingontheinput's
configuration
#you'llneedtosetthelogichereaccordinglyforeachinput
#theALM_ZONES_STATarraycontainsthedefinitivetriggervalueforeach
input
#zone1test(bit0)
localL_FLG=${ALM_ZONE_INPUT_STAT:7:1}
if[$L_FLG-eq0];thenALM_ZONES_STAT[0]=0;elseALM_ZONES_STAT[0]=1;
fi
#zone2test(bit1)
localL_FLG=${ALM_ZONE_INPUT_STAT:6:1}
if[$L_FLG-eq0];thenALM_ZONES_STAT[1]=0;elseALM_ZONES_STAT[1]=1;
fi
#zone3test(bit2)
localL_FLG=${ALM_ZONE_INPUT_STAT:5:1}
if[$L_FLG-eq0];thenALM_ZONES_STAT[2]=0;elseALM_ZONES_STAT[2]=1;
fi
#zone4test(bit3)
localL_FLG=${ALM_ZONE_INPUT_STAT:4:1}
if[$L_FLG-eq0];thenALM_ZONES_STAT[3]=0;elseALM_ZONES_STAT[3]=1;
fi
#zone5test(bit4)
localL_FLG=${ALM_ZONE_INPUT_STAT:3:1}
if[$L_FLG-eq0];thenALM_ZONES_STAT[4]=0;elseALM_ZONES_STAT[4]=1;
fi
#zone6test(bit5)
localL_FLG=${ALM_ZONE_INPUT_STAT:2:1}
if[$L_FLG-eq0];thenALM_ZONES_STAT[5]=0;elseALM_ZONES_STAT[5]=1;
fi
#zone7test(bit6)
localL_FLG=${ALM_ZONE_INPUT_STAT:1:1}
if[$L_FLG-eq0];thenALM_ZONES_STAT[6]=0;elseALM_ZONES_STAT[6]=1;
fi
#zone8test(bit7)
localL_FLG=${ALM_ZONE_INPUT_STAT:0:1}
if[$L_FLG-eq0];thenALM_ZONES_STAT[7]=0;elseALM_ZONES_STAT[7]=1;
fi
echo"[ALM]ZoneTriggerStatus:$ALM_ZONES_STAT[*]"
}
Initialization
![Page 292: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/292.jpg)
Nowthatwehavedeclaredourmodule-levelvariablesandhelperfunctions,wewillstartourmainroutine.First,we’llinitializethesystemthatclearstheSYSTEM_ARMEDstatusandreadsintheinitialsettingsfromtheconfigfile:
#initialisesystem#########
echo"[ALM]Initialisingsystem…"
almUpdateConfigSetting"SYSTEM_ARMED""0"#clearsystemarmedconsoleflag
sleep1
sudocat/etc/pi-alarm/alarm.cfg
sleep1
echo"[ALM]Initialisingdone"
#############################
ThesystemmonitoringloopThescriptthenjumpsintoanever-endingloopthatwillbethemaincontrolsystem,monitoringthearm/disarmstatusand,whenarmed,monitoringthezoneinputstatusandrespondingaccordingly:
#loopcontinuously###########
whiletrue
do
#waitforsystemtobearmed###############
echo"[ALM]AlarmnowinSTAND-BYstate-waitingtobearmed"
almSetArmedLED0#switchoffarmedLED
STAT_RET_VAL="0"
while[[$STAT_RET_VAL="0"]];do
sleep1
#readthecontrolpanelstatusfile
./etc/pi-alarm/alarm.cfg
almGetArmedSwitchStatus#resultisreturnedinSTAT_RET_VAL
echo-n"*"#indicatestandbymode
done
#############################################
ArmingthesystemWhenthesystemgoesintotheARMEDstate,itwillfirstswitchontheexitbuzzerandthenwaitforapre-determinedamountoftime.Thiswillgiveyoutimetoleavethepropertyordisarmthesystem:
#performexitdelay########################
echo"[ALM]AlarmnowinEXITDELAYstate"
almSetExitBuzzer1#switchonexitbuzzer
COUNTER=$ALM_EXIT_DELAY
while[[$STAT_RET_VAL="1"&&$COUNTER-gt0]];do
sleep1
#readthecontrolpanelstatusfile
./etc/pi-alarm/alarm.cfg
almGetArmedSwitchStatus#resultisreturnedinSTAT_RET_VAL
COUNTER-=1
echo-n"X$COUNTER"#indicateexitmode
done
almSetExitBuzzer0#switchoffexitbuzzer
![Page 293: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/293.jpg)
#############################################
#systemnowarmed-monitorinputs#########
ALM_SYS_ARMED=1
echo"[ALM]AlarmnowinARMEDstate"
almSetArmedLED1#switchonarmedLED
#readthecontrolpanelstatusfile
./etc/pi-alarm/alarm.cfg
almReadZoneInputs#>ALM_ZONES_STAT[x]
MonitoringthezonesOncearmed,thesystemwillmonitorthezoneinputsinacontinuousloopuntileitherthesystemisdisarmed,orazoneinputistriggered.Whenazoneistriggered,itwillcheckagainsttheZONE_ENABLE_nconfigurationtoseeifthatzonehasbeendisabled(thisisdoneintheWeb-basedcontrolpanel).Ifthezoneisnotdisabled,thenthealarmsystemisdeemedtriggered.
TheZONE_STATUS_nsettingisalsoupdatedheresothattheweb-basedcontrolpanelindicateswhichzoneorzoneshavebeentriggered:
#checkeachzoneinputtosetifit'senable
#andhasbeentriggered
#NUM_ZONESsettingisstoredinalarm.cfg
while[[$ALM_SYS_ARMED-eq1]];do
echo-n"A"#indicatearmedmode
ALM_ZONE_TRIGGER=0
for((i=$NUM_ZONES;i>0;i--));do
if[[$ALM_ZONES_STAT[$i-1]-eq1]];then
#zonehasbeentriggered
echo"[ALM]Zone$iTRIGGERED"
E_VAR="ZONE_ENABLE_$i"
E_VAL=`echo"$E_VAR"`#getzoneenabledstatusloadedfrom
alarm.cfg
if[[$E_VAL-eq1]];then
#zoneisenabled
ALM_ZONE_TRIGGER=1#setalarmtriggeredflag
echo"[ALM]Zone$iENABLED-alarmwillbetriggered"
almUpdateConfigSetting"ZONE_STATUS_$i""1"
##YOUCANINSERTCODEHERETOTAKECAMERAIMAGEIFYOUWANT##
##REFERBACKTOCHAPTER6##
fi
fi
done
./etc/pi-alarm/alarm.cfg
almGetArmedSwitchStatus#resultisreturnedinSTAT_RET_VAL
Entrydelay
![Page 294: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/294.jpg)
Whenanalarmzoneistriggered,itwillfirstcheckwhetheritwastheentry/exitzonethatwastriggered.Ifitwas,thenthesystemwilldelaybeforesoundingthemainalarmtogiveyouachancetodisarmthesystem.Onlytheentrybuzzerwillsoundatthistime:
if[[$ALM_ZONE_TRIGGER-eq1]];then
#alarmhasbeentriggered
almSetAlarmLED1
echo"[ALM]Azonehasbeentriggered"
#####################################
#ZONE1istheENTRYzone-ifthat'striggeredthendelay
if[[$ALM_ZONES_STAT[0]-eq1]];then
#performentrydelay###########
echo"[ALM]AlarmnowinENTRYstate"
setExitBuzzer1#switchonentry/exitbuzzer
COUNTER=$ALM_EXIT_DELAY
STAT_RET_VAL="0"
while[[$STAT_RET_VAL="1"&&$COUNTER-gt0]];do
echo-n"E$COUNTER"#indicateentrymode
sleep1
#readthecontrolpanelstatusfile
./etc/pi-alarm/alarm.cfg
almGetArmedSwitchStatus#resultisreturnedinSTAT_RET_VAL
COUNTER-=1
done
fi
#####################################
SoundingthemainalarmIf,atthispoint,thesystemhasn’tbeendisarmed,thenweneedtosoundthemainbell.Wehaveadurationlimitforsoundingthebelltocatertoenvironmentalnoiserestrictions;wewouldn’twantthealarmsoundingforhours,annoyingtheneighborsuntilwegothome.Atthispoint,youcanalsoaddcodefromChapter6,AddingCamerastoOurSecuritySystem,ifyouwanttobesentanalertemailtoyourmobiledevice:
#####################################
#STAYinTRIGGEREDmodeuntilsystemhasbeendisarmed
if[[$STAT_RET_VAL="1"]];then
#alarmhasnotbeendisabled
almSetAlarmBell1#switchonalarmbell
echo"[ALM]AlarmnowinTRIGGEREDstate"
##YOUCANINSERTCODEHERETOSENDYOUANEMAILIFYOUWANT##
##REFERBACKTOCHAPTER6##
COUNTER=0
STAT_RET_VAL="0"
while[[$STAT_RET_VAL="1"]];do
echo-n"T$COUNTER"#indicatetriggeredmode
sleep1
#readthecontrolpanelstatusfile
./etc/pi-alarm/alarm.cfg
almGetArmedSwitchStatus#resultisreturnedinSTAT_RET_VAL
![Page 295: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/295.jpg)
COUNTER+=1
if[[$COUNTER-gt$ALM_BELL_DURATION]];then
almSetAlarmBell0#switchoffalarmbell
echo"[ALM]BellhasbeenswitchedOFF"
fi
done
fi
#####################################
DisarmingandresettingthesystemWhenwedisarmthesystem,weneedtoresetitsstatusandcompletethemonitoringloopsothatwecanstartalloveragainandwaitforittobere-armed:
#alarmhasbeendisarmed##########
echo"[ALM]AlarmhasbeenDISARMED"
ALM_SYS_ARMED=0
almSetAlarmBell0#switchoffalarmbell
almSetExitBuzzer0#switchoffexitbuzzer
almSetAlarmLED0
almSetArmedLED0#switchoffarmedLED
#####################################
fi
done
#############################################
done
#############################################
We’redone(almost)…Andtherewehaveit:aframeworkforanentirealarmcontrolscriptonourRaspberryPi.Additionalfeaturesthatyoumaywanttoimplementwithinyourscriptcouldincludethefollowing:
Sendingaphotoorvideoclipfromazone’scamerawhenit’striggeredSendinganemailalertwithstatusdetailswhenthealarmhasbeentriggeredWritingaregularlogfilerecordinghistoricalstatusinformationAddingadditionalenvironmentalsensorstoportB
TipEachofthescriptblocksistakenfromthesinglescriptfile,alarm-control.sh,soyoushouldbeabletoputallofthedescribedpiecestogetherintoonefiletohaveafullyfunctionalscript.
Asalways,beforewecanrunitweneedtogivethescriptexecuterights:
$sudochmod777/etc/pi-alarm/alarm-control.sh
AfterwecopythescripttoourRaspberryPi,thisiswhatweshouldseeinour/etc/pi-alarmfolder:
![Page 296: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/296.jpg)
pi@raspberrypi~$ls-1/etc/pi-alarm
alarm.cfg
alarm-control.sh
update-alarm-setting.sh
![Page 297: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/297.jpg)
![Page 298: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/298.jpg)
AutomaticallystartingthesystemNow,obviously,wedon’twanttohavetomanuallystartthealarmcontrolscripteachtimetheRaspberryPibootsup,forexample,afterapowerfailure—forastart,wemaynotevenbethere.Therefore,weneedtosetupouroperatingsystemsothatitwillautomaticallystartupthealarm-control.shscriptatboottime.
Todothis,weneedtoedittherc.localfileusingNano:
$sudonano/etc/rc.local
Beforethelinecontainingexit0,insertthefollowingline:
sudo/etc/pi-alarm/alarm-control.sh&
NoteThe&symbolattheendofthelineisimportantbecauseitwillthenmakethescriptruninadifferentprocess,otherwisetherc.localscriptwouldneverexit.
Yourrc.localfileshouldnowlooksomethinglikethis:
#!/bin/sh-e
#
#rc.local
#
#Thisscriptisexecutedattheendofeachmultiuserrunlevel.
#Makesurethatthescriptwill"exit0"onsuccessoranyother
#valueonerror.
#
#Inordertoenableordisablethisscriptjustchangetheexecution
#bits.
#
#Bydefaultthisscriptdoesnothing.
#PrinttheIPaddress
_IP=$(hostname-I)||true
if["$_IP"];then
printf"MyIPaddressis%s\n""$_IP"
fi
sudo/etc/pi-alarm/alarm-control.sh&
exit0
Theoperatingsystemrunstherc.localscriptafterthesystembootsup,soyoucanputanythingintherethatyouwanttohappenautomaticallyatthistime.
![Page 299: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/299.jpg)
![Page 300: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/300.jpg)
PreservingtheSDcardOnefinaltopicIwanttosharewithyouisthatofpreservingyourRaspberryPi’sSDcard.SDcardshaveafinitewritecycle,andcontinuouswritingtothecardwilleventuallyburnitout.Ifwe’regoingtobewritinglotsoflogfileentriesandtakinglotsofcameraimages,wewillwanttoprotectourSDcardinordertomaintaintheintegrityandreliabilityofoursystem;usingthesystemRAMinsteadcanhelpuswiththis.
![Page 301: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/301.jpg)
CreatingaRAM-basedfilesystemOurRaspberryPihasplentyoffastsystemRAMavailabletous(1Gbonthelatestmodels)thatisn’tsusceptibletothiswriteburn-outissue.Therefore,I’mgoingtoshowyouhowtoallocatesomeofittocreateatemporarydiskinmemory,whichwecanwritefilestothatwedon’tneedkeptontheSDcard.Suchfileswouldincludethe,quitelarge,cameraimagefilesthatwillbeemailedoutofthesystem—which,therefore,don’tneedtobestoredpermanently.Youshouldalsoconsideranylogfilesthatareregularlywrittento,whichwouldthenbeshippedoffthesystematregularintervals.
NoteRememberthatthisisaRAM-basedfilesystem,socontentwillbelostwhentheRaspberryPishutsdownorreboots.So,don’tstoreanydataherethatyouwanttopersistafterarestart.
Let’screateaBashscriptfilecalledsetup-ramfs.sh,andcopyittoour/etc/pi-alarmfolder:
#!/bin/bash
#/etc/pi-alarm/setup-ramfs.sh
RAM_DISK="/ramfs"
RAM_DISK_SIZE=64M
#CreateRAMDisk##########################
if[!-z"$RAM_DISK"];then
echo"[INIT]CreatingRAMDisk…$RAM_DISK"
mkdir-p$RAM_DISK
chmod777$RAM_DISK
mount-ttmpfs-osize=$RAM_DISK_SIZEtmpts$RAM_DISK/
echo"[INIT]RAMDiskcreatedat$RAM_DISK"
fi
############################################
setup-ramfs.shRAMdiskcreationscript
RunningtheprecedingscriptwillcreateaRAMdiskfolderat/ramfs—youcantreatitjustlikeanyotherfolder;it’sjustthatitresidesinthesystemmemoryratherthanontheSDcard:
$cd/ramfs
$ls
Youcancallthisscriptfromthealarm-control.shscriptaspartoftheinitializationprocessbyincludingtheline:
./etc/pi-alarm/setup-ramfs.sh
![Page 302: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/302.jpg)
![Page 303: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/303.jpg)
ConclusionTheRaspberryPiisapowerfullittlebeastandagreatplatformforbuildinglow-cost,buthighlycapable,embeddedsystems.TheinterfacesbuiltintoitsGPIOconnectormakeiteasytoboltonmodulesusingsimplelow-costelectronicsandabitofconfigurationtocreateveryfunctionalandflexiblesystems.TheinclusionofadedicatedcamerainterfaceandnetworkinginterfacesgiveyoueverythingyoucouldpossibleneedforanInternet-connectedhomesecuritysystem.
I’vecoveredalotoftopicsinthisbook,andIcouldhavegoneonandon,butIhopethatwhatIhavepresentedhasbeendoneinastructuredandmethodicalway,andhasgivenyouthetoolsandtechniquestocarryonthisjourneysothatyouareabletocreatetheperfecthomesecuritysystemforyourneeds.
![Page 304: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/304.jpg)
TipsforbuildingsystemsAsasystemsguywhohastoworkwithmanydifferenttechnologiesanddisciplinesonaday-to-daybasis,Ijustwanttoleaveyouwiththefollowingthoughtstoconsider,ifyouchoosetobuilduponthesystemwe’veputtogetherinthisbook,which,ofcourse,Ihopeyouwill:
Createahigh-leveldiagramofyourproposedsystemfirst—abitliketheoneIproducedearlierinthischapter.Defineeverythinginamodularwaysothatyoucanbuildandtestyoursysteminsmallchunks.Thismakesitmucheasiertospotissuesearlyon.Buildingthesystemusingsmallermodulesmakesiteasiertore-useandreplacecircuitsandcode,anddon’tbeafraidtomix-and-matchtechnologiesusingwhat’sbestfortheindividualmodule.Don’ttrytore-inventthewheel—useexistingcodeandcircuitresourcesthatareproventowork.Thismakesitmuchquickertogetthingsworkingandminimizesthenumberoftimesyouhavetohityourheadagainstabrickwall.Icallitblagging.
![Page 305: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/305.jpg)
![Page 306: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/306.jpg)
SummaryWell,we’vereachedtheendofourjourneytobuildafullyfunctionalandextensiblehomesecuritysystemusingthemightyRaspberryPimini-PC.Inthisfinalchapter,weputtogetheralloftheelementsandconceptsfromthepreviouschapterstocreateahomesecurityframework,bothfromahardwareandsoftwareperspective.
Inparticular,thischapterguidedustowardbuildingamodularframeworkforourhomesecuritysystem,implementingfeaturesthatyouwouldfindinanycommerciallyavailablesystem,andalsothingsthatyoudon’tseeoutthere.Wewalkedthroughthecompletecontrolscript,exploringitsvarioussectionsandunderstandinghowtheyfitintooursystem.
Wealsolearnedhowtoautomaticallystart-upourhomesecuritysystemscriptwhenourRaspberryPibootsup,andhowdataissharedbetweenthePiandtheweb-basedcontrolpanelinreal-timeviatheconfigurationfile.Finally,welookedathowtopreventourSDcardfromburningoutbycreatingaratherusefulRAM-basedtemporaryfilesystem.
![Page 307: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/307.jpg)
IndexA
alarmsystemabout/Alarmsystemdiagramdiagram/Alarmsystemdiagramelements/Overviewofthesystemelementsstartingautomatically/Automaticallystartingthesystembuilding,tips/Tipsforbuildingsystems
anti-tampercircuitsabout/Anti-tampercircuits
anti-tamperloop/Anti-tampercircuitsArduino/Gertboardarm
about/Armingyourselfdocumenting/Armingyourself
armdevice/Connectinga433-MHzreceiverASHRAE
URL/AcarbonmonoxidedetectorATmegamicrocontroller/Gertboardattachments
sending/Sendingattachments
![Page 308: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/308.jpg)
BBashcommand-linecalculator(bctool)
usedforconvertinghxvaluestobinary/BuildingthecontrolscriptBashscript/I’msomeoneelsebattery-backed/A+12Vpowersupplybitbanging/Thealternativeapproach(becausewehavenochoice)
![Page 309: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/309.jpg)
Ccamera,addingtosecuritysystems
prerequisites/PrerequisitesRaspberryPicameramodule/TheRaspberryPicameramodulePiNoIRcameramodule/NightvisionUSBwebcam/UsingUSBcameras
cameraserialinterface(CSI)/TheRaspberryPicameramodulecarbonmonoxide(CO)detector
about/Acarbonmonoxidedetectorcascadingstyle-sheet(CSS)/Creatingthewebpagecontrolpanel
remoteaccess,settingup/RemoteaccesstoourcontrolpanelcontrolpanelHTMLtemplate/ThecontrolpanelHTMLtemplatecontrolscripts
designing/Designingthecontrolscriptsbuilding/Buildingthecontrolscriptcode,exploring/Exploringthescriptcode
controlscriptscodeexploring/Exploringthescriptcodedeclarations/Declarationsconfigsettings,updating/UpdatingconfigsettingsGPIO,settingup/SettinguptheGPIOI2Cportexpander,settingup/SettinguptheI2Cportexpanderzoneinputsstatus,decoding/Decodingthezoneinputsstatusinitialization/Initializationsystemmonitoringloop/Thesystemmonitoringloopsystem,arming/Armingthesystemzones,monitoring/Monitoringthezonesentrydelay/Entrydelaymainalarm,sounding/Soundingthemainalarmsystem,disarming/Disarmingandresettingthesystemsystem,resetting/Disarmingandresettingthesystemfeatures,implementing/We’redone(almost)…
controlvariables/Declarations
![Page 310: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/310.jpg)
Ddatalogging
detecting/Loggingdetectiondataddclientupdater/TheRaspberryPidynamicDNSclientdigitalI/Opins/DigitalI/Opinsdisarm
about/Armingyourselfdisarmdevice/Connectinga433-MHzreceiverDnsOMatic
URL/SettingupadynamicDNSaccountdoors/TheworkingofmagneticcontactsensorsdynamicDNSaccount
settingup/SettingupadynamicDNSaccountRaspberryPidynamicDNSclient/TheRaspberryPidynamicDNSclient
DynDNSURL/SettingupadynamicDNSaccount
![Page 311: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/311.jpg)
Eelaboratelightswitch
about/Themostelaboratelightswitchintheworld,TheElaboratelightswitchre-visitedbreadboard/Themostelaboratelightswitchintheworldcircuitdiagram/Themostelaboratelightswitchintheworldilluminatingscript/Theilluminatingscript
electronickeypad/Arminganddisarmingthesystemelements,alarmsystem
overview/Overviewofthesystemelements+12Vpowersupply/A+12Vpowersupply+3.3Vpowersupply/A+3.3Vpowersupplyopto-isolatorinputmodule/Theopto-isolatorinputmoduleportexpander/Theportexpanderarm/disarmswitch/Anarm/disarmswitchoutputs/Alarmoutputs
emailnotification,setting/Youhavenewmailsenderclient,settingup/Settingupthee-mailsenderclientattachments,sending/Sendingattachmentsinformation,obtaining/Wherewasthattaken?
entry/exitpurposes/Armingyourself
![Page 312: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/312.jpg)
Ffake-hwclockpackage/fake-hwclockffmpegtool/Beavideostarfilesystem,SDCard
raspi-configutility,using/BootingyourPi,Usingtheraspi-configutilityexpanding/Expandingthefilesystem
fixedIPaddress/SettingupadynamicDNSaccountflow-chart/Designingthecontrolscriptsfritzing
URL/Lettherebelightfswebcam
URL/Installingthewebcam
![Page 313: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/313.jpg)
GGertboard
about/GertboardURL/Gertboard
GPACpackage/BeavideostarGPIOconnector
prerequisites,forconnectingto/Prerequisitesabout/SayhellototheGPIOaccess,providing/SayhellototheGPIOdigitalI/Opins/DigitalI/OpinsInter-IntegratedCircuit(I2C)bus/TheI2CbusSerialPeripheralInterface(SPI)bus/TheSPIbusUniversalAsynchronousReceiverandTransmitter(UART)bus/TheUARTserialbusUniversalSerialBus(USB)ports/USBportspowerconnections/Powerconnectionsusing/GettingacquaintedwiththeGPIOconnecting,toLED/Lettherebelight,Gettingflashy…switch,adding/Addingaswitchfloatingstate/Pullingyourselftogetherdetectionscript/Thedetectionscript
GPIOpinexport/SettinguptheGPIO
![Page 314: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/314.jpg)
HH.264videostream/Beavideostarhall-effectsensors/Gettingintothezonehigh-levelprocess/DesigningthecontrolscriptsHobbytronicsMCP23017expanderportkit
about/HobbytronicsMCP23017expanderportkitURL/HobbytronicsMCP23017expanderportkit
![Page 315: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/315.jpg)
II/Opins/PowerconnectionsI2Cbus
about/TheI2CbusSerialDataLine(SDA)wire/Just2wiresSerialClockLine(SCL)wire/Just2wiresaddress,identifying/What’syouraddress?data,transmitting/Thereisaparalleluniverseserial-to-parallelconversion/Serial-to-parallelconversionenabling/EnablingtheI2CBustoolspackage,installing/InstallingtheI2Ctoolspackage
I2Cportexpanderbuilding/BuildinganI2Cexpanderboard,building/Buildingyourexpansionboardsettingup/SettinguptheI2Cportexpander,SettinguptheportexpanderI2Cbus,enabling/EnablingtheI2CBusI2Ctoolspackage,installing/InstallingtheI2Ctoolspackagedevices,searching/Findingourdevices
I2Cportexpandercircuitabout/TheI2Cportexpandercircuit,Let’swalkthroughthecircuitcomponents/TheI2CportexpandercircuitMCP23017portexpanderchip/Let’swalkthroughthecircuithigh/Let’swalkthroughthecircuitlow/Let’swalkthroughthecircuitfloating/Let’swalkthroughthecircuit
i2csettool/Settinguptheportexpanderinductiveloads
driving/Drivinginductiveloadsbells/Drivinginductiveloadslamps/Drivinginductiveloads
infra-redlighting/Isthatabadger?integratedcircuits(ICs)/Serial-to-parallelconversionInter-IntegratedCircuit(I2C)bus/TheI2Cbusintrusion/BeyondintrusionIPaddress/SettingupyourPi
![Page 316: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/316.jpg)
JJessieversion/BootingyourPi
![Page 317: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/317.jpg)
Kkeyswitch/Arminganddisarmingthesystem
![Page 318: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/318.jpg)
LLEDResistorValues
calculating/Lettherebelightlighttpdwebserver/InstallingthewebserverLinux
using/UsingLinux
![Page 319: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/319.jpg)
M433-MHzreceiver
connecting/Connectinga433-MHzreceiverconnecting,alternativeapproach/Thealternativeapproach(becausewehavenochoice)
433-MHzwirelessalarmsystemsabout/433-MHzwirelessalarmsystemsadvantages/433-MHzwirelessalarmsystemsdisadvantages/433-MHzwirelessalarmsystems
magneticcontactsensoradding,prerequisites/Prerequisitesworking/Theworkingofmagneticcontactsensorsconnecting/Connectingourmagneticcontactsensormonitoring/Monitoringthesensor
magneticfield/Theworkingofmagneticcontactsensorsmasterconfigurationfile
using/ThemasterconfigurationfileMCP23017/BuildinganI2CexpanderMicrosoftWindows
using/UsingMicrosoftWindowsmobileoptimized/CreatingthewebpageModel2/RaspberryPiModelB+andModel2Model2board/Sowhichone?ModelA/RaspberryPiModelAModelB/RaspberryPiModelBModelB+/RaspberryPiModelB+andModel2Modulesfile/EnablingtheI2CBusMP4Box/Beavideostarmulticameraset-up
about/ThemulticamerasetupSlavedriver/TheSlavedriver
![Page 320: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/320.jpg)
Nnano/Gettingflashy…Nano/GettingabitofhelpfirstNetworkTimeProtocol(NTP)/Gettingtherighttime,ntpnighttimeshots
capturing/NightvisionTIP120Darlingtontransistor,using/Anilluminatingexperienceelaboratelightswitch/TheElaboratelightswitchre-visitedinfra-redlighting,using/Isthatabadger?badger,watching/Isthatabadger?
No-IPURL/SettingupadynamicDNSaccount
NoIRcameramodule/Nightvisionnormallyclosed(NC)/ConnectingourPIRmotionsensornormallyopen(NO)/ConnectingourPIRmotionsensor
![Page 321: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/321.jpg)
Oon-boardreal-timeclockhardware
obtaining/Gettingtherighttime,fake-hwclockfake-hwclockpackage/fake-hwclockNetworkTimeProtocol(NTP)/ntp
outputsallocating/Beingincontroldocumenting/Beingincontrol
![Page 322: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/322.jpg)
Pparallel-to-serialconversion/Serial-to-parallelconversionPCF8591
URL/AsimpletemperaturesensorPHP5installation
testing/TestingthePHP5installationPHPsupport/InstallingthewebserverPi
types/WhichflavorofPi?ModelA/RaspberryPiModelAModelB/RaspberryPiModelBModelB+/RaspberryPiModelB+andModel2Model2/RaspberryPiModelB+andModel2models,comparing/Modelcomparisontableversion,selecting/Sowhichone?URL/Sowhichone?booting/BootingyourPifilesystem,expanding/Expandingthefilesystemsettingup/SettingupyourPioperatingsystem,updating/Gettinguptodateon-boardreal-timeclockhardware,obtaining/Gettingtherighttimesecurity/Talkingofsecurity…sudo/Whatisthissudothinganyway?
PiFaceDigitalI/Oexpansionboardabout/PiFaceDigitalI/OexpansionboardURL/PiFaceDigitalI/Oexpansionboard
PIRsensorsprerequisites/Prerequisitesabout/Passiveinfraredsensorsexplained,SettingupyourPIRsensorsettingup/SettingupyourPIRsensorguidelines/SettingupyourPIRsensorpowersupply/Givemepower(again)connecting/ConnectingourPIRmotionsensor
port-forwarding/Port-forwardingpowersupply
about/Givemepowerpartrequisites/Givemepower
prerequisites,expansionboard/Prerequisitesprerequisites,PIRsensors/Prerequisitespressurematsensors/GettingintothezonePuTTY
URL,fordownload/SettingupyourPi
![Page 323: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/323.jpg)
RRAM-basedfilesystem
creating/CreatingaRAM-basedfilesystemRaspberryPi
staticIP,settingup/SettingupastaticIPonyourRaspberryPiremoteadministration/RemoteadministrationforourRaspberryPiabout/Conclusion
RaspberryPicameramoduleabout/TheRaspberryPicameramoduleconnecting/Connectingthecameramodulesettingup/Settingupthecameramoduletesting/Testingthecameramodule
RaspberryPiNetworkingCookbookURL/ConnectingviaWi-Fi
Raspbianimagedownloading,URL/DownloadingtheRaspbianimage
RaspbianOSURL/DownloadingtheRaspbianimage
raspistilloptions/Wherewasthattaken?ready-madeexpansionboards
about/Usingready-madeexpansionboardsusing/Usingready-madeexpansionboardsHobbytronicsMCP23017expanderportkit/HobbytronicsMCP23017expanderportkitPiFaceDigitalI/Oexpansionboard/PiFaceDigitalI/OexpansionboardGertboard/Gertboard
receiverwiringdiagram/Thereceiverwiringdiagram
rectifierdiode/Drivinginductiveloadsreedswitch
about/Theworkingofmagneticcontactsensorsnormallyopen(NO)/Theworkingofmagneticcontactsensorsnormallyclosed(NC)/Theworkingofmagneticcontactsensors
remoteaccess,grantingtocontrolpanelabout/RemoteaccesstoourcontrolpaneldynamicDNSaccount,settingup/SettingupadynamicDNSaccountstaticIP,settinguponRaspberryPi/SettingupastaticIPonyourRaspberryPiport-forwarding/Port-forwarding
remoteadministration,RaspberryPiabout/RemoteadministrationforourRaspberryPiWebmin/GettingWebmin
rootuser/Whatisthissudothinganyway?
![Page 324: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/324.jpg)
SSDcard
preserving/PreservingtheSDcardRAM-basedfilesystem,creating/CreatingaRAM-basedfilesystem
SDCardpreparing/PreparingtheSDcardRaspbianOSimage,downloading/DownloadingtheRaspbianimageMicrosoftWindows,using/UsingMicrosoftWindowsLinux,using/UsingLinux
security/Port-forwardingsecuritykeypad/Arminganddisarmingthesystemsensors
hall-effectsensors/Gettingintothezonepressurematsensors/Gettingintothezone
serial-to-parallelconversions/Serial-to-parallelconversionSerialPeripheralInterface(SPI)bus/TheSPIbusshiftregisters/Serial-to-parallelconversionsimpletemperaturesensor
about/Asimpletemperaturesensorworking/Howitworks
simplewaterdetectorabout/Asimplewaterdetectorworking/Howitworks
soft-switchfunction/Anarm/disarmswitchstaticIPaddress
setting,onRaspberryPi/SettingupastaticIPonyourRaspberryPisudoer/I’msomeoneelsesudorights/AccessingWebminlocallysystem
arming/Arminganddisarmingthesystemdisarming/Arminganddisarmingthesystem
![Page 325: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/325.jpg)
TTIP120Darlingtontransistor/Anilluminatingexperience
![Page 326: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/326.jpg)
U433-Utilsoftwareproject
URL/Thealternativeapproach(becausewehavenochoice)Un-usedModulessection/AccessingWebminlocallyUniversalAsynchronousReceiverandTransmitter(UART)bus/TheUARTserialbusUniversalSerialBus(USB)ports/USBportsUSBwebcam
about/UsingUSBcamerasusing/UsingUSBcamerasinstalling/InstallingthewebcamURL/Installingthewebcamsnap,capturing/Takingasnapfswebcam,settingup/Snapsnapsnap
![Page 327: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/327.jpg)
V3.3Vvoltageregulator/Givemepower12Valarmzonecircuits
using/12Valarmzonecircuitsprotecting/Alarmcircuitprotectionworking/Howitworks
videocapturing/Beavideostarusing,insecuritysystem/Caughtoncamera
VideoLANURL/Beavideostar
visudoutility/I’msomeoneelse
![Page 328: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/328.jpg)
WWebmin
URL/GettingWebmin,RemotelyaccessingWebminabout/GettingWebminrepositorysources,updating/Updatingtherepositorysourcessigningkey,importing/Importingthesigningkeyaccessinglocally/AccessingWebminlocallyrootuseraccount/AccessingWebminlocallypiuser/AccessingWebminlocallyremotelyaccessing/RemotelyaccessingWebmin
webpagecreating/CreatingthewebpagecontrolpanelHTMLtemplate/ThecontrolpanelHTMLtemplatestyling/Givingitsomestylemodifyingdynamically/MakingitdynamicPHPconfigurationfilesetting,modifying/GettingabitofhelpfirstmainPHPcode/ThemainPHPcoderunning,asdifferentuser/I’msomeoneelse
webserverinstalling/InstallingthewebserverPHP5installation,testing/TestingthePHP5installation
Wi-Ficonnectingvia/ConnectingviaWi-Fi
Win32DiskImagerutilityURL/UsingMicrosoftWindows
windows/TheworkingofmagneticcontactsensorsWinSCP/Gettingflashy…wirelessPIRsensors
about/WirelessPIRmotionsensors433-MHzwirelessalarmsystems/433-MHzwirelessalarmsystems433-MHzreceiver,connecting/Connectinga433-MHzreceiverreceiverwiringdiagram/Thereceiverwiringdiagram
![Page 329: Building a Home Security System with Raspberry Piprophet/raspberrypi/Building... · Setting up your PIR sensor Give me power (again) Connecting our PIR motion sensor 12V alarm zone](https://reader035.fdocuments.us/reader035/viewer/2022081523/5fe6898c2e49df38cb314d19/html5/thumbnails/329.jpg)
Zzones
creating/Gettingintothezone