View
12
Download
0
Category
Preview:
Citation preview
HomeAutomationWithArduinoAutomateYourHomeUsingOpen-SourceHardware
MarcoSchwartz,PhD
ContentsLegalAcknowledgmentsAbouttheauthorAboutthecompanionwebsitePrefacetotheFirstEditionPrefacetotheThirdEditionIntroduction
1 HowistheBookOrganized?2 WhyOpen-Source?3 Whatwillyoulearn?4 Safetyconcerns5 Prerequisites
Chapter1 GettingStarted1.1 TheArduinoPlatform1.2 WhatyouNeedtoKnowAboutElectronics1.3 YourVeryFirstProject:aSimpleAlarmSystem
Chapter2 BuildingaWeatherMeasurementStation2.1 Hardware&SoftwareRequirements2.2 HardwareConfiguration2.3 TestingtheSensors2.4 DisplayingtheDataontheLCDScreen2.5 HowtoGoFurther
Chapter3 BuildingaSmartLamp3.1 Hardware&SoftwareRequirements3.2 HardwareConfiguration3.3 TestingtheRelay3.4 PowerMeasurements&AutomaticLightingControl3.5 HowtoGoFurther
Chapter4 XBeeMotionSensors4.1 Hardware&SoftwareRequirements4.2 BuildinganXBeeMotionSensor4.3 TestingtheMotionSensor4.4 UsingtheXBeeModule4.5 BuildingtheCentralInterface4.6 HowtoGoFurther
Chapter5 BluetoothWeatherStation5.1 Hardware&SoftwareRequirements5.2 BuildingtheBluetoothWeatherStation5.3 PairingtheBluetoothModule5.4 RemoteTemperatureMeasurements5.5 BuildingtheServerInterface5.6 HowtoGoFurther
Chapter6 ControllingLampsviaWiFi6.1 Hardware&SoftwareRequirements6.2 BuildingtheProject6.3 TestingtheWiFiModule6.4 RemoteLampControl6.5 BuildingtheSmartLampInterface6.6 HowtoGoFurther
Chapter7 BuildinganHomeAutomationSystem7.1 Hardware&SoftwareRequirements7.2 BuildingtheProject7.3 TestingtheModules7.4 BuildingtheCentralInterface7.5 HowtoGoFurther
Chapter8 Conclusion8.1 Whatdidyoulearninthisbook?8.2 Howtogofurther?
Chapter9 Resources9.1 GeneralInformationaboutArduino9.2 Components9.3 SuggestedReading
LegalCopyright©2014byMarc-OlivierSchwartz
Allrightsreserved. Nopartofthisbookmaybeusedorreproducedinanymannerwhatsoeverwithoutpermissionexceptinthecaseofbriefquotationsembodiedincriticalarticlesorreviews.
ThirdeBookedition:August2014
AcknowledgmentsToallmyfriendswhoencouragedmewhilewritingthisbookandworkingonallmyprojects.
Tomyparentswhosupportedmewhilewritingthisbook,andwhosupportedmeduringalltheotherprojectsImadeinmylife,evenintoughtimes.
TomygirlfriendSylwiaforsupportingmeandencouragingmeineverythingIdo. YouaremysourceofinspirationIneedtogetupeverydayandcontinuetoworkhardtobecomeabetterentrepreneurandabetterperson. Thankyou.
AbouttheauthorIamMarcoSchwartz,andIamanelectricalengineer,entrepreneurandauthor. IhaveaMaster’sdegreeinElectricalEngineering&ComputerSciencefromoneofthetopElectricalEngineeringschoolinFrance,andaMaster’sdegreeinMicroEngineeringfromtheEPFLuniversityinSwitzerland.
Ihavemorethan5yearsofexperienceworkinginthedomainofelectricalengineering.Myinterestsgravitatearoundelectronics,homeautomation,theArduinoplatform,open-sourcehardwareprojects,and3Dprinting.
Since2011Ihavebeenworkingfull-timeasanentrepreneur,runningwebsiteswithinformationaboutopen-sourcehardwareandbuildingmyownopen-sourcehardwareproducts.
AboutthecompanionwebsiteThisbookhasacompanionwebsite,OpenHomeAutomation,whichyoucaneasilyfindbygoingathttp://www.openhomeautomation.net. Onthiswebsiteyouwillfindevenmoreprojectsandresourcesaroundhomeautomationandopen-sourcehardware.
Allthecodethatcanbefoundinthisbookcanalsobeaccessedonlineathttps://github.com/openhomeautomation/home-automation-arduino. ThisGitHubrepositoryforthebookcontainsallthelatestup-to-datecodeforalltheprojectsyouwillfindinthisbook.
PrefacetotheFirstEditionIwasintroducedtothefascinatingworldofhomeautomationwhileIwasvisitingthehomeofoneofmyrichfriends. Iwassurprisedbyhoweasyitallseemed:lightswouldactivatethemselvesautomaticallywhenitwasstartingtogetdark,temperatureswereautomaticallymeasuredineveryroomofthehouseandsenttoacentralserver,andthestatusofeveryalarmsensorofthehousecouldbemonitoredfromacellphone. Buttheproblematthattimewashuge:thesolutionsweretailoredforthathousebyprivatecompanies,andthereforeitwasreservedonlytowealthypeople. Andthisisstillanideathatisaroundnowadays:homeautomationcostsalot.
Ipersonallyhaveanotherproblemwithsuchsystems:youdon’thaveanycontrolofthem.Youhavetofolloweverythingthemanufacturerhasdecidedforyou:themaincontroller,thesensors,thesoftware. Forexample,ifonesensorisfailinginyoursystem,youhavetoreplaceitwithasensorfromthesamebrand. IrememberwhenIwasusingoneofthesecommercialsystemsatafriend’shouse. Ialwayswantedtochangesomething:makeasensoreasiertouse,fixabugintheinterface…butIcouldn’t.
Ofcourse,theideaofbuildingyourownhomeautomationsystemhasalwaysbeenaround. Irememberplayingwithmyfirstmicrocontrollerin2003,anditwasactuallyquiteeasy…ifyouwereintheengineeringworld. Thesesystemswerequiteclosed,andeachofthemrequiredlearningspecificknowledgeabouttheplatform. Andevaluationkitsforthesemicrocontrollersalsousedtocostalot.
However,thepastfewyearssawtheriseofanewmovement:open-sourcehardware. Asforopen-sourcesoftware,thismeanthathardwaredesignsstartedtobefreelyavailableandcustomizablebyeverybody. Andattheheartofthisopen-sourcehardwaremovement,aplatformwasbornthathadahugeimpactintheworldofelectronics:theArduinoplatform. Arduinoisaniceandfriendlyenvironmentinwhichtoeasilyprogrammicrocontrollers.
Andforme,thischangedeverythingwhenitcomestohomeautomation. Nowitispossiblefornearlyeverybodywithsomeelectronicsandprogrammingexperiencetomaketheirownhomeautomationsystems. Andthisispreciselywhatyouwilllearninthisbook.
PrefacetotheThirdEditionSincethefirstedition,thousandsofpeoplehaveusedtheprinciplespresentedheretobuildtheirownhomeautomationsystems. Ihavealsoreceivedalotofconstructivefeedbackthatallowedmetoimprovethebookandcomeupwithasecondedition.
However,alotofthesecommentsthatIreceivedonthefirsttwoeditionsofthebookalsoconcernedtherelativedifficultyoftheprojectsthatwerepresented. Itwaslessaboutthecontentoftheprojectsthemselves,andmoreaboutthenumberofprogramminglanguagesusedinsomeoftheprojects. Forexample,intheprojectsincludingcommunicationsbetweentheArduinoboardandyourcomputer,IusedacombinationofPython,PHP,HTMLandJavaScript. Youalsohadtoinstallandrunawebserveronyourcomputer,whichaddedanotherlayerofcomplexity.
Thiswhyforthisthirdeditionofthebook,Iputtheemphasisonsimplifyingthings. First,Iseparatedthebookintotwoparts. Thefirstpartisaboutbuildingself-containedhomeautomationsystems,withnolinkatallwithacomputeroranotherdevice. Therefore,theseprojectsonlyusetheArduinoprogramminglanguage.
Thesecondpartofthebookuseswhatyouwilllearninthefirstpart,byaddingwirelessmodulestothehomeautomationprojects. Andtobuildtheinterfaceonyourcomputer,Ionlyusedonelanguage:JavaScript. IcompletelyremovedtheneedforotherlanguageslikePythonorPHP.Also,IusedNode.JS,whichallowstoprograminJavaScriptontheserverside. Thisalsoeliminatestheneedtoinstallawebserveronyourcomputer.
Ihopethatyouwilllikethenewpresentationofthebook,andthatyouwillusewhatyouwilllearninthisbooktobuildevenmoreexcitinghomeautomationprojectswithArduino.
Introduction
1 HowistheBookOrganized?
Thisbookisdividedintwomainparts. Thefirstpartofthebookisdedicatedtobuildingself-containedhomeautomationsystemsthatworksontheirown. Forexample,thefirstsystemthatwearegoingtobuildisasimplealarmsystemwithamotionsensor.
Thesecondpartofthebookwillbemoreadvanced,aswearegoingtointerfacehomeautomationprojectswirelesslywithyourcomputer. Forexample,wearegoingtobuildagraphicalinterfacetocontrolalampviaWiFi.
Theentirebookisorganizedaroundprojectsonaspecifictopic,inwhichyouwilllearnaspecificsetofnewskills. Ithinkthisisdefinitelybetterthana“onefits-all”solutionwhereIwouldhavetaughtyouhowtobuildaspecifichomeautomationsystem. Withsmallerprojects,youwilllearnmuchmoreandmuchfaster,andevenmoreimportantlyyouwillhavethesetoftoolstobuildyourownsystemthatistailoredtoyourownhome.Thegoalofthisbookisreallytoinitiateyoutotheworldofhomeautomationusingopen-sourcehardwareandtoshowyouwhatispossible.
Eachchapterwillstartwithverybasicconsiderationsandprojects,andthenwewillbuildontopofthemtoarriveatmorecomplexhomeautomationprojects. Ineverychapterofthebook,youwillfindsectionsthatareorganizedasmini-projects. Inproject,youwillfindalistofwhatyouwillactuallylearnbydoingthistutorial,whathardwareyouwillneed,andastep-by-stepguideonhowtodoit,alongwithscreenshotsandpicturestoguideyoubetterthroughtheprojects.
Asanaid,therewillbelinkstowebsitesforreferencepurposes. Thesearetohelpyoufindhardwarecomponents,andnotethatIhavenocommercialcontractwiththewebsitesthatImentionintheselinks. Also,ineveryprojectIgivesomeadvicetouseequivalentcomponentstotheonesIused,incaseyoualreadyhavesomecomponentsonyourdesk.
Allchaptersincludeadetailedwalkthroughofthecodeusedtobuildthedifferentprojectsinthisbook. Inthesewalkthroughs,Idetailthemostimportantpartssothatyoucanunderstandhoweachhomeautomationprojectworks. However,becauseinsomeprojectsofthisbookthecodeisreallylong,Iwillonlygothroughthemostimportantpiecesofthecode.
Therefore,itisrecommendedthereaderalwaysrefertotheGitHubrepositoryofthisbooktogetthecompletecode. YouwillfindthelinktotheGitHubrepositoryineverychapterofthisbook,orifyouwanttohavealookrightnow,thelinkis:
https://github.com/openhomeautomation/home-automation-arduino
Notethatallchaptersweredesignedtobecompletelyindependentfromeachother,soyoucanstartwithwhateverchapteryoulikeinthebookwithoutbeinglost. However,especiallyifyouareabeginner,itishighlyrecommendedtofollowthechaptersofthisbookinorderfromthestart.
InChapter1,youwilllearnaboutwhattheArduinoplatformreallyis,andwhyitissuchagreatopportunityforhomeautomationsystems. ThechapterwillstartwithageneralintroductiontotheArduinoplatform,andwewilldiveintothethemeofthebookwithafirsthomeautomationproject.
Afterthat,inChapter2,youwillperformyourfirstmeasurementsusingtheopen-sourcehardwareplatformArduino,andyouwilllearnhowtovisualizedataonaLCDscreen.
InChapter3,wewillcontinueourjourneyintohomeautomationsystems. WearegoingtobuildasmartlampwithArduino,thatautomaticallyswitchesonoroffaccordingtotheambientlightlevels.
Chapter4willintroducethesecondpartofthisbook,inwhichwewillbuildwirelesshomeautomationsystems. Forourfirstwirelessproject,wearegoingtobuildXBeemotionsensorsandmanagethemfromyourcomputer.
InChapter5,wearegoingtouseanotherwirelesstechnologywhichisusedinhomeautomation:Bluetooth. Wewillinterfaceatemperature&humiditysensortoArduino,andmeasuredataremotely. Wewillalsobuildaninterfaceonyourcomputertodisplaythedata.
InChapter6,IwillshowyouhowcontrolalampusingWiFi. Notonlywillyoubeabletocontrolthislampfromyourcomputer,butalsofromanydeviceconnectedtoyourlocalWiFinetwork.
Finally,inChapter7,wewillseehowtouseeverythingyouhavelearnedinthisbooktobuildasmallhomeautomationsystemcomposedofmanyelements,allcommunicatingwithacentralinterface.
2 WhyOpen-Source?
Alltheprojectsyouwillfindinsidethebook(andonthecompanionwebsite)arecompletelyopen-source,forbothhardwareandsoftware. Sowhatexactlydoesthismean? Whataretheadvantages? Andwhymakeitanessentialpartofthebook?
Well,letmefirstsayafewwordsabouttheopen-sourcehardwaremovement. Open-sourcesoftwarehasbeenaroundforquiteawhilealready,withtheLinuxoperatingsystemanditsentireecosystem,butopen-sourcehardwareismuchmorerecent. Sohowcanhardwarealsobeopen-source? Well,therearemanyopen-sourcehardwarelicenses,butitbasicallymeansthatwithanopen-sourcehardwaresystem,alltheschematicsandPCBdesignfilescanbefreelyaccessedandmodifiedbyanybody,asyouwoulddownloadandmodifyopen-sourcesoftware. Open-sourcehardwareactuallygoesfurtherthanjustopen-sourceelectronics,asitalsoconcernsopen-sourcedesignsfor3Dprintingforexample,butthisissomethingwewon’ttouchinthisbook.
Thereareseveraladvantagesofthisopen-sourceapproachforhardwaresystems. Thefirstoneisthatitallowspeopletohavealookintothehardwaresystemsthemselves,andunderstandwhythehardwaresystemtheyareusingisworkingalongwiththeopen-sourcesoftwarethatusuallycomeswithit. Butthemainadvantageformeisthatitallowspeopletomodifythehardwaresystemsandthensharethemagainwiththecommunity. Thisproducesamuchfasterdevelopmentprocessforhardwareproductsasitreallyengagestheusersandcreatescommunitiesaroundagivenhardwareproduct.
AndthisispreciselywhyIputopen-sourceatthecoreofthisbookandofthecompanionwebsite:becauseyoucanaccessthesourcesofalltheprojectsfoundinthisbook,youwillbeabletounderstandthemdeeply,modifythem,makethembetter,andthensharethemagainwiththecommunity. WhatIreallydidn’twantwastospeakabouthomeautomationbyjustpreachingmyownvision;Iwanttoengageyouasmuchaspossibletogobeyondthisbookandmakeyourownsystemswithwhatyouaregoingtolearninthebook.
3 Whatwillyoulearn?
Beforedivingintotheheartofthisbook,andbuildingyourfirsthomeautomationproject,Iwantedtospendafewmomentstoexplainwhatisyouwillactuallylearninthisbook.
Ofcourse,youwilllearnabouthomeautomation. Youwilllearnhowmostcommonhomeautomationsystemsworkbybuildingyourownsystem,forexamplesimplymeasuringthetemperatureinyourhomeanddisplayingitonyourcomputer. Youwillalsolearnaboutthebasicsofalarmsystems,andhowtocontrolthelightsinyourhomesotheycanadapttoyourcommandsortotheambientluminosity.
Butyouwilllearnmorethanthat. YouwilllearnaboutwhatIconsidertobeoneofthemostimportantplatformsatthemomentwhenitcomestodo-it-yourselfelectronicsprojects:theArduinoplatform. Whatyouwilllearnaboutthisplatformcanthenbeusedagaininmanyotherprojects.
Youwillalsolearnaboutelectronicsingeneral. Fromthemostbasicthing,likehowtoconnectamotionsensortotheArduinoboard,tohowtoconnectadigitalsensor,wewillcoveralotinthedomainofelectronics,andtheknowledgeyouwillacquirecanalsobeusedinseveraldomainsoutsideofhomeautomation.
Finally,youwillalsolearnaboutsoftwaredevelopment. WewillfirstprogramtheArduinoboardusingtheArduinoIDE,whichisbasedonC/C++. IwillalsointroduceabitofHTMLandJavascripttomakeremotemeasurementspossible,andtocontrolhomeautomationsystemsfromyourcomputer. Sowithalltheswitchingbetweenprojectsandlanguages,youwillalsoacquireasolidbackgroundinsoftwaredevelopment.
4 Safetyconcerns
Mostoftheprojectsyouwillfindinthisbookuselow-voltagedevices,whicharecompletelyharmless. However,becauseinagoodhomeautomationsystemwewanttocommandsome110or230Vdeviceslikelamps,someprojectswillmakeuseofsuchvoltagesourcesandcanbedangerousifcertainprecautionsarenottaken.
Don’tworry. Youcanlearnabouthomeautomation&Arduinoandcompletealloftheprojectsfoundinthisbookwithouteverconnectingyoursystemstothepowerpluginyourwall,butifyouactuallywanttoinstallsomeofthesedevicesinyourhomeIreallyadvisereadingthissectioncarefully.
Itisusuallyacceptedthatanythingabove50Visdangerous,and25Visusuallytakenasa“safe”value.
Forus,itmeansthatmostcircuitswillbesafe(Arduinooperatesat5Vor3.3V),theonlythingwherewewillhavetobecarefuliswhenconnectingsomepartofyourcircuittothemainselectricity(whichisat110VintheUSor230VinEurope,forexample).
Therisksofbeingindirectcontactwithavoltageabove50Vareveryhigh,andtheconsequencesincludeventricularfibrillation,cardiacarrest,respiratoryarrest,andseriousburns,allpossiblyleadingtodeath.
Itisactuallynotthatdifficulttoavoidriskswhenworkingwithhighvoltages. Thefirstone,whichseemsquiteevident,istoalwaysworkwiththecircuitbeingoff,andtobefarfromitwhenthecircuitisinoperation. Alsokeepinmindthatsomethinginsidethecircuitcouldhavebrokendownandtouchedthecaseofyourdevice,sodon’ttouchanythingwhenthecircuitisinoperation.
Alsomakesurethatthecircuitisde-energizedbeforetouchingit. Indeed,somehigh-voltagecircuitscancontaincomponentslikecapacitorsthatstoreenergyevenifthepowerhasbeenshutdown. However,youwon’tfindsuchcircuitsinthisbook.
5 Prerequisites
Firstofall,youcouldjustreadthisbookfromstarttofinishwithoutactuallydoinganyoftheprojects,andstilllearnalotaboutelectronics,programmingandofcoursehomeautomation. However,Ireallyrecommendspendingtimedoingtheprojectsyourself. Youwilllearnsomuchmorebydoingso.
Nowfortheprerequisites. Youactuallydonotneedtoknowmuch,butapreviousexperiencewiththeworldofelectronicsandprogrammingwillbeusefulandwillallowyoutogetthroughtheprojectsfaster. Theprojectscanberunfromanycomputer,butIwillfocusonusingtheOSXandLinuxoperatingsystems. However,theArduinosoftwarealsoperfectlyrunsonWindowsandalltutorialswillworkunderthisoperatingsystem.
Fortheprogrammingside,IwilluselanguageslikeC/C++,HTML,andJavascript. IwillnotmakeafullintroductionoftheselanguageswhenIusethem,butIwilldetaileveryoneofthefunctionsIuseandpointtoareferenceifIamusingmorecomplexfunctionsinoneoftheselanguages. Butoverall,wewillkeepitsimple.
Fortheelectronicspart,Iwillintroducethefunctionofeverynewcomponent. Also,foreverycomponentusedintheprojectsinthisbook,Iwillincludeusefullinksinthesupportpagessothatyoucaneasilyfindandbuythesecomponentsontheweb. Alloftheprojectswilluseabreadboardforrapidprototypingsoyoudon’thavetosolderanything.Again,thegoalofthisbookistoteachyouabouthomeautomationusingtheArduinoplatformsoyoucanbuildyourownsystemslater.
Mostofthehardwareandthesoftwarerequiredforthisbookarespecifictoeverychapter.However,thereareafewthingsyouwillneedthroughoutthebookandthosewewillinstallrightnow.
ThefirstthingistheArduinoIDE(IDEmeanIntegratedDevelopmentEnvironment). YoucangrabitontheofficialArduinowebsiteatthefollowingaddress:
http://arduino.cc/en/Main/Software
Inthesecondpartofthebook,wearegoingtoconnectourprojectswirelesslytoyourcomputer. Tousetheserver-sidecode,youaregoingtoneedtohaveNode.jsinstalledonyourcomputer. Node.jsissoftwarethatallowstheconstructionofserver-sidecodeusingJavascript,andwewilluseittobuildinterfacesforourhomeautomationprojects. You
cangrabitatthefollowingaddress:
http://nodejs.org/download/
Itisalsoavailableforallplatforms,andeasytoinstall. ToinstallitunderWindowsorOSX,simplydownloadtheinstallerfile,andfollowtheinstructionsgivenbytheinstallsoftware.
IfyouareunderWindows,inorderforNode.jstoworkcorrectlyyoualsoneedtocreateafoldercallednpminsidethisfolder:
C:\Users\yourUserName\AppData\Roaming\
IfyouarerunningunderUbuntuorotherLinuxdistributions,youhavetheenterthefollowingcommandsinaterminal:
sudoapt-getinstallpython-software-properties
sudoapt-add-repositoryppa:chris-lea/node.js
sudoapt-getupdate
Then,enterthefollowingcommandtoinstallNode.js:
sudoapt-getinstallnodejs
NotethatunderLinux,Node.jsissometimesdenotedasnodejsandnotnodelikefortheotheroperatingsystems.
IfyouareusingaRaspberryPi,firstenterthiscommandinaterminal:
sudowgethttp://node-arm.herokuapp.com/node_latest_armhf.deb
Then,installNode.jsbytyping:
sudodpkg-inode_latest_armhf.deb
Chapter1
GettingStarted
1.1 TheArduinoPlatform
Youarejustminutesawayfromactuallydoingyourfirstopenhomeautomationproject.Beforethat,however,Iwanttointroducetheplatformthatwewillbeusinginthiswholebook:theArduino.
ThehistoryofArduinobeganin2005,whenthefoundersMassimoBanziandDavidCuartielleswantedtomakeadevicethatwouldbeeasytoprogrambynon-experts,sothattheirstudentsindesigncouldbuildprojectsthatusedmicrocontrollers. TheArduinoplatformwascreatedtobenotonlyabouttheboardsandthemicrocontrollers,butalsoasacompletehardwareandsoftwareecosystemthatmadethelifeoftheusermuchsimplercomparedtoothermicrocontrollersolutions.
Onthehardwareside,Arduinoisasingle-boardmicrocontrollersystem,usuallyequippedwithan8-bitAtmelAVRmicrocontroller,althoughnewmodelsliketheArduinoDuehavea32-bitARMprocessor. Forourprojects,wedon’tneedthatmuchpower,andwewillonlyusethemostcommonArduinoboard:theArduinoUno.
OnecharacteristicofArduinoboardsisthattheirpinsarealwaysexposedinasimilarfashion,whichmeansthatitisveryeasytopluginextensions,calledshields,directlyintotheboards. Theseshieldscanaddvariousfunctionalitiestotheboard,liketheabilitytocontrolDCmotorsforroboticsapplications,ortoconnectwirelesslytoyourphoneviaBluetooth.
Butforme,it’sreallythesoftwarepartthatmakestheArduinoplatformsopowerful. ToprogramanArduinoboard,youcanusetheofficialArduinosoftware(whichistotallyfreetodownload)andthenusealanguageclosetoC++toactuallywritethecodethatyouwilluploadtotheboard. Comparedtoothermicrocontrollers,believeme,itisveryeasytoprogramtheboardtomakeitdowhatwewant. Forexample,asimpleinstructionlikemakinganLEDlightuponlytakesasinglelineofcodewithanArduinoboard,whereasitwouldtakemanylineswithothermicrocontrollers.
AnotherimportantpointisthatthereisalsoahugecommunityaroundtheArduinoplatform. ThismeansthateveryfunctionuseisreallywelldocumentedontheofficialArduinowebsite(www.arduino.cc). Youwillalsofindtutorialsformostofthecommonlyusedfunctionsoftheboard.
Iwillnowgiveyouabitmoredetailabouttheboardthatwewillbeusinginthisbook:theArduinoUno. HereisapictureoftheboardIpersonallyusedforalltheprojectsin
thisbook:
Theboarditselfisverytiny. WhatyoucanseeonthelowerrightportionofthepictureisanAtmelmicrocontroller,the“brain”oftheboard. Itreceivesthesoftwarewhichwewilldevelopforourhomeautomationprojects. Onthetopandonthebottomoftheboard,youwillseetworowsofconnectors. Wewillusethesetoconnecttheinputandoutputsignalssuchastheanaloginputs,thedigitalinputsandoutputs,andreferencevoltageslikethegroundand5V.Finally,youcanseetheUSBconnectorontheleftuppercorner. Thiswillconnecttheboardtothehostcomputer.
1.2 WhatyouNeedtoKnowAboutElectronics
Thisisnotabookaboutgeneralelectronics;therearemuchbetterbooksforthat. Thisbookwillteachyouhowtobuildhomeautomationsystems. Itwillcoachyouhowtoconnectdifferentcomponents,sensorsandotherdevicestotheArduinoplatform.
However,inordertounderstandhowthesecomponentswork,youneedtounderstandseveralbasicelectronicprinciples. Thissectionwillgiveyouaquickintroductionoftheprinciplesusedintheprojectsfoundinthisbook.
Mainvariablesusedinelectronics
Tocharacterizeacircuit,manyvariablesareused,butwearejustgoingtolookatthemostimportantones.
ImaginethatanelectricalcircuitislikewaterflowingfrompointAtopointB.Forwatertoflownaturallyintothecircuit,weneedadifferenceofheightbetweenAandB.Andinelectricalcircuits,thisdifferenceiscalledthevoltage,usuallynotedasV.
WecanalsodefinetheequivalentflowofwaterbetweenAandBastheflowofelectrons,whichisthecaseinanelectricalcircuit. ThiselectronflowiscalledtheelectricalcurrentandwillberepresentedbytheletterI.
WecanalsoexpressthepowerPdissipatedbyagivencomponent,inWatts,bymultiplyingthevoltagebythecurrent:P=V*I.
Basiccircuitrepresentation
Inordertorepresentelectricalcircuits,anormalizedsetofsymbolsisused. Here,forexample,isasimplecircuitwithavoltagesourceVCC,aresistorR1,anLEDcalledLED1,andagroundGND.
Lateron,wewillseemoredetailsaboutsomeofthesecomponents,butfornow,let’sjustidentifythecomponentswhichareusuallyfoundinmanycircuits.
Whenreadingacircuit,youshouldfirstlocatethepowerandgroundpins. Here,thepowerisrepresentedbytheVCCpin,whichwillusuallybeequalto5Vintheprojectsfoundinthisbook. ThegroundpinhereisrepresentedbyGND.
AfterVCCandGND,youcanlookforthecomponents. Here,wesimplyhavearesistorandanLED.
Powersources
Inthefirstcircuitofthissection,thepowersourcewasapinnamed“VCC”. Thissourcecanbeliterallyanything,butbyconvention,VCCwilldenoteapositive,low-voltagepowersource(usually3.3,5or12V).
Topowertheprojectsthatyouwillfindinthisbook,theUSBportoftheArduinoboardwillusuallybeused. However,youcanalsopowerupyourArduinoboardfromotherpowersourceslikeregulatedpowersupplieswhichcanbedirectlypluggedintothewallsocket(bewarenottoexceedthemaximumvoltageacceptedbyyourArduinoboard)orontobatteries.
Resistors
Resistorsarekeycomponentsofmostelectricalcircuits. Takingagainourpreviousanalogywithwater,aresistorwillactuallylimittheflowofwater(orelectrons)inagivenbranchofthecircuit.
Toquantifyhowmuchtheresistorislimitingthecurrentinacircuit,wecanintroduceanewvariablecalledR,resistancewhichismeasuredinOhms. Foraresistor,theformulathatlinksvoltage,currentandresistanceiscalledOhm’slaw:V=R*I.
LEDs
LEDs,shortforLightEmittingDiodes,arethemostcommonlyusedcomponentsforsignalingandtestinginacircuit. Whencurrent(usuallyabout20mA)isgoingthroughanLED,theyemitlight,whichcanbered,blue,greenorevenwhite,dependingontheLED.
OntheArduinoboardforexample,LEDsareusedtomakesuretheboardison,toindicatethataserialcommunicationisactuallyhappeningorasatestcomponentforsoftware(onpinnumber13).
Asshowninthefirstcircuitofthissection,LEDsareusuallyassociatedwithresistorstolimitthecurrentthatflowsthroughthem. Beware,thepinsofanLEDarenotequal–thepositivepowersupply(forexample,VCC)hastogoontheleftsideoftheLEDcalledtheanode,andtheotherpin,calledthecathode,hastobeconnectedtotheground. Youcaneasilyidentifythecathodeasittheonewiththeshorterlead.
Relays
Inhomeautomation,wewanttoswitchthingslikelampsonandoffasyouwoulddowhenyoupressalightswitchonthewall. Thisisdoneusingrelays,whichbasicallyareelectromechanicalswitches.
Therearetwoprimarypartsinarelay. Theleftpartofthesymbolisthecoil,andisthe“control”partoftherelay. Whenavoltage(usually5Vforrelaysusedinthisbook)isappliedtothecoil,theotherpartoftherelaywillswitchitsstate,goingfromaclosedstatetoanopenstate,forexample.
Thecoolthingisthatthissecondpartoftherelaycanhandlemuchhighervoltages(upto300Vfortheonesusedinthisbook)comparedtowhattheArduinoboardcouldhandle.ThisallowsanArduinoboardtocontroldevicesthatusepowerdirectlyfromthemainselectricity,likelamps.
Goingfurther
Thissectionisclearlyjustanintroductiontoelectronicsandtothecomponentsthatwearegoingtousethemostinthisbook.
Togofurtherandlearnmoreaboutelectronics,thereareseveralthingsthatyoucando.
Ofcourse,justbrowsingtheInternetisanoption. Youwillfindmanyresourcesbyusingthisway. YoucanalsohavealookinsidetheResourceschapterofthisbooktofindseveralbookrecommendationsaboutArduino&electronics.
1.3 YourVeryFirstProject:aSimpleAlarmSystem
Toendthischapter,wearegoingtobuildourveryfirsthomeautomationproject:asimplealarmsystem. WearegoingtointerfaceaPIRmotionsensorwithArduino. Ifmotionisdetected,wewillflashanLEDandmakesomesoundwithasmallpiezobuzzer. ThissimpleprojectwillgiveyouthebasicsofhomeautomationwithArduino.
Hereisthelistofcomponentsyouwillneedforthisproject:
ArduinoUno(http://www.adafruit.com/product/50)PIRmotionsensor(http://www.adafruit.com/product/189)LED(https://www.sparkfun.com/products/9590)330Ohmresistor(https://www.sparkfun.com/products/8377)Piezobuzzer(http://www.adafruit.com/product/160)Breadboard(http://www.adafruit.com/product/64)Jumperwires(http://www.adafruit.com/product/758)
Wecannowstartassemblingtheproject. Tohelpyouout,theschematicbelowsummarizesthehardwareconnections:
ThisimagewascreatedwithFritzing(http://fritzing.org/).
First,placeallthecomponentsonthebreadboard. Afterthat,positionthebreadboardnexttotheArduinoboard. Then,connectthePIRmotionsensortothebreadboard. ConnecttheGNDpinoftheArduinoboardtothebluerailofthebreadboardaswewillneedtoconnectalldevicestothesameground.
FortheLED,connecttheresistorinserieswiththeLEDanodeonthebreadboard(theanodeisthelongestpinontheLED). Then,connecttheotherpinoftheresistortoArduinopin5. TheothersideoftheLEDmustbeconnectedtotheArduinoground.
ForthePIRmotionsensor,connecttheGNDpintotheArduinoground,VCCtotheArduino5Vpin,andSIGpintoArduinopin7.
ForthePiezobuzzer,connectthepositivepin(markedwitha+)toArduinopin8,andtheotherpintotheArduinoground.
Thisisapictureofthefullyassembledproject:
Nowthatthehardwareisassembled,wecanstartwritingtheArduinosketchforoursimplealarmsystem. Thisisthecompletecodeforthispart:
//Codeforthesimplealarmsystem
//Pins
constintalarm_pin=8;
constintled_pin=5;
constintmotion_pin=7;
//Alarm
booleanalarm_mode=false;
//VariablesfortheflashingLDED
intledState=LOW;
longpreviousMillis=0;
longinterval=100;//Intervalatwhichtoblink(milliseconds)
voidsetup()
{
//Setpinstooutput
pinMode(led_pin,OUTPUT);
pinMode(alarm_pin,OUTPUT);
//Waitbeforestartingthealarm
delay(5000);
}
voidloop()
{
//Motiondetected?
if(digitalRead(motion_pin)){
alarm_mode=true;
}
//Ifalarmmodeison,flashtheLEDandmakethealarmring
if(alarm_mode){
unsignedlongcurrentMillis=millis();
if(currentMillis-previousMillis>interval){
previousMillis=currentMillis;
if(ledState==LOW)
ledState=HIGH;
else
ledState=LOW;
//SwitchtheLED
digitalWrite(led_pin,ledState);
}
tone(alarm_pin,1000);
}
}
Let’snowseethedetailsofthiscode. Itstartsbydeclaringthepinstowhichthedifferentcomponentsareconnectedto:
constintalarm_pin=8;
constintled_pin=5;
constintmotion_pin=7;
Wewillstorethefactthatthealarmisonornotinsideavariable:
booleanalarm_mode=false;
WewillalsohaveavariabletomaketheLEDflashwhenthealarmison:
intledState=LOW;
longpreviousMillis=0;
longinterval=100;//Intervalatwhichtoblink(milliseconds)
Now,insidethesetup()functionofthesketch,weneedtosetthepinsfortheLEDandthePiezoasoutputs:
pinMode(led_pin,OUTPUT);
pinMode(alarm_pin,OUTPUT);
Wealsowaitfor5seconds,sothealarmdoesn’tturnonrightaway:
delay(5000);
Intheloop()functionofthesketch,wecontinuouslycheckthestateofthePIRmotionsensor. Ifsomemotionhasbeendetected,wesetthealarmvariabletotrue:
if(digitalRead(motion_pin)){
alarm_mode=true;
}
Now,ifthealarmison,wedotwothings:continuouslyflashtheLEDandinitiatethePiezobuzzertomakesomenoise. Thisisdonebythefollowingpieceofcode:
if(alarm_mode){
unsignedlongcurrentMillis=millis();
if(currentMillis-previousMillis>interval){
previousMillis=currentMillis;
if(ledState==LOW)
ledState=HIGH;
else
ledState=LOW;
//SwitchtheLED
digitalWrite(led_pin,ledState);
}
tone(alarm_pin,1000);
}
NotethatallthecodesforthisfirstprojectcanbefoundontheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino/
Youcannowtestthisfirstprojectofthebook. UploadthecodetotheArduinoboardusingtheArduinoIDE.Trywavingyourhandinfrontofthesensoraftertheinitial5secondsdelayhaspassed. YoushouldhearthealarmturnonandseetheLEDflashingcontinuously. Toturnitoffagain,simplypresstheredresetbuttonontheArduinoboard.
Incaseitisnotworkingatthispoint,thereareseveralthingswhichyoucancheck. First,makesurethatallthehardwareconnectionsarecorrectbydoingthehardwareconfigurationpartagain. Also,makesurethatyouhavecorrectlyuploadedthelatestversionofthecodethatyoucanfindinsidetheGitHubrepositoryofthebook.
IhopethissimpleprojectgaveyouanideaofwhatyoucandowithArduinoforhomeautomationapplications. Inthenextchapterofthebook,wearegoingtousetheArduinoplatformtobuildevenmoreexcitinghomeautomationapplications!
Chapter2
BuildingaWeatherMeasurementStationInthepreviouschapter,whichreallyintroducedyoutotheworldofopen-sourcehomeautomation,youlearnedhowtointerfaceamotionsensorwithArduinotocreateasimplealarmsystem.
Inthisproject,Iwillshowyouhowtomonitorthetemperature,humidityandlightlevelofaroomusingArduino,atemperature&humiditysensor,aphotocell,andaLCDscreen. WearegoingtocontinuouslydisplayallthisdataontheLCDscreen.
Thisprojectperfectlyrespectsthefoundationsofthisbookasitusesonlyopen-sourcecomponents. Youcanseeitasthefoundationofamorecomplexsystemtoremotelymonitorinformationaboutyourhome.
2.1 Hardware&SoftwareRequirements
Forthisproject,youwill,ofcourse,needanArduinoUnoboard. YoucanalsouseotherArduinoboardslikeanArduinoMegaorLeonardoastheywillworkjustfinetoo.
Fortemperatureandhumiditymeasurements,youwillalsoneedaDHT11sensor,alongwitha4.7Kresistor. YoucanalsouseaDHT22sensorwhichismoreprecise,onlyyouwillhavetochangeonelineofcode.
Forlightlevelsmeasurements,Iusedaphotocellwitha10KOhmresistor. Thiswillreturnasignalwhichisproportionaltotheincominglightlevel.
YouwillalsoneedanLCDscreentodisplaythemeasurements. Iuseda4x20characterLCDsoIcandisplayuptofourdifferentmeasurementsatthesametime. Youcan,ofcourse,useasmallerLCDscreen,butyouwillonlybeabletodisplaythetemperatureandhumidityatthesametime,forexample.
ThescreenIusedforthisprojectusesanI2CinterfacetocommunicatewiththeArduinoboard. IstronglyrecommendusingascreenwiththisinterfaceasthereareonlytwodatapinsneededtoconnecttotheArduinoboard.
Finally,Iusedabreadboardandsomemale-malejumperwirestomakethedifferentelectricalconnections.
Hereisalistofallcomponentsusedinthisprojectalongwithlinkswhereyoucouldpurchasethemonline:
ArduinoUno(http://www.adafruit.com/product/50)DHT11sensor+4.7kOhmresistor(http://www.adafruit.com/product/386)Photocell(http://www.adafruit.com/product/161)10kOhmresistor(https://www.sparkfun.com/products/8374)LCDdisplay(http://www.robotshop.com/en/dfrobot-i2c-twi-lcd-module.html)Breadboard(http://www.adafruit.com/product/64)Jumperwires(http://www.adafruit.com/product/758)
YouwillalsoneedthelibraryfortheDHTsensor:
https://github.com/adafruit/DHT-sensor-library
AndtheLiquidCrystallibraryfortheLCDscreen:
https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
Toinstallalibrary,simplyputthefolderinthe/libraries/folderofyourmainArduinofolder.
2.2 HardwareConfiguration
Thehardwareconnectionsforthisprojectarequitesimple:wehavetoconnecttheDHT11sensor,theLCDscreenandthepartresponsibleforthelightlevelmeasurementwiththephotocell. Tohelpyouout,thefollowingpicturesummarizesthehardwareconnections:
ThisimagewascreatedwithFritzing(http://fritzing.org/).
First,connecttheArduinoUno+5Vpintotheredrailonthebreadboard,andthegroundpintothebluerail.
ToknowwhichpintoconnectfortheDHT11sensor,refertothepicturebelow:
Then,connectpinnumber1oftheDHT11sensor(VCC)totheredrailonthebreadboard,andpinnumber4(GND)thebluerail. Also,connectpinnumber2ofthesensortopinnumber7oftheArduinoboard. TofinishupwiththeDHT11sensor,connectthe4.7kOhmbetweenpinnumber1and2ofthesensor.
Forthephotocell,placethecellinserieswiththe10kOhmresistoronthebreadboardfirst. Next,connecttheotherendofthephotocelltotheredrailonthebreadboard,andtheotherendoftheresistortothebluerail(ground). Finally,connectthecommonpinbetweenthephotocellandtheresistortotheArduinoUnoanalogpinA0.
Now,wearegoingtoconnecttheLCDscreen. SinceweareusinganLCDwithanI2Cinterface,therewillonlybetwowiresneededtoconnectforthesignal,andtwoforthepower. ConnecttheLCDpincalledVCCtotheredrailonthebreadboard,andtheGNDpintothebluerailonthebreadboard. Then,connecttheLCDpinSDAtotheArduinopinA4,andtheSCLpintotheArduinopinA5.
Hereisapictureofthefullyassembledprojectsoyoucanhaveanideaonhowthecompleteprojectlookslike:
2.3 TestingtheSensors
Nowthatthehardwareoftheprojectisfullyassembled,wearegoingtotestthedifferentsensorsontheboard. Todoso,wearegoingtowriteasimpleArduinosketch. WewillsimplyreadoutdatafromthesensorsandprintthesedataontheSerialport. Thisisthecompletecodeforthispart:
//CodetomeasuredataandprintitontheSerialmonitor
//Libraries
#include"DHT.h"
//DHTsensor
#defineDHTPIN7
#defineDHTTYPEDHT11
//DHTinstance
DHTdht(DHTPIN,DHTTYPE);
voidsetup()
{
//InitializetheSerialport
Serial.begin(9600);
//InitDHT
dht.begin();
}
voidloop()
{
//MeasurefromDHT
floattemperature=dht.readTemperature();
floathumidity=dht.readHumidity();
//Measurelightlevel
floatsensor_reading=analogRead(A0);
floatlight=sensor_reading/1024*100;
//Displaytemperature
Serial.print("Temperature:");
Serial.print((int)temperature);
Serial.println("C");
//Displayhumidity
Serial.print("Humidity:");
Serial.print(humidity);
Serial.println("%");
//Displaylightlevel
Serial.print("Light:");
Serial.print(light);
Serial.println("%");
Serial.println("");
//Wait500ms
delay(500);
}
ItstartsbyimportingthelibraryfortheDHTsensor:
#include"DHT.h"
AndcreateaDHTinstance:
DHTdht(DHTPIN,DHTTYPE);
Inthesetup()functionofthesketch,wehavetoinitializethesensor:
dht.begin();
AndtheSerialport:
Serial.begin(9600);
Intheloop()function,wearegoingtocontinuouslyreaddatafromthesensorsandprintthemtotheSerialport. Westartbygettingdatafromthetemperatureandhumiditysensor:
floattemperature=dht.readTemperature();
floathumidity=dht.readHumidity();
Forthephotocell,wefirstreaddatafromtheanalogpinA0,whichreturnsavaluefrom0to1023astheresolutionoftheAnalog-To-DigitalconverteroftheArduinoUnoboardis10bitsor1024values. Then,wedividethisvalueby1024andmultiplyitby100tohavethelightlevelasapercentage:
floatsensor_reading=analogRead(A0);
floatlight=sensor_reading/1024*100;
Next,weprintthesedifferentmeasurementstotheSerialport. First,thetemperature:
Serial.print("Temperature:");
Serial.print((int)temperature);
Serial.println("C");
Printinghumidityissimilartothelightlevel:
Serial.print("Light:");
Serial.print(light);
Serial.println("%");
Finally,weintroduceadelayof500msbetweeneachnewsetofmeasurements:
delay(500);
NotethatthecompletecodeforthischaptercanbefoundonthecorrespondingfolderinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotestthisfirstArduinosketch. UploadthecodetotheArduinoboardand
opentheSerialmonitorinsidetheArduinoIDE(makingsuretheSerialspeedissetto9600). Thisiswhatyoushouldsee:
Temperature:25C
Humidity:36.00%
Light:83.79%
Ifthatworks,congratulations,yoursensorsareworkingcorrectly! Youcantry,forexample,topassyourhandinfrontofthephotocell,andyoushouldseethatthelightlevelchangesinstantly.
Incaseitisnotworkingatthispoint,thereareseveralthingsthatyoucancheck. First,makesurethatthesensorsandtheLCDscreenarecorrectlyconnectedtotheArduinoboard. Also,makesurethatyouhavecorrectlydownloadedandinstalledthelibrariesfortheDHTsensorandtheLCDscreen.
2.4 DisplayingtheDataontheLCDScreen
Wearenowgoingtoputthingstogether,andusewhatwealreadydidtofinishourproject. Wewillthereforekeepthemeasurementpartofthesketchwejustwrote,anddisplaytheresultsontheLCDscreen.
Asmostofthecodeisthesamecomparedtotheprevioussketch,IwillonlydetailthepartsthatwereaddedforthedisplayontheLCDscreen. Ofcourse,youcanfindallthecodeontheGitHubrepositoryofthebook. Thisisthecompletecodeforthispart:
//Codetomeasuredata&displayitontheLCDscreen
//Libraries
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
#include"DHT.h"
//DHTsensor
#defineDHTPIN7
#defineDHTTYPEDHT11
//LCDdisplayinstance
LiquidCrystal_I2Clcd(0x27,20,4);
//DHTinstance
DHTdht(DHTPIN,DHTTYPE);
voidsetup()
{
//Initializethelcd
lcd.init();
//PrintamessagetotheLCD.
lcd.backlight();
lcd.setCursor(1,0);
lcd.print("Hello!");
lcd.setCursor(1,1);
lcd.print("Initializing…");
//InitDHT
dht.begin();
//ClearLCD
delay(2000);
lcd.clear();
}
voidloop()
{
//MeasurefromDHT
floattemperature=dht.readTemperature();
floathumidity=dht.readHumidity();
//Measurelightlevel
floatsensor_reading=analogRead(A0);
floatlight=sensor_reading/1024*100;
//Displaytemperature
lcd.setCursor(1,0);
lcd.print("Temperature:");
lcd.print((int)temperature);
lcd.print((char)223);
lcd.print("C");
//Displayhumidity
lcd.setCursor(1,1);
lcd.print("Humidity:");
lcd.print(humidity);
lcd.print("%");
//Displaylightlevel
lcd.setCursor(1,2);
lcd.print("Light:");
lcd.print(light);
lcd.print("%");
//Wait100ms
delay(100);
}
ItstartsbyincludingtherequiredlibrariesfortheLCDscreenandtheDHTsensor:
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
#include"DHT.h"
Then,wecancreatetheinstanceoftheLCDscreen. Ifyouareusingotherscreensizes,forexampleswithtwolinesonly,thisisthetimetochangeit:
LiquidCrystal_I2Clcd(0x27,20,4);
Inthesetup()functionofthesketch,weneedtoinitializetheLCDscreen:
lcd.init();
Stillinthisfunction,weputthebacklightoftheLCDon,andprintawelcomemessage:
lcd.backlight();
lcd.setCursor(1,0);
lcd.print("Hello!");
lcd.setCursor(1,1);
lcd.print("Initializing…");
Aftertwoseconds,wesimplycleardownthescreenbeforedoingmeasurements:
delay(2000);
lcd.clear();
Now,intheloop()functionofthesketch,afterthedifferentmeasurements,weprintoutthetemperatureonthefirstlineoftheLCDscreen:
lcd.setCursor(1,0);
lcd.print("Temperature:");
lcd.print((int)temperature);
lcd.print((char)223);
lcd.print("C");
Wethenprintthehumidityonthesecondline:
lcd.setCursor(1,1);
lcd.print("Humidity:");
lcd.print(humidity);
lcd.print("%");
Now,ifyouhaveathirdlineavailable,likeonthescreenIused,youcandirectlyprintthelightlevelaswellonthethirdline:
lcd.setCursor(1,2);
lcd.print("Light:");
lcd.print(light);
lcd.print("%");
Ifyoudon’thaveathirdlineavailableonyourLCDscreen,youhaveseveraloptions. Forexample,youcanjustintroducesomedelay,clearthescreenagain,andprintoutthelightlevelonthefirstline.
Wealsointroducea100msdelaybetweeneachsetofmeasurementsandrefreshoftheLCDscreen:
delay(100);
NotethatthecompletecodeforthischaptercanbefoundinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotesttheproject. UploadthecodeagaintoyourArduinoboardandwaitforsometime. YoushouldbeabletoseetheLCDprintingthewelcomemessagebeforemovingontodisplaythemeasurements. Hereisapictureoftheprojectinaction:
Ifitdoesn’twork,thereareseveralthingsthatyoucancheck. Thefirstonetocheckisthatthecodetotestthedifferentsensorsisworkingcorrectly. So,donothesitatetogobacktotheprevioussectionsifnecessary. Also,makesurethatyourLCDscreeniscorrectlywired. Finally,makesurethatyouareusingthecorrectLCDlibraryforthescreenyouareusing.
2.5 HowtoGoFurther
Inthischapter,webuiltasimplehomeautomationproject:anLCDweatherstationbasedonArduino. WeinterfacedseveralsensorswithArduinolikedigitalhumidityandtemperaturesensors. Then,wedisplayedthesedataonanLCDscreen,whichisalsocontrolledbytheArduinoboard.
Thereareseveralwaystousewhatyouhavelearnedinthischaptertobuildevenmoreexcitingprojects. YoucanconnectmoresensorstotheprojectsanddisplaytheirmeasurementsontheLCDscreen. Forexample,youcanconnectabarometricpressuresensortotheproject. YoucanalsokeepthesamesensorsandgraphicallydisplaytheirmeasureddataonanOLEDscreen.
Chapter3
BuildingaSmartLampInthisproject,wearegoingtobuildaverycommonhomeautomationsystem:asmartlamp. Andbysmart,Imeanalampthatautomaticallyswitchesonwhentheambientlightlevelislow,andswitchesoffagainwhenthelightlevelrises. Todoso,wewillusearelaymoduletocontrolthelamp,andaphotocelltomeasuretheambientlightlevel.SincewewillusetheArduinoplatformtodoso,wearegoingtointroducesomeextrafeatures.
First,wewilladdacurrentsensortotheproject,sowecanknowhowmuchcurrentandenergythelampisconsumingatagivenmoment. WewillalsoaddanLCDscreentotheproject,soyoucaninstantlycheckthestateoftherelay,theenergyconsumptionofthelamp,andthevalueoftheambientlightlevel. Asforthelampitself,wearesimplygoingtouseasimpledesklamp,however,theprinciplesofthisprojectshouldworkwithanylamp.
3.1 Hardware&SoftwareRequirements
Forthisproject,youwill,ofcourse,needanArduinoUnoorasimilarboard.
Fortherelaymodule,Iuseda5VrelaymodulefromPololu,whichnicelyintegratesarelayonaboard,alongwithalltherequiredcomponentstotheArduinoboard. HereisapictureoftherelaymoduleIused:
Tomeasurethecurrentflowingthroughthelamp,IusedaboardbasedontheAC712sensorfromITeadStudio. ThissensorisreallyeasytousewithArduino,asitreturnsavoltagethatisproportionaltothemeasuredcurrent. Withthecorrectformula,wewilltheninferthecurrentflowingthroughthelampfromthevoltagemeasuredbytheArduinoboard. Ofcourse,youcanuseotherboardsbasedonthesamesensor. Hereisapictureofthecurrent-measuringboardIusedforthisproject:
Forlightlevelsmeasurements,Iusedaphotocellwitha10KOhmresistor. Thiswillreturnasignalwhichisproportionaltotheincominglightlevel.
YouwillalsoneedanLCDscreentodisplaythestateoftherelay,thepowerconsumptionofthedevice,andthelightlevel. Iuseda4x20charactersLCDsothatIcandisplayuptofourlinesatthesametime. Youcan,ofcourse,useasmallerLCDscreen,butyouwillonlybeabletodisplaythestateoftherelayandthecurrentconsumptionatthesametime,forexample.
ThescreenIusedforthisprojectusesanI2CinterfacetocommunicatewiththeArduinoboard. IrecommendusingascreenwiththisinterfaceasthereareonlytwodatapinsneededtoconnecttotheArduinoboard.
Toconnectthelamptotheproject,Iusedastandardpairofpowerplugswithbarecablesattheend,withonefemalesocket(toplugthelampin)andonemalesocket(toplugitintothepowersocketinthewall). HereisapictureofthecablesIused:
Becarefulinworkingonthecablesasthisisahigh-voltageproject.
Finally,Iusedabreadboardandsomejumperwirestomakethedifferentelectricalconnections.
Hereisalistofallcomponentsusedinthisproject,alongwiththelinkswhereyoucanpurchasethemonline:
ArduinoUno(http://www.adafruit.com/product/50)Relaymodule(http://www.pololu.com/product/2480)Currentsensor(http://imall.iteadstudio.com/im120710011.html)Photocell(http://www.adafruit.com/product/161)10kOhmresistor(https://www.sparkfun.com/products/8374)LCDdisplay(http://www.robotshop.com/en/dfrobot-i2c-twi-lcd-module.html)Breadboard(http://www.adafruit.com/product/64)Jumperwires(http://www.adafruit.com/product/758)
Forthelampitself,Iusedastandarddesklamp(30W)forthisproject.*However,therelaymoduleIusedcansupportupto1200W,soyoucanpluginmorepowerfullampsordevicesifyouwish.
Onthesoftwareside,allyouneedistheArduinoIDE,andtheLiquidCrystallibraryfortheLCDscreen:
https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
Toinstallalibrary,simplyputthefolderinyour/libraries/folderofyourmainArduinofolder.
*Note:InUSAandCanadawhere110VACisused,standardwattageis60W.
3.2 HardwareConfiguration
Let’snowassemblethehardwareforthisproject. Wewilldosointwoparts. WewillfirstconnectthedifferentcomponentsliketherelaymoduletotheArduinoboard,andthenwewillconnectthelamptotheproject.
Thehardwareconnectionsforthefirstpartareactuallyquitesimple:wehavetoconnecttherelaymodule,thecurrentsensorandthephotocell. First,connecttheArduinoUno+5Vpintotheredrailonthebreadboard,andthegroundpintothebluerail.
Forthephotocell,placethecellinserieswiththe10kOhmresistoronthebreadboardfirst. Then,connecttheotherendofthephotocelltotheredrailonthebreadboard,andtheotherendoftheresistortothebluerail(ground). Finally,connectthecommonpinbetweenthephotocellandtheresistortotheArduinoUnoanalogpinA0.
Fortherelaymodule,therearethreepinsyouneedtoconnect:VCC,GNDandasignalpin,usuallydenotedasSIG.VCCneedstogototheArduino5Vpin,soconnectittotheredpowerrail. GNDgoestotheArduinogroundpin,soconnectittothebluepowerrail.Finally,connecttheSIGpintopinnumber8oftheArduinoboard.
Inasimilarway,connectthecurrentsensormodule. Ithasthreepins:VCC,GND,andOUT.Asfortherelay,VCCneedstogototheArduino5Vpin,soconnectittotheredpowerrail. GNDgoestotheArduinogroundpin,soconnectittothebluepowerrail.Then,connecttheOUTpintotheanalogpinA1oftheArduinoboard.
Now,wearegoingtoconnecttheLCDscreen. SinceweareusinganLCDwithanI2Cinterface,therewillonlybetwowirestoconnectforthesignal,andtwoforthepower.ConnecttheLCDpincalledVCCtotheredrailonthebreadboard,andtheGNDpintothebluerailonthebreadboard. Then,connecttheLCDpinSDAtotheArduinopinA4,andtheSCLpintoArduinopinA5.
Hereisapictureofthefullyassembledproject,withoutthelampconnectedyet:
Wearenowgoingtoconnectthelamptothehardwarewealreadyassembled. Basically,theideaistohavethemainpowersupply(comingfromthepowersocketinthewall)gototherelay,thentothecurrentsensor,andfinallytothelamp. Followthisschematictomaketherequiredconnections:
Asitimpliesdangerousvoltagelevels(110vor230vdependingonwhereyouareintheworld),youshouldtakesomeprecautionsatthispoint. Youcanfindthemintheintroductionofthisbook. Notethatyoucantestthisprojectwithouthavinganydeviceconnectedtotherelay&thecurrentsensor.
3.3 TestingtheRelay
Itisnowtimetotesttheproject. Asthemostimportantpartoftheprojectistherelaycontrollingthelamp,wearegoingtotestthere. Wearesimplygoingtoswitchtherelayonandoffcontinuouslyevery5secondsjusttocheckthattherelayisworkingandthattheconnectionswiththelampwerecorrectlymade. Hereisthecompletecodeforthispart:
//Simplesketchtotesttherelay
//Relaypin
constintrelay_pin=8;
voidsetup(){
pinMode(relay_pin,OUTPUT);
}
voidloop(){
//Activaterelay
digitalWrite(relay_pin,HIGH);
//Waitfor5seconds
delay(5000);
//Deactivaterelay
digitalWrite(relay_pin,LOW);
//Waitfor5seconds
delay(5000);
}
Itstartsbydeclaringonwhichpintherelayisconnectedto:
constintrelay_pin=8;
Inthesetup()functionofthesketch,wesetthispinasanoutput:
pinMode(relay_pin,OUTPUT);
Then,intheloop()functionofthesketch,wesetthispintoaHIGHstate,switchingontherelay:
digitalWrite(relay_pin,HIGH);
Waitfor5seconds:
delay(5000);
Wethenswitchtherelayoffagain:
digitalWrite(relay_pin,LOW);
Andwaitfor5secondsbeforerepeatingtheloop():
delay(5000);
NotethatthecompletecodeforthischaptercanbefoundonthecorrespondingfolderinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotestthesketch. Makesurethatthelampiscorrectlyconnectedtotheproject,andthatthemaleplugispluggedintothepowersocketinthewall. Then,uploadtheArduinosketchtotheboard. Youshouldseethatevery5seconds,therelayisswitching,turningthelamponandoff.
Besuretofixtherelayinapositionsuchthatitcannotbetouchedbyaccident.
3.4 PowerMeasurements&AutomaticLightingControl
Let’snowmovetothemainpartoftheproject:buildingtheArduinosketchforoursmartlamp. Webasicallyneedtocontinuouslymeasurethelightlevelandthecurrentconsumptionofthelamp,printthisdataontheLCDscreen,andchangethestateoftherelayaccordingly. Hereisthecompletecodeforthispart:
//Codeforthesmartlampproject
//Libraries
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
//Relaystate
constintrelay_pin=8;
booleanrelay_state=false;
//LCDdisplayinstance
LiquidCrystal_I2Clcd(0x27,20,4);
//Definemeasurementvariables
floatamplitude_current;
floateffective_value;
floateffective_voltage=230;//Setvoltageto230V(Europe)or110V(US)
floateffective_power;
floatzero_sensor;
voidsetup()
{
//Initializethelcd
lcd.init();
//PrintamessagetotheLCD.
lcd.backlight();
lcd.setCursor(1,0);
lcd.print("Hello!");
lcd.setCursor(1,1);
lcd.print("Initializing…");
//Setrelaypintooutput
pinMode(relay_pin,OUTPUT);
//Calibratesensorwithnullcurrent
zero_sensor=getSensorValue(A1);
//ClearLCD
delay(2000);
lcd.clear();
}
voidloop()
{
//Measurelightlevel
floatsensor_reading=analogRead(A0);
floatlight=(sensor_reading/1024*100);
//Performpowermeasurement
floatsensor_value=getSensorValue(A1);
//Converttocurrent
amplitude_current=(float)(sensor_value-zero_sensor)/1024*5/185*1000000;
effective_value=amplitude_current/1.414;
effective_power=abs(effective_value*effective_voltage/1000);
//Switchrelayaccordingly
//Ifthelightlevelismorethan75%,switchthelightsoff
if(light>75){
digitalWrite(relay_pin,LOW);
relay_state=false;
}
//Ifthelightlevelislessthan50%,switchthelightsoff
if(light<50){
digitalWrite(relay_pin,HIGH);
relay_state=true;
}
//UpdateLCDscreen
//Displayrelaystate
lcd.setCursor(1,0);
lcd.print("Relay:");
if(relay_state){lcd.print("On");}
else{lcd.print("Off");}
//Displayenergyconsumption
lcd.setCursor(1,1);
lcd.print("Power:");
lcd.print(effective_power);
lcd.print("W");
//Displaylightlevel
lcd.setCursor(1,2);
lcd.print("Light:");
lcd.print(light);
lcd.print("%");
//Wait500ms
delay(500);
}
//Getthereadingfromthecurrentsensor
floatgetSensorValue(intpin)
{
intsensorValue;
floatavgSensor=0;
intnb_measurements=100;
for(inti=0;i<nb_measurements;i++){
sensorValue=analogRead(pin);
avgSensor=avgSensor+float(sensorValue);
}
avgSensor=avgSensor/float(nb_measurements);
returnavgSensor;
}
ItstartsbyincludingthelibrariesrequiredfortheLCD:
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
WecancreatetheinstanceoftheLCDscreenatthispoint. Notethatyouwillhavetomodifythenumberoflinesdependingonyourscreen(4forthescreenIused):
LiquidCrystal_I2Clcd(0x27,20,4);
Weneedtodeclarethepinonwhichtherelayisconnectedto,andavariabletostorethestateoftherelay:
constintrelay_pin=8;
booleanrelay_state=false;
Then,wehavetocreatesomevariabletocalculatethevalueofthecurrentandpowerconsumedbythelamp. Here,ifyouareusing110Vinsteadof230V,youwillneedtochangetheeffective_voltagevariabletothecorrectvalue:
floatamplitude_current;
floateffective_value;
floateffective_voltage=230;//Setvoltageto230V(Europe)or110V(US)
floateffective_power;
floatzero_sensor;
Now,inthesetup()functionofthesketch,weinitializetheLCD:
lcd.init();
Wealsosetthepinoftherelayasanoutput:
pinMode(relay_pin,OUTPUT);
Now,weneedtocalibratethecurrentsensor. ThecurrentsensorIusedinthisprojectisananalogsensor–itreturnsavoltageproportionaltothemeasuredcurrent. However,weneedtoknowwhatisthevoltageatwhichthesensormeasuresanullcurrent. Astherelayisswitchedofffornow,wearesuretohavenocurrentflowingthroughthelamp. WegetthenullcurrentvalueofthesensorbycallingafunctioncalledgetSensorValue()onthepinA1:
zero_sensor=getSensorValue(A1);
Wewon’tseethedetailsofthisfunction,butitbasicallyaveragesthereadingontheanalogpinoverseveralmeasurementstohaveastablereadingasanoutput. Westoretheresultinavariablecalledzero_sensor.
Finally,toendthesetup()function,wewaitforsometimebeforeclearingtheLCDscreen:
delay(2000);
lcd.clear();
Now,intheloop()functionofthesketch,wefirstreaddatafromtheanalogpinA0,whichreturnsavaluefrom0to1023. TheresolutionoftheAnalog-To-DigitalconverteroftheArduinoUnoboardis10bits,sowehave1024values. Then,wedividethisreadingby1024andmultiplyitby100tohavethelightlevelasapercentage:
floatsensor_reading=analogRead(A0);
floatlight=sensor_reading/1024*100;
Next,wegetthereadingfromthecurrentsensorusingthesamefunctionweusedbefore
(thataveragesthereadingsoverseveralsamples):
floatsensor_value=getSensorValue(A1);
Fromthisvalue,weneedtocalculatethecurrent,andthenthepower. First,wecalculatethecurrentusingthecalibrationdataweacquiredbefore,andaformulagiveninthedatasheetofthesensor. Then,weconvertthiscurrenttoitseffectivevaluebydividingitbythesquarerootof2. Finally,wecalculatetheeffectivepowerbymultiplyingtheeffectivevalueofthecurrentwiththeeffectivevalueofthevoltage(andwealsodivideitby1000togettheresultinWatts):
amplitude_current=(float)(sensor_value-zero_sensor)/1024*5/185*1000000;
effective_value=amplitude_current/1.414;
effective_power=abs(effective_value*effective_voltage/1000);
Afterthat,wemakeadecisiononwhethertoswitchtherelayonornot. Ifthelightlevelismorethan75%,weswitchthelampoff,asthismeansitisbrightandwedon’tneedlights:
if(light>75){
digitalWrite(relay_pin,LOW);
relay_state=false;
}
Ifthelightlevelislessthan50%,weswitchthelighton:
if(light<50){
digitalWrite(relay_pin,HIGH);
relay_state=true;
}
Ofcourse,youshoulduseyourownvaluesforthetwothresholds. Forexample,youcanmeasurethelightlevelsatnightwhentheroomisinanalmostcompletedarknesswithlightonlycomingfromyourlampandduringthedaywithsunlightseepingintoyourroom. Usingthesevalues,youcanmodifythetwothresholdsaccordingly.
Notethatitisnecessarytousetwothresholdshere. Rememberthatthereadingfromthephotocellcanoscillateabitovertime. Andyoudon’twantyourlamptocontinuouslyswitchonandoffifthereadingfromthephotocellisaroundthethreshold.
Finally,weprintdataontheLCDscreen. Wefirstprintthestateoftherelay:
lcd.setCursor(1,0);
lcd.print("Relay:");
if(relay_state){lcd.print("On");}
else{lcd.print("Off");}
Then,weprinttheeffectivepowerthatwecalculatedfromthecurrentsensorreading:
lcd.setCursor(1,1);
lcd.print("Power:");
lcd.print(effective_power);
lcd.print("W");
Afterthat,weprintthevalueoftheambientlightlevel:
lcd.setCursor(1,2);
lcd.print("Light:");
lcd.print(light);
lcd.print("%");
Wealsowait500msbetweeneachmeasurement:
delay(500);
NotethatthecompletecodeforthischaptercanbefoundonthecorrespondingfolderinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
Itisnowtimetotestoursmartlamp. MakesurethatalltheconnectionsarecorrectlymadeandthenecessarycodeshavebeenuploadedtotheArduinoboard. Let’sassumeitiscurrentlybrightinyourhome:therelayshouldthereforebeswitchedoff. ThisiswhattheLCDscreenshouldbedisplayingaspicturedfrommyownproject:
Youcanseethatevenifthelightisoff,theArduinoboardmeasuressomepowerconsumedbythelamp. ThisisbecausetheACS712currentsensoroutputcanpickupnoiseduetoseveralfactorslikemagneticfields.
Now,tosimulateadarkroom,Isimplyputapieceoftissueontopofthephotocell.Instantly,themeasuredlightleveldropped,andthelampswitchedon:
Alsonotethatthemeasuredpowerwasaround25W,whichmakessenseasthelampisratedat30W.
Incaseyourprojectisnotworkingatthispoint,thereareseveralthingsyoucancheck.First,makesurethattherelay,theLCDscreenandthesensorsarecorrectlyconnectedtoyourArduinoboard. AlsomakesuretomodifythecodeaccordinglyifyouareusingasmallerLCDscreenthantheoneIusedonthisproject.
3.5 HowtoGoFurther
Let’ssummarizewhatwelearnedinthisproject. WebuiltasmartlampusingArduinoandsomebasiccomponents. Thelampisnowautomaticallyswitchingonoroffaccordinglytotheambientlightlevel. Wealsoaddedatwisttotheprojectbyaddingacurrentmeasurementdevice,whichtellsushowmuchpowerthelampisconsumingwhenitison. WealsoaddedanLCDscreenwhichdisplaysthestateofthelamp,thepowerconsumptionandtheambientlightlevel.
Youcanimprovethisprojectbyusingmoresensors. Forexample,youcancombineitwiththeprojectinthepreviouschapterandhavemoresensormeasurementsdisplayedontheLCDscreen. Youcanalsoaddmorecontrolstothelamptomakeitevensmarter. Forexample,youcanaddamotionsensortothemixtoswitchthelightonwhenthelightlevelisloworwhensomemotionisdetectedintheroom
Chapter4
XBeeMotionSensorsInthepreviouschaptersofthisbook,webuilt“self-contained”homeautomationsystems,whichcouldworkcompletelyautonomously,withoutcommunicatingwiththeexternalworld. However,that’snothowmostcommercialhomeautomationsystemswork.Usually,thecomponentsinthesesystemscommunicatewitheachotherwirelessly. Andthat’sexactlywhatwearegoingtodointheremainingchaptersofthisbook.
TostartwithwirelesshomeautomationsystemsbasedonArduino,wearegoingtouseatechnologythatiswidelyusedinhomeautomationsystems:XBee. XBeeisatechnologybuiltontheZigBeestandard,whichdefineslow-power,digitalradiocommunicationsbasedontheIEEE802.15standard. Itwasmadeforsystemsthatrequiresmalldatatransfer(likesensors),runningonbatteries,andthathavetobesecure. Needlesstosay,it’stheperfecttechnologyforhomeautomationsystems.
Inthisproject,wearegoingtotakeanewlookataprojectwehavealreadybuilt:thesimplealarmbasedonArduinoandaPIRmotionsensor. WearegoingtotakethesamesensorandArduino,andaddanXBeemoduletoit. Wearealsogoingtobuildaninterfaceonyourcomputer,soyoucanmonitorthestateofmanyoftheseXBeemotionsensorsfromyourwebbrowser.
4.1 Hardware&SoftwareRequirements
Let’sfirstseewhatweneedforthisproject. Therearetwodistinctthingsthatwewillhavetobuildinthisproject. Ononeside,wewillhavetheXBeemotionsensors,andtheotherside,wewillhaveoneXBeemodulethatwillbeconnectedtoyourcomputerviaUSB.
ForoneXBeemotionsensor,youwillfirstneedanArduinoboard. IusedagainanArduinoUnoboardforthisproject.
Then,youneedamotionsensor. Forthisproject,IusedthesamePIRmotionsensorthatwealreadyusedinthefirstprojectofthisbook.
Next,youneedtointerfacetheXBeemodulewiththeArduinoboard. ToconnecttheXBeemoduletoArduino,IusedaSparkFunXBeeshieldforArduino. ItintegratesasocketforanyXBeemodule,andalsoaswitchtoconnectanddisconnecttheXBeemodulefromtheArduinomicrocontrollerSerialport. We’llseelaterinthischapterthatitisveryuseful.
FortheXBeemodules,IusedSeries2XBeemodules,withawireantenna. Series1aremucheasiertouse,butSeries2addthepossibilitytocreatemeshednetworks,andtotargetagivenmodule,whichissomethingwewilluseinthischapter.
HereisapictureoftheArduinoUnoboardwiththeXBeeshieldonit,withoneXBeemodulealreadypluggedin:
HereisalistofallcomponentsforoneXBeemotionsensor,alongwiththelinkswhereyoucouldpurchasethemonline:
ArduinoUno(http://www.adafruit.com/product/50)PIRmotionsensor(https://www.adafruit.com/products/189)ArduinoXBeeshield(https://www.sparkfun.com/products/10854)XBeeSeries2modulewithwireantenna(https://www.sparkfun.com/products/11215)Jumperwires(http://www.adafruit.com/product/758)
Now,weneedtogetyourcomputersomeXBeeconnectivity. Indeed,unlikeBluetoothorWiFi,computersdon’tcomewithbuilt-inXBeeconnectivity.
ToconnectanXBeemoduletomycomputer,IchoseaUSBexplorermodulefromSparkfun. YoucanmountanyXBeemoduleonit,andyoucanconnectitviaUSBtoyourcomputer. ItbehaveslikeaSerialport,whichmeansyoucansendmessagestoitviatheArduinoIDEserialmonitor.
FortheXBeemodule,IchosethesamemoduleasfortheXBeemotionsensors.
HereisapictureoftheXBeeexplorerboardwiththeXBeemodulemountedonit:
TouseXBeeonyourcomputer,youwillneedthesecomponents:
USBXBeeexplorerboard(https://www.sparkfun.com/products/11812)XBeeSeries2modulewithwireantenna(https://www.sparkfun.com/products/11215)
Onthesoftwareside,youneedtohavethelatestversionoftheArduinoIDEinstalledonyourcomputer,aswellastheaRESTlibraryforArduinowhichyoucanfindonthefollowinglink:
https://github.com/marcoschwartz/aREST
Toinstallagivenlibrary,simplyextractthefolderinyourArduino/librariesfolder(orcreatethisfolderifitdoesn’texistyet).
4.2 BuildinganXBeeMotionSensor
WearenowgoingtoseehowtobuildoneXBeemotionsensor. Ifyouwanttousemanyofthemforthisproject,justrepeatthefollowingstepsforeachmodule.
Theconfigurationofthisprojectisactuallyverysimple. First,plugtheXBeeshieldontheArduinoboard,andplugoneXBeemoduleontheshield. ForthePIRmotionsensor,connecttheGNDpintotheArduinoground,VCCtotheArduino5Vpin,andSIGpintotheArduinopin8. Youshouldendupwithsomethingsimilartothefollowingpicture:
YouwillalsoneedtoputtheswitchontheXBeeshieldtothecorrectposition. Atthispoint,wewanttoprogramtheArduinoboardtosettheswitchsuchthattheXBeemoduleisnotconnectedtotheSerialportoftheArduinomicrocontroller. Todoso,puttheswitchon“DLINE”:
Finally,alsoconnecttheXBeeexplorerboardwiththeXBeemoduleonittoyourcomputer.
4.3 TestingtheMotionSensor
Wearenowgoingtotestthemotionsensor. WewillwriteasimplesketchthatcontinuouslyprintsthestatusofthemotionsensortotheSerialportoftheArduino. Fornow,leavetheswitchoftheXBeeshieldto“DLINE”. Hereisthecompletesketchforthispart:
//Simplemotionsensor
intsensor_pin=8;
voidsetup(){
Serial.begin(9600);
}
voidloop(){
//Readsensordata
intsensor_state=digitalRead(sensor_pin);
//Printdata
Serial.print("Motionsensorstate:");
Serial.println(sensor_state);
delay(100);
}
ThesketchstartsbydeclaringwhichpinthePIRmotionsensorisconnectedto:
intsensor_pin=8;
Inthesetup()functionofthesketch,westarttheSerialport:
Serial.begin(9600);
Intheloop()functionofthesketch,wereadthePIRmotionsensorpin:
intsensor_state=digitalRead(sensor_pin);
Finally,weprintthestateofthatpinevery100msontheSerialport:
Serial.print("Motionsensorstate:");
Serial.println(sensor_state);
delay(100);
NotethatthecompletecodeforthissectioncanbefoundinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotestthisfirstsketchofthischapter. UploadthesketchtotheArduinoboard,andopentheSerialmonitor(makingsurethattheSerialspeedissetto9600). Youcanpassyourhandinfrontofthesensor,andyoushouldseethatthestateofsensor
changes:
Motionsensorstate:0
Motionsensorstate:0
Motionsensorstate:0
Motionsensorstate:0
Motionsensorstate:1
Motionsensorstate:1
Motionsensorstate:1
Motionsensorstate:1
Motionsensorstate:0
Motionsensorstate:0
Motionsensorstate:0
Ifitisnotworkingatthispoint,thereareseveralthingsyoucancheck. First,makesurethatyouhavecorrectlypluggedthemotionsensorintotheArduinoboardasdefinedearlierinthechapter. Then,makesurethatyouhavecorrectlyuploadedthelatestversionofthecode.
4.4 UsingtheXBeeModule
Inthissection,wearegoingtousetheXBeemodulethatissittingontheXBeeshieldtoaccessthemotionsensorwirelessly. WearegoingtowriteasimpleArduinosketchwhichmakesuseoftheaRESTlibrarytoreceiveandhandlerequestscomingfromtheoutside.
ButthefirstthingwehavetodoistoconfigureourXBeeradios. Bydefault,allXBeemodulesareconfiguredtousethesamecommunicationchannelcalledthePAN(PersonalAreaNetwork)ID.Thisisgoodtotestthemoutofthebox,butthisisnotgoodatallwhenyouactuallywanttousetheminyourhome. IfyouleavethemonthedefaultPANID,theywillbroadcastmessagesonalldeviceswiththesamePANID,includingthoseofyourneighbors! Worse,somebodycouldactuallyhackintoyourXBeesensorsfromtheoutside.
Wealsoneedtosetourradioscorrectlybygivingthemroles. InaSeries2XBeenetwork,oneoftheradiosshouldbethe‘coordinator’ofthenetwork. Withoutone,itwillsimplynotworkatall. Theotherradioscanbeeither‘routers’thatcanrelaymessages,or‘EndDevices’thatsimplygetmessagesfromthenetwork. Becausewehaveasimplenetworkhere,wewillsimplyconfiguretheXBeeradioconnectedtoourcomputertobeacoordinator,andtheothertobeenddevices.
Therefore,weneedtochangealltheseparameters. ThisisactuallyeasytodousingtheofficialsoftwaretoconfigureXBeemodulescalledXCTU.Youcandownloaditatthefollowingaddress:
http://www.digi.com/support/productdetail?pid=3352&type=utilities
Onceitisinstalled,openthesoftware,andconnecttheXBeemoduleyouwanttoconfiguretotheXBeeexplorermodulewhichisconnectedviaUSBtoyourcomputer. BylookingattheSerialportoftheexplorermodule,youcanaccessthesettingsofthisXBeemodule.
First,lookfor“PANID”inthe“RadioConfiguration”window:
Fromthismenu,youcansetthePANIDfortheXBeemodulethatiscurrentlypluggedinsidetheXBeeexplorerboard. SimplyrepeattheoperationforeveryXBeemoduleyouwanttoconfigure.
Now,wewillgiverolestoourXBees. PlugthemodulewhichwillbethecoordinatorintotheXBeeexplorer. Addthedeviceusingtheleftmenuagain,andthenclickontheupdatefirmwarebuttononthetopmenubar(theonewithalittlearrowgoingintothechip).
Fromthere,youwillbeabletoselectthefirmwarewewantforourcoordinatorXBee. Wehavetoselect‘XB24-ZB’ontheleft,andthen‘ZigBeeCoordinatorAPI’fromthelist.Selectthelatestfirmwareversion,andconfirmourchoice:
Afterawhile,youwillseethatyourdeviceisnowconfiguredasanXBeecoordinatorin
APImode:
StillforthisXBeedevice,weneedtogodownthelistofparameters,andchoose‘2’intheAPIEnableparameter,andwritetheparameterintotheXBeeradiowiththerightbutton:
Finally,weneedtoconfiguretheotherXBeeradiosasendpoints. Foreachofthem,connectthemtotheXBeeexplorer,clickonthebuttontowritethefirmwareagain,select‘XB24-ZB’ontheleft,andselect‘ZigBeeEndDeviceAT’fromthelist. Confirm,andthisiswhatyoushouldget:
WearenowgoingtobuildthisArduinosketchontopofthetestsketch,soIwillonlydefinethecodeadditionshere. Hereisthecompletesketchforthispart:
//Libraries
#include<SPI.h>
#include<aREST.h>
//MotionsensorID
char*xbee_id="2";
//CreateArduRESTinstance
aRESTrest=aREST();
voidsetup(){
//StartSerial
Serial.begin(9600);
//GivenameandIDtodevice
rest.set_id(xbee_id);
rest.set_name("motion2");
}
voidloop(){
//HandleRESTcalls
rest.handle(Serial);
}
Thissketchstartsbyincludingthecorrectlibrariesforthesketch:
#include<aREST.h>
WealsodefinetheIDofthesensor. Thisisreallyusefulifyouhavemanymotionsensorsinyourhome. MakesuretogivethemdifferentIDs:
Stringxbee_id="1";
WealsoneedtocreateaninstanceoftheaRESTlibrary:
aRESTrest=aREST();
Inthesetup()functionofthesketch,westarttheSerialport. Notethatitisreallyimportanttouseaspeedof9600hereasitisthedefaultspeedofXBeemodules:
Serial.begin(9600);
WealsosettheIDofthedevicethatwedefinedbefore:
rest.set_id(xbee_id);
Finally,intheloop()functionofthesketch,wesimplyhandletherequestscomingfromtheSerialportusingtheaRESTlibrary:
rest.handle(Serial);
NotethatthecompletecodeforthissectioncanbefoundinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotestthissketch. UploadthesketchtotheArduinoboard. Then,puttheswitchoftheXBeeshieldto“UART”sothattheXBeemodulecandirectlycommunicate
withtheArduinomicrocontrollerviatheSerialport. NotethatifyouneedtoprogramtheArduinoboardagain,youneedtoswitchitbackto“DLINE”.
YoushouldalsomakesurethattheXBeeexplorermoduleispluggedinyoursystem. IfyouarerunningunderWindowsorOSX,youmightneedadditionaldriverstoinstallforthisUSBboard. Youcanfindallthedownloadandinstallationdetailshere:
http://www.ftdichip.com/FTDrivers.htm
Now,youneedtolocatetheSerialportcorrespondingtotheXBeeexplorerboardconnectedtoyourcomputer. YoucandosobylookingattheTools>SerialPortmenuoftheArduinoIDE.Forexample,mineiscalled“/dev/cu.usbserial-A702LF8B”. OnWindows,itwilllooklike‘COM3’. Alsowriteitdownforyouwillneeditlaterwhenbuildingtheinterfaceforyourmotionsensors.
OpentheSerialmonitoroftheArduinoIDE.Makesurethatthespeedissetto9600,andthattheendlinecharacterissetto‘Carriagereturn’. NotethatbecausewearenowconnectedtotheXBeeexplorerboard,allcommandsthatyouaresendingnowarebeingsenttoallXBeemodulesinyourhome.
IntheSerialmonitor,type:
/id
ThiswillsimplyquerytheIDoftheallXBeeboardsthatareinyourhome. WhenItestedmyproject,Ionlyhadoneinmyhome. Itrespondedwith:
{"id":"1","name":"","connected":true}
Afterthisstep,wearegoingtoreadthestatusofthemotionsensor. Remember,itisconnectedtopinnumber8. Toreadfromthispin,simplytype:
/digital/8
Thesensorshouldanswerwiththefollowingmessage:
{"return_value":1,"id":"1","name":"","connected":true}
Ifthesensorsareansweringtothequeriesatthispoint,itmeansthattheyareworkingcorrectlyandthatyoucanaccessthemwirelessly.
Incaseitisnotworkingatthispoint,thereareseveralthingsyoucancheck. First,makesurethatyouhaveuploadedthelatestversionofthecode. YoucanfinditinsidetheGitHubrepositoryofthebook. Also,makesurethattheXBeeexplorerboardiscorrectly
pluggedintoyourcomputerbycheckingthattheproperdriversareinstalled. Finally,makesurethattheXBeeshieldissettothe‘UART’position.
4.5 BuildingtheCentralInterface
Wearenowgoingtobuildtheinterfacethatyouwillusetomonitorthemotionsensorsfromyourcomputer. Usingthisinterface,youwillbeabletoseethestateofeachsensorviaXBee,rightinyourwebbrowser.
TheinterfacethatwearegoingtodevelopisbasedonNode.js,whichallowsthecodingofserver-sideapplicationsinJavaScript. First,wearegoingtocodethemainfilecalledapp.js,whichwewillrunlaterusingthenodecommandinaterminal. Hereisthecompletecodeforthisfile:
//Modules
varexpress=require('express');
varapp=express();
//Defineport
varport=3000;
//Viewengine
app.set('viewengine','jade');
//Setpublicfolder
app.use(express.static(__dirname+'/public'));
//Rest
varrest=require("arest")(app);
rest.addDevice('xbee','/dev/tty.usbserial-A702LF8B');
//Serveinterface
app.get('/',function(req,res){
vardevices=rest.getDevices();
res.render('interface',{devices:devices});
});
//Startserver
app.listen(port);
console.log("Listeningonport"+port);
Itstartsbyimportingtheexpressmodule:
varexpress=require('express');
Then,wecreateourappbasedontheexpressframework,andthesettheportto3000:
varapp=express();
varport=3000;
Wealsoneedtotelloursoftwarewheretolookforthegraphicalinterfacethatwearegoingtocodelater. WealsosetthedefaultviewenginetoJade,whichaswewillseeisasimplifiedwaytocodeinHTML:
app.set('viewengine','jade');
app.use(express.static(__dirname+'/public'));
Atthispoint,wealsoimportthenode-aRESTmodule,thatwillhandleallthecommunicationbetweentheinterfaceandthemodule. Here,wealsoneedtodefinetheSerialportonwhichtheXBeeexplorermoduleisconnectedto:
varrest=require("arest")(app);
rest.addDevice('xbee','/dev/tty.usbserial-A702LF8B');
ThiswillautomaticallylookforallXBeemodulesinthesamenetworkasourcoordinatorradio,andaddthemautomaticallytotheserversowecanaccessthemfromtheinterface.
Now,wearegoingtobuildthemainrouteofourserver. WedefinethisroutebylinkingtherootURLofourservertothecorrespondingJadefile. Becausewewanttobuildtheinterfaceautomaticallydependingonhowmanydevicesarepresent,weneedtogetallthedevicesfirst,andthentransmitthisdatatotheJadefilesoitcanberenderedcorrectly:
app.get('/',function(req,res){
vardevices=rest.getDevices();
res.render('interface',{devices:devices});
});
Finally,stillinthisapp.jsfile,westarttheappwiththeportwedefinedbefore,andwriteamessageintheconsole:
app.listen(port);
console.log("Listeningonport"+port);
Thiswasforthemainserverfile. Now,wearegoingtobuildtheinterfaceitself. Let’sseethecontentofthisJadefilefirst. Thisfileislocatedinthe/viewsfolderofourproject.Hereisthecompletecodeforthisfile:
doctype
html
head
titleXBeemotionsensors
link(rel='stylesheet',
href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css')
script(src="https://code.jquery.com/jquery-2.1.1.js")
script(src="/js/interface.js")
body
.container
.row
h1XBeemotionsensors
if(devices!='[]')
eachdeviceindevices
if(device.type=='xbee')
.row
.col-md-4
h3Sensor#{device.id}
.col-md-4
h3.display(id=device.id)
JadeisbasicallyatemplatelanguagethatallowstowriteHTMLwithlesscodethanHTMLitself,andalsotoinsertsomecoderightintotheinterfacefile,togenerateHTML
dependingonsomevariables.
ThefilestartsbyimportingthedifferentJavaScriptfileswhichwillhandletheclickontheinterface,andsendthecorrectcommandstotheArduinoboard:
script(src="https://code.jquery.com/jquery-2.1.1.js")
script(src="/js/interface.js")
WewillalsousetheTwitterBootstrapCSSframeworktogiveourinterfaceabetterlook:
link(rel='stylesheet',
href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css')
Themainpartoftheinterfaceconsistsingoingthroughthelistofallsensorsthatweredetectedbefore,andbuildarowforeachsensor. Thisisdonebythefollowingpieceofcode:
if(devices!='[]')
eachdeviceindevices
if(device.type=='xbee')
.row
.col-md-4
h3Sensor#{device.id}
.col-md-4
h3.display(id=device.id)
Next,wearegoingtohavealookatthecodeinsidetheinterface.jsfile,whichdefineshowtheinterfaceoftheprojectisworking. ItwillmakethequeriestotheboardviatheNode.jsserver,andupdatetheinterfaceaccordingly. Thisfileislocatedinthepublic/jsfolderoftheinterface. Hereisthecompletecodeforthisfile:
$(document).ready(function(){
$.get('/devices',function(devices){
//Setinputs
for(i=0;i<devices.length;i++){
//Getdevice
vardevice=devices[i];
//Setinput
$.get('/'+device.name+'/mode/8/i');
}
setInterval(function(){
for(i=0;i<devices.length;i++){
//Getdevice
vardevice=devices[i];
//Getdata
$.get('/'+device.name+'/digital/8',function(json_data){
//Updatedisplay
if(json_data.return_value==0){
$("#"+json_data.id).html("Nomotion");
$("#"+json_data.id).css("color","red");
}
else{
$("#"+json_data.id).html("Motiondetected");
$("#"+json_data.id).css("color","green");
}
});
}
},2000);
});
});
ThemainpartofthisJavaScriptfileisprogrammedtocontinuouslycheckthestatesofthesensorsbysendingthemqueries. ThisisdoneinsideasetInterval()function:
setInterval(function(){
Insidethisfunction,wegothroughalldevices,andsendthemacommandtoreadthepinonwhichthemotionsensorsareconnectedto:
$.get('/'+device.name+'/digital/8',function(json_data){
TheaRESTlibraryalwaysreturndatainaJSONcontainer,soitisreallyeasytoaccessthisdatawithinJavaScript. Weneedtoknowthestateofthatmotionsensor. Thisisstoredinthereturn_valuefield. Ifthedatainthisfieldisequalto0,wesettheindicatorofthissensorto‘Nomotion’inred. Otherwise,wesetittogreenwiththe‘Motiondetected’message,meaningmotionwasdetectedbythissensor:
if(json_data.return_value==0){
$("#"+json_data.id).html("Nomotion");
$("#"+json_data.id).css("color","red");
}
else{
$("#"+json_data.id).html("Motiondetected");
$("#"+json_data.id).css("color","green");
}
Afterthat,weclosethesetInterval()function,repeatingtheloopeverytwoseconds:
},2000);
NotethatthecompletecodeforthissectioncanbefoundinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotesttheinterface. MakesurethatyoudownloadallthefilesfromtheGitHubrepository,andupdatethecodewithyourowndataifnecessary,liketheSerialportcorrespondingtoyourXBeeexplorerboard. Also,makesurethattheArduinoboardisprogrammedwiththecodewesawearlierinthischapter.
Gotothefolderoftheinterfacewithaterminalandtypethefollowingcommandtoinstallthenode-aREST,jade&expressmodules:
sudonpminstallarestexpressjade
NotethatifyouareunderWindows,youhavetoleaveoutthesudoinfrontofthecommands. ItisalsorecommendedtousetheNode.jscommandprompt. Finally,youcanstarttheNode.jsserverbytyping:
sudonodeapp.js
Youshouldbegreetedwiththefollowingmessageintheterminal:
Listeningonport3000
YoushouldalsoseeintheterminalthatyourXBeeradiosareautomaticallydiscoveredandaddedtothesystem. Youcannowgototheyourwebbrowserandtype:
localhost:3000
Youshouldseetheinterfaceofourprojectbeingdisplayed:
Totestthisproject,Iusedtwomotionsensors. Toillustratethebehaviorofonemodule,IsimplypassedmyhandinfrontofthesensorwithIDnumber1. Thecorrespondingindicatorimmediatelyturnedtogreen. Ofcourse,ifyouhavemoresensors,theinterfacewillautomaticallybemodified.
Ifitisnotworkingatthispoint,thereareseveralthingsyoucancheck. First,makesurethatyouhavedownloadedthelatestversionofthecodefromtheGitHubrepositoryofthebook. Also,makesurethatyouhavecorrectlymodifiedthefilestouseyourownsettings,liketheSerialportforyourXBeeexplorermodule. Finally,makesureyouhaveinstalledtherequiredNodemoduleswithnpmbeforestartingthewebinterface.
4.6 HowtoGoFurther
Let’ssummarizewhatwelearnedinthisproject. WetooktheprojectwealreadybuiltinChapter1andaddedwirelesscapabilitiestoitusingXBee. WelearnedhowtointerfaceXBeemoduleswithArduino,andbuildXBeemotionsensorswithit. Wewereabletomonitorthestateofseveralwirelessmotionsensorsfromyourwebbrowser.
Thereareofcoursemanywaystogofurtherwiththisproject. Theeasiestthingistoaddmoremotionsensorstotheprojecttocoverallyourhome. Youcanalsoadddifferentkindsofdigitalsensorstotheproject. Forexample,youcanusethesamecodetomonitorthestateofcontactsensorswhichyoucanputondoorsandwindows.
YoucanalsousethesameprinciplesseeninthischaptertomonitorotherdatausingXBee,likemeasurementscomingfromtemperaturesensors.
Chapter5
BluetoothWeatherStationInthischapter,wearegoingtogivewirelesscapabilitiestotheprojectwealreadysawinChapter2. WearegoingtobuildawirelessweathermeasurementstationusingBluetooth.
Thestationwillmeasuretemperature,humidityandlightlevelintheroomwheretheprojectislocated,anddisplaythisdataonanLCDscreen. However,inthisnewprojectwewilladdaBluetoothmoduletotheprojecttobeabletomonitorthemeasureddatafromanywhereinyourhome. Wearegoingtobuildaninterfaceonyourcomputersoyoucancheckthemeasurementsdonebythestationinsideyourwebbrowser.
5.1 Hardware&SoftwareRequirements
Forthisproject,youwillofcourseneedanArduinoUnoboard. YoucanalsouseotherArduinoboardslikeanArduinoMegaorLeonardo,itwillworkjustfineaswell.
Fortemperatureandhumiditymeasurements,youwillalsoneedaDHT11sensor,alongwitha4.7Kresistor. YoucanalsouseaDHT22sensorwhichismoreprecise,youwillonlyhaveonelineofcodetochange.
Forlightlevelsmeasurements,Iusedaphotocellwitha10KOhmresistor. Thiswillreturnasignalwhichisproportionaltotheincominglightlevel.
YouwillalsoneedaLCDscreentodisplaythemeasurements. Iuseda4x20charactersLCDsoIcandisplayuptofourdifferentmeasurementsatthesametime. YoucanofcourseuseasmallerLCDscreen,butyouwillonlybeabletodisplaythetemperature&humidityatthesametime,forexample.
ThescreenIusedforthisprojectisalsousinganI2CinterfacetocommunicatewiththeArduinoboard. Ireallyrecommendusingascreenwhichsuchaninterface,asthereareonlytwodatapinstoconnecttotheArduinoboardinordertousetheLCD.
FortheBluetoothmodule,IusedaBluetooth2.1modulefromAdafruit. ThismoduleinterfacesdirectlywiththeSerialportoftheArduinoboard,whichmakesitveryconvenient. Youcanbasicallyuseanymodule(includeBluetooth4.0modules)thatcaninterfacedirectlywiththeSerialportoftheArduinomicrocontroller. ModulesthatrequiretheirownlibrariesforArduino(forexamplebasedonthenRF8001chip)won’tworkoutoftheboxforthisproject. ThisisapictureofthemoduleIused:
Finally,Iusedabreadboardandsomemale-malejumperwirestomakethedifferentelectricalconnections.
Thisisalistofallcomponentsusedinthisproject,alongwithlinkstopurchasethemonline:
ArduinoUno(http://www.adafruit.com/product/50)DHT11sensor(http://www.adafruit.com/product/386)Photocell(http://www.adafruit.com/product/161)10kOhmresistor(https://www.sparkfun.com/products/8374)LCDdisplay(http://www.robotshop.com/en/dfrobot-i2c-twi-lcd-module.html)AdafruitEZ-LinkBluetoothmodule(https://www.adafruit.com/products/1588)Breadboard(http://www.adafruit.com/product/64)Jumperwires(http://www.adafruit.com/product/758)
YouwillneedtheaRESTlibraryforArduinowhichyoucanfindonthefollowinglink:
https://github.com/marcoschwartz/aREST
YouwillalsoneedthelibraryfortheDHTsensor:
https://github.com/adafruit/DHT-sensor-library
AndtheLiquidCrystallibraryfortheLCDscreen:
https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
Toinstallalibrary,simplyputthefolderinyour/libraries/folderofyoumainArduinofolder.
5.2 BuildingtheBluetoothWeatherStation
Thehardwareconnectionsforthisprojectareactuallyquitesimple:wehavetoconnecttheDHT11sensor,thepartresponsibleforthelightlevelmeasurementwiththephotocell,theLCDscreen,andfinallytheBluetoothmodule.
Tohelpyouout,thefollowingpicturesummarizesthehardwareconnections,withouttheLCDscreenshown:
ThisimagewascreatedwithFritzing(http://fritzing.org/).
First,connecttheArduinoUno+5Vpintotheredrailonthebreadboard,andthegroundpintothebluerail.
ToknowwhichpintoconnectfortheDHT11sensor,thispicturecanhelpyouout:
Then,connectpinnumber1oftheDHT11sensor(VCC)totheredrailonthebreadboard,andpinnumber4(GND)thebluerail. Alsoconnectpinnumber2ofthesensortopinnumber7oftheArduinoboard. TofinishupwiththeDHT11sensor,connectthe4.7kOhmbetweenpinnumber1and2ofthesensor.
Forthephotocell,firstplacethecellinserieswiththe10kOhmresistoronthebreadboard. Then,connecttheotherendofthephotocelltotheredrailonthebreadboard,andtheotherendoftheresistortotheground. Finally,connectthecommonpinoftheresistor&thephotocelltotheArduinoUnoanalogpinA0.
Now,wearegoingtoconnecttheLCDscreen. AsweareusingaLCDwithanI2Cinterface,therewillonlybetwowirestoconnectforthesignal,andtwoforthepower.ConnecttheLCDpincalledVCCtotheredrailonthebreadboard,andtheGNDpintothebluerailonthebreadboard. Then,connecttheLCDpinSDAtotheArduinopinA4,andtheSCLpintoArduinopinA5.
TheBluetoothmoduleisalsoquiteeasytoconnect. First,thepowersupply. ConnecttheVinpin(orVCC,dependingonyourmodule)totheredpowerrail,andtheGNDpintothebluepowerrail. Then,wehavetoconnecttheSerialportoftheBluetoothmoduleto
theArduinoboard. ConnecttheRXpinofthemoduletotheTXpin(pinnumber1)oftheArduinoboard,andtheTXpinofthemoduletotheRXpin(pinnumber0)oftheArduinoboard.
Thisisapictureofthefullyassembledprojectsoyoucanhaveanideaonhowthecompleteprojectlookslike:
ThispictureisacloserlookattheBluetoothmoduleonthebreadboard:
5.3 PairingtheBluetoothModule
Beforeweproceedfurther,wearegoingtotestourassembledhardware. WealreadymadethetestofthedifferentsensorsinChapter2,soyoucanrefertothischaptertotestthesensorsoftheproject. Here,wearesimplygoingtocheckifwecanaccesstheBluetoothmodule.
Simplypoweruptheproject,forexamplebyconnectingaUSBcablebetweentheArduinoboardandyourcomputer. Then,gotheBluetoothpreferencesofyourcomputer,andyoushouldseetheBluetoothmoduleappearinginthelistofnearbyBluetoothdevices:
Clickon“Pair”topairtheBluetoothmodulewithyourcomputer. Then,goovertoyourArduinoIDE.OpentheTools>SerialPortlist. YoushouldseethatanewSerialportisavailable,containing“AdafruitEZ”inthenameoftheSerialport(orthenameoftheBluetoothmodulethatyouareusing):
Ifthisisnotthecase,simplycloseandre-opentheArduinoIDE.IftheBluetoothmoduleiscorrectlypairedwithyourcomputer,thereisnoreasonforitnottoappearinyourArduinoIDE.
5.4 RemoteTemperatureMeasurements
NowthatwearesurethatwecanpairtheBluetoothmodulewithyourcomputer,wearegoingtowriteasketchtoreceivecommandsviaBluetooth. Todoso,wewillusetheaRESTlibraryagain,thatwealreadyusedinthepreviouschaptertohandlecommandscomingviaBluetooth. Thisisthecompletecodeforthispart:
//Codetomeasuredata&makeitaccessiblevia
//Libraries
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
#include"DHT.h"
#include<aREST.h>
//DHTsensor
#defineDHTPIN7
#defineDHTTYPEDHT11
//LCDdisplayinstance
LiquidCrystal_I2Clcd(0x27,20,4);
//DHTinstance
DHTdht(DHTPIN,DHTTYPE);
//CreateaRESTinstance
aRESTrest=aREST();
//VariablestobeexposedtotheAPI
inttemperature;
inthumidity;
intlight;
voidsetup()
{
//StartSerial
Serial.begin(115200);
//ExposevariablestoRESTAPI
rest.variable("temperature",&temperature);
rest.variable("humidity",&humidity);
rest.variable("light",&light);
//Setdevicename&ID
rest.set_id("1");
rest.set_name("weather_station");
//Initializethelcd
lcd.init();
//PrintamessagetotheLCD.
lcd.backlight();
lcd.setCursor(1,0);
lcd.print("Hello!");
lcd.setCursor(1,1);
lcd.print("Initializing…");
//InitDHT
dht.begin();
//ClearLCD
lcd.clear();
}
voidloop()
{
//MeasurefromDHT
temperature=(int)dht.readTemperature();
humidity=(int)dht.readHumidity();
//Measurelightlevel
floatsensor_reading=analogRead(A0);
light=(int)(sensor_reading/1024*100);
//HandleRESTcalls
rest.handle(Serial);
//Displaytemperature
lcd.setCursor(1,0);
lcd.print("Temperature:");
lcd.print((int)temperature);
lcd.print((char)223);
lcd.print("C");
//Displayhumidity
lcd.setCursor(1,1);
lcd.print("Humidity:");
lcd.print(humidity);
lcd.print("%");
//Displaylightlevel
lcd.setCursor(1,2);
lcd.print("Light:");
lcd.print(light);
lcd.print("%");
//Wait100ms
delay(100);
}
First,weneedtoincludetherequiredlibrariesfortheproject:
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
#include"DHT.h"
#include<aREST.h>
WealsohavetodefinethepinsonwhichtheDHTsensorisconnectedto,andthetypeofthesensor:
#defineDHTPIN7
#defineDHTTYPEDHT11
WealsoneedtocreateaninstanceoftheLCDscreen:
LiquidCrystal_I2Clcd(0x27,20,4);
Then,wehavetocreateaninstanceoftheDHTsensor:
DHTdht(DHTPIN,DHTTYPE);
WealsoneedtocreateaninstanceoftheaRESTlibrary:
aRESTrest=aREST();
Finally,justbeforethesetup()function,wedeclarethedifferentvariablesthatwillstore
themeasurementsdonebytheweatherstation:
inttemperature;
inthumidity;
intlight;
Now,inthesetup()functionofthesketch,weinitializetheSerialport:
Serial.begin(115200);
Notethathere,itisimportanttostartitusing115200bpsastheBluetoothmoduleisoperatingatthisspeed. IftheBluetoothmoduleyouareusingforthisprojectisdifferent,youneedtochangetheSerialspeedaccordingly.
Then,wehavetoexposethedifferentmeasurementvariablestotheaRESTAPI,sowecanaccessthemviaBluetooth:
rest.variable("temperature",&temperature);
rest.variable("humidity",&humidity);
rest.variable("light",&light);
WealsogiveanIDtothestation,andsomename:
rest.set_id("1");
rest.set_name("weather_station");
Finally,toendthesetup()function,weinitializetheLCDscreenandstarttheDHTsensor:
lcd.init();
dht.begin();
Now,intheloop()function,wewillfirstmaketherequiredmeasurements,handlethecallscomingfromtheBluetoothmodule,andfinallydisplaythemeasurementsontheLCDscreen. First,wegetthemeasurementsfromtheDHTsensor:
temperature=(int)dht.readTemperature();
humidity=(int)dht.readHumidity();
Wealsogetdatafromthephotocell,andconvertthisresultto%:
floatsensor_reading=analogRead(A0);
light=(int)(sensor_reading/1024*100);
Afterthat,wehandletherequestscomingfromtheBluetoothmodule:
rest.handle(Serial);
Finally,weendthesketchbydisplayingthedifferentmeasurementsontheLCDscreen.
Forexample,onthefirstlineofthescreenIchosetodisplaythetemperature:
lcd.setCursor(1,0);
lcd.print("Temperature:");
lcd.print((int)temperature);
lcd.print((char)223);
lcd.print("C");
NotethatthecompletecodeforthischaptercanbefoundinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotesttheproject. Butfirst,weneedtodoalittlehardwaremodification.Indeed,theSerialportiscurrentlydirectlyconnectedtotheBluetoothmodule,whichpreventsusfromprogrammingtheArduinoboardusingtheUSBcable. Sofirst,disconnectthewiresgoingfromtheBluetoothmoduletotheArduinoboard(TX&RX).
Now,youcanuploadthesketchtotheArduinoboardasusual. Whenthisisdone,reconnecttheTXandRXwiresbetweentheBluetoothmoduleandtheArduinomodule.Whenthisisdone,youcanpairagaintheBluetoothmodulewithyourcomputer,andthenselecttheBluetoothSerialport(theonestartingwithcu. andcontainingthenameofyourmodule).
Then,opentheSerialmonitor,andselectthecorrectSerialspeedthatyoudefinedinthesketch. Alsomakesurethattheendlinecharacterissetto‘Carriagereturn’,justnexttotheSerialspeed. Youcannowsimplytype:
/id
TheprojectshouldanswerwiththeID&nameoftheweatherstation:
{"id":"1","name":"weather_station","connected":true}
Wecanalsotestthereadoutofonevariable. Forexample,thelightlevelwiththefollowingcommand:
/light
Youshouldgettheanswerfromtheproject:
{"light":83,"id":"1","name":"weather_station","connected":true}
Ofcourse,atthesametimetheprojectshouldprintallthemeasurementsontheLCDscreen:
Ifitisnotworkingatthispoint,thereareseveralthingsyoucancheck. First,makesurethatyoucorrectlyassembledthehardware,aswesawearlierinthischapter. Also,makesurethatyoucorrectlyuploadedthecodeforthispart,andthatyouconnectedagaintheBluetoothmoduletoyourArduinoboardviatheSerialpins.
5.5 BuildingtheServerInterface
WearenowgoingtobuildaninterfaceforourBluetoothweatherstation,sowecanmonitorthedifferentmeasurementsmadebythestationfromawebbrowser. WewillstillbeabletocheckthemeasurementsfromtheLCDscreen,butwewillalsohavethepossibilitytowatchthesemeasurementsremotely.
Notethatthispartissimilartowhatwedidinthepreviouschapterfortheinterface. Ifyoufeelconfidentwithit,youcanskipthebeginningofthecodewalkthrough.
Asfortheotherinterfaceswedevelopedinthisbook,theinterfacewearegoingtodevelopisbasedonNode.js. First,wearegoingtocodethemainfilecalledapp.js,whichwewillrunlaterusethenodecommandinaterminal. Thisisthecompletecodeforthisfile:
//Modules
varexpress=require('express');
varapp=express();
//Defineport
varport=3000;
//Viewengine
app.set('viewengine','jade');
//Setpublicfolder
app.use(express.static(__dirname+'/public'));
//Rest
varrest=require("arest")(app);
rest.addDevice('serial','/dev/tty.usbmodem1a12121',115200);
//Serveinterface
app.get('/',function(req,res){
res.render('interface');
});
//Startserver
app.listen(port);
console.log("Listeningonport"+port);
Itstartsbyimportingtheexpressmodule:
varexpress=require('express');
Then,wecreateourappbasedontheexpressframework,andthesettheportto3000:
varapp=express();
varport=3000;
Wealsoneedtotelloursoftwarewheretolookforthegraphicalinterfacethatwearegoingtocodelater,andwealsosetJadeasourdefaultviewengine:
app.use(express.static(__dirname+'/public'));
app.set('viewengine','jade');
Wealsoneedtoimportthenode-aRESTmodule,andalsoaddthedeviceconnectedtoyourBluetoothSerialport. Notethathere,youneedtoinsertyourownSerialportaddresssotheinterfacecancommunicatewithyourBluetoothmodule:
varrest=require("arest")(app);
rest.addDevice('serial','/dev/tty.AdafruitEZ-Link06d5-SPP',115200);
Now,wearegoingtobuildthemainrouteofourserver. WedefinethisroutebylinkingtherootURLoftheservertothecorrespondingJadefile:
app.get('/',function(req,res){
res.render('interface');
});
Finally,stillinthisapp.jsfile,westarttheappwiththeportwedefinedbefore,andwriteamessageintheconsole:
app.listen(port);
console.log("Listeningonport"+port);
Thiswasforthemainserverfile. Now,wearegoingtobuildtheinterfaceitself. Let’sseethecontentoftheJadefilefirst. Thisfileislocatedinthe/viewfolderofourproject. Thisisthecompletecodeforthisfile:
doctype
html
head
titleBluetoothWeatherStation
link(rel='stylesheet',href='/css/interface.css')
link(rel='stylesheet',
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css")
script(src="https://code.jquery.com/jquery-2.1.1.min.js")
script(src="/js/interface.js")
body
.container
h1BluetoothWeatherStation
.row.voffset
.col-md-6
.display#temperatureDisplayTemperature:
.col-md-6
.display#humidityDisplayHumidity:
.row
.col-md-6
.display#lightDisplayLightlevel:
.col-md-6
.status#statusStationOffline
ThefilestartsbyimportingthedifferentJavaScriptfilesthatwillhandletheclickontheinterface,andsendthecorrectcommandstotheArduinoboard:
script(src="https://code.jquery.com/jquery-2.1.1.min.js")
script(src="/js/interface.js")
WealsousetheBootstrapframeworkagaintogiveabetterlooktoourinterface:
link(rel='stylesheet',href='/css/interface.css')
link(rel='stylesheet',
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css")
Then,themainpartoftheinterfacewillbebuiltofseveralblocksthatshowthestateofeachsensor. Toseethatonesensorisactive,wewillsimplychangethecoloroftheindicatorfromgraytoorange. Thisisthecodeforthesensors:
.row.voffset
.col-md-6
.display#temperatureDisplayTemperature:
.col-md-6
.display#humidityDisplayHumidity:
.row
.col-md-6
.display#lightDisplayLightlevel:
.col-md-6
.status#statusStationOffline
Now,wearegoingtohavealookatthecodeinsidetheinterface.jsfile,whichdefineshowtheinterfaceoftheprojectisworking. ItwillmakethequeriestotheboardviatheNode.jsserver,andupdatetheinterfaceaccordingly. Thisfileislocatedinthepublic/jsfolderoftheinterface. Thisisthecompletecodeforthisfile:
vardevices=[];
$.get('/devices',function(json_data){
devices=json_data;
});
$(document).ready(function(){
functionupdateSensors(){
//Updatelightlevelandstatus
$.get('/'+devices[0].name+'/light',function(json_data){
console.log(json_data.light);
$("#lightDisplay").html("Lightlevel:"+json_data.light+"%");
//Updatestatus
if(json_data.connected==1){
$("#status").html("StationOnline");
$("#status").css("color","green");
}
else{
$("#status").html("StationOffline");
$("#status").css("color","red");
}
$.get('/'+devices[0].name+'/temperature',function(json_data){
$("#temperatureDisplay").html("Temperature:"+json_data.temperature+"°C");
$.get('/'+devices[0].name+'/humidity',function(json_data){
$("#humidityDisplay").html("Humidity:"+json_data.humidity+"%");
});
});
});
}
setTimeout(updateSensors,500);
setInterval(updateSensors,5000);
});
ItstartsbydefiningthatweareusingSerialcommunications,andspecifyingwhichSerialportisusedandtheSerialspeed:
type='serial';
address='/dev/cu.AdafruitEZ-Link06d5-SPP';
speed=115200;
Notethathereyouwillhavetomodifythe“address”variablewithyourownSerialportaddressoftheBluetoothmoduleyouareusing.
ThemainpartofthisJavaScriptfileconsistsincontinuouslyrequestingthevalueofthedifferentmeasurementvariablesontheboard,bysendingqueriesviatheaRESTAPI.ThisisdoneinsideasetInterval()function:
setInterval(function(){
Insidethisfunction,wesendarequestviaourcomputerBluetoothconnection. Forexample,togetthelightlevelmeasuredbytheArduinoboard,wesendthesame/lightcommandthatweusedbefore:
$.get('/'+devices[0].name+'/light',function(json_data){
TheaRESTlibraryalwaysreturndatainaJSONcontainer,soitisreallyeasytoaccessthisdatawithinJavaScript. Whenwehavethisdata,wecanupdatethecorrespondingdisplayaccordingly:
$("#lightDisplay").html("Lightlevel:"+json_data.light+"%");
Thesameisdonewiththetemperature&humiditymeasurements.
Wealsoneedtoknowifthestationisonlineornot. Todoso,wereadthefieldcalled“connected”whenameasurementiscomingback,andweupdatethecorrespondingdisplayinsidetheinterface:
if(json_data.connected==1){
$("#status").html("StationOnline");
$("#status").css("color","green");
}
else{
$("#status").html("StationOffline");
$("#status").css("color","red");
}
Afterthat,weclosethesetInterval()function,repeatingthisloopevery5seconds.
NotethatthecompletecodeforthischaptercanbefoundinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotesttheinterface. MakesurethatyoudownloadallthefilesfromtheGitHubrepository,andupdatethecodewithyourowndataifnecessary,liketheSerialportcorrespondingtoyourBluetoothmodule. Also,makesurethattheArduinoboardisprogrammedwiththecodewesawearlierinthischapter.
Then,gotothefolderoftheinterfacewithaterminal,andtypethefollowingcommandtoinstalltheaREST,expressandJademodules:
sudonpminstallarestjadeexpress
NotethatifyouareunderWindows,youhavetoleaveoutthesudoinfrontofthecommands,anditisrecommendedtousetheNode.jscommandprompt. Finally,youcanstarttheNode.jsserverbytyping:
nodeapp.js
Youshouldbegreetedwiththefollowingmessageintheterminal:
Listeningonport3000
Youcannowgototheyourwebbrowser,andtype:
localhost:3000
Afterawhile(theBluetooth2.1connectioncanbeprettyslow),youshouldseetheinterfaceoftheweatherstationbeingdisplayed:
YoucanofcoursedoublecheckwiththedisplayofthemeasurementsontheLCDscreen,tobesurethattheymatchwithwhattheinterfaceisdisplaying.
Ifitisnotworkingatthispoint,thereareseveralthingsyoucancheck. First,makesurethatyoudownloadedthelatestversionofthecodefromtheGitHubrepositoryofthebook. Alsomadesurethatyoucorrectlymodifiedthefilestoputyourownsettings,liketheSerialportforyourBluetoothmodule. Finally,makesuretoinstalltherequiredNode.jsmoduleswithnpmbeforestartingthewebinterface.
5.6 HowtoGoFurther
Let’ssummarizewhatwelearnedinthisproject. WetooktheprojectwealreadybuiltinChapter2andaddedwirelesscapabilitiestoitusingBluetooth. WelearnedhowtointerfaceaBluetoothmodulewithArduino,andbuildawirelessweatherstationwithit.Wewereabletomonitorthemeasurementsmadebytheweatherstationfromyourwebbrowser.
Thereareofcoursemanywaystogofurtherwiththisproject. Ofcourse,youcanaddmanydifferentweatherstationinyourhome. BecauseeachBluetoothmodulehasadifferentname(asadifferentSerialport),youcanusewhatyoulearnedinthischaptertoputthesestationseverywhereinyourhome.
Youcanalsoaddmoresensorstoeachofthesestations. Forexample,tomaketheprojectevenclosetoacommercialweatherstation,youcanaddapressuresensor,forexamplebasedontheBMP180chip. Thiswillallowyoutomeasuretheatmosphericpressure,butalsotellyouthealtitudeoftheweatherstation. Youcanalsoaddananemometertotheproject,tomeasurewindspeedifyouareusingthestationoutside.
Chapter6
ControllingLampsviaWiFiInthischapter,wearegoingtoupgradeanotherprojectwebuiltbefore:thesmartlampprojectfromChapter3. WearegoingtoremovetheLCDscreenthatweusedtodisplaythestatusofthelamp,andinsteadaddaWiFimoduletotheproject.
Youwillthenbeabletocontrolyourlampremotelyfromyourcomputer,butalsofromanydeviceconnectedonyourlocalWiFinetwork. Usingtheinterfacethatwearegoingtobuild,you’llalsobeabletomonitorthepowerconsumptionofthelamp,andcheckthevalueoftheambientlightlevel. Finally,youwillalsobeabletocreateyourownrulesbasedonthemeasureddata,forexampletoautomaticallyswitchthelampoffwhentheambientlightlevelgoesaboveagivenvalue. Let’sdivein!
6.1 Hardware&SoftwareRequirements
Forthisproject,youwillofcourseneedanArduinoUnoboard. YoucanalsouseotherArduinoboardslikeanArduinoMegaorLeonardo,itwillworkjustfineaswell.
Fortherelaymodule,Iuseda5VrelaymodulefromPolulu,whichnicelyintegratesarelayonaboard,alongwithalltherequiredcomponentstocontroltherelayfromtheArduinoboard. ThisisapictureoftherelaymoduleIused:
Tomeasurethecurrentflowingthroughthelamp,IusedaboardbasedontheAC712sensorfromITeadStudio. ThissensorisreallyeasytousewithArduino,asitreturnsavoltagethatisproportionaltothemeasuredcurrent. Withthecorrectformula,wewilltheninferthecurrentflowingthroughthelampfromthevoltagemeasuredbytheArduinoboard. Ofcourse,youcanuseotherboardsbasedonthesamesensor. ThisisapictureoftheboardIusedforthisproject:
Forlightlevelsmeasurements,Iusedaphotocellwitha10KOhmresistor. Thiswillreturnasignalwhichisproportionaltotheincominglightlevel.
Then,youneedaWiFimodulebasedontheCC3000WiFichip. Therearealsomanyalternativestodothat. WhatIrecommendisusingtheAdafruitCC3000breakoutboard,whichistheonlyoneItestedthatworkedwithoutproblem. Itisniceandcompact,hasvoltageregulatorsonboard,aswellasanonboardantenna. ItriedtheofficialTICC3000board,butitneverworkedproperly,andyouhavetheuselevelshiftersaswell(theCC3000workswith3.3V,andtheArduinoUnowith5V). Theotheralternativeistomakeyourownbreakoutboard,therearemanyPCBlayoutavailableonline.
Toconnecttothelamptotheproject,Iusedastandardpairofpowerplugswithbarecablesattheend,withonefemalesocket(toplugthelampin)andonemalesocket(toplugitintothepowersocketinthewall). ThisisapictureofthecablesIused:
Finally,Iusedabreadboardandsomejumperwirestomakethedifferentelectricalconnections.
Thisisalistofallcomponentsusedinthisproject,alongwithlinkstopurchasethemonline:
ArduinoUno(http://www.adafruit.com/product/50)Relaymodule(http://www.pololu.com/product/2480)Currentsensor(http://imall.iteadstudio.com/im120710011.html)Photocell(http://www.adafruit.com/product/161)10kOhmresistor(https://www.sparkfun.com/products/8374)CC3000WiFibreakoutboard(http://www.adafruit.com/products/1469)Breadboard(http://www.adafruit.com/product/64)Jumperwires(http://www.adafruit.com/product/758)
Onthesoftwareside,youneedtohavethelatestversionoftheArduinoIDEinstalledonyourcomputer,aswellastheaRESTlibraryforArduinowhichyoucanfindatthefollowinglink:
https://github.com/marcoschwartz/aREST
ThisprojectalsorequireshavingtheCC3000chiplibrary:
https://github.com/adafruit/Adafruit_CC3000_Library
AndtheCC3000mDNSlibrary:
https://github.com/adafruit/CC3000_MDNS
Toinstallagivenlibrary,simplyextractthefolderinyourArduino/librariesfolder(orcreatethisfolderifitdoesn’texistyet).
6.2 BuildingtheProject
Let’snowassemblethehardwareforthisproject. Asforthepreviousprojectusingarelay,wewilldosointwoparts. WewillfirstconnectthedifferentcomponentsliketherelaymoduletotheArduinoboard,andthenwewillconnectthelamptotheproject.
Thehardwareconnectionsforthefirstpartareactuallyquitesimple:wehavetoconnecttherelaymodule,thecurrentsensor,theWiFimoduleandthephotocell. First,connecttheArduinoUno+5Vpintotheredrailonthebreadboard,andthegroundpintothebluerail.
Forthephotocell,firstplacethecellinserieswiththe10kOhmresistoronthebreadboard. Then,connecttheotherendofthephotocelltotheredrailonthebreadboard,andtheotherendoftheresistortotheground. Finally,connectthecommonpinoftheresistor&thephotocelltotheArduinoUnoanalogpinA0.
Now,theWiFimodule. First,connecttheIRQpinoftheCC3000boardtopinnumber3oftheArduinoboard,VBATtopin5,andCStopin10. Then,youneedtoconnecttheSPIpinstotheArduinoboard:MOSI,MISO,andCLKgotopins11,12,and13,respectively. Finally,takecareofthepowersupply:VingoestotheArduino5V(redpowerrail),andGNDtoGND(bluepowerrail).
Thisisaschematicoftheproject,withouttherelaymoduleandcurrentsensorconnectedyet:
ThisimagewascreatedwithFritzing(http://fritzing.org/).
Fortherelaymodule,therearethreepinsyouneedtoconnect:VCC,GNDandSIG.VCCneedstogotheArduino5Vpin,soconnectittotheredpowerrail. GNDgoestotheArduinogroundpin,sotothebluepowerrail. Finally,connecttheSIGpintopinnumber8oftheArduinoboard.
Itisactuallysimilarforthecurrentsensormodule. Ithasthreepins:VCC,GND,andOUT.Asfortherelay,VCCneedstogotheArduino5Vpin,soconnectittotheredpowerrail. GNDgoestotheArduinogroundpin,sotothebluepowerrail. Then,connecttheOUTpintotheanalogpinA1oftheArduinoboard.
Thisisapictureofthefullyassembledproject,withoutthelampconnectedyet:
Wearenowgoingtoconnectthelamptothehardwarewealreadyassembled. Basically,theideaistohavethemainpowersupply(comingfromthepowersocketinthewall)goingtotherelay,thentothecurrentsensor,andfinallytothelamp. Followthisschematictomaketherequiredconnections:
Asitimpliesdangerousvoltagelevels(110vor230vdependingonwhereyouareintheworld),youshouldtakesomeprecautationsatthispoint,thatyoucanfindintheintroductionofthisbook. Ofcourse,youcanmake&testthewholeprojectofthischapterwithoutconnectinganyhigh-powerdevice.
6.3 TestingtheWiFiModule
Beforewebuildourwirelesssmartlamp,wearefirstgoingtocheckthatthemostimportantcomponentoftheprojectisworking:theWiFimodule. WearegoingtowriteanArduinosketchthatinitializesthechip,connectstoyourlocalWiFinetwork,anddisplaytheIPaddressofthemodule,meaningthatitwassuccessfullyconnectedtothenetwork. Thisisthecompletecodeforthispart:
//CodeforthetesttheWiFimodule
//Importrequiredlibraries
#include<Adafruit_CC3000.h>
#include<SPI.h>
//ThesearethepinsfortheCC3000chipifyouareusingabreakoutboard
#defineADAFRUIT_CC3000_IRQ3
#defineADAFRUIT_CC3000_VBAT5
#defineADAFRUIT_CC3000_CS10
//CreateCC3000instance
Adafruit_CC3000cc3000=Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ,ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIV2);
//YourWiFiSSIDandpassword
#defineWLAN_SSID"yourSSID"
#defineWLAN_PASS"yourPassword"
#defineWLAN_SECURITYWLAN_SEC_WPA2
voidsetup(void)
{
//StartSerial
Serial.begin(115200);
//SetupCC3000andgetconnectedtothewirelessnetwork.
Serial.println("Initializingchip…");
if(!cc3000.begin())
{
while(1);
}
//ConnecttoWiFi
Serial.println("ConnectingtoWiFinetwork…");
if(!cc3000.connectToAP(WLAN_SSID,WLAN_PASS,WLAN_SECURITY)){
while(1);
}
while(!cc3000.checkDHCP())
{
delay(100);
}
Serial.println("Connected!");
//Displayconnectiondetails
displayConnectionDetails();
Serial.println(F("Testcompleted"));
}
voidloop(){
}
//Displayconnectiondetails
booldisplayConnectionDetails(void)
{
uint32_tipAddress,netmask,gateway,dhcpserv,dnsserv;
if(!cc3000.getIPAddress(&ipAddress,&netmask,&gateway,&dhcpserv,&dnsserv))
{
Serial.println(F("UnabletoretrievetheIPAddress!\r\n"));
returnfalse;
}
else
{
Serial.print(F("\nIPAddr:"));cc3000.printIPdotsRev(ipAddress);
Serial.print(F("\nNetmask:"));cc3000.printIPdotsRev(netmask);
Serial.print(F("\nGateway:"));cc3000.printIPdotsRev(gateway);
Serial.print(F("\nDHCPsrv:"));cc3000.printIPdotsRev(dhcpserv);
Serial.print(F("\nDNSserv:"));cc3000.printIPdotsRev(dnsserv);
Serial.println();
returntrue;
}
}
ItstartsbyincludingtherequiredlibrariesfortheCC3000chip:
#include<Adafruit_CC3000.h>
#include<SPI.h>
AnddefiningthepinsonwhichtheCC3000moduleisconnectedto:
#defineADAFRUIT_CC3000_IRQ3
#defineADAFRUIT_CC3000_VBAT5
#defineADAFRUIT_CC3000_CS10
Then,wecancreateaninstanceoftheCC3000WiFichip:
Adafruit_CC3000cc3000=Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ,ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIV2);
Now,youwillneedtomodifythesketchtoenteryourownSSIDnetworkname,andtheassociatedpassword. IfyournetworkisnotusingWPA2authentication,youwillalsohavetochangethissecurityparameter:
#defineWLAN_SSID"yourSSID"
#defineWLAN_PASS"yourPassword"
#defineWLAN_SECURITYWLAN_SEC_WPA2
Now,inthesetup()functionofthesketch,youneedtostarttheSerialportthatwewillusefordebuggingpurposes:
Serial.begin(115200);
WecannowinitializetheCC3000WiFichip:
Serial.println("Initializingchip…");
if(!cc3000.begin())
{
while(1);
}
Afterthat,thesketchwilltrytoconnecttheWiFichiptotheWiFinetworkyoudefinedbefore,andgetanIPaddress:
Serial.println("ConnectingtoWiFinetwork…");
if(!cc3000.connectToAP(WLAN_SSID,WLAN_PASS,WLAN_SECURITY)){
while(1);
}
while(!cc3000.checkDHCP())
{
delay(100);
}
Serial.println("Connected!");
Whenthechipisconnectedtothenetwork,wegettheIPaddressoftheWiFimoduleandprintitontheSerialportaswell. Finally,weprintthatthetestisnowcompleted:
displayConnectionDetails();
Serial.println(F("Testcompleted"));
NotethatthecompletecodeforthischaptercanbefoundonthecorrespondingfolderinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotestthisfirstsketchoftheproject. MakesurethatyoumodifiedthesketchwithyourownWiFinetworknameandpassword. Then,uploadthesketchtotheArduinoboard,andopentheSerialmonitor. Thisiswhatyoushouldsee:
Initializingchip…
ConnectingtoWiFinetwork…
Connected!
IPAddr:192.168.1.100
Netmask:255.255.255.0
Gateway:192.168.1.1
DHCPsrv:192.168.1.1
DNSserv:192.168.0.254
Testcompleted
IfyoucanseeanIPaddress,congratulations,itmeansthattheWiFimoduleiscorrectlywiredandcanconnecttoyourWiFinetwork. Wecannowstartcodingtheremotecontrolpartofyoursmartlampproject.
Ifitisnotworkingatthispoint,thereareseveralthingsyoucancheck. First,makesurethatyoucorrectlywiredtheCC3000WiFimodule. Therearelotsofcablestoconnect,anditiseasytomixthemup. Also,makesurethatyourInternetconnectionisupandrunning,ortheWiFichipwon’tbeabletoconnecttothetestwebsite.
6.4 RemoteLampControl
Inthissection,wearegoingtobuildtheArduinosketchthatwewillusetocontrolthelampviaWiFi,andalsotogetthemeasuredambientlightlevel&powerconsumptionofthelamp.
Todoso,weareagaingoingtousetheaRESTlibrarysowecanhaveaneasyaccesstothepinsoftheArduinoboard,andtothevariablesinwhichthemeasurementsarestored.
AsthesketchisbuiltonthesketchthatweusedtotesttheWiFiconnections,Iwillonlydetailthecodethatwasaddedcomparedtotheprevioussketch. Thisisthecompletecodeforthispart:
//Codeforthewirelesssmartlampproject
#defineNUMBER_VARIABLES2
#defineNUMBER_FUNCTIONS1
//Importrequiredlibraries
#include<Adafruit_CC3000.h>
#include<SPI.h>
#include<CC3000_MDNS.h>
#include<aREST.h>
//Relaystate
constintrelay_pin=8;
//Definemeasurementvariables
floatamplitude_current;
floateffective_value;
floateffective_voltage=230;//Setvoltageto230V(Europe)or110V(US)
floateffective_power;
floatzero_sensor;
//ThesearethepinsfortheCC3000chipifyouareusingabreakoutboard
#defineADAFRUIT_CC3000_IRQ3
#defineADAFRUIT_CC3000_VBAT5
#defineADAFRUIT_CC3000_CS10
//CreateCC3000instance
Adafruit_CC3000cc3000=Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ,ADAFRUIT_CC3000_VBAT);
//CreateaRESTinstance
aRESTrest=aREST();
//YourWiFiSSIDandpassword
#defineWLAN_SSID"KrakowskiePrzedm51m.15(flat15)"
#defineWLAN_PASS"KrK51flat15_1944_15"
#defineWLAN_SECURITYWLAN_SEC_WPA2
//TheporttolistenforincomingTCPconnections
#defineLISTEN_PORT80
//Serverinstance
Adafruit_CC3000_ServerrestServer(LISTEN_PORT);
//DNSresponderinstance
MDNSRespondermdns;
//VariablestobeexposedtotheAPI
intpower;
intlight;
voidsetup(void)
{
//StartSerial
Serial.begin(115200);
//InitvariablesandexposethemtoRESTAPI
rest.variable("light",&light);
rest.variable("power",&power);
//Setrelay&ledpinstooutputs
pinMode(relay_pin,OUTPUT);
//Calibratesensorwithnullcurrent
zero_sensor=getSensorValue(A1);
//GivenameandIDtodevice
rest.set_id("001");
rest.set_name("smart_lamp");
//SetupCC3000andgetconnectedtothewirelessnetwork.
if(!cc3000.begin())
{
while(1);
}
if(!cc3000.connectToAP(WLAN_SSID,WLAN_PASS,WLAN_SECURITY)){
while(1);
}
while(!cc3000.checkDHCP())
{
delay(100);
}
//StartmulticastDNSresponder
if(!mdns.begin("arduino",cc3000)){
while(1);
}
//Displayconnectiondetails
displayConnectionDetails();
//Startserver
restServer.begin();
Serial.println(F("Listeningforconnections…"));
}
voidloop(){
//Measurelightlevel
floatsensor_reading=analogRead(A0);
light=(int)(sensor_reading/1024*100);
//Performpowermeasurement
floatsensor_value=getSensorValue(A1);
//Converttocurrent
amplitude_current=(float)(sensor_value-zero_sensor)/1024*5/185*1000000;
effective_value=amplitude_current/1.414;
effective_power=abs(effective_value*effective_voltage/1000);
power=(int)effective_power;
//HandleanymulticastDNSrequests
mdns.update();
//HandleRESTcalls
Adafruit_CC3000_ClientRefclient=restServer.available();
rest.handle(client);
}
booldisplayConnectionDetails(void)
{
uint32_tipAddress,netmask,gateway,dhcpserv,dnsserv;
if(!cc3000.getIPAddress(&ipAddress,&netmask,&gateway,&dhcpserv,&dnsserv))
{
Serial.println(F("UnabletoretrievetheIPAddress!\r\n"));
returnfalse;
}
else
{
Serial.print(F("\nIPAddr:"));cc3000.printIPdotsRev(ipAddress);
Serial.print(F("\nNetmask:"));cc3000.printIPdotsRev(netmask);
Serial.print(F("\nGateway:"));cc3000.printIPdotsRev(gateway);
Serial.print(F("\nDHCPsrv:"));cc3000.printIPdotsRev(dhcpserv);
Serial.print(F("\nDNSserv:"));cc3000.printIPdotsRev(dnsserv);
Serial.println();
returntrue;
}
}
//Getthereadingfromthecurrentsensor
floatgetSensorValue(intpin)
{
intsensorValue;
floatavgSensor=0;
intnb_measurements=100;
for(inti=0;i<nb_measurements;i++){
sensorValue=analogRead(pin);
avgSensor=avgSensor+float(sensorValue);
}
avgSensor=avgSensor/float(nb_measurements);
returnavgSensor;
}
Itstartsbyincludingalltherequiredlibraries:
#include<Adafruit_CC3000.h>
#include<SPI.h>
#include<CC3000_MDNS.h>
#include<aREST.h>
Anddeclaringthepinonwhichtherelaymoduleisconnected:
constintrelay_pin=8;
Then,wedeclarethedifferentvariablesthatarerequiredforthepowermeasurementpart:
floatamplitude_current;
floateffective_value;
floateffective_voltage=230;//Setvoltageto230V(Europe)or110V(US)
floateffective_power;
floatzero_sensor;
Then,wecreatetheinstanceoftheaRESTobjectthatwewillusetohandletherequestscomingviatheWiFiconnection:
aRESTrest=aREST();
WealsoneedtodefineonwhichportwewanttotheWiFichiptolistento. Forconvenience,wewillusetheport80,soyoucandirectlycommandyourArduinoboardfromawebbrowser:
#defineLISTEN_PORT80
WealsocreateaninstanceoftheCC3000server:
Adafruit_CC3000_ServerrestServer(LISTEN_PORT);
WealsoneedtocreateaninstanceoftheMDNSserver,sowecanaccesstheArduinoboardwithouthavingtotypetheboardIPaddresstoaccessit:
MDNSRespondermdns;
Finally,wedeclaretwovariablesthatwillcontainthemeasurementsofthepowerconsumptionandthelightlevel:
intpower;
intlight;
Now,inthesetup()functionofthesketch,wefirstexposethetwomeasurementvariablestotheRESTAPIsowecanaccessthemfromtheoutsideworldviaWiFi:
rest.variable("light",&light);
rest.variable("power",&power);
Afterthat,wedeclaretherelaypinasanoutput:
pinMode(relay_pin,OUTPUT);
Wealsouseafunctionthataveragesthemeasurementsofthecurrentsensortogetthesensor’sreadingatwhichthecurrentisnull:
zero_sensor=getSensorValue(A1);
WecanalsosetanameandanIDforthedevice,thatwillbereturnedateachcalloftheboardviatheaRESTAPI:
rest.set_id("001");
rest.set_name("smart_lamp");
Afterthisstep,wesetanamefortheArduinoboardonthenetwork,forexample“arduino”. Thismeansthattheboardwillbeaccessiblebythenamearduino.localonyourlocalnetwork:
if(!mdns.begin("arduino",cc3000)){
while(1);
}
Finally,stillinthesetup()functionwestarttheCC3000serverandwaitforincomingconnections:
restServer.begin();
Serial.println(F("Listeningforconnections…"));
Intheloop()functionofthesketch,wefirstgetthevalueoftheambientlightlevel,expressedin%:
floatsensor_reading=analogRead(A0);
light=(int)(sensor_reading/1024*100);
Wealsogetthereadingcomingfromthecurrentsensor,againbyusingafunctiontoaveragetheresultoverseveralmeasurements:
floatsensor_value=getSensorValue(A1);
Then,wecancalculatethepowerfromthemeasuredcurrent:
amplitude_current=(float)(sensor_value-zero_sensor)/1024*5/185*1000000;
effective_value=amplitude_current/1.414;
effective_power=abs(effective_value*effective_voltage/1000);
power=(int)effective_power;
Afterthat,weupdatetheMDNSserver:
mdns.update();
AndprocessanyincomingconnectionusingtheaRESTlibrary:
Adafruit_CC3000_ClientRefclient=restServer.available();
rest.handle(client);
NotethatthecompletecodeforthischaptercanbefoundonthecorrespondingfolderinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotestthissketchonourproject. DownloadthecodefromtheGitHubrepository,andmakesurethatyoumodifythenameandthepasswordoftheWiFinetworkonwhichtheWiFichipwillconnectto. Then,uploadthecodetotheArduinoboard,andopentheSerialmonitor. Thisiswhatyoushouldsee:
Listeningforconnections…
Now,closetheSerialmonitor,andopenyourwebbrowser. YoucannowmakedirectcallstotheRESTAPIrunningontheboardtocontrolthepinsoftheArduinoboard. Forexample,toturnthelampon,justtype:
http://arduino.local/digital/8/1
Youshouldheartherelayswitching,thelampshouldturnonandyoushouldhaveaconfirmationmessageinsideyourbrowser:
PinD8setto1
Toswitchthelampoffagain,justtype:
http://arduino.local/digital/8/0
NotethatthesecommandswillworkfromanydevicesconnecttothesamelocalnetworkastheArduinoboard. Forexample,youcanuseyoursmartphonetocontrolyourArduinoboardwiththesamecommands.
Ifitdoesn’twork,thefirstthingtodoistousetheIPaddressoftheboardinplaceofthearduino.localname. YoucangettheIPaddressbylookingatthemessagesdisplayedontheSerialmonitorwhenstartingtheproject.
Ifitisstillnotworkingatthispoint,thereareseveralthingsyoucancheck. First,makesurethatallthehardwarecomponentsoftheprojectsarecorrectlywired,aswesawearlierinthechapter. Then,makesurethatyoudownloaded&installedtherequiredlibrariesforthisproject,especiallytheaRESTlibrary.
6.5 BuildingtheSmartLampInterface
Wearenowgoingtobuildtheinterfacethatyouwillusetocontroltheprojectfromyourcomputer. Usingthisinterface,youwillbeabletocontrolthelampviaWiFi,butalsotoseeinreal-timethepowerconsumptionofthelampandtheambientlightlevelcomingfromthephotocell.
Notethatthispartissimilartowhatwedidinthepreviouschapterfortheinterface. Ifyoufeelconfidentwithit,youcanskipthebeginningofthecodewalkthrough.
Asfortheotherinterfaceswedevelopedinthisbook,theinterfacewearegoingtodevelopisbasedonNode.js. First,wearegoingtocodethemainfilecalledapp.js,whichwewillrunlaterusethenodecommandinaterminal. Thisisthecompletecodeforthisfile:
//Module
varexpress=require('express');
varapp=express();
//Defineport
varport=3000;
//Viewengine
app.set('viewengine','jade');
//Setpublicfolder
app.use(express.static(__dirname+'/public'));
//Rest
varrest=require("arest")(app);
rest.addDevice('http','192.168.1.103');
//Serveinterface
app.get('/',function(req,res){
res.render('interface');
});
//Startserver
app.listen(port);
console.log("Listeningonport"+port);
Itstartsbyimportingtheexpressmodule:
varexpress=require('express');
Then,wecreateourappbasedontheexpressframework,andthesettheportto3000:
varapp=express();
varport=3000;
Wealsoneedtotelloursoftwarewheretolookforthegraphicalinterfacefilesthatwearegoingtocodelater,andwealsodefineJadeasourdefaultviewengine:
app.use(express.static(__dirname+'/public'));
app.set('viewengine','jade');
Wealsoneedtousethenode-aRESTmodule,thatwillhandleallthecommunicationsbetweentheinterfaceandoursmartlamp. AtthispointyoualsoneedtoentertheIPaddressofyourWiFichip:
varrest=require("arest")(app);
rest.addDevice('http','192.168.1.103');
Now,wearegoingtobuildthemainrouteforourserver. WedefinethisroutebylinkingtherootURLoftheservertotheinterfaceoftheproject:
app.get('/',function(req,res){
res.render('interface');
});
Finally,stillinthisapp.jsfile,westarttheappwiththeportwedefinedbefore,andwriteamessageintheconsole:
app.listen(port);
console.log("Listeningonport"+port);
Thiswasforthemainserverfile. Now,wearegoingtobuildtheinterfaceitself. Let’sseethecontentoftheJadefilefirst. Thisfileislocatedinthe/viewfolderofourproject. Thisisthecompletecodeforthisfile:
doctype
html
head
titleSmartLamp
link(rel='stylesheet',href='/css/interface.css')
link(rel='stylesheet',
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css")
script(src="https://code.jquery.com/jquery-2.1.1.min.js")
script(src="/js/interface.js")
body
.container
h1SmartLamp
.row.voffset
.col-md-6
button.btn.btn-block.btn-lg.btn-primary#1On
.col-md-6
button.btn.btn-block.btn-lg.btn-danger#2Off
.row
.col-md-4
h3#powerDisplayPower:
.col-md-4
h3#lightDisplayLightlevel:
.col-md-4
h3#statusOffline
ThefilestartsbyimportingthedifferentJavaScriptfilesthatwillhandletheclickontheinterface,andsendthecorrectcommandstotheArduinoboard:
script(src="https://code.jquery.com/jquery-2.1.1.min.js")
script(src="/js/interface.js")
WealsousetheTwitterBootstrapframeworktogiveabetterlookatourinterface:
link(rel='stylesheet',href='/css/interface.css')
link(rel='stylesheet',
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css")
Then,weneedtocreatetwobuttons:onetoturntherelayonandthereforeswitchonthelight,andanotheronetoswitchthelightoffagain. Thisisthecodeforbothbuttons:
.col-md-6
button.btn.btn-block.btn-lg.btn-primary#1On
.col-md-6
button.btn.btn-block.btn-lg.btn-danger#2Off
WewilldefineintheJavaScriptfileofthisprojecthowtheclicksonthesebuttonsarehandled.
Finally,wealsoneedtocreatetextfieldstodisplaythedifferentmeasurementsmadebyourArduinoproject,likethepowerandthelightlevel. Wealsocreateoneindicatortocheckthattheprojectisonline:
.col-md-4
h3#powerDisplayPower:
.col-md-4
h3#lightDisplayLightlevel:
.col-md-4
h3#statusOffline
Now,wearegoingtoseethecontentsoftheinterface.jsfile,locatedinthepublic/jsfolderoftheproject. Thisisthecompletecodeforthisfile:
vardevices=[];
$.get('/devices',function(json_data){
devices=json_data;
});
$(document).ready(function(){
//Updatesensorsandrepeatevery5seconds
setTimeout(updateSensors,500);
setInterval(updateSensors,5000);
//Functiontocontrolthelamp
$('#1').click(function(){
$.get('/'+devices[0].name+'/digital/8/1');
});
$('#2').click(function(){
$.get('/'+devices[0].name+'/digital/8/0');
});
functionupdateSensors(){
//Updatelightlevel
$.get('/'+devices[0].name+'/light',function(json_data){
$("#lightDisplay").html("Lightlevel:"+json_data.light+"%");
//Updatestatus
if(json_data.connected==1){
$("#status").html("LampOnline");
$("#status").css("color","green");
}
else{
$("#status").html("LampOffline");
$("#status").css("color","red");
}
//Updatepower
$.get('/'+devices[0].name+'/power',function(json_data){
$("#powerDisplay").html("Power:"+json_data.power+"W");
});
});
}
});
Therearetwomainpartsinthisfile:onethatdefineshowtheclicksonthebuttonsarehandled,andonewhichisheretorefreshthesensors.
Let’sseethepartaboutthebuttonsfirst. WebasicallyjustneedtolinkeachbuttonwiththecorrespondingdigitalWrite()commandoftheArduinoboard. Thisisdonebythefollowingpieceofcode:
$('#1').click(function(){
$.get('/'+devices[0].name+'/digital/8/1');
});
$('#2').click(function(){
$.get('/'+devices[0].name+'/digital/8/0');
});
Wealsoneedtocodethepartresponsibleofupdatingtheinterfacewiththemeasurementsdonebytheboard. Todoso,wearegoingtoquerythesemeasurementsfromtheboardatregularintervals,usingthesetIntervalfunctionofJavaScript:
setInterval(updateSensors,5000);
Let’snowseethedetailsofthisupdateSensorsfunction. Togetthedatafromtheboard,forexamplethelightlevelmeasurement,weusethesamefunctionasbefore,bysendingthe/lightcommand. Howeverthistime,weusetheJSONdatareturned:
$.get('/'+devices[0].name+'/light',function(json_data){
Withthisdata,wecanupdatethedisplayaccordingly:
$("#lightDisplay").html("Lightlevel:"+json_data.light+"%");
ThisJSONdataalsocontainssomeinformationofthestatusoftheboard. Ifthe“connected”fieldispresent,wesetthestatusindicatortoonline,andsetthecolortogreen. Ifthedataisnotpresentorcorrupted,wesetittoofflineandapplyaredcolortothisindicator:
if(json_data.connected==1){
$("#status").html("LampOnline");
$("#status").css("color","green");
}
else{
$("#status").html("LampOffline");
$("#status").css("color","red");
}
Thesameisdoneforthepowermeasurementontheboard:
$.get('/'+devices[0].name+'/power',function(json_data){
$("#powerDisplay").html("Power:"+json_data.power+"W");
});
Thisfunctionisrepeatedevery5seconds. Thisalsowhereyoucandefineyourownfunctionstocontrolyourlampaccordinglytothemeasurements. Forexample,youcantellthelamptoautomaticallyswitchoffiftheambientlightlevelmeasurementisreachingagivenvalue.
NotethatthecompletecodeforthischaptercanbefoundonthecorrespondingfolderinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotesttheinterface. MakesurethatyoudownloadallthefilesfromtheGitHubrepository,andupdatethecodewithyourowndataifnecessary,liketheArduinoboardaddress. Also,makesurethattheArduinoboardisprogrammedwiththecodewesawearlierinthischapter.
Then,gotothefolderoftheinterfacewithaterminal,andtypethefollowingcommandtoinstalltheaREST,expressandJademodules:
sudonpminstallarestexpressjade
NotethatifyouareunderWindows,youhavetoleaveoutthesudoinfrontofthecommands,anditisrecommendedtousetheNode.jscommandprompt. Finally,youcanstarttheNode.jsserverbytyping:
sudonodeapp.js
Youshouldbegreetedwiththefollowingmessageintheterminal:
Listeningonport3000
Youcannowgototheyourwebbrowser,andtype:
localhost:3000
Youshouldseetheinterfacebeingdisplayedinsideyourbrowser,withthebuttonstocontrolthelamp. Don’tworry,whenyourfirstopentheinterfacethelampshouldappearasofflineandtheindicatorshouldnotdisplayanydata. Afteramoment,theinterfacewillmakeaquerytotheArduinoboardandupdatethedataaccordingly:
Youcannowalsotestthedifferentbuttonsoftheinterface. Bydefault,thelampisturnedoff,soclickonthe“On”buttontoturnthelamponinstantly. Youshouldalsohearthe“click”comingfromtherelay. Whenthelampison,youshouldalsoseethatthepowermeasurementdisplayisupdatedaccordinglyontheinterface. Then,youcanclickonthe“Off”buttontoswitchthelampoffagain.
IfyoudefinedcodeintheJavaScriptfileoftheinterface,likeswitchingthelampoffautomaticallywhentheambientlightreachesagivenlevel,youshouldalsoseetheeffectsofthiscodeatthispoint.
Ifitisnotworkingatthispoint,thereareseveralthingsyoucancheck. First,makesurethatyoudownloadedthelatestversionofthecodefromtheGitHubrepositoryofthebook. Alsomadesurethatyoucorrectlymodifiedthefilestoputyourownsettings,liketheaddressofyourWiFimodule. Finally,makesuretoinstalltherequiredNode.jsmoduleswithnpmbeforestartingthewebinterface.
6.6 HowtoGoFurther
Let’ssummarizewhatwelearnedinthisproject. WetooktheprojectwealreadybuiltinChapter3andaddedWiFicapabilitiestoit. WelearnedhowtointerfaceaWiFichipwithArduino,andcontrolourprojectfromawebbrowser. Wewereabletocontrolthelampwirelessly,andaccessthedifferentmeasurementsfromyourbrowser. Finally,webuildasoftwarerunningonyourcomputertocontrolthewholeprojectfromagraphicalinterfacewithinyourwebbrowser.
Thereareofcoursemanywaystogofurtherwiththisproject. YoucanofcourseaddmoresensorstotheArduinoboardandaccessthesemeasurementswirelessly. Forexample,youcouldperfectlyaddatemperaturesensortotheprojectanddisplaythedataonthegraphicalinterfaceaswell. Youcanalsoaddasecondlamptothisproject,andcontrolbothlampsindependently.
Bychangingthecoderunningonyourcomputer,insidetheJavaScriptfile,youcanalsodefinemorecomplexbehaviorsforthelamp. Notonlyyoucancontrolthelampaccordingtothelightlevelmeasurements,butyoucanalsousethefactthatyourcomputerisconnectedtothewebtocreatemorecomplexbehaviors. Forexample,youcanautomaticallyswitchthelampoffafteragiventimeintheevening,andswitchitonagainintheearlymorningtowakeyouup.
Finally,youcanhaveseveraloftheseprojectsinyourhome,simplybygivingdifferentnamestoyourArduinoboards,andaddingmoreelementsinthegraphicalinterface. Youcanalsocreatemorebehaviorsandbuttonsforyourproject,forexampleabuttontoautomaticallyswitchoffallthelampsinyourhomewithasimpleclick.
Chapter7
BuildinganHomeAutomationSystemInthislastchapterofthebook,wearegoingtousewhatwelearnedinthepreviouschapterstobuildasmallhomeautomationsystem. ThissystemwillintegrateXBeemotionsensorsaswellasaWiFicontrolledlamp. Allofthesecomponentswillbecontrolledfromacentralinterface.
Wearefirstgoingtoseewhatisneededforthishomeautomationsystem. Then,wearegoingtobuildthedifferentmodules. Afteraquicktestofthemodules,wearegoingtobuildaninterfacesoyoucanmonitoreverythingfromyourcomputer. Finally,Iwillgiveyousomeadvicesabouthowtogofurtherandbuildmorecomplexhomeautomationsystems.
7.1 Hardware&SoftwareRequirements
Let’sfirstseewhatweneedforthischapter. WebasicallyneedtobuildagivennumberofXBeemotionsensors,andoneWiFilampcontroller.
ThisisalistofallcomponentsforoneXBeemotionsensor,alongwithlinkstopurchasethemonline:
ArduinoUno(http://www.adafruit.com/product/50)PIRmotionsensor(https://www.adafruit.com/products/189)ArduinoXBeeshield(https://www.sparkfun.com/products/10854)XBeeSeries2modulewithwireantenna(https://www.sparkfun.com/products/11215)Jumperwires(http://www.adafruit.com/product/758)
TouseXBeeonyourcomputer,youwillalsoneedtogetthesecomponents:
USBXBeeexplorerboard(https://www.sparkfun.com/products/11812)XBeeSeries2modulewithwireantenna(https://www.sparkfun.com/products/11215)
FortheWiFilampcontroller,youwillneedthefollowingcomponents:
ArduinoUno(http://www.adafruit.com/product/50)Relaymodule(http://www.pololu.com/product/2480)Currentsensor(http://imall.iteadstudio.com/im120710011.html)Photocell(http://www.adafruit.com/product/161)10kOhmresistor(https://www.sparkfun.com/products/8374)CC3000WiFibreakoutboard(http://www.adafruit.com/products/1469)Breadboard(http://www.adafruit.com/product/64)Jumperwires(http://www.adafruit.com/product/758)
Onthesoftwareside,youneedtohavethelatestversionoftheArduinoIDEinstalledonyourcomputer,aswellastheaRESTlibraryforArduinowhichyoucanfindatthefollowinglink:
https://github.com/marcoschwartz/aREST
ThisprojectalsorequireshavingtheCC3000chiplibrary:
https://github.com/adafruit/Adafruit_CC3000_Library
AndtheCC3000mDNSlibrary:
https://github.com/adafruit/CC3000_MDNS
Toinstallagivenlibrary,simplyextractthefolderinyourArduino/librariesfolder(orcreatethisfolderifitdoesn’texistyet).
7.2 BuildingtheProject
Wearenowgoingtobuildthedifferentmodulesofourhomeautomationsystem. Aswealreadysawinpreviouschaptershowtoassemblethedifferentprojects,Iwillsimplyrefertothesechaptersforthecompleteinstructionsonhowtoassemblethehardware.
FortheXBeemotionsensors,pleaserefertoChapter4. Thisiswhatyoushouldendupwith:
FortheWiFilampcontroller,pleaserefertoChapter6. Thisiswhatyoushouldendupwith:
7.3 TestingtheModules
WearenowgoingtotestoneXBeemotionsensor,andtheWiFilampcontroller. Becausewealreadysawhowthesemodulesworkinpreviouschapters,wearedirectlygoingtotestthemwirelesslytocheckifeverythingisworkingfine.
First,hereisthecodefortheXBeemotionsensor:
//CodefortheXBeemotionsensor
//Libraries
#include<SPI.h>
#include<aREST.h>
//MotionsensorID
Stringxbee_id="1";
//CreateArduRESTinstance
aRESTrest=aREST();
voidsetup(){
//StartSerial
Serial.begin(9600);
//GivenameandIDtodevice
rest.set_id(xbee_id);
rest.set_name("motion_sensor");
}
voidloop(){
//HandleRESTcalls
rest.handle(Serial);
}
Thissketchstartsbyincludingthecorrectlibrariesforthesketch:
#include<SPI.h>
#include<aREST.h>
WealsodefinetheIDofthesensor. Thisisreallyusefulifyouaremanymotionsensorsinyourhome,makesuretogivethemdifferentIDs:
Stringxbee_id="1";
WealsoneedtocreateaninstanceoftheaRESTlibrary:
aRESTrest=aREST();
Inthesetup()functionofthesketch,westarttheSerialport. Notethathere,itisreallyimportanttouseaspeedof9600asitisthedefaultspeedofXBeemodules:
Serial.begin(9600);
WealsosettheIDofthedevicethatwedefinedbefore:
rest.set_id(xbee_id);
Finally,intheloop()functionofthesketch,wesimplehandletherequestscomingfromtheSerialportusingtheaRESTlibrary:
rest.handle(Serial);
It’snowtimetotestthissketch. UploadthesketchtheArduinoboard,andnowputtheswitchoftheXBeeshieldto“UART”sotheXBeemoduleisnowdirectlycommunicatingwiththeArduinomicrocontrollerviatheSerialport. NotethatifyouneedtoprogramtheArduinoboardagain,youneedtoswitchitbackto“DLINE”.
Now,youneedtolocatetheSerialportcorrespondingtotheXBeeexplorerboardconnectedtoyourcomputer. YoucandosobylookingattheTools>SerialPortmenuoftheArduinoIDE.Forexample,mineiscalled“/dev/cu.usbserial-A702LF8B”. Alsowriteitdownforlater,wewillneeditwhenbuildingtheinterfaceforourmotionsensors.
Now,opentheSerialmonitoroftheArduinoIDE.Makesurethatthespeedissetto9600.NotethatbecausewearenowconnecttotheXBeeexplorerboard,allcommandsthatyouaresendingnowarebeingsenttoallXBeemodulesinyourhome.
IntheSerialmonitor,type:
/id
ThiswillsimplyquerytheIDoftheallXBeeboardsthatareinyourhome. WhenItestedtheproject,Ihadonlyoneinmyhome. Itrespondedwith:
{"id":"1","name":"","connected":true}
Afterthisstep,wearegoingtoreadthestatusofthemotionsensor. Remember,itisconnectedtopinnumber8. Toreadfromthispin,simplytype:
/digital/8
Thesensorshouldanswerwiththefollowingmessage:
{"return_value":1,"id":"1","name":"","connected":true}
Ifthesensorisansweringtothequeriesatthispoint,itmeansthatitisworkingcorrectlyandthatyoucanaccessitwirelessly. AlsomakesuretoconfigureyourXBeemodulessotheyareallinthesameXBeePANID.RefertoChapter4formoreinformationonthis
topic.
WearenowgoingtotesttheWiFilampcontroller. Hereisthecodeforthismodule:
//DemooftheaRESTlibrarywiththeCC3000WiFichip
//Importrequiredlibraries
#include<Adafruit_CC3000.h>
#include<SPI.h>
#include<CC3000_MDNS.h>
#include<aREST.h>
//ThesearethepinsfortheCC3000chipifyouareusingabreakoutboard
#defineADAFRUIT_CC3000_IRQ3
#defineADAFRUIT_CC3000_VBAT5
#defineADAFRUIT_CC3000_CS10
//CreateCC3000instance
Adafruit_CC3000cc3000=Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ,ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIV2);
//CreateArduRESTinstance
aRESTrest=aREST();
//YourWiFiSSIDandpassword
#defineWLAN_SSID"yourSSID"
#defineWLAN_PASS"yourPassword"
#defineWLAN_SECURITYWLAN_SEC_WPA2
//TheporttolistenforincomingTCPconnections
#defineLISTEN_PORT80
//Serverinstance
Adafruit_CC3000_ServerrestServer(LISTEN_PORT);
//DNSresponderinstance
MDNSRespondermdns;
voidsetup(void)
{
//StartSerial
Serial.begin(115200);
//GivenameandIDtodevice
rest.set_id("2");
rest.set_name("relay_module");
//SetupCC3000andgetconnectedtothewirelessnetwork.
if(!cc3000.begin())
{
while(1);
}
if(!cc3000.connectToAP(WLAN_SSID,WLAN_PASS,WLAN_SECURITY)){
while(1);
}
while(!cc3000.checkDHCP())
{
delay(100);
}
//StartmulticastDNSresponder
if(!mdns.begin("arduino",cc3000)){
while(1);
}
//Startserver
restServer.begin();
Serial.println(F("Listeningforconnections…"));
//InitDHTsensor&outputpin
pinMode(7,OUTPUT);
}
voidloop(){
//HandleanymulticastDNSrequests
mdns.update();
//HandleRESTcalls
Adafruit_CC3000_ClientRefclient=restServer.available();
rest.handle(client);
}
Notethatforthelampcontroller,wearesimplygoingtousetherelaytoswitchthelamponandoff,andwewillnotusethedifferentsensorsoftheproject. Butyoucanintegratethemlaterinyourcentralinterfaceasanexercise.
Thecodestartsbyincludingalltherequiredlibraries:
#include<Adafruit_CC3000.h>
#include<SPI.h>
#include<CC3000_MDNS.h>
#include<aREST.h>
Anddeclaringthepinonwhichtherelaymoduleisconnected:
constintrelay_pin=8;
Then,wecreatetheinstanceoftheaRESTobjectthatwewillusetohandletherequestscomingviatheWiFiconnection:
aRESTrest=aREST();
WealsoneedtodefineonwhichportwewanttotheWiFichiptolistento. Forconvenience,wewillusetheport80,soyoucandirectlycommandyourArduinoboardfromawebbrowser:
#defineLISTEN_PORT80
WealsocreateaninstanceoftheCC3000server:
Adafruit_CC3000_ServerrestServer(LISTEN_PORT);
WealsoneedtocreateaninstanceoftheMDNSserver,sowecanaccesstheArduinoboardwithouthavingtotypetheboardIPaddresstoaccessit:
MDNSRespondermdns;
Now,inthesetup()functionofthesketch,wedeclaretherelaypinasanoutput:
pinMode(relay_pin,OUTPUT);
WecanalsosetanameandanIDforthedevice,thatwillbereturnedateachcallofthe
boardviatheRESTAPI:
rest.set_id("2");
rest.set_name("relay_module");
Afterthisstep,wesetanamefortheArduinoboardonthenetwork,forexample“arduino”. Thismeansthattheboardwillbeaccessiblebythenamearduino.localonyourlocalnetwork:
if(!mdns.begin("arduino",cc3000)){
while(1);
}
Finally,stillinthesetup()functionwestarttheCC3000serverandwaitforincomingconnections:
restServer.begin();
Serial.println(F("Listeningforconnections…"));
Intheloop()functionofthesketch,weupdatetheMDNSserver:
mdns.update();
AndprocessanyincomingconnectionusingtheaRESTlibrary:
Adafruit_CC3000_ClientRefclient=restServer.available();
rest.handle(client);
It’snowtimetotestthissketchonourproject. DownloadthecodefromtheGitHubrepository,andmakesurethatyoumodifythenameandthepasswordoftheWiFinetworkonwhichtheWiFichipwillconnectto. Then,uploadthecodetotheArduinoboard,andopentheSerialmonitor. Thisiswhatyoushouldsee:
Listeningforconnections…
Now,closetheSerialmonitor,andopenyourwebbrowser. YoucannowmakedirectcallstotheRESTAPIrunningontheboardtocontrolthepinsoftheArduinoboard. Forexample,toturnthelampon,justtype:
http://arduino.local/digital/8/1
Youshouldheartherelayswitching,thelampshouldturnonandyoushouldhaveaconfirmationmessageinsideyourbrowser:
PinD8setto1
Toswitchthelampoffagain,justtype:
http://arduino.local/digital/8/0
NotethatthecompletecodeforthissectioncanbefoundinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
7.4 BuildingtheCentralInterface
Wearenowgoingtobuildtheinterfacethatyouwillusetocontrolthewholehomeautomationsystemfromyourcomputer. Usingthisinterface,youwillbeabletocontrolthelampviaWiFi,andgetreadingsfromtheXBeemotionsensors,allfromthesamewebpage.
Notethatthispartissimilartowhatwedidinthepreviouschaptersfortheinterface. Ifyoufeelconfidentwithit,youcanskipthebeginningofthecodewalkthrough.
Asfortheotherinterfaceswedevelopedinthisbook,theinterfacewearegoingtodevelopisbasedonNode.js. First,wearegoingtocodethemainfilecalledapp.js,whichwewillrunlaterusethenodecommandinaterminal. Thisisthecompletecodeforthisfile:
//Module
varexpress=require('express');
varapp=express();
//Defineport
varport=3000;
//Viewengine
app.set('viewengine','jade');
//Setpublicfolder
app.use(express.static(__dirname+'/public'));
//Rest
varrest=require("arest")(app);
rest.addDevice('http','192.168.1.103');
rest.addDevice('xbee','/dev/tty.usbserial-A702LF8B');
//Serveinterface
app.get('/',function(req,res){
vardevices=rest.getDevices();
res.render('interface',{devices:devices});
});
//Startserver
app.listen(port);
console.log("Listeningonport"+port);
Itstartsbyimportingtheexpressmodule:
varexpress=require('express');
Then,wecreateourappbasedontheexpressframework,andthesettheportto3000:
varapp=express();
varport=3000;
Wealsoneedtotelloursoftwarewheretolookforthegraphicalinterfacefilesthatwearegoingtocodelater,andwealsodefineJadeasourdefaultviewengine:
app.use(express.static(__dirname+'/public'));
app.set('viewengine','jade');
Atthispoint,wealsoimportthenode-aRESTmodule,thatwillhandleallthecommunicationbetweentheinterface,theXBeemodules,andtheWiFichip. Here,wealsoneedtodefinetheSerialportonwhichtheXBeeexplorermoduleisconnectedto,andtheIPaddressoftheWiFichip:
varrest=require("arest")(app);
rest.addDevice('xbee','/dev/tty.usbserial-A702LF8B');
rest.addDevice('http','192.168.1.103');
Now,wearegoingtobuildthemainrouteofourserver. WedefinethisroutebylinkingtherootURLofourservertothecorrespondingJadefile. Becausewewanttobuildtheinterfaceautomaticallydependingonhowmanydevicesarepresent,weneedtogetallthedevicesfirst,andthentransmitthisdatatotheJadefilesoitcanberenderedcorrectly:
app.get('/',function(req,res){
vardevices=rest.getDevices();
res.render('interface',{devices:devices});
});
Finally,stillinthisapp.jsfile,westarttheappwiththeportwedefinedbefore,andwriteamessageintheconsole:
app.listen(port);
console.log("Listeningonport"+port);
Thiswasforthemainserverfile. Now,wearegoingtobuildtheinterfaceitself. Let’sseethecontentoftheJadefilefirst. Thisfileislocatedinthe/viewfolderofourproject. Thisisthecompletecodeforthisfile:
doctype
html
head
titleHomeAutomationSystem
link(rel='stylesheet',href='/css/interface.css')
link(rel='stylesheet',
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css")
script(src="https://code.jquery.com/jquery-2.1.1.min.js")
script(src="/js/interface.js")
body
.container
h1.text-centerHomeAutomationSystem
.row.voffset
h2LampControl
.row
.col-md-6
button.btn.btn-block.btn-primary.btn-lg#lamp1On
.col-md-6
button.btn.btn-block.btn-danger.btn-lg#lamp2Off
.row
.col-md-4
h3#powerDisplayPower:
.col-md-4
h3#lightDisplayLightlevel:
.col-md-4
h3#statusOffline
.row.voffset
h2XBeeMotionSensors
if(devices!='[]')
eachdeviceindevices
if(device.type=='xbee')
.row
.col-md-4
h3Sensor#{device.id}
.col-md-4
h3.display(id=device.id)
ThefilestartsbyimportingthedifferentJavaScriptfilesthatwillhandletheclickontheinterface,andsendthecorrectcommandstotheArduinoboard:
script(src="https://code.jquery.com/jquery-2.1.1.min.js")
script(src="/js/interface.js")
WealsousetheTwitterBootstrapframeworktogiveabetterlookatourinterface:
link(rel='stylesheet',href='/css/interface.css')
link(rel='stylesheet',
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css")
Afterthat,youcanseetwomainblocksinthisfile. ThefirstoneistocreatetwobuttonstocontrolthelampviaWiFi,andtodisplaydatafromthesensors:
.row.voffset
h2LampControl
.row
.col-md-6
button.btn.btn-block.btn-primary.btn-lg#lamp1On
.col-md-6
button.btn.btn-block.btn-danger.btn-lg#lamp2Off
.row
.col-md-4
h3#powerDisplayPower:
.col-md-4
h3#lightDisplayLightlevel:
.col-md-4
h3#statusOffline
ThesecondblockistodisplaythestatusoftheXBeemotionsensors:
if(devices!='[]')
eachdeviceindevices
if(device.type=='xbee')
.row
.col-md-4
h3Sensor#{device.id}
.col-md-4
h3.display(id=device.id)
Now,wearegoingtoseethecontentsoftheinterface.jsfile,locatedinthepublic/jsfolderoftheproject. Thisisthecompletecodeforthisfile:
$(document).ready(function(){
$.get('/devices',function(devices){
//Updatesensorsandrepeatevery5seconds
setTimeout(updateSensors,500);
setInterval(updateSensors,5000);
//Functiontocontrolthelamp
$('#lamp1').click(function(){
$.get('/'+devices[0].name+'/digital/8/1');
});
$('#lamp2').click(function(){
$.get('/'+devices[0].name+'/digital/8/0');
});
//Updatelampsensors
functionupdateSensors(){
//Updatelightlevel
$.get('/'+devices[0].name+'/light',function(json_data){
$("#lightDisplay").html("Lightlevel:"+json_data.light+"%");
//Updatestatus
if(json_data.connected==1){
$("#status").html("LampOnline");
$("#status").css("color","green");
}
else{
$("#status").html("LampOffline");
$("#status").css("color","red");
}
//Updatepower
$.get('/'+devices[0].name+'/power',function(json_data){
$("#powerDisplay").html("Power:"+json_data.power+"W");
});
});
}
//Setinputsformotionsensors
for(i=0;i<devices.length;i++){
//Getdevice
vardevice=devices[i];
//Setinput
if(device.type=='xbee'){
$.get('/'+device.name+'/mode/8/i');
}
}
setInterval(function(){
for(i=0;i<devices.length;i++){
//Getdevice
vardevice=devices[i];
//Getdata
if(device.type=='xbee'){
$.get('/'+device.name+'/digital/8',function(json_data){
//Updatedisplay
if(json_data.return_value==0){
$("#"+json_data.id).html("Nomotion");
$("#"+json_data.id).css("color","red");
}
else{
$("#"+json_data.id).html("Motiondetected");
$("#"+json_data.id).css("color","green");
}
});
}
}
},2000);
});
});
Youwillseethatthiscodebasicallycombinesthefunctionswesawinthemotionsensorschapter,andinthesmartlampchapter.
NotethatthecompletecodeforthissectioncanbefoundinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
It’snowtimetotesttheinterface. MakesurethatyoudownloadallthefilesfromtheGitHubrepository,andupdatethecodewithyourowndataifnecessary,liketheArduinoboardaddressandtheXBeeexplorerSerialport. Also,makesurethattheArduinoboardisprogrammedwiththecodewesawearlierinthischapter.
Then,gotothefolderoftheinterfacewithaterminal,andtypethefollowingcommandtoinstalltheaREST,expressandJademodules:
sudonpminstallarestexpressjade
NotethatifyouareunderWindows,youhavetoleaveoutthesudoinfrontofthecommands,anditisrecommendedtousetheNode.jscommandprompt. Finally,youcanstarttheNode.jsserverbytyping:
sudonodeapp.js
Youshouldbegreetedwiththefollowingmessageintheterminal:
Listeningonport3000
Youcannowgototheyourwebbrowser,andtype:
localhost:3000
Youshouldseetheinterfacebeingdisplayedinsideyourbrowser,withthebuttonstocontrolthelamp,thesensordatafromthelamp,andthestateoftheXBeesensors. Trytopassyourhandinfrontofoneofthesensor,theinterfaceshouldchangeaccordingly:
Youcanalsoclickononeofthebuttons,andthelampshouldturnonoroffinstantly.
Ifitisnotworkingatthispoint,thereareseveralthingsyoucancheck. First,makesurethatyoudownloadedthelatestversionofthecodefromtheGitHubrepositoryofthebook. Alsomadesurethatyoucorrectlymodifiedthefilestoputyourownsettings,liketheSerialportforyourBluetoothmodule,andtheaddressoftheWiFimodule. Finally,makesuretoinstalltherequiredNode.jsmoduleswithnpmbeforestartingthewebinterface.
7.5 HowtoGoFurther
Let’ssummarizewhatwelearnedinthisproject. WetooktheprojectwealreadybuiltinChapter4andinChapter6tobuildasmallhomeautomationsystem. WebuiltseveralXBeemotionsensors,andaWiFilampcontroller. Wetestedthesemodules,andthenintegratedeverythinginoneuniqueinterfacesowecanmonitoreverythingfromacentralplace.
Thereareofcoursemanywaystogofurtherwiththisproject. Withnearlythesamecode,youcanaddmoreWiFilampcontrollers,andalsomoreXBeemotionsensors. Youcanalsoaddmoresensorstotheproject.
Youcanalsodefinemorecomplexbehaviorsintothesystem,forexamplelinkingthemeasurementofthemotionsensortotheactivationoftherelay. Iftheyarelocatedinthesameroom,youcansetthesystemsotherelayautomaticallyturnsonwhenmotionisdetectedintheroom(forexampleintoilets).
Notethatitisnotrecommendedtomixmanywirelessmodulesinthesamesystem. Forexample,itisbettertouseWiFiforeveryactuators(relays),andXBeeforeverysensors(motion,temperature,humidity…).
Chapter8
Conclusion
8.1 Whatdidyoulearninthisbook?
Wearealreadyclosetotheendofthisbook,andIreallyhopedyouenjoyedreadingitasmuchasIenjoyedwritingitandrealizingalltheprojectscontainedinthebook. Let’ssummarizeeverythingyouhavelearnedbyreadingthisbook.
Inthefirstpartofthebook,wesawhowtointerfacesensorsandothercomponentswiththeArduinoplatformtobuildhomeautomationsystems.
Intheveryfirstchapter,youlearnedthebasicsoftheArduinoplatform,andyoualsolearnedhowyoucouldusethisplatformforhomeautomationprojects. WealsobuiltourveryfirsthomeautomationsystemwithArduino:asimplemotionsensorconnectedtoanalarm.
Thenextchapterwasallaboutlearningthebasicsofatypicalhomeautomationproject:howtomeasuredatafromsensorsusingArduino,andhowtodisplaytheseresultsonaLCDscreen.
Then,youlearnedhowtocontrolalampusingArduino. Weusedarelaytocontrolthislampatwill,andalsousedanothercomponenttoautomaticallymeasurethecurrent&powerconsumptionofthislamp. Wealsointegratedalightlevelsensortotheproject,sowecouldprogramthelamptoautomaticallyswitchonwhenthenightapproaches.
Afterthat,inthesecondpartofthebook,weusedwhatwelearnedinthefirstparttobuildwirelesshomeautomationsystemsbasedonArduino.
First,wetookthemotionsensorprojectthatwedevelopedearlierinthebook,andmonitoredthemotionsensorswirelesslyusingtheXBeetechnology. Withthisnewhardware,webuiltanarrayofmotionsensorsthatcanbedeployedinyourhome,andwemonitoredthemusingacentralinterfaceonyourcomputer.
Weusedthesameconcepttoaddwirelesscapabilitiestothetemperature,humidityandlightlevelsmeasurementproject. WeaddedaBluetoothmoduletotheproject,andwewereabletomonitorthemeasureddatafromawebbrowser.
Inthenextchapter,weaddedWiFitothelampcontrolproject,andwereabletocontrolalamp&monitoritsenergyconsumptionremotely. BecauseweusedWiFitodoso,wewerealsoabletocontrolthelampdirectlyfromasmartphoneortablet.
Finally,inthelastchapterofthebook,weusedeverythingwelearnedinthebooktobuildanhomeautomationsystembasedonseveralXBeemotionsensors&aWiFi-controlled
lamp. Wealsointegratedeverythingintoacentralsoftware,soyoucanmonitor&controlyourhomefromasingleinterface.
Ofcourse,throughthisentirebookyoudidn’tlearnonlyaboutArduinoandhomeautomation. YoualsoacquiredsolidknowledgeaboutotherprogramminglanguageslikeJavaScriptandHTML,whichcanbeusefulinmanyotherdomains.
8.2 Howtogofurther?
WithalltheknowledgeyouacquiredinthisbookabouttheArduinoplatformandhomeautomation,itisnowtimetogofurtherandbuildyourownhomeautomationsystems.Buttheessentialquestionis:howtostart?
Ifyou’renot100%confidentaboutyourskillsyet,thefirststepisreallytogothroughalltheprojectsofthisbookandtrytodothemagainyourselfwithoutthehelpofthebook.Thatwillreallygiveyoutheskillsandconfidencetobuildmoreprojects.
Mysecondadviceistostartsmall. Istheresomeprojectinyourhomeyoualwayswantedtodoandthatyoucouldn’tdobecausealackofskills? Nowisagoodtimetodoit. Butdon’tstartbydesigningandbuildingacompletesecuritysystemforyourhome! StartbyconnectingasensortoArduinotodetectifadoorisopenedforexample. Thenaddothersensors. Whenthisisworking,addaLCDscreenandsomebuttonstohaveabasicinterface. Thenconnectittoyourcomputerusingwhatyou’velearnedinthisbook. Andsoonenough,youwillhaveyourwholesecuritysystem.
Mylastadviceforyou:havefun! Ifyouchosetofollowtheprojectsofthisbook,itisprobablythatyouareinterestedinbuildingyourownhomeautomationsystemsinsteadofbuyingcommercialones,mainlybecauseyouareinterestedinexperimentingandhavingcontroloveryourinstallation. Andthebestwaytobuildbettersystemsistohavefundoingit. Itdoesn’tmatterifwhatyoubuiltisnotperfectthefirsttime:taketimetoexperiment,adjust,andplaywithwhatyoubuild. Thiswillboostyourconfidence,makeyouhappyandpushyoutoexperimentwithmoreandmorecomplexsystems.
Iwillfinishthisbookwithanopeningtothefutureofhomeautomationusingopen-sourcehardware. Iseemanytrendsinthefuturefromwhichthehomeautomationdomaincanreallybenefit.
Thefirstone,whichisamajortrendatthemomentthisbookwaswritten,is3Dprinting.Forthosewhodon’tknowwhat3Dprintingis,it’ssimplyatechniqueofbuildingobjectsby“printing”themlayer-by-layer. Thecoreofa3Dprinterisaprintingheadthatcanalsomoveupanddowniscontrolledbyaprocessortobuildtheexactreplicaofa3Dobjectthathasbeendesignedonacomputer. Thistechniqueallowsrapidprototypingofsmallobjectsandisalreadyusedbydesignerstoreducethetimetodevelopanewproduct.Comparedtotypicalfabricationtechniqueslikeinjectionmolding,3Dprintingismuchbettertoprototypesmallobjectsasitischeaperandthemachinecanstandonyourdesk.
Now,whatdoesitmeanforhomeautomationenthusiasts? Well,Ibelieveitwillbearealgamechangerinthefuture. Withwhatwesawinthisbook,youcanbuildabasicalarmsystemforyourhomethathavethesamefunctionalitiescomparedtoanalarmsystemthatyouwouldhaveboughtinastore. However,itstilllackssomethingcomparedtothecommercialsystem:youdon’thavethenicedesignoftheplasticprotectionandcasesthatcomeswiththecommercialsystem. Itisfineforprototypingandplayingaround,butitisnotniceifyouwanttobuildalongerlastinghomeautomationsystem.
AndIbelieve3Dprintingcanchangethat. Before,nobodycoulddesignhisorherowncasesforanalarmsystemorasensor. Youneededtobuildamold,whichwasveryexpensive,andthengotoafactorytobuildthepiecesforyoursystem. Butnowwe3Dprinting,itbecomespossible. Youcandesignthepartsonyourcomputer,andhavethembuiltonebyonebya3Dprinter,withareallylimitedcost. Therearemoreandmorespacesintheworldwhereyoucan“rent”a3Dprinterforalimitedamountoftimetoprintyourdesigns. Oneexampleisthefablabs,whereyoucanfindallsortoftoolstobuildobjects. Youcanfindalistoffabsatthisaddress:
http://fab.cba.mit.edu/about/labs/
Withthiskindoftechnologies,youcanreallybuildhomeautomationsystemsthatlookasprofessionalascommercialsystems.
AnothertrendIamcurrentlyseeingistheavailabilityofmoreconnectedobjects. ThistrendisusuallydenotedastheInternetofThings(IoT),whichsaysthatallobjectsinourhomeandeveninourlifeingeneralwillendupbeingconnectedtotheInternet. Westilllackthehardwareandanopenprotocoltostandardizeeverything,butthisisdefinitelysomethingwehearaboutmoreandmoreinthecomingyears.
Fortheworldofhomeautomationusingopen-sourcecomponents,thiswillalsohaveanimpact. Itisstillcomplicatedtoconnectanobject,forexampleasensor,totheweb,asyouhavetouseadedicatedshieldforArduinoforexample. However,moreandmoreboardsbasedontheArduinoplatformarecomingwithbuilt-inconnectivity. Andatthetimethisbookwaswritten,Arduinoactuallyhasseveralboardswithbuilt-inWiFiconnectivity,liketheArduinoYun. Ibelievethatwiththiskindofconnectedboards,itwillbeeasierandeasiertobuildconnectedhomeautomationsystemsthatintegratewithotherdevicesseamlessly.
Chapter9
ResourcesThefollowingisalistofthebestressourcesconcerningopen-sourcehomeautomationwithArduino. Iorganizedthischapterindifferentcategoriessoitiseasierforyoutofindtheinformationyouneed.
9.1 GeneralInformationaboutArduino
OpenHomeAutomation:Thecompanionwebsiteofthisbook,whereyouwillfindmanymoreprojectsusingArduino&open-sourcehardwaretobuildhomeautomationprojects.Arduino:thereferencewebsiteoftheArduinoplatform. EspeciallygoovertotheirfantasticforumstofindhelponyourArduinorelatedprojects.Instructables:Awebsitecontainingstep-by-stepprojects. Searchtherefor“Arduino”or“Homeautomation”andyouwillfindalotofexcitingprojects.AdafruitLearningSystem:Anonlinelearningplatformwithaselectionofhigh-qualitystep-by-steparticlesonmakingthingsingeneral. ManyprojectsusetheArduinoplatform,andsomeareabouthomeautomation.
9.2 Components
SparkFun:AwebsitesellingmanyArduinorelatedproducts. Alltheirproductsareopen-sourceandyoucandownloadthesourcefilesdirectlyfromtheirproductdescriptions.Adafruit:AcompanybasedinNewYorkthatsellshighqualityproductsfortheArduinoplatform.SeeedStudio:AChinesecompanythatsellsmanyoriginalproductsfortheArduinoplatform. TheyalsooffertheirownPCBproduction&assemblyservices.
9.3 SuggestedReading
ProgrammingArduino:GettingStartedWithSketches:WrittenbySimonMonk,thisbookisaveryclearandpracticalintroductiontoArduino.ArduinoWorkshop:AHands-OnIntroduction:Awell-writtenbookwithmanysimpleprojectstolearnabouttheArduinoplatform.ArduinoCookbook:WrittenbyMichaelMargolis,thebookisanexcellentin-depthresourceabouttheArduinoplatform.
TableofContents
FrontmatterChapter1Chapter2Chapter3Chapter4Chapter5Chapter6Chapter7Chapter8Chapter9
Recommended