Date post: | 02-Nov-2015 |
Category: |
Documents |
Upload: | anonymous-fosu0re95j |
View: | 54 times |
Download: | 0 times |
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
LegalCopyright2014byMarc-OlivierSchwartz
Allrightsreserved. Nopartofthisbookmaybeusedorreproducedinanymannerwhatsoeverwithoutpermissionexceptinthecaseofbriefquotationsembodiedincriticalarticlesorreviews.
ThirdeBookedition:August2014
AcknowledgmentsToallmyfriendswhoencouragedmewhilewritingthisbookandworkingonallmyprojects.
Tomyparentswhosupportedmewhilewritingthisbook,andwhosupportedmeduringalltheotherprojectsImadeinmylife,evenintoughtimes.
TomygirlfriendSylwiaforsupportingmeandencouragingmeineverythingIdo. YouaremysourceofinspirationIneedtogetupeverydayandcontinuetoworkhardtobecomeabetterentrepreneurandabetterperson. Thankyou.
AbouttheauthorIamMarcoSchwartz,andIamanelectricalengineer,entrepreneurandauthor. IhaveaMastersdegreeinElectricalEngineering&ComputerSciencefromoneofthetopElectricalEngineeringschoolinFrance,andaMastersdegreeinMicroEngineeringfromtheEPFLuniversityinSwitzerland.
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:youdonthaveanycontrolofthem.Youhavetofolloweverythingthemanufacturerhasdecidedforyou:themaincontroller,thesensors,thesoftware. Forexample,ifonesensorisfailinginyoursystem,youhavetoreplaceitwithasensorfromthesamebrand. IrememberwhenIwasusingoneofthesecommercialsystemsatafriendshouse. Ialwayswantedtochangesomething:makeasensoreasiertouse,fixabugintheinterfacebutIcouldnt.
Ofcourse,theideaofbuildingyourownhomeautomationsystemhasalwaysbeenaround. Irememberplayingwithmyfirstmicrocontrollerin2003,anditwasactuallyquiteeasyifyouwereintheengineeringworld. 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. Ithinkthisisdefinitelybetterthanaonefits-allsolutionwhereIwouldhavetaughtyouhowtobuildaspecifichomeautomationsystem. 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,butthisissomethingwewonttouchinthisbook.
Thereareseveraladvantagesofthisopen-sourceapproachforhardwaresystems. Thefirstoneisthatitallowspeopletohavealookintothehardwaresystemsthemselves,andunderstandwhythehardwaresystemtheyareusingisworkingalongwiththeopen-sourcesoftwarethatusuallycomeswithit. Butthemainadvantageformeisthatitallowspeopletomodifythehardwaresystemsandthensharethemagainwiththecommunity. Thisproducesamuchfasterdevelopmentprocessforhardwareproductsasitreallyengagestheusersandcreatescommunitiesaroundagivenhardwareproduct.
AndthisispreciselywhyIputopen-sourceatthecoreofthisbookandofthecompanionwebsite:becauseyoucanaccessthesourcesofalltheprojectsfoundinthisbook,youwillbeabletounderstandthemdeeply,modifythem,makethembetter,andthensharethemagainwiththecommunity. WhatIreallydidntwantwastospeakabouthomeautomationbyjustpreachingmyownvision;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.
Dontworry. Youcanlearnabouthomeautomation&Arduinoandcompletealloftheprojectsfoundinthisbookwithouteverconnectingyoursystemstothepowerpluginyourwall,butifyouactuallywanttoinstallsomeofthesedevicesinyourhomeIreallyadvisereadingthissectioncarefully.
Itisusuallyacceptedthatanythingabove50Visdangerous,and25Visusuallytakenasasafevalue.
Forus,itmeansthatmostcircuitswillbesafe(Arduinooperatesat5Vor3.3V),theonlythingwherewewillhavetobecarefuliswhenconnectingsomepartofyourcircuittothemainselectricity(whichisat110VintheUSor230VinEurope,forexample).
Therisksofbeingindirectcontactwithavoltageabove50Vareveryhigh,andtheconsequencesincludeventricularfibrillation,cardiacarrest,respiratoryarrest,andseriousburns,allpossiblyleadingtodeath.
Itisactuallynotthatdifficulttoavoidriskswhenworkingwithhighvoltages. Thefirstone,whichseemsquiteevident,istoalwaysworkwiththecircuitbeingoff,andtobefarfromitwhenthecircuitisinoperation. Alsokeepinmindthatsomethinginsidethecircuitcouldhavebrokendownandtouchedthecaseofyourdevice,sodonttouchanythingwhenthecircuitisinoperation.
Alsomakesurethatthecircuitisde-energizedbeforetouchingit. Indeed,somehigh-voltagecircuitscancontaincomponentslikecapacitorsthatstoreenergyevenifthepowerhasbeenshutdown. However,youwontfindsuchcircuitsinthisbook.
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. Alloftheprojectswilluseabreadboardforrapidprototypingsoyoudonthavetosolderanything.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-propertiessudoapt-add-repositoryppa:chris-lea/node.jssudoapt-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,wedontneedthatmuchpower,andwewillonlyusethemostcommonArduinoboard:theArduinoUno.
OnecharacteristicofArduinoboardsisthattheirpinsarealwaysexposedinasimilarfashion,whichmeansthatitisveryeasytopluginextensions,calledshields,directlyintotheboards. Theseshieldscanaddvariousfunctionalitiestotheboard,liketheabilitytocontrolDCmotorsforroboticsapplications,ortoconnectwirelesslytoyourphoneviaBluetooth.
Butforme,itsreallythesoftwarepartthatmakestheArduinoplatformsopowerful. ToprogramanArduinoboard,youcanusetheofficialArduinosoftware(whichistotallyfreetodownload)andthenusealanguageclosetoC++toactuallywritethecodethatyouwilluploadtotheboard. Comparedtoothermicrocontrollers,believeme,itisveryeasytoprogramtheboardtomakeitdowhatwewant. Forexample,asimpleinstructionlikemakinganLEDlightuponlytakesasinglelineofcodewithanArduinoboard,whereasitwouldtakemanylineswithothermicrocontrollers.
AnotherimportantpointisthatthereisalsoahugecommunityaroundtheArduinoplatform. ThismeansthateveryfunctionuseisreallywelldocumentedontheofficialArduinowebsite(www.arduino.cc). Youwillalsofindtutorialsformostofthecommonlyusedfunctionsoftheboard.
Iwillnowgiveyouabitmoredetailabouttheboardthatwewillbeusinginthisbook:theArduinoUno. HereisapictureoftheboardIpersonallyusedforalltheprojectsin
thisbook:
Theboarditselfisverytiny. WhatyoucanseeonthelowerrightportionofthepictureisanAtmelmicrocontroller,thebrainoftheboard. 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,letsjustidentifythecomponentswhichareusuallyfoundinmanycircuits.
Whenreadingacircuit,youshouldfirstlocatethepowerandgroundpins. Here,thepowerisrepresentedbytheVCCpin,whichwillusuallybeequalto5Vintheprojectsfoundinthisbook. ThegroundpinhereisrepresentedbyGND.
AfterVCCandGND,youcanlookforthecomponents. Here,wesimplyhavearesistorandanLED.
Powersources
Inthefirstcircuitofthissection,thepowersourcewasapinnamedVCC. 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,currentandresistanceiscalledOhmslaw:V=R*I.
LEDs
LEDs,shortforLightEmittingDiodes,arethemostcommonlyusedcomponentsforsignalingandtestinginacircuit. Whencurrent(usuallyabout20mA)isgoingthroughanLED,theyemitlight,whichcanbered,blue,greenorevenwhite,dependingontheLED.
OntheArduinoboardforexample,LEDsareusedtomakesuretheboardison,toindicatethataserialcommunicationisactuallyhappeningorasatestcomponentforsoftware(onpinnumber13).
Asshowninthefirstcircuitofthissection,LEDsareusuallyassociatedwithresistorstolimitthecurrentthatflowsthroughthem. Beware,thepinsofanLEDarenotequalthepositivepowersupply(forexample,VCC)hastogoontheleftsideoftheLEDcalledtheanode,andtheotherpin,calledthecathode,hastobeconnectedtotheground. Youcaneasilyidentifythecathodeasittheonewiththeshorterlead.
Relays
Inhomeautomation,wewanttoswitchthingslikelampsonandoffasyouwoulddowhenyoupressalightswitchonthewall. Thisisdoneusingrelays,whichbasicallyareelectromechanicalswitches.
Therearetwoprimarypartsinarelay. Theleftpartofthesymbolisthecoil,andisthecontrolpartoftherelay. 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;
//Alarmbooleanalarm_mode=false;
//VariablesfortheflashingLDEDintledState=LOW;longpreviousMillis=0;longinterval=100;//Intervalatwhichtoblink(milliseconds)
voidsetup(){//SetpinstooutputpinMode(led_pin,OUTPUT);pinMode(alarm_pin,OUTPUT);//Waitbeforestartingthealarmdelay(5000);}
voidloop(){//Motiondetected?if(digitalRead(motion_pin)){alarm_mode=true;}
//Ifalarmmodeison,flashtheLEDandmakethealarmringif(alarm_mode){unsignedlongcurrentMillis=millis();if(currentMillis-previousMillis>interval){previousMillis=currentMillis;if(ledState==LOW)ledState=HIGH;elseledState=LOW;//SwitchtheLEDdigitalWrite(led_pin,ledState);}tone(alarm_pin,1000);}}
Letsnowseethedetailsofthiscode. 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,sothealarmdoesntturnonrightaway:
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;elseledState=LOW;//SwitchtheLEDdigitalWrite(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
//DHTinstanceDHTdht(DHTPIN,DHTTYPE);
voidsetup(){//InitializetheSerialportSerial.begin(9600);//InitDHTdht.begin();}
voidloop(){//MeasurefromDHTfloattemperature=dht.readTemperature();floathumidity=dht.readHumidity();//Measurelightlevelfloatsensor_reading=analogRead(A0);floatlight=sensor_reading/1024*100;//DisplaytemperatureSerial.print("Temperature:");Serial.print((int)temperature);Serial.println("C");//DisplayhumiditySerial.print("Humidity:");Serial.print(humidity);Serial.println("%");//DisplaylightlevelSerial.print("Light:");Serial.print(light);Serial.println("%");Serial.println("");//Wait500msdelay(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
ItsnowtimetotestthisfirstArduinosketch. UploadthecodetotheArduinoboardand
opentheSerialmonitorinsidetheArduinoIDE(makingsuretheSerialspeedissetto9600). Thisiswhatyoushouldsee:
Temperature:25CHumidity: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#include#include"DHT.h"
//DHTsensor#defineDHTPIN7#defineDHTTYPEDHT11
//LCDdisplayinstanceLiquidCrystal_I2Clcd(0x27,20,4);
//DHTinstanceDHTdht(DHTPIN,DHTTYPE);
voidsetup(){//Initializethelcdlcd.init();//PrintamessagetotheLCD.lcd.backlight();lcd.setCursor(1,0);lcd.print("Hello!");lcd.setCursor(1,1);lcd.print("Initializing");//InitDHTdht.begin();//ClearLCDdelay(2000);lcd.clear();}
voidloop(){//MeasurefromDHTfloattemperature=dht.readTemperature();floathumidity=dht.readHumidity();//Measurelightlevelfloatsensor_reading=analogRead(A0);floatlight=sensor_reading/1024*100;//Displaytemperaturelcd.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("%");//Displaylightlevellcd.setCursor(1,2);lcd.print("Light:");lcd.print(light);lcd.print("%");//Wait100msdelay(100);}
ItstartsbyincludingtherequiredlibrariesfortheLCDscreenandtheDHTsensor:
#include#include#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("%");
IfyoudonthaveathirdlineavailableonyourLCDscreen,youhaveseveraloptions. Forexample,youcanjustintroducesomedelay,clearthescreenagain,andprintoutthelightlevelonthefirstline.
Wealsointroducea100msdelaybetweeneachsetofmeasurementsandrefreshoftheLCDscreen:
delay(100);
NotethatthecompletecodeforthischaptercanbefoundinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-arduino
Itsnowtimetotesttheproject. UploadthecodeagaintoyourArduinoboardandwaitforsometime. YoushouldbeabletoseetheLCDprintingthewelcomemessagebeforemovingontodisplaythemeasurements. Hereisapictureoftheprojectinaction:
Ifitdoesntwork,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
Letsnowassemblethehardwareforthisproject. 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//Relaypinconstintrelay_pin=8;
voidsetup(){pinMode(relay_pin,OUTPUT);}
voidloop(){//ActivaterelaydigitalWrite(relay_pin,HIGH);//Waitfor5secondsdelay(5000);//DeactivaterelaydigitalWrite(relay_pin,LOW);//Waitfor5secondsdelay(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
Itsnowtimetotestthesketch. Makesurethatthelampiscorrectlyconnectedtotheproject,andthatthemaleplugispluggedintothepowersocketinthewall. Then,uploadtheArduinosketchtotheboard. Youshouldseethatevery5seconds,therelayisswitching,turningthelamponandoff.
Besuretofixtherelayinapositionsuchthatitcannotbetouchedbyaccident.
3.4 PowerMeasurements&AutomaticLightingControl
Letsnowmovetothemainpartoftheproject:buildingtheArduinosketchforoursmartlamp. Webasicallyneedtocontinuouslymeasurethelightlevelandthecurrentconsumptionofthelamp,printthisdataontheLCDscreen,andchangethestateoftherelayaccordingly. Hereisthecompletecodeforthispart:
//Codeforthesmartlampproject
//Libraries#include#include
//Relaystateconstintrelay_pin=8;booleanrelay_state=false;
//LCDdisplayinstanceLiquidCrystal_I2Clcd(0x27,20,4);
//Definemeasurementvariablesfloatamplitude_current;floateffective_value;floateffective_voltage=230;//Setvoltageto230V(Europe)or110V(US)floateffective_power;floatzero_sensor;
voidsetup(){//Initializethelcdlcd.init();//PrintamessagetotheLCD.lcd.backlight();lcd.setCursor(1,0);lcd.print("Hello!");lcd.setCursor(1,1);lcd.print("Initializing");//SetrelaypintooutputpinMode(relay_pin,OUTPUT);//Calibratesensorwithnullcurrentzero_sensor=getSensorValue(A1);//ClearLCDdelay(2000);lcd.clear();}
voidloop(){//Measurelightlevelfloatsensor_reading=analogRead(A0);floatlight=(sensor_reading/1024*100);//Performpowermeasurementfloatsensor_value=getSensorValue(A1);//Converttocurrentamplitude_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%,switchthelightsoffif(light>75){digitalWrite(relay_pin,LOW);relay_state=false;}//Ifthelightlevelislessthan50%,switchthelightsoffif(light