Upload
others
View
4
Download
1
Embed Size (px)
Citation preview
BuildingaHomeSecuritySystemwithRaspberryPi
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
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
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
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?
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
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
Monitoringthezones
Entrydelay
Soundingthemainalarm
Disarmingandresettingthesystem
We’redone(almost)…
Automaticallystartingthesystem
PreservingtheSDcard
CreatingaRAM-basedfilesystem
Conclusion
Tipsforbuildingsystems
Summary
Index
BuildingaHomeSecuritySystemwithRaspberryPi
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
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
AbouttheAuthorMatthewPooleisasystemsengineerbasednearSouthamptononthesouthcoastofEnglandwithover20yearsofindustryexperience.Aftergraduatinginelectronicsandcommunicationsengineering,hewentontotrainasandtobecomeanairtrafficengineerfortheUKCivilAviationAuthority,workingonmicroprocessor-basedcontrolandcommunicationssystems.
Later,hebecameasoftwarearchitectandmobiletechnologyspecialist,andworkedforseveralconsultanciesandglobalorganizations.HeisnowapartneratUKMobileMedia,aboutiquesystemsconsultancyfocusedondesigningBluetoothandotherwirelesssystems,takingideasfromconcepttoprototype.HeisalsothedirectoroftechnologyforMobileOnboard,aleadingUK-basedtransporttechnologycompanythatspecializesinon-busconnectivityandmobileticketing.
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.
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmoreForsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<[email protected]>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.
https://www2.packtpub.com/books/subscription/packtlib
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigitalbooklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.
Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser
FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.
PrefaceTheRaspberryPiisapowerful,low-cost,credit-cardsizedcomputer,whichlendsitselfperfectlyasthecontrollerofasophisticatedhomesecuritysystem.Usingtheavailableon-boardinterfaces,theRaspberryPicanbeexpandedtoallowtheconnectionofavirtuallyinfinitenumberofsecuritysensorsanddevices.TheRaspberryPihastheprocessingpowerandinterfacesavailabletobuildasophisticatedhomesecuritysystembutatafractionofthecostofcommerciallyavailablesystems.
BuildingaHomeSecuritySystemwithRaspberryPistartsoffbyshowingyoutheRaspberryPiandhowtosetuptheLinux-basedoperatingsystem.ThebookthenguidesyouthroughconnectingswitchsensorsandLEDstothenativeGPIOconnectorsafely,anditalsoshowsyouhowtoaccesstheseusingsimpleBashscripts.Asyoudivefurtherin,you’lllearnhowtobuildaninput/outputexpansionboardusingtheI2Cinterfaceandpowersupply,allowingtheconnectionofthelargenumberofsensorsneededforatypicalhomesecuritysetup.
Thebookfeaturescleardiagramsandcodelistingeverystepofthewaytoallowyoutobuildatrulysophisticatedandmodularhomesecuritysystem.
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
Bashscripts,whichwillgluetogetheralloftheseelementsandprovidethecontrollogicfortheentiresystem.
WhatyouneedforthisbookYou’llneedthefollowingsoftware:
Gpartedddfake-hwclockWin32DiskImager0.9.5PuTTYi2c-tools
WhothisbookisforThisbookisforanyonewhoisinterestedinbuildingamodularhomesecuritysystemfromscratchusingaRaspberryPiboard,basicelectronics,sensors,andsimplescripts.Thisbookisidealforenthusiasticnoviceprogrammers,electronicshobbyists,andengineeringprofessionals.Itwouldbegreatifyouhavesomebasicsolderingskillsinordertobuildsomeoftheinterfacemodules.
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.
ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedormayhavedisliked.Readerfeedbackisimportantforustodeveloptitlesthatyoureallygetthemostoutof.
Tosendusgeneralfeedback,simplysendane-mailto<[email protected]>,andmentionthebooktitleviathesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideonwww.packtpub.com/authors.
CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.
DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
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.
PiracyPiracyofcopyrightmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucomeacrossanyillegalcopiesofourworks,inanyform,ontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluablecontent.
QuestionsYoucancontactusat<[email protected]>ifyouarehavingaproblemwithanyaspectofthebook,andwewilldoourbesttoaddressit.
Chapter1.SettingUpYourRaspberryPiBeforewecangetintotherealmsofbuildingourhomesecuritysystem,there’sabitofpreparationworkneededtogetourRaspberryPiupandrunning.So,we’regoingtogothroughtheinitialstepsneededtogetourPireadytobeworkedon.
Inthischapter,wewillcoverthefollowingtopics:
ExploringthedifferentversionsoftheRaspberryPithatareavailableChoosingtherightRaspberryPiversionforyoursystemPreparingtheSDCardwiththeRaspbianOperatingSystemLearninghowtoremotelyaccesstheRaspberryPioveryourhomenetworkUpdatingouroperatingsystemwiththelatestpackagesExploringthetime-keepingoptionsontheRaspberryPiSettingtheuserandrootpasswordstosecureourRaspberryPi
WhichflavorofPi?SincetheRaspberryPiwasreleasedin2012,therehavebeenseveralversionsofthemini-PCboardreleased.I’llgothougheachoftheversionsreleasedwiththeirrespectivefeaturessothatyoucanchoosewhichoneissuitableforyourparticularproject.
Thegoodnewsisthatitdoesn’treallymatterwhichversionyouuseintermsofpower,asourhomesecuritysystemdoesn’tnecessarilyneedloadsofprocessingpower,dependingonwhatyouwantyoursystemtodo,ofcourse).Youmighthaveanolderboardkickingaboutthatwillworkforyou.
TheotherpieceofgoodnewsisthattheGPIOinterfacepinlayoutsarethesameacrossalltheversions.Thelaterversionshavemorepins,buttheoriginal26pinsstillremaininthesameplace.
ThelatestRaspberryPiVersion2
RaspberryPiModelAThebabyofthefamilyistheModelA;itwasreleasedasalower-costversionoftheModelB,showninthefollowingsection.ItsmaindifferencesfromtheModelBarethatitfeaturesjust256MbofmemoryandhasnoEthernetport;soifyouwanttoconnectthisboardtoanetwork,youarelimitedtousingaUSBWi-Fidongle.
TheRaspberryPiModelABoardLayout
RaspberryPiModelBThiswasthefirstversionofRaspberryPitobereleased;anupdatedrevision,whichimprovedthepowersystemandUSBportprotection,camelater.Itfeatures512MbofmemoryandhasanEthernetportforconnectingtoyournetwork.Thisisprobablythemostcommonversionused,andhavingtheEthernetportisincrediblyuseful,especiallytogetupandrunquicklyinordertosetupandconfigureyourPiwithouttheneedforakeyboardandmonitor.
TheRaspberryPiModelBLayout
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.
TheRaspberryPiModelB+andModel2Layout
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
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.
PreparingtheSDcardTheRaspberryPionlybootsfromanSDcard(ormicroSDcardfortheB+andv2models),andcannotbootfromanexternaldriveorUSBstick(wellthat’snotstrictlytrue,butisbeyondthescopeofthisbook).
It’srecommendedthatyouuseaClass10SDcardforperformance,butaClass4or6cardwillbefineforthisproject.You’llneedtohaveaminimumcardsizeof4Gb.
NowthatwehaveourRaspberryPiboardandSDcardtohand,weneedtopreparetheSDCardspecificallyforourhomesecuritysystem.We’regoingtousethestandardRaspbianoperatingsystemastherereallyisnoreasontouseanyotherdistribution;it’sthedefactochoicefortheRaspberryPi.
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…
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.
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.
BootingyourPiYou’renowreadytobootupyourRaspberryPi.PopyourshinynewSDcardintoitandpluginthepower.
AssumingthatyouhaveamonitorattachedtoyourPi,youshouldseeyoursystembootingupnicely.Althoughyoucouldwaitforittobootupandconnecttoitviaaterminalsession(we’lllookatthatlater),Irecommendthatyouconnectamonitortoit,atleastinthefirstinstance,justtomakesureeverythingisworkingcorrectly.
InthenewJessieversionofRaspbian,you’llbootstraightintoadesktopGUI,whichisamajorchangefrompreviousversions,whereyou’dbetakentotheraspi-configutility,thefirsttimethesystemisrun,whereyou’dsetupyourPi,andimportantly,expandthefilesystemtousetheentirespaceavailableonyourSDcard.
DebianJessiebootsintotheGUIbydefault
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
raspi-configutility.
ThefirstoptionistheExpandFilesystemoption;selectthisandyou’llseevariouscommandsscrollingupthescreen.Onceit’sfinished,you’llseethefollowingmessage:
Rootpartitionhasbeenresized.
Thefilesystemwillbeenlargeduponthenextreboot
ClickonOK.
SelectFinishontheconfigscreenandrebootyourPiwhenprompted.
AfteryourPirebootswithitsfullerfilesystem,you’llbetakenstraighttotheshellpromptwhereyoucanloginwiththedefaultuserandpassword.
Login:pi
Password:raspberry
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.
Todothis,downloadPuTTY:autilitythatallowsyoutoconnecttoshellterminalsremotelyoverthenetwork.Youcandownloaditfromhttp://www.putty.org.
InstallandlaunchPuTTYandyou’rereadytoconnecttoyourPiremotelyfromthecomfortofyoursofa.
TypetheIPaddressoftheRaspberryPiintotheHostNameboxandclickonOpen.You’llbeconnectedtoyourPiinaremoteterminalwindow.Onceyou’veloggedin,youcandoprettymucheverythingonyourPi,asifyouweresittinginfrontofit.
We’llassumefromnowonthatmostoftheworkwedowillbethrougharemoteshellsession,unlesshighlightedotherwise.
IfyouwanttousethecommandlinetolaunchtheRaspberryPiremoteshell—forexample,fromanotherLinuxsystem—usethefollowingcommandfromyourterminalwindow:
You’llthenbepromptedforthePi’spasswordandtakenintoashellsession.
ThePishellsessionlaunchedfromaDebiandesktopterminalwindow
GettinguptodateSomethingthatyoushouldgetintothehabitofdoingisupdatingtheoperatingsystemregularly;eventhoughyoumayhavethelatestimageinstalled,it’sverylikelythatthereareupdatedpackagesavailable.ToupdateyourOS,enterthefollowingcommand:
$sudoapt-getupdate
Afterthis,enterthefollowingone:
$sudoapt-getdist-upgrade
Thismaytakeawhile,dependingonthenumberofupdatesrequired.
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
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#
ConnectingviaWi-FiYoucanalsoconnectyourRaspberryPitoyournetworkusingWi-FibypluggingaUSBdongleintoit.Thereareadditionalconfigurationstepsrequiredtomakethiswork,whicharebeyondthescopeofthischapter,buttherearemanyresourcesavailablecoveringthissubject.
NoteYoucanfindrecipesforconnectingyourRaspberryPiusingWi-FiintheRaspberryPiNetworkingCookbookbyRickGolden,publishedbyPacktPublishing(https://www.packtpub.com/hardware-and-creative/raspberry-pi-networking-cookbook).
SummaryInthischapter,wetookourRaspberryPioutofitsboxandpreparedittobethecenterpieceofourhomesecuritysystem.Alongtheway,weinstalledandsetuptheoperatingsystem,connectedourPitothenetwork,andaccesseditremotely.WealsosecuredourPiandmadesureitcouldkeeptherighttime.
Inthenextchapter,we’regoingtoexploretheGPIOportandthevariousinterfacesitfeatures.We’lllookatthevariousthingswecanconnecttotheRaspberryPiusingtheGPIOport,includingswitchesandsensors,aswestarttobuildourhomesecuritysystem.
Chapter2.ConnectingThingstoYourPiwithGPIOTheRaspberryPihaslotsofwaystoconnectthingstoit,suchaspluggingthingsintotheUSBports,connectingdevicestotheon-boardcameraanddisplayports,andconnectingthingstothevariousinterfacesthatmakeuptheGPIOconnector.Aspartofourhomesecurityproject,we’llbefocusingmainlyonconnectingthingstotheGPIOconnector.
Inthischapter,wewillcoverthefollowingtopics:
ExaminingtheGPIOconnectorandwhateachofthepinsdoesLearningabouttheI2CandSPIbusesthatwillbeusedinlaterchaptersConnectinganLEDandaswitchsafelytothedatapins,andaccessingthesedatapinsusingsimplescriptsUnderstandingtheUSBportsandtheirlimitations
PrerequisitesAlongwithyourRaspberryPi,you’llneedthefollowingpartsfortheprojectsinthischapter:
AbreadboardAnLEDA220ohmresistor(red,red,black)A10Kohmresistor(brown,black,orange)ApushbuttonortoggleswitchAhook-upwire:
Ourlittlecollectionofparts
SayhellototheGPIOTheGPIOconnectoristhelargegroupofpinsontheedgeofyourRaspberryPiboard.Onearliermodels,therewere26pinsthatmadeupthisconnector.But,eversincetheModelB+,therehavebeen40pins,althoughthefirst26pinsareidenticaltothepreviousmodels,andit’sthese26pinswe’llbeworkingwith.Youwon’tneedtoworryabouttherestofthepins.
Essentially,theGPIOconnectorprovidesaccesstofollowing:
PowersuppliesDigitalI/OpinsI2CbusSPIbusUARTSerialbus
SomeofthepinsontheGPIOhavemorethanonepurpose,dependingonhowtheyareprogrammed.ThefollowingdiagramisareferenceguidetoallofthepinsontheGPIO.TheGPIOnumbersontheyellowlabelsrelatedirectlytothoseontheBroadcomchip,andarenumbersgenerallyusedwithinthescripts.
DigitalI/OpinsTheGPIOhas8digitalinput/outputpinsavailableforuse.Thesecanbeusedtoswitchthingsonandoff(inoutputmode),andalsotodetectwhenexternalthingsareswitchedonandoff(inputmode).Eachpincanbeconfiguredindependentlyforinputoroutputoperation,andIhavelabelledthemD0toD7intheprecedingdiagram.
Obviously,ifweweretouseeachofthesepinstodriveorsenseanindividualdevice,wewouldbelimitedtoamaximumof8devicesthatcouldbeconnectedtoourhomesecuritysystem.Inmanyscenarios,thisisprobablynotenough,sointhenextchapterwe’lllearnhowtousetheGPIOtoconnectmanymorethingstoourRaspberryPi.
TheI2CbusTheInter-IntegratedCircuit(I2C)busisalow-speedinterfacethatcanconnectmultipledevicesandsimplesensorsusinga2-wireinterfacewithouttheneedforaseparateclockordeviceselectline.Typically,thisbuscanoperateatspeedsupto100kbit/s.We’llbecoveringthisinthenextchaptertohelpusexpandourdigitalI/Oandconnectmorethings.
TheSPIbusTheSerialPeripheralInterface(SPI)busisasynchronoustwo-wayserialconnectionbetweenamasterandaslavedevice.Itcanbeusedtoaccessmorecomplexsensorsordrivedisplays.
Themasterdeviceprovidesthesynchronization,andeachtransmissionissynchronizedbyaclockpulseonSCLK(GPIO11/pin23).DataistransmittedontheMOSI(master-out-slave-in)andMISO(master-in-slave-out)(pins19and21respectively).
TheUARTserialbusTheUniversalAsynchronousReceiverandTransmitter(UART)busisawaytocommunicatewithexternaldevicesoveraserialdataconnection,andisacommonwayfortheRaspberryPitoaccessdatafromdevicessuchasGPSmodules,whichoftencomewithserialconnections.ItcanbealittlebitfiddlygettingthePisetuptocommunicatewithUART-connecteddevices,asit’salsotiedinwiththeoperatingsystem’sserialconsole.
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.
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!
GettingacquaintedwiththeGPIOBeforeweembarkonconnectinglotsofthingstoourPiboard,itmightbeagoodideatojustgetacquaintedwiththeGPIOthroughacoupleofsimpleprojectsthatwillhelpusunderstandhowtointeractwiththedigitalI/Opinsusingshellscripts.
LettherebelightThissimplelittleprojectshowshowtoconnectaGPIOoutputtoanLED,andswitchitonandoffusingshellcommands.
Thefollowingdiagramshowshowtoconnectupthecircuitusingabreadboard:
NoteTheprettydiagramthatyoujustsawwasproducedusingafreesoftwaretoolfromfritzing,whichisanopen-sourcehardwareinitiativetomakeelectronicsaccessibleascreativematerialforanyone.Downloaditfromfritzing.org.
TheLEDanode(thepositiveside)isconnectedtotheD0digitalI/O(pin11oftheconnectororGPIO17).Whenthispinisswitchedon,itwillprovidea3.3VsupplytotheLED.
TheLEDisconnectedtotheGroundpinviaa220Rresistoronthecathode(negativeside).TheresistorlimitsthevoltagetotheLEDandthecurrentthroughit,otherwiseitwouldburnout,asyoucanonlysupplyuptoabout2VtoLEDs.Withacurrentofaround10mAbeingdrawnbytheLEDona3.3Vsupply,a220RresistorworkswelltoprotectbothitandtheGPIO.
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.
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
SincethisisanendlessloopwiththeLEDflashingonandoffathalfsecondintervals,you’llneedtobreakoutofitbyusingCTRL+Ctostopthescript.
Don’tforgettoremovetheGPIOpinfromfileaccessbyusingthefollowingcommand:
$sudoecho17>/sys/class/gpio/unexport
Otherwise,you’llseetheerror,echo:writeerror:Deviceorresourcebusy,ifyoure-runthescript,asthefirstlinetriestosetGPIO17forfileaccessagain.
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:
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:
$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.
ThemostelaboratelightswitchintheworldBycombiningthetwolittleprojectsearlier,wecannowcreateasystemthatwilldosomethingusefulwhenthepushbuttonswitchispushed—forexample,switchingontheLEDthatwealsohaveconnected.Granted,wecouldjustconnecttheLEDdirectlytotheswitchandabattery,butnotonlywouldthatbeboring,itwoulddefeatthepointofwhatwe’retryingtodo,whichisprogrammaticallysensingandcontrollingthings.
Here’sthebreadboardlayoutforourelaboratelightswitch:
Andhere’sthecircuitdiagram:
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.
SummaryInthischapter,weintroducedvariouswaystoconnectyourRaspberryPitotheoutsideworldbylookingatthevariousinterfacesavailableontheGPIO.We’veunderstoodhowtoconnectthingstothedigitalpinsonyourRaspberryPi’sGPIOconnector,andcontrolandreadthemusingsimpleBashscripts.Inparticular,we’vesafelyandproperlyconnectedaswitchtoadigitalinputpin,whichwillformthefoundationforourhomesecuritydetectioncircuits.
Inthenextchapter,we’lllookatwaystoexpandthenumberofthingswecanconnecttoourRaspberryPi,overcomingthelimitationofhavingjustthe8digitalpinsavailabletousontheGPIObytappingintootherinterfacesontheGPIOandbuildingourowninput/outputexpansionboard.
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
PrerequisitesAlongwithyourRaspberryPi,you’llneedthefollowingpartsfortheprojectsinthischapter:
Acopperstripboard(orVeroboard®)AnLD1117V33voltageregulatorA2x100nF,16VceramiccapacitorA10uF,16VelectrolyticcapacitorA1xMCP2301716-bitportexpanderICA4x10K-ohmresistorAhook-upwire
TheI2CbusInthepreviouschapter,webrieflytouchedontheI2Cbus(orInter-IntegratedCircuitbus),whichisawaytoconnectmultipledevicestogetherusingjusttwowires.I2Cwasinventedintheearly1980sbyPhilipsasawaytolinkcomputerperipheralstogetherusingacommonprotocol.YoucanthinkofI2CasakindofearlyformofUSB.
I2Ctypicallyoperatesatrelativelylowspeedsofupto100kbit/s,comparedtomuchfasterinterfacessuchasEthernet,whichtypicallyoperatesatupto1Gbit/s,orUSB,whichcanoperateatupto480Mbit/s.However,thisisfastenoughtoconnectbasicsensors,displaydevices,orotherperipheralssuchasreal-timeclocks—infact;therearefasterversionsoftheprotocolthatsomedeviceswillsupport.
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.
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!
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
So,nowthatweknowwhatnumberstosendtoourbustoswitchonorswitchoffcertaindigitaloutputs,orreadcertaindigitalinputs,howdowedothisusingourI2Cbus,whichisaserialinterface?
Fortunately,therearemanyintegratedcircuits(ICs)availablethatallowustodothissimplyandeasily.TheseICsarecalledshiftregistersandperformserial-to-parallelconversions,takingthedatafromtheserialI2Cbusandconvertingtheincomingbitstoaparallelrepresentationbysettingeachoftheparallelbusoutputs.
Whenreadingtheparallelbusdatalinesasinputs,thereversehappens,convertingthebitsintoaserialformontheI2Cbus;thisisknownasparallel-to-serialconversion.
Thisisquiteasimplisticoverviewandtherearemanyresourcesavailablethatexplaintheseoperations;we’llseethisinactionlaterinthechapter,butfirst…
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.
Ourpowersupplycanbeeasilybuiltonasmallpieceofstripboardlikethis:
NoteThestripboardisshownfromthetopintheprecedinglayout.Thatis,thecoppertracksareontheundersideoftheboardandthecomponentsareinsertedfromtheplaintop-sideandsolderedtothestripsunderneath.Inthislayout,it’snotnecessarytocutanyofthetracksonthestripboard.
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.
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
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).
BuildingyourexpansionboardThiscircuitcaneasilybebuiltonasmallpieceofstripboard.Thefollowingimageshowsanexampleofthelayout,whichlooksabitsimplerthanthecircuitdiagram.Inthenextchapter,we’lllearnhowtoconnectupourboardandprogramitsowecancheckthatitworks.
TipWhenusingstripboard,makesurethatyoucutthetracksbetweenthetworowsofpinsontheMCP23017sothattheyaren’tshortedtogether.Youcanbuytrackcutters,whichmakethistaskeasy,frommanyelectronicsuppliers.Again,ontheprecedinglayout,thecopperstripsareunderneaththeboardwiththecomponentsontheplainside.
Youmightwanttoaddthe+3.3Vpowersupplycircuittothesamepieceofstripboardtoo,tokeepeverythingcontainedtogether.
NoteInthenextchapter,wewilllearnhowtoprogramthedevicesothatwecanuseitinourhomesecuritysystem.
Usingready-madeexpansionboardsWhileit’smuchmoresatisfyingtobuildyourownstuff,youmightwanttolookatbuyingsomereadilyavailableexpansionboardsforyourhomesecuritysystemifyou’renotyetconfidentwithyoursolderingiron,orifyoujustsimplydon’thavethetime.
Followingaresomeready-madeexpansionboardsthatyoucanobtain;theyshouldworkaspartofourhomesecuritysystemwithabitofmodificationtoourscriptstosupportthelibrariesthatarerequiredbythehardware.
HobbytronicsMCP23017expanderportkitThiskitisalmostidenticaltoourowncircuitintheprevioussectionofthischapter.ThekitcomeswithanMCP23017,aPCB,andvariousconnectors.Theboardsaredesignedtobedaisy-chainedtogethersothatyoucanhavemultipleexpanderstogiveyoumoreinput/outputports.Notethatthiskitisnotpre-builtandrequiressoldering,butIthoughtI’dincludeitbecauseit’stheboardthatIusetobuildsuchsystemswhenprototyping.YoucangetitdirectlyfromHobbytronicsathttp://bit.ly/mcp23017.
PiFaceDigitalI/OexpansionboardThePiFaceDigitalI/Oexpansionboardisapre-builtversionofourboard,butitusestheMSP23S17chipvariantthatoperatesovertheSPIbusinsteadoftheI2Cbus.Theboardisdesignedwith8inputsand8outputs,aswellasseveraladditionalpiecesofhardwareincludingacoupleofrelays,someLEDs,andsomeswitches.Notethatthecodeinthisbookforoursystemwillneedtobemodifiedtoworkwiththisboard,sinceitusesadifferentinterfaceanddifferentlibraries.It’savailablefromFarnellelement14athttp://bit.ly/2434230.
ThePiFaceDigitalI/OExpansionBoard
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
SummaryWe’venowlookedattheI2Cbusindetail,andlearnedhowtobuildanexpansionportusingthisinterfacesothatwecanconnectmanymorethingstoourRaspberryPi,ratherthanbeingrestrictedtojustthe8digitalI/OpinsofferedbytheRaspberryPi’sGPIOport.Inadditiontothat,weexploredotherready-madeboardsthatcanbeusedtoconnectlotsofthingstoourRaspberryPi.Wehavealsobuiltapowersupplythatwillgiveusmore+3.3VpowerthanwecanobtainfromtheRaspberryPidirectly.
Inthenextchapter,we’llstarttoactuallyconnectthingstoourhomesecuritysystem,suchasmagneticsensorsandothertypesofcontactdevices,andlearnhowtoprogramourI2CexpansionportusingBashscriptssothatwecanreadthestateofoursensorsandswitchonwarningLEDs.We’llalsostartdevelopingthecontrolscriptsforoursystem,whichwillallowustoarmanddisarmthesystemandadddelaytimers.
Chapter4.AddingaMagneticContactSensorNowthatwehavebuiltourportexpanderhardware,weneedtolearnhowtoprogramitsothatourRaspberryPicandetectthethingsthatweconnecttoitaspartofourhomesecuritysystem.Wewillbeginbyconnectingswitchestooursystemintheformofmagneticsensors—themostcommoncomponentusedinhomesecuritysystemstodetectintrusionsthroughdoorsandwindows.
Inthischapterwewillcoverthefollowingtopics:
LearningaboutreedswitchesandhowtheyworkasdoorsensorsEnablingandsettinguptheI2CbusontheRaspberryPiConnectingoursensortoaninputonourportexpanderLearninghowtoaccessourI2CportexpanderfromaBashscriptWritingascriptthatwilldetectthestateofourdoorsensorLookingatothertypesofcontactsensorsthatcanbeconnectedandprogrammedinthesameway
PrerequisitesYou’llneedthefollowingpartsfortheexercisesinthischapter:
OurRaspberryPiandPortExpanderboard8x10KohmresistorsAmagneticdoorsensorandmagnetAhook-upwireA4-corealarmwire
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.
Adoor-frame-mountedmagneticsensorcontainingareedswitch(Type:CherryMP201801)
Themagneticsensorismountedonthedoorframe(obviously,soitcanconnecttothealarmcircuitwires),whiletherespectivemagnetwillbeattachedtothedoor,closeenoughtotheedgesuchthatthesensorcontactsconnect(orbreak,dependingonthetype)whenthemagnetisdirectlyoppositeit.
Arespectivedoor-mountedmagneticactuator(Type:CherryAS201801)
SettinguptheI2CportexpanderNowthatwehavebuiltourportexpander,weneedtogetitreadytoconnectoursensorsto.First,weneedtoinstallthetoolsontheRaspberryPitoallowustousetheI2Cbusandprogramdevicesconnectedtoit,includingtheMCP23017chipthatmakesupourportexpander.
NoteDon’tconnectyourportexpandertotheRaspberryPiuntilafteryou’vesetuptheI2Cbusonyoursystem.
EnablingtheI2CBusIt’shighlylikelythatthemoduleforusingtheI2Cbushasn’tbeenloadedbydefault.Fortunately,doingthisisfairlystraightforwardandcanbedoneusingtheRaspberryPiconfigurationtool.Performthefollowingsteps:
1. LaunchtheRaspberryPiconfigurationtoolwiththefollowingcommand:
$sudoraspi-config
2. Selectoption8:AdvancedOptions.
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.
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.
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:—--—--—--—--—--—--—--—--
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.
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.
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).
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
#switchwaspushedsoturnonLEDpin
sudoecho1>/sys/class/gpio/gpio17/value
fi
#shortdelay
sleep0.5
done
NoteLater,asweaddmoresensorstodifferentinputpins,wewillneedtobeabletodetectwhichonehasbeentriggered.We’lllookatwritingaBashfunctionlaterinthebook,whichwillparsethereturnedhexvaluefromthei2cgetcommand,andtellusexactlywhichofthe8inputsishigh.
Anti-tampercircuitsIfyoutakeacloserlookatoursystem,youmightrealizethatdependingonwhetheryouaredetectingnormallyopenornormallyclosedsensorswitches,itispossibletotamperwiththesensorchannelbysimplycuttingthewire.So,inthecaseofanormallyopenswitch,itwouldn’tactivatethemonitoringsystemifthewireswerecut,asitwouldalwaysappeartobeopen,eveniftheswitchwasclosed.
Tomitigatethis,mostalarmsystemsfeaturea4-corewiringsystemtoconnectthesensordevicestothemaincontrolboard—twocoresareusedtoconnectthesensorandtwoareusedtocreateananti-tamperloop,whichthenitselfformsasensorinputformonitoring.
4-corealarmcable
TakealookatthefollowingcircuitsothatyouseewhatImean:
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.
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.
Apressureswitchcanbeusedunderafront-doormat
SummaryInthischapter,wegotourI2C-basedportexpanderconfiguredandworking,andweexperimentedwithitbyconnectingamagneticsensor—oneofthemostcommonlyusedsensorsinsecuritysystems.We’vealsolearnedhowtointeractwithI2CdevicesusingBashscripts,andhowtoreadandwritedatatoandfromthesedevices.
Inaddition,weshouldnowbebeginningtounderstandthevariouselementsandbuildingblocksofasecuritysystem,includinganti-tamperloopsandzones.Theseareconceptsthatwillprepareusforlateroninthebook,whenwestarttopieceallofthistogetherandbuildourfinal,all-encompassingsystem.
Inthenextchapter,wewilllookatpassiveinfra-redmotiondetectors,howtheywork,andhowwecanconnectthewiredandwirelesstypestoourhomesecuritysystem.We’llalsolearnhowtocreatelogfilesbasedoneventsusingBashscriptssothatwecanmaintainahistoryofdetectorstatesastheychange.
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
PrerequisitesYou’llneedthefollowingpartsforthischapter(apartfromthecomponentsusedinthepreviouschapter):
Apassiveinfrareddetector,thewiredtype(thisisavailablefromanyDIYstore)A4N25/4N35opto-isolatorA1N4148diodeA1-KohmresistorA10-KohmresistorA433MHzreceivermoduleandremotetransmitter(thisisoptional)A12VpowersupplyAhook-upwireA6corealarmwire
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.
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.
GardScanQX-PIRcoveragepatternforits110degreefieldview(top/planview)
Hereisadiagramofthesideviewaswell:
GardScanQX-PIRcoveragepatterndependingontheangleconfiguredplusa“look-down”window(sideview)
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.
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:
Aschematicforourzonewithallthreesensorsplustamperloopinthesamezone
Upuntilnow,weusedthe+3.3Vpowersupplytopassthroughthesensorswitchesandalarmcircuit.Infact,thisisnotagoodidea,andwe’vebeendoingthisonlyforconveniencetotestoutourGPIOinputs.
Inreality,andinourfinalsystem,wereallyshouldusea12Vsupplytopassthroughthesensorandantitampercircuits.Thisisbecauseahighervoltagetravelsbetterthroughthesystemandislesssusceptibletonoise,whichcouldpreventtriggeringorcausefalsetriggering.Thisalsomakesitcompatiblewithcommerciallyavailablesystemsandaccessories.
12ValarmzonecircuitsMakingourzonecircuitsuse12Vinsteadof3.3Visassimpleaschangingthepowersupply,andinfactallofsensorsweusedsofarcanhandle12Vpowerpassedthroughtheirswitches.
However,ifweweretopresentthe12VcircuittotheinputsonourGPIOportontheRaspberryPiorourportexpander,wewouldexpecttoseesomemagicsmokeandsmellsomethingburning.So,weneedtoaddsomecircuitrythatallowsustouse12Valarmcircuitsaswellasprotectourcontrolboardinputs.
AlarmcircuitprotectionAneffectivewaytoprotectourzoneinputsfrom12Valarminputsistousealittlelow-costdevicecalledanopto-isolator.Asthenamesuggests,thisisolatesthealarmcircuitfromthedigitalinputsofthecontrolboardusinglight.
Insideanopto-isolator(alsocalledanopto-coupler)isaninfraredLED,whichtransmitslighttoaphoto-transistorwhenacurrentispassedthroughit,thusswitchingiton.Thecircuitsareelectricallyisolatedastheyarecontrolledonlybylight.
The4N25(shownintheprecedingimage)and4N35arelow-cost,6-pinopto-couplerdevices,andmostmanufacturestendtousethepinlayoutshowninthefollowingdiagram:
Nowthatweknowhowwewillcoupleour12Valarmcircuitwiththeinputsonourcontrolpanel,let’sbuildtheentirecircuit,whichwe’lluseforeachofthezonesthatweaddtooursystem.
A12VzonecircuitopticallyisolatedfromtheGPIOinput
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.
WirelessPIRmotionsensorsWirelessmotionsensorsarenowcommonlyavailableatalowcost,allowingthemtobeinstalledpracticallyanywherewithoutanywiringfromthealarmcontrolpanel.Someofthemstillrequireanexternalpowersupply,butmanyoperateonbatteries.Thealarmsystemmustcontainawirelessreceivercompatiblewiththewirelesssensor.
Inthissection,we’lltakealookathowwecanuseourRaspberryPi-basedsecuritysystemwithwirelessreceiverdevices.
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
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.
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
£5onAmazonanddoesn’trequireallthissoftwarebitbangingnonsense.You’llnoticefromthefollowingimagethatitstillusesasimilarXY-MK-5Vradioreceiver;it’sjustthatthehostboarddecodesthesignalsforusandswitchesarelayonoroffinresponsetoacommandfromtheremotecontrol.
NoteIfyou’restillinterestedinthe433-Utilsoftwareprojectandwanttotryandrolloutyourownreceiver,youcanfindtheoriginalprojectathttps://github.com/ninjablocks/433Utils.
AHielectransmitterfobandreceivermodule,availableonAmazon
Thefactthatitjustswitchesarelayonandoffmeansthatwecaneasilyimplementthisinourhomesecuritysystembecauseitsimplyactsasaswitch.Whenyoupressthebuttononthetransmitter,therelayswitchesthecontactson;pressitagain,andtherelayswitchesoff.Thescrewterminalsontheboardprovideuswithaccesstotherelayterminals.
ThereceiverwiringdiagramAswearejustdealingwithaswitchinput,wecanusethesamecircuitaswedidwiththezonecircuitearlierbutconnectedtoourarm/disarmGPIOinput,whichwe’lldetermineinChapter9,PuttingItAllTogether.
CircuittointerfacethereceivermodulewithaGPIOinput
Whenthereceivermoduleswitchestherelayon,thiswillcompletethe12Vcircuitthroughtheopto-coupler’sLEDbyturningiton.ThiswillmakethetransistorpulltheGPIOpindowntoground,givingitalowinput.
Youcanusethistypeofcircuitforanypairedreceiverforthewirelesssecuritydevicesthatyouwanttouseinyoursystem.
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.
SummaryInthischapter,westartedoffbylearninghowpassiveinfraredsensorsareusedtodetectmotiontoprotectapredefinedcoverageareafromintrusion.Wethenlookedatconnectingthesetotheinputsonourportexpanderviaopto-couplersaswewillnowuse12Vtopowerthealarmzonecircuits.
Wethenlookedatwirelessalarmsystemsthatoperateontheopen433-MHzband,whichiscommonlyusedforsecuritydevices.Afterexploringthepossibilityofusingthelegacy433-Utilbit-bangingsoftwareonourRaspberryPitodecodethesignalstransmittedbydevicesusingasimplereceiver,weoptedtouseapairedreceiverdevicethatwillinterfaceeasilywithouralarmcircuitinputs.
Finally,wecreatedasimplescriptthatwilllogthechangesinouralarminputstoatextfile,whichcanlaterbeexpandedtologexactlywhat’sgoingonwiththesystemindetail.
Chapter6.AddingCamerastoOurSecuritySystemUntilnow,we’vebeenputtingtogethertheelementsthatwillallowustoconnectsensorstoouralarmsystemtodetectintrusionsusingeitherswitchesorpassiveinfra-redmotiondetectors,whichinturnwilltellourRaspberryPithatsomethinghashappenedinaparticularzone.Theseelementswillallcometogetherasawholesystemlaterinthisbook.
Oursystemisnowgoingtobecomeawholelotmoresophisticatedwiththeadditionofcamerastotakepicturesandvideoclips,ande-mailthemtousstraightawaywhenitdetectssomething.
We’llalsousee-mailtosendusalertsonoursmartphonewhenwe’reoutandaboutwhenanyofthesensorsinthesystemaretriggered.
Inthischapterwewillcoverthefollowingtopics:
SettinguptheRaspberryPicameramoduleandlearninghowtocapturestillsandvideoimagesLearninghowtooverlaycapturedimageswithtextandtime-stampsTriggeringimagecaptureswithamotiondetectorE-mailingtheimageandvideofilestousinrealtimeUnderstandingthedifferencesbetweencapturingimagesduringthedayandduringthenightSwitchingonandoffsecuritylightingandotherhigh-currentdeviceswhenrequiredConnectingaUSBwebcaminsteadofthenativecameramodule
PrerequisitesYou’llneedthefollowingpartsforthischapter,ontopofthecomponentsusedinthepreviouschapter:
ARaspberryPistandardcameramoduleARaspberryPiNoIRcameramoduleAnInfra-RedLEDarrayand/orvisibleLEDarrayAUSBwebcam
TheRaspberryPicameramoduleTheRaspberryPiCameraModuleisanofficialRaspberryPiaccessorythatworkswithallmodelsofthePi,andcanbeusedtotakehigh-definitionstillsandvideoimages.ItconnectsdirectlytothePiboard’scameraserialinterface(CSI)port,whichisdedicatedtothesemodulestoenablehigh-speedoperation.
Thecameraitselfisa5megapixelfixed-focussensorsupporting1080p,720p,andVGAvideomodesandstillcaptures.
TheofficialRaspberryPiCameraModule
Youcanalsoobtainhousingsforthecameramodules,which,unlessyou’regoingtobuildyourownenclosureforthecamerasystem,Irecommendyouuse.
RaspberryPicamerahousingscomeinvariouscolorsandstyles
ConnectingthecameramoduleAspreviouslymentioned,themoduleconnectsdirectlytotheRaspberryPiboardviaitsdedicatedcamerainterfaces,asshowninthefollowingimage.Whenconnectingthecamera,thecontactsideoftheribboncableistowardtheHDMIconnectorandthebluesideofthecableistowardthenetworkconnector.
Connectthecameramoduletothededicatedinterface
Asyoucanseeinthefollowingimage,theribbonconnectorisnotthatlong,sothecameraneedstobelocatedclosetotheRaspberryPi.Byusingacameraenclosure,youcouldactuallymountthecameradirectlyontopoftheRaspberryPicaseitself,ifthatworksforyou.
Thecameramodule,housedwithinanenclosure
SettingupthecameramoduleBeforewecanusethecameramodule,weneedtoenablecamerasupportontheRaspberryPi.Todothis,weusetheraspi-configtool,aswedidwiththeI2Cbusearlierinourjourney.
1. ConnecttoyourRaspberryPithelazywayfromyoursofausingSSH,ordirectlyusingakeyboardandmonitor.
2. Onceyou’veloggedin,launchtheconfigtoolwiththefollowingcommand:
$sudoraspi-config
3. Andthen,select5EnableCamera.
4. You’llthenbeaskedtoconfirmwhetheryouwanttoenablecamerasupport.
5. Select<Enable>.6. Then,selectFinishandrebootyourPitoenablethecamerasettings.
TestingthecameramoduleOnceyourRaspberryPihasrebooted,yourcamerashouldbeenabled.Wecantestthisbytakingastillimageusingtheraspistillutility:
$raspistill–v-otest.img
Thiswilldelayfor5secondsthentakeapicture,whiledisplayingvariouspiecesofinformation,suchasthatshowninthefollowingscreenshot:
NoteThecameramoduleneedsatleast128MBofGPUmemorytooperateproperlyonRaspian.Ifyouexperienceanyissues,firstensurethatthethegpu_memsettinginthe/boot/config.txtconfigurationfileissettoatleast128.
Andifallgoeswell,youshouldfindthefile,test.jpg,inyourhomefolder.Asyou’reconnectedviatheshell,youwouldn’thaveseenthe5secondpreviewimagedisplayedwhenthecommandwasrunning.
IfyoudownloadtheimagefiletoyourPC,youshouldseeanicequalitysnaptakenbythecameramodule.
ThetestphototakenbytheRaspberryPiCameraModule
TipIfyoufindthatraspistilloutputserrorswhenyourunit,ensurethatitisconnectedproperlyatbothendsoftheribboncable.Oneothercatchisthatsometimestheribbonthatconnectstheactualcameralenscomponenttothetinyconnectoronthecameraboardcancomeloose.Justensurethatthisissecurelyconnectedtoo.I’vehadthisissueacoupletimesafterthecameramoduleshavebeentakenoutofmyboxofrandomtestbitstobeused.
Theraspistillutilityhasloadsofoptionsformanipulatingtheimagesitcaptures,andwe’llusesomeofthemabitlaterinourcapturescript.Inthemeantime,toseetheavailableoptions,runraspistillwithoutanyoptionsandtheywillbelisted:
$raspistill
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.
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
YouhavenewmailHavingtheimagesstoredonyourRaspberryPiisnotreallymuchuse—ideally,youwouldwanttheimagessenttoyoustraightaway,assoonastheyarecaptured,sothatyoucanviewthemonyoursmartphone.
Aneasy,quick,andreliablewaytodothisistosimplyhavetheme-mailedtoyou.Hencewe’regoingtoaddane-mailingfunctionalitytoourhomesecuritysystemsothatimagecapturesareattachedtoamessageandsenttoyoure-mailaddressstraightaway,whichyoucanaccessfromyoursmartphone.TheimagescanthenberemovedfromyourRaspberryPitopreventtheSDcardspacefrombeingcloggedupwiththesereasonablylargefiles.
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.
SendingattachmentsNowthatwecansendbasicemailsfromourhomesecuritysystem,let’strysendingthestillimagetakenfromourcameraearlier.Butfirst,weneedtoinstallyetanotherpackagetohelpuswiththis:
$sudoapt-getinstallmpack
Oncethat’sinstalled,youcansendthetestimagefilewetookpreviouslybyusingthefollowingcommand:
$sudompack–s"SecurityPhoto"[email protected]
Wenowhavealloftheelementsneededtosendalertsandimagesfromourhomesecuritysystemdirectlytooursmartphoneusingemail.
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.
Tocapturesmallerimagefiles,tryusingthefollowingcommand:
$raspistill-otest.img–h768–w1024–q25
NightvisionThestandardRaspberryPicameraisgreatfortakingdaytimesnapsofpeoplewalkingupthegardenpath,butwhenitcomestonighttimeshots,it’snotreallysuitable.Therearetwowaysofdealingwiththis:thefirstistoilluminatethecaptureareawithabrightlightwhenthePIRdetectoristriggered,andthesecondistousetheRaspberryPiNoIRcameramoduleandaninfra-redLEDarraytoletthecameraseeinthedark.Moreaboutthatinaminute.
TheRaspberryPiNoIRcameramodule;itlookssimilartothestandardmodel
AnilluminatingexperienceInordertoswitchonalightorLEDarrayfromtheRaspberryPiGPIOorourportexpandercircuit,weneedsomethingthatwillallowustodrivehighercurrentsandvoltagesthancanbeprovidedbytheGPIOportsalone.
AgoodcandidateforthisistheTIP120Darlingtontransistor,whichwillallowustoswitchonandoffloadsofupto80Vand5AfromourGPIOpins.Inourfullsystemlateron,we’regoingtousePortBofourMCP23017portexpandertocontroloutputs,buttheprinciplestandsforanyoftheGPIOoutputsavailabletous.
TIP120transistorscanbeboughtcheaplybutcandrivelargeloads
ThefollowingcircuitshowshowwecandrivebigloadsfromourGPIOportoutputs.
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.
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
pir-camera-trigger.sh
You’llnowseethatwe’vestarteddevelopingthefoundationsofthesoftwarethatwillcontrolourhomesecuritysystem.
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.
UsingUSBcamerasInsteadofusingtheRaspberryPiCameraModule,it’salsopossibletouseastandardUSBwebcamtotakestillimages.YoushouldbeawarethoughthatthededicatedcameramoduleisfarsuperiortoaUSBwebcamintermsofimagequality.Although,youmayalreadyhaveawebcamknockingaboutinyourboxofbits,sowhynottryit?
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
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.
ThemulticamerasetupItmayhaveoccurredtoyouthattheRaspberryPihasonlyonecameramoduleinput.Now,thisisobviouslylimitingifyouwanttohavemultiplecamerasaroundyourpropertythataretriggeredbymotiondetectors.
However,thereisnothingstoppingusfrombuildingstandaloneunitsthathaveaseparateRaspberryPiboardwithaPIRdetector,CameraModule,andnetworkconnection,eitherusingaWi-FidongleorEthernet.
BecauseyouonlyneedasingleinputtotheRaspberryPitodetectwhenthePIRmotionsensoristriggered,youcanusetheon-boardGPIOporttoconnectthesensor,ratherthanusingaportexpander.TheRaspberryPiwillemailthealertoverthenetwork,andcouldalertthemaincontrollerPiifrequired—makingitaslavesensordevice.
YoucanreadilyobtainsmallPIRdetectors,suchastheParallaxoneshownnext,whichyoucanmountontoaRaspberryPiCasealongwiththecameramodule,creatingaself-containedunit.
AParallaxPIRmotionsensor(type555-28027)
TheSlavedriverWhileitmayseemquiteelaboratetohaveaRaspberryPiforeachcamera—thinkaboutit—youcanactuallybuildeachcameraunitwithallofthecomponentsforaround£50,whichissignificantlycheaperthanbuyingawirelesssmartcamera.Ifyoureallywanttobeclever,youcouldalsousethisasaslavedevicetoacceptfurthersensorinputslocaltotheunit.
ThereisnothingtostopyoufromconnectingaGPIOoutputpinontheslaveunittodriveaninputonthemaincontrollerandcontrolthepindependingonthestateofitslocalsensors.Byrunninga6-corecablebetweentheunits,youcouldevenpowertheslaveunitifyourpowersupplyismanenough(you’dneedtohaveasupplyof5V@1AfortheslavePirunningalongthewire).
I’mnotgoingtogointoanymoredetailaboutthisconfigurationatthistime,butyoucouldsetyourselfachallengetocreateafullydistributedhomesecuritysystemusingmultipleRaspberryPisandthebuildingblocksandconceptslearnedinthisbook.
SummaryInthischapter,welearnedhowtoconnectbothRaspberryPicameramodulesandUSBcamerastoourPiboardinordertotakeimageandvideocaptureswhenrequiredbyourhomesecuritysystem.Wealsolearnedhowtooverlayourimageswithinformativetextandhavethefilesimmediatelyemailedtous.
Inordertocaptureimagesfromourcameraatnight,wealsolookedatwaystoilluminatethecaptureareausingbothvisibleandinfra-redlighting,withtheabilitytoswitchthelightingonandoffasrequiredbyusingahigh-currentDarlingtontransistordriver.
Inthenextchapter,we’regoingtogetdowntothebusinessofputtingtogethermodulesbybuildingamobile-optimizedweb-basedcontrolpanelforourhomesecuritysystem.We’lllearnhowtosetupaWebserveronourRaspberryPiandmanipulatefilesusingourWebcontrolpanel,whichmeansthatwe’llstarttoexplorehowalloftheelementswe’veencounteredsofarcancometogetheraspartofourfinalsystem.
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
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:
TheLighttpdplaceholderpage
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:
ThePHPinfopagegeneratedbytheWebserver
Nowthatweknowourwebserverisworkingproperly,wecanstartcreatingourconsolewebpage.
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)
1(GP1)
2(GP2)
3(GP3)
4(GP4) ArmedLED(Output)
5(GP5) Arm/DisarmBuzzer(Output)
6(GP6) AlarmLED(Output)
7(GP7) AlarmBell(Output)
ArmingyourselfThetermsarmanddisarmarealarmsystem-speakforswitchingthealarmmonitoringon(armingthesystem)andoff(disarmingthesystem).Zone1ofoursystemisgoingtobelinkedtothearminganddisarmingpartofthesystemasitwillbeconnectedtothesensorsonthedoorthatweleaveorenterfrom;thiswillbeaspecialzoneforentryorexitpurposes.
Whenwesetthealarm,weneedabitoftimetogetoutofthehouse.Thewaythatthesystemknowswe’veleftthepropertyisbymonitoringtheexitzonetoseeifwe’veopenedandthenclosedthefrontdoorbehinduswithinthetimeallowed.
Similarly,whenwereturn,wewillopenthefrontdoor,butwedon’twantthealarmtogooffstraightaway—weneedachancetodisarmthesystemwithinagivenamountoftime.Wewillarmanddisarmthesystemviaourweb-basedcontrolpanel,orbyusingaswitchofsomesortontheinputGP0.
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
#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
CreatingthewebpageOurWeb-basedcontrolpanelisgoingtobeasinglePHP-drivenHTML5webpagewhichwillbemobileoptimized.HTML5isthelatestmark-upstandardforwebpagesandissupportedbymostmodernsmartphonesandbrowsers.Wewillalsocreateacascadingstyle-sheet(CSS)thatwillmakeourpagelookhalfreasonableonmobiledevices.
Tocreatethewebfiles,IrecommendthatyouusesomethingliketheexcellentNotepad++onyourdesktopcomputer,ratherthandoingitdirectlyontheRaspberryPi.Alternatively,ifyouareaseasonedwebdeveloper,youmayalreadyhaveyourIDEofchoice.
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.
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
/*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;
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;
}
.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{
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;
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):
Thewebcontrolpanelwithstyling
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
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:
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.
Thefinaloperationalcontrolpanel
RemoteaccesstoourcontrolpanelWhilewecansetupoursystemtoreceiveemailalertswhenoursystemdetectsanintrusion,itwouldbereallyusefultobeabletoaccessourWeb-basedcontrolpanelwhereverwearesothatwecanperhapsarmanddisarmthesystemorswitchoffcertainzoneswhenwe’renotthere.
However,inordertomakethispossibleweneedtodoafewthings:
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
MyNetgearRouterhastheoptionofupdatingaDynamicDNSservice
TheRaspberryPidynamicDNSclientSinceyourRaspberryPi-basedhomesecuritysystemislikelytoalwaysbeon,youmightwanttoinstalltheddclientupdaterserviceonthereinstead:
$sudoapt-getinstallddclient
Onceinstalled,youcansetitupforyourparticularserviceandaccountdetailsusingthefollowingconfigfile:
$sudonano/etc/ddclient.conf
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.
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.
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.
Chapter8.AMiscellanyofThingsThepreviouschaptershaveprovideduswiththefoundationandelementstodesignandputtogetherourentirehomesecuritysystem,whichwewilldointhenextchapter.IhopethatI’veguidedyouthroughthisjourneyinafairlystructuredandlogicalwaysothatyouarereadytodothat.
Beforehand,though,I’mincludingthischapterdubbedaMiscellanyofThings,asthat’sexactlywhatitis.Itcomprisesafewoptional,butuseful,extrasthatweshouldconsiderforoursystem,butthatdon’treallywarrantawholechapterintheirownright.Iguessyoucouldrefertothemasfootnotestopreviouschapters.
Assuch,wewilltakealookatthefollowingtopics:
Waystoarmanddisarmthesystemwithouttheweb-basedpanelDrivinginductiveloadssafelyfromourGPIOoutputsAddinganescapedwatersensorinputtooursystemAddingatemperaturesensorinputtooursystemHowcarbonmonoxidedetectorscouldbeaddedtooursystemRemotelymanagingourRaspberryPiusingWebmin
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.
TheIP67-ratedkeyswitch,suitableforoutdooruse(typeLorlinWRL-5-E-S-2-B)
Byusingastandalonesecuritykeypad,youcanalloweachusertohavetheirowncodetoarmanddisarmthesystem.Forexample,theCDVIECO100isalow-costkeypadthatallowsuptoa100users.Whenthecorrectcodeisentered,itwillarmthesystembyclosinganinternalswitch.Whenthecodeisenteredagain,thekeypadwilldisarmthesystembyopeningtheswitch.
TheCDVIECO100programmablekeypad
DrivinginductiveloadsItalkedaboutdrivinglargeloadsinChapter6,AddingCamerastoOurSecuritySystem,butnowisprobablyagoodtimetoexpandonthisabitandtalkaboutdrivinginductiveloadssuchasbellsandincandescentlamps.Inthepreviouscircuitexample,IusedtheTIP120DarlingtontransistortodriveanLEDarraythatwasnotinductive.Withinductiveloads,youneedtoaddabitofdiodeprotectiontoprotectthecircuitagainstspikesgeneratedbythecoilswithinrelaysandbellsastheyswitchonandoff.
Here’sthemodifiedcircuitforourdigitalloaddriverwitha1N4007rectifierdiodeforprotection:
Thedigitalloaddriverwithdiodeprotection
BeyondintrusionHomesecurityisnotjustaboutprotectingourpropertyagainstintrusion,it’salsoaboutprotectingagainstotherriskstoo,suchasflood,fire,carbonmonoxideleaks,andsoon.So,itmakessensetoextendourhomesecuritysystemtodetecttheseotherriskstoo.
Youmaychoosetosetupthesystemsothatcertaintypesofalertsonlycometoyourphoneasemails,ratherthantriggeringalloftheoutsidebells,lights,andwhistles.Thiscanbedonebyadaptingthescriptsinthenextchaptersothattheyoperatehowyouwantthemto.
AsimplewaterdetectorThere’snothingworsethanbeingawayforafewdaysandcominghometoafloodedkitchenbecausealeakhasdevelopedunderthesink.Oursimplecircuitwilldetectthepresenceofwaterandtriggeraninputonourhomesecuritysystem,whichcanthenalertyou.Youcanalsobuykitsandready-builtmodulestodothis,butthefollowingcircuitischeapandfeaturesouropto-isolatoraswe’regoingtohaveadifferentvoltageforouractualdetector.
Thecircuitforasimplewaterdetector,isolatedfromourGPIOinput
HowitworksWhenwaterisplacedacrosstheprobes,currentflowsthroughthewater,andso,throughtheR3/R4potentialdivideronthebaseoftransistorQ1.Whenthecurrentatthebaseishighenoughtosaturateit,thetransistorwillswitchonfully,allowingtheLEDinsidetheopto-couplertoswitchon.Thisinturnwillpulldowntheinputpintooursystemto
groundviathephoto-transistorinsidetheoptocoupler.
Youcanusethetrimmer,R4,tocalibratethesensorbyadjustingitssensitivity.AnygenericNPNbipolartransistorshouldworkhere,butobviously,theyallhavedifferentoperatingparameters,sochooseasuitableone.
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.
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.
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
tobealertedassoonasitpicksupanything,thereforeweshouldsetourcomparator’sreferencevoltagetothelowerendofthescale,inaccordancewiththesensitivitycurvetakenfromthedatasheet,shownasfollows:
ThesensitivitycurvetakenfromtheWinsenMQ-7manufacturer’sdatasheet.
NoteWarning
I’veincludedthissectiononcarbonmonoxidedetectionmoreforinterestthananythingelse.It’snastystuff,andwhilerollingoutyourowndetectorisOKforinterest’ssake,pleasekeepitjustforthat.It’susefultohavethisinourhomesecuritysystemtoalertuswhenwe’reoutofthehouseasanaddition,butthisshouldnotbeareplacementforacommerciallyavailableonethatsitsnexttoyourboilerwithallofthecertifications,standards,andsoon,andmakesaveryloudnoisewhenwe’reinthehouse.
RemoteadministrationforourRaspberryPiInthepreviouschapter,welearnedhowtosetupoursystemandhomenetworksothatwecanremotelyaccessthealarmcontrolpanelfromwhereverweare.I’mnowgoingtoshowyouhowtoextendthistobeabletoadministerandmonitorourentireRaspberryPisystem.
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:
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).
YoucanlogintoWebminusingtherootorpiuseraccount,oranyotheraccountthathassudorights:
Webminlogin
Onceloggedin,you’llbepresentedwiththemainsysteminformationpage.Haveagoodpokearoundinitbecausethere’slotsofusefulstuffyoucanseeanddo.
Webminsysteminformationview
Webmincomeswithalotofmodules,andnotallofthemareinstalled;therefore,youmightwanttoexploretheUn-usedModulessectionofthepaneltoseeifthereisanythingyouwanttoaddtoWebmin.
RemotelyaccessingWebminInthesamewaythatwesetupremoteaccessforouralarmcontrolpanelinthepreviouschapter,youcandoitwithWebmin—justsetupport-forwardingonyourrouterforport10000.YoucanthenaccessWebminfromanywhereusinghttps://<my-public-ip>:10000.
SummaryWell,thishasbeenabitofamix-and-matchofvarioustopicstoendonbeforeweputtogetherourhomesecuritysystemframework.Ihopeyouenjoyedthesevariousfootnotestopreviouschapters,andthatit’sgivenyousomeideasonhowfaryoucantakeyourhomesecuritysystem.
WestartedbylookingatwayswecanarmanddisarmoursystemwithouthavingtoaccesstheWeb-basedcontrolpanel,byaddingamechanicalordigitalswitchtoanarm/disarminput.
Wethenlookedataddinganalogue-typesensorstooursystem,whichcanalertuswhenathresholdhasbeenreachedbyusingoperationalamplifierssetupasvoltagecomparators.Theideabehindthesecomparatorcircuitscanbeimplementedfordifferenttypesofsensorswhereyouwanttoknowwhenacertainvoltagethresholdhasbeenreachedattheanaloguesensoroutput.
Finally,welearnedhowtoinstallWebminonourRaspberryPisothatwecanmonitorandconfiguremanyaspectsoftheLinuxoperatingsystem.
Thenextchapteristhemomentwe’veallbeenwaitingfor;we’regoingtotakealloftheelementsandconceptsfromthepreviouschaptersandputtogetherourfullsystemcomprisingtheelementswewanttofeature.ThestaroftheshowwillbeourBashscripts,whichwillgluetogetheralloftheseelementsandprovidethecontrollogicfortheentiresystem.
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
AlarmsystemdiagramSothatwedon’tgetlostinthisprocess,thefirstthingIrecommendistocomeupwithacompletesystemdiagramthatwecanfollow.IdothisforanysystemIdesignandputtogethersothatitcanbebuiltinastructuredway,andeasilydocumentedandmodified.
Forthehomesecuritysysteminthischapter,Ihavecomeupwiththefollowingsystemdiagramthatwewilllooktoasaframework.Thewholeconceptisdesignedtobemodular,soyoucancomeupwithyourownsystemtosuityourrequirementsandimplementitaccordingly,usingthescriptspresentedinthischapter.
Thefinalhomesecuritysystemdiagram
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.
RemembertoconnectanyswitchcircuitappropriatelytotheGPIOpintoavoiddamagetoyourRaspberryPi.ThiswasdiscussedinChapter2,ConnectingThingstoYourPiwithGPIO.
AlarmoutputsInoursystem,wehaveseveraloutputdevicesthatarecontrolledbyourRaspberryPiviaoutputdrivercircuits.Wehaveanoutputforanentry/exitbuzzer,anarmedstatusLED,analarmbell,andanalarmLEDindicator.
TheseareswitchedonandoffbyourRaspberryPiGPIOconnectorviadrivercircuitsthatallowustodrivehighcurrentandinductiveloadsusingtheGPIOpins.Thesedrivercircuits,basedaroundTIP120Darlingtontransistors,werediscussedinChapter6,AddingCamerastoOurSecuritySystemandChapter8,AMiscellanyofThings.
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.
Thecontrolscriptflowchart
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.
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:
#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:
#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"
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
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
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
#############################################
#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
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
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:
pi@raspberrypi~$ls-1/etc/pi-alarm
alarm.cfg
alarm-control.sh
update-alarm-setting.sh
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.
PreservingtheSDcardOnefinaltopicIwanttosharewithyouisthatofpreservingyourRaspberryPi’sSDcard.SDcardshaveafinitewritecycle,andcontinuouswritingtothecardwilleventuallyburnitout.Ifwe’regoingtobewritinglotsoflogfileentriesandtakinglotsofcameraimages,wewillwanttoprotectourSDcardinordertomaintaintheintegrityandreliabilityofoursystem;usingthesystemRAMinsteadcanhelpuswiththis.
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
ConclusionTheRaspberryPiisapowerfullittlebeastandagreatplatformforbuildinglow-cost,buthighlycapable,embeddedsystems.TheinterfacesbuiltintoitsGPIOconnectormakeiteasytoboltonmodulesusingsimplelow-costelectronicsandabitofconfigurationtocreateveryfunctionalandflexiblesystems.TheinclusionofadedicatedcamerainterfaceandnetworkinginterfacesgiveyoueverythingyoucouldpossibleneedforanInternet-connectedhomesecuritysystem.
I’vecoveredalotoftopicsinthisbook,andIcouldhavegoneonandon,butIhopethatwhatIhavepresentedhasbeendoneinastructuredandmethodicalway,andhasgivenyouthetoolsandtechniquestocarryonthisjourneysothatyouareabletocreatetheperfecthomesecuritysystemforyourneeds.
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.
SummaryWell,we’vereachedtheendofourjourneytobuildafullyfunctionalandextensiblehomesecuritysystemusingthemightyRaspberryPimini-PC.Inthisfinalchapter,weputtogetheralloftheelementsandconceptsfromthepreviouschapterstocreateahomesecurityframework,bothfromahardwareandsoftwareperspective.
Inparticular,thischapterguidedustowardbuildingamodularframeworkforourhomesecuritysystem,implementingfeaturesthatyouwouldfindinanycommerciallyavailablesystem,andalsothingsthatyoudon’tseeoutthere.Wewalkedthroughthecompletecontrolscript,exploringitsvarioussectionsandunderstandinghowtheyfitintooursystem.
Wealsolearnedhowtoautomaticallystart-upourhomesecuritysystemscriptwhenourRaspberryPibootsup,andhowdataissharedbetweenthePiandtheweb-basedcontrolpanelinreal-timeviatheconfigurationfile.Finally,welookedathowtopreventourSDcardfromburningoutbycreatingaratherusefulRAM-basedtemporaryfilesystem.
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
BBashcommand-linecalculator(bctool)
usedforconvertinghxvaluestobinary/BuildingthecontrolscriptBashscript/I’msomeoneelsebattery-backed/A+12Vpowersupplybitbanging/Thealternativeapproach(becausewehavenochoice)
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
Ddatalogging
detecting/Loggingdetectiondataddclientupdater/TheRaspberryPidynamicDNSclientdigitalI/Opins/DigitalI/Opinsdisarm
about/Armingyourselfdisarmdevice/Connectinga433-MHzreceiverDnsOMatic
URL/SettingupadynamicDNSaccountdoors/TheworkingofmagneticcontactsensorsdynamicDNSaccount
settingup/SettingupadynamicDNSaccountRaspberryPidynamicDNSclient/TheRaspberryPidynamicDNSclient
DynDNSURL/SettingupadynamicDNSaccount
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
Ffake-hwclockpackage/fake-hwclockffmpegtool/Beavideostarfilesystem,SDCard
raspi-configutility,using/BootingyourPi,Usingtheraspi-configutilityexpanding/Expandingthefilesystem
fixedIPaddress/SettingupadynamicDNSaccountflow-chart/Designingthecontrolscriptsfritzing
URL/Lettherebelightfswebcam
URL/Installingthewebcam
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
HH.264videostream/Beavideostarhall-effectsensors/Gettingintothezonehigh-levelprocess/DesigningthecontrolscriptsHobbytronicsMCP23017expanderportkit
about/HobbytronicsMCP23017expanderportkitURL/HobbytronicsMCP23017expanderportkit
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
JJessieversion/BootingyourPi
Kkeyswitch/Arminganddisarmingthesystem
LLEDResistorValues
calculating/Lettherebelightlighttpdwebserver/InstallingthewebserverLinux
using/UsingLinux
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
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
Oon-boardreal-timeclockhardware
obtaining/Gettingtherighttime,fake-hwclockfake-hwclockpackage/fake-hwclockNetworkTimeProtocol(NTP)/ntp
outputsallocating/Beingincontroldocumenting/Beingincontrol
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
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?
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
TTIP120Darlingtontransistor/Anilluminatingexperience
U433-Utilsoftwareproject
URL/Thealternativeapproach(becausewehavenochoice)Un-usedModulessection/AccessingWebminlocallyUniversalAsynchronousReceiverandTransmitter(UART)bus/TheUARTserialbusUniversalSerialBus(USB)ports/USBportsUSBwebcam
about/UsingUSBcamerasusing/UsingUSBcamerasinstalling/InstallingthewebcamURL/Installingthewebcamsnap,capturing/Takingasnapfswebcam,settingup/Snapsnapsnap
V3.3Vvoltageregulator/Givemepower12Valarmzonecircuits
using/12Valarmzonecircuitsprotecting/Alarmcircuitprotectionworking/Howitworks
videocapturing/Beavideostarusing,insecuritysystem/Caughtoncamera
VideoLANURL/Beavideostar
visudoutility/I’msomeoneelse
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
Zzones
creating/Gettingintothezone