Arduino networking marco schwartz

187

Transcript of Arduino networking marco schwartz

Page 1: Arduino networking   marco schwartz
Page 2: Arduino networking   marco schwartz
Page 3: Arduino networking   marco schwartz

ArduinoNetworking

Page 4: Arduino networking   marco schwartz

TableofContents

ArduinoNetworking

Credits

AbouttheAuthor

AbouttheReviewers

www.PacktPub.com

Supportfiles,eBooks,discountoffers,andmore

Whysubscribe?

FreeaccessforPacktaccountholders

Preface

Whatthisbookcovers

Whatyouneedforthisbook

Whothisbookisfor

Conventions

Readerfeedback

Customersupport

Downloadingtheexamplecode

Errata

Piracy

Questions

1.DiscovertheArduinoEthernetShield

Hardwareandsoftwarerequirements

Hardwareconfiguration

Testingyourconnection

Summary

2.SendingDatatoaWebServer

Hardwareandsoftwarerequirements

Hardwareconfiguration

Sendingdatatoaserver

Logincomingdatainadatabase

Page 5: Arduino networking   marco schwartz

Displayingtheresults

Summary

3.DataLoggingStation

Hardwareandsoftwarerequirements

Hardwareconfiguration

LoggingdataonanSDcard

CreatingawebserveronArduino

Plottingthedatalocally

Summary

4.ControllingObjectsfromAnywhere

Hardwareandsoftwarerequirements

Hardwareconfiguration

Testingtherelay

Controllingtherelayremotely

Controllingtherelayfromanywhere

Summary

5.InternetofThingswithXively

Hardwareandsoftwarerequirements

Hardwareconfiguration

CreatingyourXivelyaccount

SendingdatatoXively

Visualizingtherecordeddata

Summary

6.LoggingDatainGoogleDocs

Hardwareandsoftwarerequirements

Hardwareconfiguration

SettingupyourGoogleAccount

CreatingyourTembooaccount

Loggingdatainaspreadsheet

Sendingautomatede-mails

Summary

Page 6: Arduino networking   marco schwartz

Index

Page 7: Arduino networking   marco schwartz
Page 8: Arduino networking   marco schwartz

ArduinoNetworking

Page 9: Arduino networking   marco schwartz
Page 10: Arduino networking   marco schwartz

ArduinoNetworkingCopyright©2014PacktPublishing

Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.

Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.

PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.

Firstpublished:August2014

Productionreference:1140814

PublishedbyPacktPublishingLtd.

LiveryPlace

35LiveryStreet

BirminghamB32PB,UK.

ISBN978-1-78398-686-6

www.packtpub.com

CoverimagebyPratyushMohanta(<[email protected]>)

Page 11: Arduino networking   marco schwartz
Page 12: Arduino networking   marco schwartz

CreditsAuthor

MarcoSchwartz

Reviewers

C.M.Banas

RyanDunn

PhillipMayhew

TomO’Connor

KrisjanisRijnieks

CommissioningEditor

PramilaBalan

AcquisitionEditor

HarshaBharwani

ContentDevelopmentEditor

SumeetSawant

TechnicalEditors

KunalAnilGaikwad

SiddhiRane

CopyEditors

MradulaHegde

AdithiShetty

ProjectCoordinator

DanutaJones

Proofreader

AmeeshaGreen

Indexer

RekhaNair

ProductionCoordinator

MelwynD’sa

CoverWork

MelwynD’sa

Page 13: Arduino networking   marco schwartz
Page 14: Arduino networking   marco schwartz
Page 15: Arduino networking   marco schwartz

AbouttheAuthorMarcoSchwartzisanelectricalengineer,entrepreneur,andblogger.HehasaMaster’sdegreeinElectricalEngineeringandComputerSciencefromSUPELECinFrance,andaMaster’sdegreeinMicroengineeringfromEPFLinSwitzerland.

Hehasmorethan5yearsofexperienceworkinginthedomainofelectricalengineering.Hisinterestsgravitatearoundelectronics,homeautomation,theArduinoandtheRaspberryPiplatforms,opensourcehardwareprojects,and3Dprinting.

HerunsseveralwebsitesaroundArduino,includingtheOpenHomeAutomationwebsite(http://www.openhomeautomation.net/),whichisdedicatedtobuildinghomeautomationsystemsusingopensourcehardware.

Hehaswrittenanotherbook,HomeAutomationwithArduino,AmazonDigitalServices,Inc.,whichisaself-publishedKindlebook.HehasalsowrittenabookonhowtobuildInternetofThingsprojectswithArduinocalledInternetofThingswiththeArduinoYun,PacktPublishing.

Page 16: Arduino networking   marco schwartz
Page 17: Arduino networking   marco schwartz

AbouttheReviewersRyanDunnisasolutionsarchitect,whospecializesinwebtechnologiesandenterprise-leveldeployments.HecurrentlylivesinSouthernKansasCity,KS.

HeholdsaBachelor’sdegreeinComputerSciencefromKansasStateUniversityandaMaster’sdegreeinBusinessAdministrationfromtheUniversityofKansas.Hehasworkedforavarietyoforganizations,withhiscareerspanninganumberofindustries,includinge-commerce,digitalmarketing,SEO,education,security,andmobile.

Hehasbeenworkingwithwebtechnologiesforover10years,andduringthistime,hehasalwaysretainedanagnosticapproachtothetechnology,whichhasresultedinawiderangeofexperience.Asasolutionsarchitect,hemanageseveryaspectofsolutiondeployments,includinganalysis,networkarchitecture,systemarchitecture,creativedesign,anddevelopment.

Ihaveawife,Crystal,andtwochildren.Asaresultoftheirsupport,Ihavebeenabletopursuemypassionfortechnologyandamforevergratefulforalltheirlove.

PhillipMayhewhasaBachelorofSciencedegreeinComputerSciencefromNorthCarolinaStateUniversity.HeisthefounderandmanagingprincipalofRextencyTechnologiesLLC,whichisbasedinStatesville,NorthCarolina.Hisprimaryexpertiseliesinsoftwareapplicationperformancetestingandmonitoring.

TomO’ConnorisanexperiencedsystemsarchitectandDevOpsengineer.HelivesintheWestMidlandsintheUnitedKingdom.Overthelast8years,hehasworkedforawidevarietyofcompanies,frome-commercetovideoeffects,andnowistheownerofthecompanyhefounded,whichprovidessystemsconsultancyforwirelessnetworkdesignandinstallations.

Hewritesatechnicalblogonhiswebsitethatprovidesbothtutorialarticlesandupdatesonwhathe’sbeenworkingon.Hehaswide-reachingskillsandexperiencegatheredoverthelast10yearsofworkingonWindows,Linux,andUnixsystemsformostofthattime,coupledwithrecentexperienceindesigningandbuildinghigh-performancecomputersystems.

HeisalsoanactivememberoftheUKDevOpscommunityaswellasacommunitymoderatoronwww.serverfault.com,wherehedemonstrateshisexpertiseandskillstoawideaudience.

KrisjanisRijnieksisadigitalinteractivemediaprofessionalworkingwithprojectsthatinvolvegraphicdesign,animation,userinterfacedesign,projectionmapping,programming,andelectronics.Theoutcomeofhisprojectsusuallyarewebsites,games,andhardwareprototypesorinteractiveinstallations.Healsorunsworkshopsinthefieldofcreativecodingandprojectionmapping.Oneofhismostinterestingcurrentprojectsisthedevelopmentofanopenframeworksadd-onforprojectionmappingontheRaspberryPi—ofxPiMapper.

HeisalsoanMAstudentattheMediaLabHelsinki(AaltoUniversitySchoolofArts,

Page 18: Arduino networking   marco schwartz

DesignandArchitecture),andheiscurrentlyworkingonhismasterthesis,whichisrelatedtotheofxPiMapperprojectionmappingsoftwareproject.

KrisjanisrunsasmalldigitalmediacompanyCodeBark(www.codebark.com)withhiscolleague,IrinaSpicaka.Together,theyalsodevelopedaplatformcalledCreativeCodingforLiveAudioandVisuals(www.cc4av.info),whichactsasaplaceholderfordifferenteventsandworkshopsrelatedtoelectronicaudiovisualculture.

HeisalsocollaboratingwiththeFabLab,Berlin,andthisiswherehespendsmostofhistimewheninBerlin.

Cinder–BeginCreativeCoding,PacktPublishing,isthefirstbookthathehasworkedon.It’sanintroductiontoCinder,theC++creativecodingframework,(similartoopenFrameworks)andcontainstutorialstogetyoustartedwithCinderasfastandpainlessaspossible.

Page 19: Arduino networking   marco schwartz
Page 20: Arduino networking   marco schwartz

www.PacktPub.com

Page 21: Arduino networking   marco schwartz

Supportfiles,eBooks,discountoffers,andmoreYoumightwanttovisitwww.PacktPub.comforsupportfilesanddownloadsrelatedtoyourbook.

DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<[email protected]>formoredetails.

Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.

http://PacktLib.PacktPub.com

DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigitalbooklibrary.Here,youcanaccess,read,andsearchacrossPackt’sentirelibraryofbooks.

Page 22: Arduino networking   marco schwartz

Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviawebbrowser

Page 23: Arduino networking   marco schwartz

FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandviewnineentirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.

Page 24: Arduino networking   marco schwartz
Page 25: Arduino networking   marco schwartz

PrefaceArduinoisanamazingplatformtoquicklycreateexcitingelectronicsprojects.UsingtheArduinoplatform,evennon-expertscanconnectsensors,actuators,anddisplaystogetherandbuildcomplexprojectsthatprovideimmediateapplicationsforeverydaylife.

However,theseprojectsareevenbetterwhentheyareconnected,meaningtheyhavesomewaytocommunicatewithotherdevices,andnotnecessarilywithotherArduinoboards.TherearemanywaystoconnectArduinoprojectstogetherandtootherdevicessuchascomputers:WiFi,XBee,Bluetooth,andEthernet.ThisbookwillfocusentirelyonhowtocreateamazingprojectsusingthislatesttechnologytoconnectArduinoprojects.

UsingEthernethasseveraladvantagesoverwirelesssolutions:itisfast,cheap,andyouwillfindplentyofhelponthesubjectontheInternet.Forme,themostimportantthingisthattheEthernetlibraryforArduinoisverywelldocumented,andcomesbuilt-inwiththeArduinosoftware.It’shardwarecounterpart,theArduinoEthernetshield,isalsoverywellbuiltandwellsupportedbytheArduinocommunity.

Inthisbook,wearegoingtoseehowtousetheEthernetshieldandtheEthernetlibraryviasixexcitingprojects.WearegoingtostartwiththeverybasicsandseehowtoconnecttheEthernetshieldtoyourlocalnetworkandtheWeb.Then,wewillsenddatafromtheEthernetshieldtoaserverlocatedonyourlocalnetwork.Finally,wewillintegratetheEthernetshieldinan“InternetofThings”framework,bybuildingseveralprojectsconnecteddirectlytotheWeb.

Page 26: Arduino networking   marco schwartz

WhatthisbookcoversChapter1,DiscovertheArduinoEthernetShield,introducestheArduinoEthernetshieldbyshowingyouhowtosetupeverythingsoyoucaneasilybuildmoreexcitingapplicationsinthenextchapters.WearegoingtoconnecttheEthernetshieldtoyourrouter,andmakesurethatitcanaccesstheWeb.

Chapter2,SendingDatatoaWebServer,explainshowtoconnectatemperatureandhumiditysensortoyourArduinoboardandusetheEthernetshieldtosendthisdatacontinuouslytoawebserverrunningonyourcomputer.Wewillalsoplotthisdatainrealtimeonthewebserversothatyoucanvisualizeitinyourbrowser.

Chapter3,DataLoggingStation,usesthesamehardwareasinthepreviouschapter,butwewillmaketheArduinoEthernetmoreindependent.WewilllogthedatameasuredbytheboardlocallyonanSDcard,andalsocreateawebserverontheEthernetshieldsothatitcanbeaccessedfromanydeviceinyourlocalnetwork.

Chapter4,ControllingObjectsfromAnywhere,covershowtoconnectarelaymoduletoourArduinoandEthernetshieldhardwaresothatitcanbecontrolledviathenetwork.Wearefirstgoingtocontrolthisrelaymodulefromwithinyourlocalnetwork,andthenuseadedicatedservicetobeabletocontrolthisrelayfromanywhere.Asanexample,wearealsogoingtoconnectalamptothisrelaymodule.

Chapter5,InternetofThingswithXively,continueswithcloud-connectedprojectsbyinterfacingtheEthernetshieldwithacloudservicecalledXively.Usingthisservice,wewillbeabletosendthedatameasuredbyourprojecttotheWebandmonitoritinrealtimefromtheXivelywebsite,fromanywhereintheworld.

Chapter6,LoggingDatainGoogleDocs,usesthewebserviceTembootointerfacetheEthernetshieldwithevenmorewebservicessuchasGoogleDocsorGmail.Forexample,wearegoingtomakemeasurementsusingourArduinoboardandautomaticallylogtheseresultsinaGoogleDocsspreadsheet,whichcanbeaccessedfromanywhereintheworld.

Page 27: Arduino networking   marco schwartz
Page 28: Arduino networking   marco schwartz

WhatyouneedforthisbookYouwillneedseveralhardwareandsoftwarecomponentstomakealltheprojectsfoundinthisbook.Ofcourse,youcanjustreadthedescriptionoftheprojectsandlearnthisway.However,IreallyrecommendactuallydoingtheprojectsyourselftoreallylearnabouthowtousetheArduinoEthernetshieldtobuildexcitingnetworkingapplications.

Thehardwarecomponentsrequiredaredetailedatthebeginningofeachchapter.However,whatyouwillreallyneedforalltheprojectsisanArduinoboard.

AlltheprojectsofthebookarebasedontheArduinoUnoboard:

http://arduino.cc/en/Main/arduinoBoardUno

Foralltheprojectsofthisbook,youwillalsoneedtheArduinoEthernetshield:

http://arduino.cc/en/Main/ArduinoBoardEthernet

Onthesoftwareside,thereissomesoftwarethatwewilluseinallthechaptersofthebook.ThefirstsoftwarethatwewilluseinallthechaptersistheArduinoIDEthatyouneedtoinstall.Youcandownloaditfrom:

http://arduino.cc/en/main/software

TheEthernetlibraryitselfiscontainedwithintheArduinoIDE,soyouwon’tneedtoinstallityourself.Therearealsoseveralexternallibrariesyouwillneed,butthesearedetailedineachchapterwheretheyarenecessary.

Youwillalsoneedawebserverrunningonyourcomputerforsomeoftheprojects.Irecommendusingsoftwarethatintegratesawebserverandadatabase,andthathandlesallthedetailsforyou.

IfyouareworkingonWindows,IrecommendusingEasyPHP:

http://www.easyphp.org/

UnderOSX,IrecommendusingMAMP:

http://www.mamp.info/

ForLinux,youcanfollowtheinstructionsprovidedatthefollowinglinktoinstallawebserver:

http://doc.ubuntu-fr.org/lamp

Makesurethattheserverisrunningatthispoint;wearegoingtouseitinseveralprojectsinthisbook.

Page 29: Arduino networking   marco schwartz
Page 30: Arduino networking   marco schwartz

WhothisbookisforThisbookisforallthosewhoarewillingtobuildexcitingconnectedArduinoprojectsusingtheEthernetshield.Youactuallydon’tneedtoknowtheArduinoplatformbeforehandasalltheprojectswillbeexplainedstepbystepwithclearinstructions.Youalsodon’tneedanypriorknowledgeintheEthernettechnology.Theonlythingyouneedtounderstandistheprojectsfoundinthisbookarejustbasicknowledgeinelectronicsandprogramming.

ThisbookisalsoforelectronichobbyistswhowanttolearnmoreabouttheArduinoplatform.Byexecutingtheprojectsfoundinthisbook,youwilllearnaboutmanypossiblewaystousetheArduinoEthernetshield.YouwillalsolearnhowtoconnectsensorsandactuatorstoArduinoandcontrolthemwithinyourlocalnetwork.

Finally,thisbookisalsoforthosewhoarewillingtolearnmoreabouttheInternetofThingsframeworkusingtheArduinoEthernetshield.Thelastchaptersofthebookarededicatedtobuildingprojectsthatareconnectedtocloudservicesandcanbeaccessedfromanywhereintheworld,simplybyconnectingyourArduinoprojectstoyourInternetrouterviaEthernet.

Page 31: Arduino networking   marco schwartz
Page 32: Arduino networking   marco schwartz

ConventionsInthisbook,youwillfindanumberofstylesoftextthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.

Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Inthesetup()functionofthesketch,wewilltrytogetanIPaddressusingDHCP.”

Ablockofcodeissetasfollows:

Stringlog_time=String(day())+"/"+

String(month())+"/"+String(year())+""+

String(hour())+":"+String(minute())+":"+

String(second());

Anycommand-lineinputoroutputiswrittenasfollows:

#192.168.1.103/digital/7/1

Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,inmenusordialogboxesforexample,appearinthetextlikethis:“IfyouareusingWindows,youwillfindtheinformationyouneedunderNetworkSettingsinyourControlPanel.”

NoteWarningsorimportantnotesorsomeadditionalinformationappearinaboxlikethis.

TipTipsandtricksappearlikethis.

Page 33: Arduino networking   marco schwartz
Page 34: Arduino networking   marco schwartz

ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedormayhavedisliked.Readerfeedbackisimportantforustodeveloptitlesthatyoureallygetthemostoutof.

Tosendusgeneralfeedback,simplysendane-mailto<[email protected]>,andmentionthebooktitlethroughthesubjectofyourmessage.

Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideonwww.packtpub.com/authors.

Page 35: Arduino networking   marco schwartz
Page 36: Arduino networking   marco schwartz

CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.

Page 37: Arduino networking   marco schwartz

DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.

Alltheup-to-datecodefortheprojectsofthisbookcanalsobefoundatthefollowingaddress:

https://github.com/openhomeautomation/arduino-networking/

Page 38: Arduino networking   marco schwartz

ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyouwouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/support,selectingyourbook,clickingontheerratasubmissionformlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsite,oraddedtoanylistofexistingerrata,undertheErratasectionofthattitle.

Page 39: Arduino networking   marco schwartz

PiracyPiracyofcopyrightmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucomeacrossanyillegalcopiesofourworks,inanyform,ontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.

Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.

Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluablecontent.

Page 40: Arduino networking   marco schwartz

QuestionsYoucancontactusat<[email protected]>ifyouarehavingaproblemwithanyaspectofthebook,andwewilldoourbesttoaddressit.

Page 41: Arduino networking   marco schwartz
Page 42: Arduino networking   marco schwartz

Chapter1.DiscovertheArduinoEthernetShieldInthisfirstchapterofthebook,wewillonlyfocusonthebasicsandgetstartedwiththeArduinoEthernetshield.Inordertobuildmorecomplexprojectsinthenextchaptersofthebook,wefirstneedtobeabsolutelysurethatourshieldisfunctioningcorrectly,anditcanconnecttoourlocalnetworkandtheWeb.

Toensurethis,we’llfirstassemblethehardware,andthenbuildasimpleArduinosketchthatwillconnecttotheWeb,grabatestwebpage,anddisplayitbackinsidetheArduinoSerialMonitor.

Thesewillbethemajortakeawaysofthischapter:

First,we’llmakesurethatyouhavealltherequiredhardwareandsoftwarecomponents.WearealsogoingtoassembletheshieldandtheArduinoUnoboard,andconnecteverythingtoourlocalnetworkviaarouter.Then,wewillwritethesketchthatwillconnectyourshieldtoyourlocalnetworkaswellastheWeb,andthissketchwillgrabatestpagetomakesureyourconnectionisworkingcorrectly.Finally,wearegoingtotestthissketchandmonitorthestatusoftheEthernetshieldontheArduinoSerialMonitor.Fromthisfirsttestoftheshield,we’llbeabletotellwhethertheshieldiscorrectlyconnectedtotheInternetornot.

Page 43: Arduino networking   marco schwartz

HardwareandsoftwarerequirementsYoudon’tneedalotofhardwareforthisfirstproject.YouonlyneedanArduinoUnoboard,andofcourse,theArduinoEthernetshield.OtherboardssuchastheArduinoMegawillworkaswellfortheprojectsinthefirstchapterofthebook,butyoumightfacedifficultiesfortheprojectsinthefollowingchaptersinthebook.Therefore,IrecommendthatyouuseanArduinoUnoboardforalltheprojectsofthisbook.

Beforeactuallyassemblingtheshieldwiththeboard,makesuretowritedowntheMACaddressoftheshield,whichiswrittenonthebackoftheshield.Wewillneeditlaterintheprojectwhenwewritethefirstsketch.

ThisisanimageoftheassembledboardandtheEthernetshield:

YouwillalsoneedaUSBBtoUSBAcabletoconnecttheArduinoboardtoyourcomputer,andanEthernetcabletoconnecttheshieldtoarouter.

Onthesoftwareside,allyouneedistheArduinoIDE,whichcanbefoundatthefollowingaddress:

http://arduino.cc/en/main/software

TheEthernetlibraryisincludedbydefaultintheArduinosoftware,soyoudon’tneedtoinstallanyadditionalcomponents.

Page 44: Arduino networking   marco schwartz

HardwareconfigurationThehardwareconfigurationinthischapterisreallysimple.Atthispoint,youshouldalreadyhavetheArduinoEthernetshieldconnectedtoyourArduinoUnoboard.Ifthat’snotthecase,pleasedosonow.

Youthenhaveonlytwocablestoplugin:aUSBcablebetweenyourcomputerandtheArduinoUnoboardandtheEthernetcable.SimplyconnecttheUSBcabletooneportofyourcomputer.

FortheEthernetcable,youhaveseveraloptions.Theeasiestthingyoucando,whichiswhatIrecommend,istoconnecttheEthernetcabledirectlyfromtheshieldtothemainrouterofyourhome.Usually,youwillhaveaWi-Firouterinyourhome,whichyouusetoenableWi-Ficonnectivityforyourcomputerandotherdevices.ThisroutershouldalsohavesomeEthernetports,whereyoucanconnectyourEthernetshield.TheadvantageofthissolutionisthatyourshieldwillautomaticallygetanIPaddressandwillhaveaccesstotheInternetautomatically.ThisassumesthatyourrouterisconfiguredforDHCP;gotoyourroutersettingstoenableDHCP.Asthisprocedurevariesdependingonthebrandofyourrouter,refertoyourrouterdocumentationtofindouthowtodothisonyourspecificrouter.

Ifyoudon’thavearouter,youcandirectlyconnecttheEthernetcabletoyourcomputer.Idon’trecommendthisalternative,asconfiguringyourcomputertoconnecttotheshieldandsharingtheInternetconnectionwiththeshieldisreallycomplex,anditalsodependsonyouroperatingsystem.

Ifyoureallydon’thaveaccesstoarouterbutyouhaveaccesstoaWi-Finetwork,IrecommendbuyingoneofthesesmallWi-FiroutersthathaveanEthernetport.ItcanconnecttoanyWi-FinetworkinrangeandsharetheconnectionautomaticallywithotherdevicesviaEthernet.

Forexample,asshowninthefollowingimage,IrecommendtheTP-LinkMR3020router:

Thisisanimageoftheassembledhardwareforthetasksinthischapter,withtheUSB

Page 45: Arduino networking   marco schwartz

cableandtheEthernetcablepluggedintheproject:

Ifeverythingiswiredcorrectly,youshouldseetheONLEDontheEthernetshieldisswitchedon,aswellastheLINKLEDneartheEthernetport.

Page 46: Arduino networking   marco schwartz
Page 47: Arduino networking   marco schwartz

TestingyourconnectionNowthatthehardwareisready,wecanwriteourfirstsketchtotesttheEthernetshieldandtheconnectiontotheWeb.Notethatthepiecesofcodeshowninthissectionareonlythemostimportantpartsofthecode,andyoucanfindthecompletecodeinsidetheGitHubrepositoryofthebook.

StarttheArduinosketchbyincludingthefollowingrequiredlibrariestousetheshield:

#include<SPI.h>

#include<Ethernet.h>

TipDownloadingtheexamplecode

YoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.

Then,wehavetodefinetheMACaddressoftheEthernetshield.Thisaddressislocatedjustbehindtheshield,andyoushouldhavenoteditdownalready.Youhavetoenteritinthefollowingformat:

bytemac[]={0x90,0xA2,0xDA,0x0E,0xFE,0x40};

Wealsoneedtodefinewherewearegoingtoconnecttotesttheconnection.Youcanuseanywebpageyouwant,orevenperformasearchonGoogle,butforthisfirsttest,Iwanttouseasimplepage.

Ifoundthiswebsitewithasimpletestpagethatwe’lltrytograbwhilemakingarequestlaterinthesketch.Youcanalsosetupyourownpageifyouhaveawebserveronline,forexample,ifyouhaveabloghostedsomewhere.

Thewebsiteaddressisstoredinacharvariable:

charserver[]="www.brainjar.com";

Notethatyoucanalsouseotherpageshere,forexamplehttp://www.example.com/hello.

TheEthernetshieldwillthenautomaticallygettheIPaddressofthiswebsite.

TogetanIPaddressfortheEthernetshielditself,we’lluseDHCPtoautomaticallygetonefromtherouterweareconnectedto.However,ifDHCPfails,weneedtoassignadefaultaddresstotheshield.

ThisisstoredinanIPAddressvariable.Notethatyoucanputanythingyouwantinsidethisvariable.Asforthisfirstproject,wereallyneedDHCPtoworktogetconnectedtotheWeb.However,itisagoodpracticetospecifyanIPaddressinthesamesubnetasyourrouter,sotheshieldcanatleastconnecttoyourlocalnetwork.Forexample,theIPaddress

Page 48: Arduino networking   marco schwartz

ofmycomputerwas192.168.1.100,soIspecifiedasimilarIPaddressfortheshield:

IPAddressip(192,168,1,50);

WecannowcreatetheinstancefortheEthernetclientwiththefollowingcode:

EthernetClientclient;

Now,inthesetup()functionofthesketch,wewilltrytogetanIPaddressusingDHCP.Ifyou’reconnectedtoarouter,thereisnoreasonitwouldfail.However,ifitdoesindeedfail,wewillautomaticallysetthedefaultIPaddressfortheshield:

if(Ethernet.begin(mac)==0){

Serial.println("FailedtoconfigureEthernetusingDHCP");

Ethernet.begin(mac,ip);

}

Then,wewillprintouttheIPaddressontheSerialportfordebuggingreasons:

Serial.begin(115200);

Serial.print("IPaddress:");

Serial.println(Ethernet.localIP());

Now,intheloop()functionofthesketch,wewillactuallyconnecttotheserver.Itstartsbycallingtheconnectfunctionandcheckswhetherweareindeedconnected.Ifthat’sthecase,weprintitoutontheSerialmonitorfordebuggingpurposes:

if(client.connect(server,80)){

if(client.connected()){

Serial.println("connected");

Nowthatweareconnected,wecansettheGETrequestforthetestpagewewanttoaccess:

client.println("GET/java/host/test.htmlHTTP/1.1");

client.println("Host:www.brainjar.com");

client.println("Connection:close");

client.println();

Aftertherequestissent,wewillreadthedatathatiscomingbackfromtheserver,tocheckwhethereverythingwentfine.WewillalsoprintoutthisdataontheSerialmonitor:

while(client.connected()){

while(client.available()){

charc=client.read();

Serial.print(c);

}

}

Finally,whenwearesurethattheclientisnotconnectedanymore,wewillprinttheinformationontheSerialmonitorandcalltheclose()functionontheEthernetclient:

if(!client.connected()){

Serial.println();

Serial.println("disconnecting.");

Page 49: Arduino networking   marco schwartz

client.stop();

}

Finally,wedon’twanttocontinuouslydothisaction,butonlyrepeatiteveryfiveseconds.Thisisdonewithadelay()function:

delay(5000);

It’snowtimetotestthesketch.

NoteThecompletecodeforthisfirstchaptercanbefoundtheGitHubrepositoryofthebook:

https://github.com/openhomeautomation/arduino-networking/tree/master/chapter1

MakesurethattheEthernetcableispluggedinyourshieldandyourrouter,anduploadthesketchtotheArduinoboard.YoucannowalsoopentheSerialMonitor,andselectthecorrectSerialspeed(115200fortheArduinosketchofthischapter);that’sthefirstthingyoushouldsee,whichistheIPaddressofyourboard:

IPaddress:192.168.1.103

Then,theArduinoboardshouldconnecttotheserver:

Connecting…

Ifthisissuccessful,theoutputwillshowthatitisindeedconnected:

connected

Now,theArduinoboardwillsendtheGETrequesttotheserverinordertograbthecontentofthetestpage.TheserverwillanswerwithanHTTP200OKstatusiftherequestwassuccessful,alongwiththecontentsofthepage:

HTTP/1.1200OK

Content-Length:308

Content-Type:text/html

Last-Modified:Tue,27May200315:17:04GMT

Accept-Ranges:bytes

ETag:"6291ea76324c31:5897"

Server:Microsoft-IIS/6.0

X-Powered-By:ASP.NET

Date:Thu,15May201417:35:40GMT

Connection:close

Insidethislonganswer,youshouldseemanyHTMLtags,suchas<html>and<head>tags.Insidetheanswer,youshouldalsogetthecontentofthepageinsidea<p>tagasfollows:

<p>ThisisaverysimpleHTMLfile.</p>

Ifyoucanseethis,congratulations!YourEthernetshieldisworkingcorrectly!Finally,theArduinoboardwillalsodisplaythattheEthernetshieldhasbeendisconnectedfromtheremoteserver:

disconnecting

Page 50: Arduino networking   marco schwartz

Ifeverythingworkedcorrectly,itmeansthatyourEthernetshieldisworkingcorrectly,anditcanconnectwithoutanyproblemstoyourlocalnetworkandtotheWeb.

Ifsomethingdidn’tworkasexpected,thereareseveralthingsyoucancheck.First,makesurethatallconnectionsarecorrectlymade,andthattheEthernetcableiscorrectlypluggedbetweentheshieldandyourrouter.

IftheDHCPfailsatthebeginningofthesketchandyourshieldcan’tgetanIPaddress,pleasecheckwhetherDHCPisactivatedwithoutlimitationsontheMACaddressesintheconfigurationpanelofyourrouter.

Finally,iftheArduinoboardcan’tconnecttotheremoteserver,firstcheckwhethertheserveritselfisworkingbyenteringtheURLofthetestpagemanuallyinyourbrowser.

Page 51: Arduino networking   marco schwartz
Page 52: Arduino networking   marco schwartz

SummaryInthisfirstchapterofthebook,webuiltourfirstprojectwiththeArduinoEthernetshield,onlytocheckwhethertheshieldwasworkingcorrectlyandwhetheritcouldconnecttoyourlocalnetworkandtotheInternet.WeonlymadesurethattheEthernetshieldcouldindeedbeconnectedtotheInternet,butthisalreadygaveyouanoverviewofeverythingthatyoucandowiththeEthernetshield.YousawhoweasyitistosendrequestswiththeEthernetshield,whichissomethingwewilluselaterinthebooktosenddatafromtheEthernetshieldtoaremoteserver.

Thesewerethemajortakeawaysfromthisfirstchapter:

First,wemadesurethatallthehardwarewascorrectlysetandthattheshieldwasconnectedtoyourrouterviaanEthernetcable.Then,webuiltthefirstsketchofthisbooksimplytotestthattheEthernetshieldcouldindeedconnecttothelocalnetworkandtheWeb.Totestthis,webuiltasketchthatconnectstotheWebandgrabsatestpagefromaremoteserver.Finally,weuploadedthiscodetotheboardandcheckedthateverythingwasworkingcorrectlybymonitoringthestatusoftheconnectionintheArduinoSerialMonitor.Wealsodefinedsomestrategiesonwhattodoifthesketchdidn’tworkandtheshieldcouldnotconnecttotheWeb.

Inthenextchapterofthebook,wearegoingtobuildourfirstapplicationusingtheEthernetshield.WearealsogoingtouseanEthernetclient,butthistimetoconnecttoaserverrunningonourowncomputerandtosendmeasurementsthatcomefromatemperatureandhumiditysensor.

Page 53: Arduino networking   marco schwartz
Page 54: Arduino networking   marco schwartz

Chapter2.SendingDatatoaWebServerInthepreviouschapter,wemadesurethatyourArduinoEthernetshieldcouldactuallyconnecttoyourlocalnetworkandtotheWeb.Inthischapter,wearegoingtobuildonthat,andbuildourfirstapplicationusingtheEthernetshield.

WearegoingtoseeinmoredetailhowtheEthernetclientworksbymeasuringdatafromadigitalsensorandsendingthisdatatoawebserver.Inthischapter,thiswebserverwillbeaserverrunningonyourowncomputer.

Thesewillbethemajortakeawaysfromthischapter:

First,wearegoingtochoosethetemperatureandhumiditysensorthatwewillalsouselaterinthebook.Wearealsogoingtoinstallthedifferentsoftwarecomponentsthatarerequiredforthischapter,especiallythelibrarytoplotdataonyourcomputer.Then,wearegoingtobuildtheArduinocodethatwillperformmeasurementsandsendthesemeasurementstothewebserverrunningonyourcomputer.Afterthat,we’llstartbuildingtheserver-sidecode.Inthefirstpart,wearegoingtobuildthecoderesponsibleforsimplyloggingthereceiveddataintoalocaldatabase.Finally,wewillinterfacethedatabasewithaliveplottinglibrarysothemeasurementscanbeseenastheycomefromtheEthernetshieldandareloggedinthedatabase.

Page 55: Arduino networking   marco schwartz

HardwareandsoftwarerequirementsOnthehardwareside,youwillofcourseneedtheArduinoUnoboardandArduinoEthernetshield.

Youwillalsoneedasensortomeasuresomedata.AsthisbookisabouthowtousetheEthernetshieldandnothowtomeasuredatafromsensors,youcanactuallytakeanysensorofyourchoice.

IusedaDHT11sensor,whichisadigitaltemperatureandhumiditysensor.IchosethissensorforthischapterandformanychaptersofthebooksinceitisaverycheapsensorandeasytointerfacewithArduino.AlongwiththeDHT11sensor,youwillalsoneeda4.7kOhmresistor.

Youcanalsouseotherkindofsensors.Youcanuseanalogsensors,whichreturnasignaldependingonthemeasureddata.Forexample,theTMP36sensorisananalogtemperaturesensorthatreturnsavoltageproportionaltotheambienttemperature.

OtherkindofsensorsyoucanuseherearesensorsbasedontheSPIorI2Cprotocols,whicharedigitalcommunicationprotocolsthatareeasytousewithArduino.Forexample,youcanusetheBMP085orBMP180sensors,whichhaveanI2Cinterface,andyoucanalsomeasurethebarometricpressureandambienthumidity.

YouwillalsoneedabreadboardandsomejumperwirestomaketheconnectionsbetweenthesensorandtheEthernetshield.

Thisisalistofallthecomponentsthatwereusedforthischapter:

ArduinoUno(https://www.adafruit.com/products/50)ArduinoEthernetShield(https://www.adafruit.com/products/201)DHT11sensor(https://www.adafruit.com/products/386)Breadboard(https://www.adafruit.com/product/64)Jumperwires(https://www.adafruit.com/product/758)

Onthesoftwareside,thefirstthingyouwillneedisthelibrarytointerfacewiththesensoryouchosebefore.AsIchoseaDHT11sensorforthisproject,youwillneedtodownloadandinstalltheDHTlibrary:

https://github.com/adafruit/DHT-sensor-library

ToinstallanArduinolibrary,simplyunzipthecontentofthedownloadedfileintothe/librariesfolderofyourmainArduinofolder(orcreatethisfolderifitdoesn’texistalready).

Youwillalsoneedalibrarytoplotthedatastoredinthedatabase.Iusedtheflotlibrary,whichisveryconvenienttouseandallowsreal-timevisualizationofincomingdata.Thislibraryisincludedinthecodeofthischapter,butifyouwantmoreinformationonthelibraryyoucangotohttp://www.flotcharts.org/.

Aboutthedatabaseitself,thisprojectusesSQLite,whichisaliteandeasy-to-usedatabase.Itisperfectforsuchprojects,asitdoesn’trequireadatabaseserverrunningon

Page 56: Arduino networking   marco schwartz

yourcomputer.

ItcomespreinstalledonmanyoperatingsystemssuchasOSXorLinux,butifthat’snotthecase,goovertotheirwebsitetodownloadandinstallit:

http://www.sqlite.org/

IfyouareusingLinux,thebestoptionistoinstallSQLitewithyourLinuxdistributionpackagemanager.

NotethatitisalsopossibletouserelationaldatabasesotherthanSQLite,suchasMySQL.ManywebserverscomewiththeMySQLserveraswell,andyouwillonlyneedtomakesmallchangesinthecodeofthischaptertouseaMySQLdatabase.YoucanalsousenonrelationaldatabasessuchasMongoDB(http://www.mongodb.org/),butthiswillrequiremorechangesinthecode.

Finally,youwillalsoneedtohaveawebserverupandrunningtomakethisprojectwork.Youcanfindmoreinformationabouthowtosetupawebserverintheprefaceofthisbook.Ifyoudon’thaveawebserverinstalledyet,youcanvisitthefollowinglinkstogetone:

Windows:EasyPHP(http://www.easyphp.org/)orWAMP(http://www.wampserver.com/en/)OSX:MAMP(http://www.mamp.info/)Linux:LAMP(https://help.ubuntu.com/community/ApacheMySQLPHP)

Page 57: Arduino networking   marco schwartz

HardwareconfigurationIt’snowtimetosetupthehardwareforthisproject.Atthispoint,ifyoufollowedthefirstchapter,youshouldalreadyhaveyourArduinoEthernetshieldpluggedintotheArduinoboard,andoneEthernetcableconnectingtheEthernetshieldandyourInternetrouter.Ifthat’snotthecasealready,pleasedoso.

TheonlythingyouwillhavetoconnectinthisprojectistheDHT11sensorandtheresistor.Youcanhaveanoverviewofthedifferentconnectionsyouhavetomakebylookingatthefollowingschematics:

First,plugtheDHT11sensortothebreadboard.Then,connectpinnumber1and2ofthesensorusingthe4.7kOhmresistor.

Now,forthepowersupply.Connectpinnumber1ofthesensortoArduino5V,andpinnumber4totheArduinoGND.Finally,connectpinnumber2oftheDHTsensortoArduinopinnumber7.

Thisiswhatitshouldlooklikeattheend:

Page 58: Arduino networking   marco schwartz

Ifyourprojectlooksthesame,congratulations,youcanmovetothenextpartwherewearegoingtobuildtheArduinosketchforthisproject.

Page 59: Arduino networking   marco schwartz
Page 60: Arduino networking   marco schwartz

SendingdatatoaserverItisnowtimetobuildthesketchforourfirstapplicationusingtheArduinoEthernetshield.Butfirst,weneedonemorepieceofdata:thelocalIPaddressofyourcomputer.InsidetheArduinosketch,wearegoingtospecifywheretheArduinoEthernetshieldhastosendthedata.

FindingyourIPaddressiseasy,butitdependsonyouroperatingsystem.IfyouareusingOSX,youcanfindyourIPaddressinsideNetworkPreferences.

IfyouareusingWindows,youwillfindtheinformationyouneedundertheNetworkSettingsinyourControlPanel:

AnotherwayunderWindowsistogotoStart,thenRun,andtypecmd.Then,insidetheconsole,typeipconfigandhitEnter.Yourcomputer’sIPaddresswillbedisplayed.

IfyouareusingLinuxorOSX,youcansimplygotoaterminalandtype:

ifconfig

ThiscommandshouldprintyourIPaddressinsidetheterminalwindow.Itwillingeneralbesomethinglikeeth0oren0.ThisiswhatIhadonmymachine:

en0:flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST>mtu1500

etherb8:f6:b1:12:c4:d7

inet6fe80::baf6:b1ff:fe12:c4d7%en0prefixlen64scopeid0x4

inet192.168.1.100netmask0xffffff00broadcast192.168.1.255

nd6options=1<PERFORMNUD>

media:autoselect

status:active

SomeLinuxdistributionsmadethemovetoanothertoolcalledip.Touseit,simplygotoaterminalandtype:

Page 61: Arduino networking   marco schwartz

ipaddr

Thiswillalsodisplayyourcomputer’sIPaddress.

WearenowreadytobuildtheArduinosketch.First,weneedtoincludetherequiredlibraries:

#include<SPI.h>

#include<Ethernet.h>

#include"DHT.h"

InserttheMACaddressofyourEthernetshield,whichyoucanfindonthebackoftheshield:

bytemac[]={0x90,0xA2,0xDA,0x0E,0xFE,0x40};

YouwillalsoneedtodefinethepinonwhichtheDHTsensorwasconnected,aswellasthetypeofsensoryouareusing:

#defineDHTPIN7

#defineDHTTYPEDHT11

NotethatyoudonotneedasensorconnectedtoyourArduinoboardtotestthisproject.Youcansimplysendthecontentofanyvariableasatest,orusetherandom()functionofArduinotogeneraterandomdatameasurements.

First,wewilldefineadefaultIPaddressfortheEthernetshield.Thesketchshouldnotusethisaddresssincewe’llattempttoconnectusingDHCP,butifDHCPfails,weneedthisdefaultIPaddress.IrecommendusinganaddressthatisinthesameIPdomainasyourcomputerIPaddress:

IPAddressip(192,168,1,50);

Then,wecandefinetheIPaddressoftheserver,whichinthiscaseisyourcomputer.ThisiswhereyouneedtoentertheIPaddressyougotbefore:

IPAddressserver(192,168,1,100);

WecanthencreateaninstanceoftheEthernetclient:

EthernetClientclient;

WecanalsocreateaninstanceoftheDHTlibrary:

DHTdht(DHTPIN,DHTTYPE);

Nowinthesetup()functionofthesketch,wefirsttrytouseDHCPtoautomaticallygetanIPaddressfortheEthernetshield.Thisisdoneusingthefollowingpieceofcode:

Serial.begin(115200);

if(Ethernet.begin(mac)==0){

Serial.println("FailedtoconfigureEthernetusingDHCP");

Ethernet.begin(mac,ip);

}

Afterthisstep,weprinttheIPaddressontheSerialport:

Page 62: Arduino networking   marco schwartz

Serial.print("IPaddress:");

Serial.println(Ethernet.localIP());

Intheloop()functionofthesketch,thefirststepistotakemeasurementsfromtheDHT11sensor:

floath=dht.readHumidity();

floatt=dht.readTemperature();

Convertthesemeasurementsintostrings:

Stringtemp=String((int)t);

Stringhum=String((int)h);

Fordebuggingpurposes,wealsoprintthesevaluesontheSerialport.We’llchecklaterwhetherthesevaluesarecorrectwhentestingthesketch:

Serial.println("Temperature:"+temp);

Serial.println("Humidity:"+hum);

Now,weareactuallygoingtosendthedatatotheserver.Don’tworryaboutunderstandingwhattheserver-sidecodedoesfornow,aswe’lldealwiththatlater.First,wehavetoconnecttotheserverrunningonyourcomputer:

if(client.connect(server,80)){

if(client.connected()){

Serial.println("connected");

Ifthisissuccessful,wecanmaketherequest.AsinChapter1,DiscovertheArduinoEthernetShield,wearegoingtouseastandardGETrequest,andtopassthetemperatureandhumiditymeasurementsasarguments.Atthispoint,youwillalsoneedtoentertheIPaddressofyourcomputer.Thisisalldoneusingthefollowingpieceofcode:

client.println("GET/datalogger/datalogger.php?temp="+temp+"&hum="+

hum+"HTTP/1.1");

client.println("Host:192.168.1.100");

client.println("Connection:close");

client.println();

Youcanseethatthecodecallsafilenamedatalogger.php,whichwearegoingtoexamineinthenextsection.

Then,aftertherequestismade,wecanreadtheanswerfromtheserver:

while(client.connected()){

while(client.available()){

charc=client.read();

Serial.print(c);

}

}

Next,wecanclosetheconnectioniftheclientisnotconnectedtotheserveranymore:

if(!client.connected()){

Serial.println();

Serial.println("disconnecting.");

client.stop();

Page 63: Arduino networking   marco schwartz

}

Wearealsogoingtorepeatthewholeloopeverysecond:

delay(1000);

NoteYoucanfindallthecodeforthissectionintheGitHubrepositoryofthischapter:

https://github.com/openhomeautomation/arduino-networking/tree/master/chapter2

Now,ifwejustuploadedthecodetotheArduinoboard,notmuchwouldhavehappened,sincewedidn’tdoanythingontheserverside.TheArduinoboardwouldmaketherequest,butastherequestfiledoesn’texistontheserver,theserverwouldreturnanerrorcode.

Sofirst,weneedtobuildafileontheserverthatwillhandletherequestfromtheboardandlogthedatasomewhere.That’sexactlywhatwearegoingtodonext.

Page 64: Arduino networking   marco schwartz
Page 65: Arduino networking   marco schwartz

LogincomingdatainadatabaseInthissection,wearegoingtousePHPtobuildtheserver-sidepartoftheproject.IfyouareacompletenoviceinPHP,Irecommendthefollowingresourcetolearnthebasicsofthelanguage:

http://php.net/manual/en/tutorial.php

First,wearegoingtoseethecontentofthedatalogger.phpfile.ThisfilewillhandletherequestscomingfromtheArduinoboard,logthedatainadatabase,andanswerwithasimplemessage.Notethatthisfilehastobeinafoldernameddataloggeronyourwebserver.Wewillseetheimportantpartsofthecode.Togetthecompletecodeforthissection,pleaserefertotheGitHubrepositoryofthechapter.NotethatallthePHPcodeshouldbebetweenthe<php…?>tags.

ThefilestartsbyreceivingthedatafromtheGETrequestsentbytheArduinoEthernetshield:

$temperature=intval($_GET["temp"]);

$humidity=intval($_GET["hum"]);

WealsoinstantiatetheconnectionwiththeSQLitedatabase:

$db=newSQLite3('database.db');

Then,weneedtogivesomestructuretothedatabaseifthedatabasefileisbrandnew.IfyouarenotfamiliarwiththeSQLcommands,Iinviteyoutovisitthefollowinglink:

http://www.cs.utexas.edu/~mitra/csFall2013/cs329/lectures/sql.html

Wearegoingtocreatefourdifferentcolumnsinsidethedatabase:auniqueIDthatwillbeautomaticallyincrementedbySQLite,atimestamptoknowwhenthemeasurementwasmade,andthetemperatureandhumiditydata.Thisisdoneusingthefollowingpieceofcode:

$db->exec('CREATETABLEIFNOTEXISTSmeasurements(idINTEGERPRIMARYKEY,

timestampTIMESTAMPDEFAULTCURRENT_TIMESTAMPNOTNULL,temperature

INTEGER,humidityINTEGER);');

Notethatifyouareusingmoresensors(forexample,ifyouarealsomeasuringtheambientlightlevel),youcanaddmorefieldshere.Simplyaddanewfieldtothelist,forexample:pressureINTEGER.

Now,wecanactuallyinsertthedataasanewrowinthedatabase.SinceSQLiteautomaticallyaddstheIDandtimestampfields,wejustneedtoinsertthedataconcerningthetemperatureandhumidity:

$db->exec("INSERTINTOmeasurements(temperature,humidity)VALUES

('$temperature','$humidity');");

Ifyouneedtoinsertmoredataintothedatabase,forexample,ifyouhaveanothermeasurementtolog,youcansimplyextendthiscommandtoinsertmoredataintotheSQLitedatabase.

Page 66: Arduino networking   marco schwartz

TipThissimplecodeillustrateshoweasyitistoinsertdataintotheSQLitedatabase.However,itleavesourserverexposedtoasecurityissueknownastheSQLinjection.Sinceourprojectismadeforyourownlocalnetworkonly,thisisnotreallyanissuehere.However,ifyouplantodeploytheprojectonline,Irecommendmodifyingthecodetosolvethissecurityproblem.Thefollowinglinkwillgiveyoumoreinformationaboutthisissuehttp://www.tutorialspoint.com/sqlite/sqlite_injection.htm.

Finally,wereplytotheArduinoboardwithasimplemessage:

echo"Datareceived";

Now,wehaven’tactuallytalkedaboutthedatabaseitselfyet.Thereisadatabase.dbfileincludedasanexampleinthecodeforthischapter,butIrecommendyousimplydeleteitandtrytomakeyourowndatabase.Youcansimplygotothedirectoryinaterminalwhereallfilesoftheprojectarelocatedandtype:

sqlite3database.db

TipIfyouareusingWindows,IrecommendusingConsoleasaterminal.Youcangetitatthefollowinglinkhttp://sourceforge.net/projects/console/.

Thiscommandwillcreateyourdatabasefile.Youcannowagainexitthedatabasefilebytypingthefollowingcommand:

.exit

NotethatifyouareunderLinux,youmighthavetochangethepermissionsonthedatabaseandthefolderthatcontainstheproject.Todoso,gotheproject’sfolderviaaterminalandtype:

chmod777database.db

Now,itistimetomakeafirsttestoftheproject.Makesurethatallthefilesoftheserverarelocatedinafoldercalleddataloggeronyourwebserver.YoucannowuploadtheArduinosketchtoyourboardandopentheSerialmonitor.YoushouldfirstseethatthesketchisconnectingtoyournetworkandreceivinganIPaddressasfollows:

IPaddress:192.168.1.103

Then,itshouldenterthefirstiterationoftheloop()function,andprintoutthetemperatureandhumiditymeasurements:

Temperature:21

Humidity:37

Afterthisstep,youshouldseethatthesketchisconnectedtoyourserver,andthattheserverisansweringwithastandard200OKanswer:

connected

HTTP/1.1200OK

Page 67: Arduino networking   marco schwartz

Date:Mon,19May201408:09:57GMT

Server:Apache/2.2.23(Unix)mod_ssl/2.2.23OpenSSL/0.9.8yDAV/2PHP/5.4.10

X-Powered-By:PHP/5.4.10

Content-Length:13

Connection:close

Content-Type:text/html

Also,attheendofthisanswer,youshouldseetheconfirmationmessagethatwedefinedinthePHPfile:

Datareceived

disconnecting.

Ifyouareseeingthesemessages,congratulations!ItmeansthatyourArduinoEthernetshieldissuccessfullycommunicatingwiththewebserverrunningonyourcomputer,andisactuallyloggingsomedata.

Ifthisisnotthecase,firstcheckyourhardwareconnections.MakesuretheDHT11sensoriscorrectlywiredwiththeArduinoboard,andthattheEthernetcableispluggedintotheshieldandyourInternetrouter.Don’thesitatetoredoChapter1,DiscovertheArduinoEthernetShield,tomakesurethatyourEthernetshieldisworkingproperly.

Also,makesurethatthewebserverisactiveonyourcomputer,andthatallthefilesoftheproject(especiallythedatalogger.phpfile)arelocatedinafoldernameddataloggerinsideyourwebserverfolder.YoucantestthisindependentlyfromtheArduinoEthernetshield.Simplygotoyourfavoritewebbrowser,andtype:

localhost/folder_of_the_project/datalogger.php?temp=20&hum=40

Thiswilllogsomefakedatainsidethedatabase,soyoucanbesurethatthewebserverisrunningcorrectly.

Wearenowgoingtocheckontheserversidewhetherthedatawasrecordedcorrectly.Andweareactuallygoingtokilltwobirdswithonestone,sincethiscodewillalsobeusedinthenextsectiontoplotthedata.

Tocheckthatthedatawasrecordedcorrectly,youcansimplycreateafilenamedreadout.php,whichwillreaddatafromthedatabase,formatit,andprinttheformatteddatasoyouthatcanseeit.First,weneedtoaccesstheSQLitedatabase:

$db=newSQLite3('database.db');

Wethenneedtomakeaquerytothedatabasesoitreturnsthedatawewant.Inthisrequest,wearesimplygoingtotakeallthefieldsfromthetablecalledmeasurements.Thisisdoneusingthefollowingpieceofcode:

$results=$db->query('SELECTid,timestamp,temperature,humidityFROM

measurements');

Now,weneedtousePHPtoparsethisvariablethatcontainsalltheresultsfromthequery.Wesimplyuseawhilestatementforthat:

while($row=$results->fetchArray())

{

Page 68: Arduino networking   marco schwartz

$dataset[]=array(strtotime($row['timestamp'])*

1000,$row['temperature']);

}

Notethatintheprocessofparsingtheresults,weformatthedatainanothervariable,sothatthescriptwewillusetoplotthedatacanuseit.Wealsoconvertthetimestampcolumnsothattheplottingscriptcanuseit.Inthisexample,wearejustgoingtodisplayandlaterplotthetemperature,whichiswhyweonlytakethesetwovariablesoutfromthedatabase.Youcan,ofcourse,dothesameforthehumidity.

Finally,weprintouttheformatteddataintheJSONformat:

echojson_encode($dataset);

Now,wecantestthisreadoutfile.Simplygoovertoaterminal,gotothefolderwherethefileislocated,andtype:

phpreadout.php

Thisshouldplotalltherecordingsthathavebeenmadesofar:

[[1400486855000,20],[1400486868000,20],[1400486879000,21],

[1400486890000,21],[1400486901000,21],[1400486912000,21],

[1400486922000,22],[1400486933000,23],[1400486944000,23]]

Whatareyouareseeingintheterminalwindowistherawdatathatwasrecordedforthetemperature.Itconsistsofseveralsmallarraysoftwoelements,whicharethetimestampandrecordedtemperature.IfyouwanttolearnmoreabouttheJSONformatthatthisPHPscriptisreturning,youcanvisithttp://json.org/.

Ifyoucanseethisrawdatabeingdisplayed,itmeansthatthedatacomingfromtheArduinoboardwascorrectlyloggedinyourcomputer.

Page 69: Arduino networking   marco schwartz
Page 70: Arduino networking   marco schwartz

DisplayingtheresultsWearenowgoingtousethedatathatwasloggedinthedatabaseanddisplayitonagraphformoreconvenience.Forthistask,wearegoingtouseaJavaScriptlibrarycalledflot,whichisalreadyincludedinthecodeforthischapter.Thislibraryprovidesnicefunctionstoplotdataonawebpage,andalsoallowsyoutoplotdatainrealtime,soyouwillseethegraphbeingautomaticallyupdatedasmoredatacomesin.

EverythingwillhappeninsideanHTMLfilecalledplot.html.Wewillonlyseethemostimportantpartsofthecodehere.PleaserefertotheGitHubrepositoryofthechaptertogetthecompletefiles.Insidethisfile,youfirsthavetoincludethefilesrequiredfortheflotlibrary:

<scriptsrc="flot/jquery.js"></script>

<scriptsrc="flot/jquery.flot.js"></script>

<scriptsrc="flot/jquery.flot.time.js"></script>

YoualsoneedanelementintheHTMLpagethatwillhostthegraph.Thisisdoneusingthefollowingpieceofcode:

<divid="placeholder"style="width:800px;height:450px;"></div>

Let’salsodefinesomeoptionsfortheplot.SincethisisnowJavaScript,wehavetowritethiscodeinsidethe<script>…</script>tags.IfyouwanttolearnmoreaboutJavaScriptfirst,Irecommendthisexcellentinteractivetutorial:

http://www.codecademy.com/en/tracks/javascript

Becausewehavetimestampsasthex-axis,weneedtospecifythatthedataforthisaxisisaspecifictime,andthatwewanttodisplaythehours,minutes,andseconds:

varoptions={

xaxis:{

mode:"time",

timeformat:"%H:%M:%S"

}

};

Wealsoneedtoreceivethedataeverytimewecallthescripttoplotthedata.ThisisdonebyanAJAXcalltothePHPfilewecreatedbefore:

$.ajax({

url:"readout.php",

type:"GET",

dataType:"json",

success:onDataReceived

});

Notethatthiscodehastogoinsidetheupdate()functionintheJavaScriptcode.Youcandefinethisfunctionwith:

functionupdate(){

YoucanseethatthisAJAXcall,ifsuccessful,callsanotherJavaScriptfunction.This

Page 71: Arduino networking   marco schwartz

functionwillactuallytakethedataasanargumentandplotitwiththeoptionswedefinedbefore:

functiononDataReceived(series){

vardata=[];

data.push(series);

$.plot("#placeholder",data,options);

}

Allthiscodeiscontainedintheupdate()function,andthisfunctioniscalledcontinuously(every10milliseconds)sothattheplotisalwaysupdatedwhenanewdatapointcomesin:

setTimeout(update,10);

Finally,attheendofthescript,wecallthisfunctiononcetogetthegraphstarted:

update();

Itisnowtimetotestthepagewejustcreated.PlaceallthefilesinthedataloggerfolderonyourwebserverandmakesurethatthesketchisstillloadedontheArduinoboard.

Forillustrationpurposes,Iresetthemeasurementdatabaseatthispoint,butyoucanofcoursejustkeepthemeasurementsthatthesensoralreadyperformed.

Opentheplot.htmlfile.ThisistheresultIgotafterthefirsttwomeasurementpoints:

Toillustratethebehaviorofthesensorontheplot,Ipincheditwithmyfingersandreleaseditabitlater.Asexpected,thetemperaturewentupbeforegoingdownagainafterawhile.Thefollowingscreenshotistheresultonthewebpage:

Page 72: Arduino networking   marco schwartz

Ifitdoesn’tworkatthispoint,therearemanythingsyoucancheck.First,makesureagainthatthecodefortheprevioussectionsisworkingandthattheArduinoEthernetshieldiscorrectlysendingdatatotheserver.Also,checkthatallthecodefilesarelocatedinsidethesamefolderonthewebserver.Andmakesurethatyouareaccessingplot.htmlviathelocalhostURLinyourbrowser.

Then,opentheJavaScriptconsoletocheckthateverythingisfine.Youwillusuallyfindtheconsoleinthedevelopertoolsofyourwebbrowser.Forexample,inChrome,youwillfindtheconsoleintheView|Developermenu:

Page 73: Arduino networking   marco schwartz

Insidethisconsole,youwillbeabletoseewhetherthereareanyerrorsintheJavaScriptcodeonthepage,andthiswillusuallygiveyouagoodideaofwhatisgoingoninthepageandwhatyouhavetofix.

Page 74: Arduino networking   marco schwartz
Page 75: Arduino networking   marco schwartz

SummaryInthissecondchapterofthebook,webuiltourfirstapplicationbasedontheArduinoEthernetshieldandEthernetclientclass.WedidsomebasicmeasurementsontheArduinoboard,sentthesemeasurementsonalocalwebserver,andfinallydisplayedthisdatainrealtimeonagraph.

Toproceedfurtherwiththischapter,IinviteyoutocarefullyrepeatallthestepsofthischaptertoreallyunderstandwellhowtheArduinoEthernetshieldcommunicateswiththePHPcoderunningonyourcomputer.Youcanalsoaddmoresensorstotheprojectsandlogthisdatainsidethedatabase.Also,youcantrytoplotseveralvariablesatonceondifferentgraphs.

Thesewerethemajortakeawaysfromthischapter:

First,weinterfacedadigitaltemperatureandhumiditysensortotheArduinoboardsothatwecansendthemeasurementstoalocalwebserverusingtheEthernetshield.Wealsoinstalledsomeusefulsoftwarecomponentssuchasalibrarytoplotdatainawebpage.Then,webuiltanArduinosketchtosenddatadirectlytoawebserverrunningonyourcomputer.Afterthat,westartedbuildingtheserver-sidecodebycodingthefileresponsibleforloggingdataintoalocaldatabase.WealsotestedthiscodewiththeArduinoEthernetshield,andmadesurethatthedatawascorrectlytransmittedtotheserverandloggedinthedatabase.Finally,webuiltawebpagetoautomaticallyplotthedataasitisreceivedonthewebserver,usingaJavaScriptlibrarycalledflot.

Inthenextchapter,wearegoingtodosimilarthings,butusingacompletelydifferentapproach:insteadofrunningaclientontheArduinoboardandtransmittingthedataonalocalwebserver,wearegoingtoruntheserverrightontheArduinoboard.TheArduinoprojectwillconstantlydisplaythemeasurementsonawebpageandlogthedatalocallyonaSDcard.

Page 76: Arduino networking   marco schwartz
Page 77: Arduino networking   marco schwartz

Chapter3.DataLoggingStationInthischapter,wearegoingtocreatesomethingreallysimilartowhatwedidinChapter2,SendingDatatoaWebServer,thatismeasuringdatafromasensor,storingthedata,andsendingitbacktoawebserversothatitcanbeplotted.

However,thingsaregoingtobesimilaronlyontheappearancefront.InsteadofhavinganEthernetclientthatrunsontheArduinoboardandsendsdatatoaserver,wearegoingtomaketheArduinoboardmoreindependent.Inthefirstpartofthechapter,wearegoingtologthedatalocallyusingtheintegratedMicroSDcardreaderoftheEthernetshield.

Then,wearegoingtocreateaserverrightontheArduinoboard.Theboardwillmeasuredataasusual,buttheserverwillservethedatatotheincomingclients.Finally,wewilluseamodifiedversionofthecodeweusedintheChapter2,SendingDatatoaWebServer,toplotthemeasureddataonyourcomputer.

Thefollowingwillbethemajortakeawaysofthischapter:

First,wearegoingtobuildthehardwareforthisproject,includingthetemperatureandhumiditysensor,andtheSDcardtologthemeasureddata.Then,wewillcreatethefirstpartoftheproject,andlogdataautomaticallyontheSDcard,whichisinsertedinsidetheEthernetshield.Atthispoint,wearegoingtousetheInternetconnectionoftheEthernetshieldtoautomaticallyobtainthecurrenttimefromaNetworkTimeProtocol(NTP)timeserver.Finally,wearegoingtobuildawebserverandrunitontheArduinoboard.Youwillthenbeabletoaccessthedatameasuredbytheboardjustbyenteringintheaddressoftheboardinawebbrowser.WearealsogoingtomodifythecodefromthelastchaptertoobtainthemeasurementsfromtheArduinoboardandplotthemliveinyourbrowser.

Page 78: Arduino networking   marco schwartz

HardwareandsoftwarerequirementsOnthehardwarefront,youwillofcourse,needtheArduinoEthernetshieldandanArduinoboardsuchastheArduinoUno.

Youwillalsoneedasensortomeasuresomedata.AsthisbookisabouthowtousetheEthernetshieldandnothowtomeasurefromsensors,youcouldactuallytakeanysensorofyourchoice.

IusedaDHT11sensor,whichisadigitaltemperatureandhumiditysensor.IchosethissensorforthischapterandformanychaptersofthebookasitisaverycheapsensorandeasytointerfacewithArduino.AlongwiththeDHT11sensor,youwillalsoneeda4.7kohmresistor.

Tologthedata,youwillneedtohaveaMicroSDcardthatyoucanplugintotheEthernetshield.Idon’thaveaspecificbrandtorecommend,butIusedaSanDiskMicroSDcardwithanormalSDadapter(whichworkedwellforme),soyoucanalsoplugitintoyourcomputertocheckwhetherthedatawascorrectlylogged.Also,makesurethattheSDcardisformattedusingtheFAT32format.

YouwillalsoneedabreadboardandsomejumperwirestocreatetheconnectionbetweenthesensorandtheEthernetshield.

Thefollowingisalistofallcomponentsthatwereusedforthischapter:

TheArduinoUno(https://www.adafruit.com/products/50)TheArduinoEthernetshield(https://www.adafruit.com/products/201)TheDHT11sensor(https://www.adafruit.com/products/386)AMicroSDcard(http://www.amazon.com/SanDisk-Micro-SDHC-Memory-Adapter/dp/B0052MHQM6)Abreadboard(https://www.adafruit.com/product/64)Jumperwires(https://www.adafruit.com/product/758)

Onthesoftwarefront,thefirstthingyouwillneedisthelibrarytointerfacewiththesensoryouchosebefore.IchoseaDHT11sensorforthisproject.YouwillneedtodownloadandinstalltheDHTlibraryfromhttps://github.com/adafruit/DHT-sensor-library.

ToinstallanArduinolibrary,simplyunzipthecontentofthedownloadedfiletoyourlibrariesfolderofyourmainArduinofolder(orcreatethisfolderifyouhaven’tdonesoalready).

Page 79: Arduino networking   marco schwartz

HardwareconfigurationIt’snowtimetosetupthehardwareforthisproject.Atthispoint,ifyoufollowedanyofthepreviouschaptersofthisbook,youshouldalreadyhaveyourArduinoEthernetshieldpluggedintotheArduinoboard,andoneEthernetcableconnectingtheEthernetshieldandyourInternetrouter.Ifthat’snotthecasealready,pleasedoso.

TheonlythingyouwillhavetoconnectinthisprojectistheDHT11sensorandtheresistor.Youcanseeanoverviewofthedifferentconnectionsyouhavetomakebylookingatthefollowingschematicdiagram:

First,plugtheDHT11sensorintothebreadboard.Then,connectthepinnumber1and2ofthesensorusingthe4.7kohmresistor.

Nowcomesthepowersupply.Connectthepinnumber1ofthesensortotheArduino5V,andthepinnumber4totheArduinoGND.Finally,connectthepinnumber2oftheDHTsensortotheArduinopinnumber7.

Attheend,itshouldlooklikethefollowingimage:

Page 80: Arduino networking   marco schwartz

Finally,simplyinserttheSDcardintotheSDcardslotontheEthernetshield.

Page 81: Arduino networking   marco schwartz
Page 82: Arduino networking   marco schwartz

LoggingdataonanSDcardLet’sstartwiththefirsttopicofthischapter—loggingdataonaSDcardusingtheintegratedSDcardslotoftheEthernetshield.WhatwearegoingtodoisperformsomemeasurementsontheArduinoboardandlogeachofthesemeasurementstotheSDcardinasimpletextfile.

However,comparedtotheprojectoftheChapter2,SendingDatatoaWebServer,wedon’tactuallyknowthedatewhenthemeasurementwastaken.Inthepreviouschapter,wesimplyusedthedateofthecomputer,butwedon’thavethisinformationhere.TogetthetimeontheArduinoboard,wearegoingtouseanotherstrategy.WearegoingtousetheEthernetshieldtoconnecttoanNTPtimeserver,grabthetimeoncewhentheArduinosketchstarts,andthenusetheTimelibrarytotrackthetimefromthere.

TolearnmoreabouttheTimelibrary,youcanvisitthefollowingpageontheArduinowebsite:

http://playground.arduino.cc/Code/Time

TheprocessofloggingdataonaSDcardstartsbyincludingthecorrectlibrariesasfollows:

#include"DHT.h"

#include<SD.h>

#include<Time.h>

#include<Ethernet.h>

#include<EthernetUdp.h>

#include<SPI.h>

Wealsoneedtodefinethesensortypeandthepintowhichthesensorisconnected.Thisisdonewiththefollowinglinesofcode:

#defineDHTPIN7

#defineDHTTYPEDHT11

TodefinetheMACaddressoftheEthernetshield,usethefollowinglineofcode:

bytemac[]={0x90,0xA2,0xDA,0x0E,0xFE,0x40};

TousetheSDcard,youwillalsoneedtodefinethechipSelectpin,whichisthepinnumber4ontheEthernetshield.Thisisdoneusingthefollowingline:

constintchipSelect=4;

Now,wearegoingtodealwiththeNTPserver.ThereareactuallyseveralNTPserversyoucanuse(youcanseetheIPaddressesofmanyoftheseserversinsidetheTimeNTPexamplethatcomewiththeTimelibrary).Youcanalsosetyourtimezonehere.TogetmoreinformationaboutwhichNTPserveryoucanuseandwhichtimezonetoset,youcanhavealookattheexampleTimeNTPsketch.ThissketchisgivenasanexampleinsidetheTimelibrary.Forthisproject,Iusedthefirstserveravailablewithtimezonenumber1,asshowninthefollowingcode:

Page 83: Arduino networking   marco schwartz

IPAddresstimeServer(132,163,4,101);

constinttimeZone=1;

Toconnecttothisserver,wealsoneedtodefineanEthernetclient.Thistime,wearegoingtouseaprotocoldifferentfromtheearlierone,whichiscalledUDP.UDPisdifferentfromTCP—it’smuchsimplerandlighter.However,itdoesn’tguaranteethatthedatawascorrectlydelivered,whichTCPdoes.Youdon’tactuallyneedtocareaboutthedetailsofthisprotocol,astheTimelibraryhandleseverything.YoucanjustleavethedefaultUDPport,asshowninthefollowingcode:

EthernetUDPUdp;

unsignedintlocalPort=8888;

YoualsoneedtocreateaninstanceoftheDHTsensorasfollows:

DHTdht(DHTPIN,DHTTYPE);

Now,inthesetup()functionofthesketch,youneedtodefinethefollowingcoderesponsibleforgettinganIPaddressfortheEthernetshield:

Serial.begin(9600);

if(Ethernet.begin(mac)==0){

//nopointincarryingon,sodonothingforevermore:

while(1){

Serial.println("FailedtoconfigureEthernetusingDHCP");

delay(10000);

}

}

Afterthat,wewilltrytoinitializetheSDcard,asshowninthefollowingcode:

Serial.print("InitializingSDcard…");

pinMode(10,OUTPUT);

Ifthisissuccessful,wewillprintoutamessageontheSerialport,asshowninthefollowingcode:

if(!SD.begin(chipSelect)){

Serial.println("Cardfailed,ornotpresent");

//don'tdoanythingmore:

return;

}

Serial.println("cardinitialized.");

WewillalsostarttheDHTsensorasfollows:

dht.begin();

Finally,stillinthesetup()function,wewillprintouttheIPaddressoftheEthernetshieldandcreatetheconnectiontotheNTPserver.NotethatherewearecallingafunctioncalledgetNtpTime,whichisdefinedlaterinthesketch.AsthisisafunctionprovidedbytheTimelibrary,wearenotgoingtolookintothedetailsofthisfunction.Thefollowingisthecodeforthispart:

Serial.print("IPnumberassignedbyDHCPis");

Serial.println(Ethernet.localIP());

Page 84: Arduino networking   marco schwartz

Udp.begin(localPort);

Serial.println("waitingforsync");

setSyncProvider(getNtpTime);

Now,intheloop()functionofthesketch,wewillfirstmeasurethetemperatureandhumidityfromthesensorusingthefollowingcode:

floath=dht.readHumidity();

floatt=dht.readTemperature();

Secondly,wewillconvertthesemeasurementstostringsasfollows:

Stringtemp=String((int)t);

Stringhum=String((int)h);

WearenowgoingtobuildastringthatcontainsthedateandtimeofthemeasurementusingtheTimelibrary.Thislibrarycontainsfunctionstogetthecurrenttime,day,ormonth,forexample,whicharecalculatedfromtheinitialcalltotheNTPserver.Forexample,callingtheday()functionwillreturnthecurrentday.Thefollowingpieceofcodereturnsastringwiththedateandtime:

Stringlog_time=String(day())+"/"+

String(month())+"/"+String(year())+""+

String(hour())+":"+String(minute())+":"+

String(second());

Wethenassemblethisstringwiththetemperatureandhumiditymeasurementsusingcommasasseparatorsbetweenthedifferentstrings,asshowninthefollowinglineofcode:

StringdataString=log_time+","+temp+","+hum;

WearenowgoingtowritethisdataontheSDcard.Wefirstneedtoopenthecardtowritedatausingthefollowingline:

FiledataFile=SD.open("datalog.txt",FILE_WRITE);

Ifthat’ssuccessful,wewillputthecontentsofthedataStringvariabletothisfilenameddatalog.txt,asshowninthefollowingcode:

if(dataFile){

dataFile.println(dataString);

dataFile.close();

Serial.println(dataString);

}

else{

Serial.println("erroropeningdatalog.txt");

}

Finally,wewillrepeattheoperationevery10seconds,butyoucan,ofcourse,modifythisdelaywiththefollowingline:

delay(10000);

Note

Page 85: Arduino networking   marco schwartz

AllthecodeforthissectioncanbefoundinsidetheGitHubrepositoryofthischapterathttps://github.com/openhomeautomation/arduino-networking/tree/master/chapter3.

It’snowtimetotestthissketch.MakesurethattheEthernetcableispluggedintotheshieldandyourInternetrouter,andtheSDcardispluggedintotheEthernetshieldSDcardslot.YoucannowuploadthesketchtotheboardandopentheSerialMonitor.Thefollowinglineiswhatyoushouldseefirst:

InitializingSDcard…cardinitialized.

Then,youshouldseethatyourEthernetshieldhasanIPaddress,asshowninthefollowingline:

IPnumberassignedbyDHCPis192.168.1.103

YoushouldseethatthisshieldiscurrentlysynchronizingthetimewiththeNTPserver,asshowninthefollowingoutput:

waitingforsync

TransmitNTPRequest

ReceiveNTPResponse

Afterthat,youshouldseethatthefirstmeasurementismadeasfollows:

21/5/20149:32:13,22,38

Afterthedelayyoufixedinthesketch,youwillseethatasecondmeasurementismadewiththecorrespondingdateandtime.TobesurethatthesketchiscorrectlywritingdataontheSDcard,youcanletitrunforawhileandthendisconnecttheEthernetshieldfromthepowersupply.Afterthis,removetheSDcard,andreaditonyourcomputerviaanadapter.Youshouldseethefollowingscreenshot:

Page 86: Arduino networking   marco schwartz

Asyoucansee,allthemeasurementswerecorrectlyloggedontheSDcard,andwecanclearlyseethattheintervalbetweentwomeasurementswas10seconds.

Page 87: Arduino networking   marco schwartz
Page 88: Arduino networking   marco schwartz

CreatingawebserveronArduinoFortherestofthischapter,wearegoingtotakeanotherapproach.WearestillgoingtomaketheArduinowiththeEthernetShieldworkasanindependentsystem,butthistimeweareevengoingtocreateawebserverontheArduinoboard.ThisisactuallysimilartotheprojectwesawintheChapter2,SendingDatatoaWebServer,butthistimeitistheArduinoboarditselfthatwilldisplaythedataasitismeasured.

Thesketchforthispartstartsbyincludingtherightlibraries,asshowninthefollowingcode:

#include"DHT.h"

#include<Ethernet.h>

#include<SPI.h>

Definethepinandthetypeofthesensorinthefollowingmanner:

#defineDHTPIN7

#defineDHTTYPEDHT11

Also,youhavetodefinetheMACaddressofyourEthernetshieldasusual,asshowninthefollowinglineofcode:

bytemac[]={0x90,0xA2,0xDA,0x0E,0xFE,0x40};

WewillalsodefineadefaultIPaddressincasetheDHCPfails,asshowninthefollowingline:

IPAddressip(192,168,1,50);

Thisiswherethenewfeaturecomesin.Sofar,weonlyusedtheEthernetClientclasstodefineaclientthatwillconnecttoaremoteserver.Here,however,becausewewanttocreateaserverrightontheArduinoboard,wearegoingtousetheEthernetServerclass,asshowninthefollowinglineofcode:

EthernetServerserver(80);

Youcanusetheport80foryourserver,asitwillbemucheasiertoaccesstheserverfromyourwebbrowser.

WealsoshouldnotforgettocreateaninstanceoftheDHTsensor.Thisisdoneusingthefollowingline:

DHTdht(DHTPIN,DHTTYPE);

Now,inthesetup()functionofthesketch,wewilltrytouseDHCPtogetanIPaddressfortheEthernetshieldusingthefollowingcode:

if(Ethernet.begin(mac)==0){

Serial.println("FailedtoconfigureEthernetusingDHCP");

Ethernet.begin(mac,ip);

}

Stillinthesetup()function,wealsohavetostartourEthernetserver,andprintouttheIP

Page 89: Arduino networking   marco schwartz

addressoftheserverusingthefollowingcode:

server.begin();

Serial.print("Serverisat");

Serial.println(Ethernet.localIP());

Finally,wewillstarttheDHTsensorasfollows:

dht.begin();

Now,intheloop()partofthesketch,wewillperformthetemperatureandhumiditymeasurements,asshowninthefollowingcode:

floath=dht.readHumidity();

floatt=dht.readTemperature();

Convertthemeasurementstostringsusingthefollowingcode:

Stringtemp=String((int)t);

Stringhum=String((int)h);

Then,weneedtohandletheconnectionsthatcometotheArduinoboard,forexample,fromawebbrowser.Todoso,weareactuallygoingtocreateaninstanceoftheEthernetClientclasseverytimetheserverbecomesavailable.Asthisisaclasswealreadysawinpreviouschaptersofthebook,thisissomethingwealreadyknowhowtoworkwith.

Ifaconnectionisdetected,wecreatethisclient,andprintitoutontheSerialportfordebuggingpurposes,asshowninthefollowingcode:

EthernetClientclient=server.available();

if(client){

Serial.println("Newclient");

Thenextpartisabittechnical.Weneedtoreadouttherequestthatcomesfromtheclient,butalsodetectthemomentwhentherequestisoversothatwecanclosetheconnection.Thisishandledbyalwayscheckingwhetherthecurrentlineisblankornot.Thefirststepisthentoreadouttherequestthatcomesfromtheclient,characterpercharacter,usingthefollowingpieceofcode:

booleancurrentLineIsBlank=true;

while(client.connected()){

//Readdata

if(client.available()){

charc=client.read();

Serial.write(c);

NotethattheincomingrequestisalsoprintedoutontheSerialportfordebuggingpurposes.Now,ifwedetectthatwehaveanendoflinecharacterandthatthecurrentlineisblank,it’sasignthattherequestisover,asshowninthefollowingline:

if(c=='\n'&&currentLineIsBlank){

Page 90: Arduino networking   marco schwartz

Therefore,wecananswertheclient.WewillfirstsendastandardHTTPheaderthatstateseverythingwentOK,andthatwewanttorefreshthepageautomaticallyevery5seconds,asshowninthefollowingcode:

client.println("HTTP/1.1200OK");

client.println("Content-Type:text/html");

client.println("Connection:close");

client.println("Refresh:5");//Refreshthepageautomaticallyevery5

sec

client.println();

client.println("<!DOCTYPEHTML>");

client.println("<html>");

Then,wewillprintoutthedatafromthemeasurementonthepageusingthefollowingcode:

client.print("Temperature:");

client.print(temp);

client.print("<br/>");

client.print("Humidity:");

client.print(hum);

client.println("<br/>");

client.println("</html>");

Therestofthefollowingcodeistheretodetectwhetherwereachedtheendoftherequestornot:

if(c=='\n'){

//Startinganewline

currentLineIsBlank=true;

}

elseif(c!='\r'){

//you'vegottenacharacteronthecurrentline

currentLineIsBlank=false;

}

Finally,wewillgivethebrowserasmalldelaytoreceivetheanswer,andwewillclosetheconnection,asshowninthefollowingcode:

//Givethewebbrowsertimetoreceivethedata

delay(1);

//Closetheconnection:

client.stop();

Serial.println("Clientdisconnected");

NoteAllthecodeforthissectioncanbefoundintheGitHubrepositoryofthischapterathttps://github.com/openhomeautomation/arduino-networking/tree/master/chapter3.

It’snowtimetotestthecodethatwewroteinthissection.Again,makesurethattheEthernetcableispluggedtotheEthernetshieldandtoyourrouter.Then,youcanuploadthecodetotheboard,andopentheSerialMonitor.YoushouldfirstseetheIPaddressofthewebserverrunningontheArduinoboardasfollows:

Page 91: Arduino networking   marco schwartz

Serverisat192.168.1.103

Afterthat,thesketchwilljustdonothingwhilewaitingforanyincomingconnection.Tomakeaconnectionhappen,justgoovertoyourwebbrowserandtypeintheIPaddressoftheboard.YoushouldimmediatelyseetheGETrequestfromthebrowserbeingprintedoutintheArduinoSerialMonitor,asshowninthefollowingoutput:

Newclient

GET/HTTP/1.1

Host:192.168.1.103

Connection:keep-alive

Cache-Control:max-age=0

Accept:

text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

User-Agent:Mozilla/5.0(Macintosh;IntelMacOSX10_9_3)

AppleWebKit/537.36(KHTML,likeGecko)Chrome/34.0.1847.137Safari/537.36

Referer:http://192.168.1.103/

Accept-Encoding:gzip,deflate,sdch

Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de;q=0.2

Aswecansee,thereisalotoftextandthisdependsonyourbrowser.However,theimportantthingisactuallythefirstlineoftherequest,whichmeansit’saGETrequesttoourArduinoboard.

Finally,aftertheArduinoanswerstheserver,theconnectionisclosedandthefollowingmessageisdisplayed:

Clientdisconnected

Inyourbrowser,youshouldalsodirectlyseethatthedataisbeingprintedoutonthepagecreatedbytheArduinoboard,asshowninthefollowingscreenshot:

Ifyoucanseethis,congratulations,youjustcreatedyourownwebserverthatrunsonanArduinoboard.Ifyoucan’tseeapage,firstmakesurethatArduinohasanIPaddressanditcanbeconnectedtoyourlocalnetwork.Todoso,repeattheinstructionsinChapter1,DiscovertheArduinoEthernetShield,again.

AlsomakesurethatyoucorrectlyenteredtheIPaddressoftheboardinyourbrowser.YoucanalsocheckontheSerialMonitorthatyouarenotreceivinganyerrormessagesfromtheDHTsensor,whichwillcompromisethebehaviorofthewebserver.

Page 92: Arduino networking   marco schwartz
Page 93: Arduino networking   marco schwartz

PlottingthedatalocallyToendthechapter,wearegoingtoseehowtoplotdatameasuredbytheArduinoboard.Todoso,wewillmodifytheArduinosketchalittlebit,andthenusepartofthecodefromthepreviouschaptertoplotthedatarightinyourwebbrowser.

First,wearegoingtomodifytheArduinosketchsothatitreturnsdatainamoreusefulformat;inthepresentcase,theJSONformat.Inplaceofthecoderesponsibletoprintoutthemeasurements,wearegoingtosimplyprintthedataintheJSONformat.Thisisdoneusingthefollowingpieceofcode:

client.println("HTTP/1.1200OK");

client.println("Content-Type:application/json");

client.println("Connection:close");

client.println();

client.print("{\"temperature\":");

client.print(temp);

client.print(",\"humidity\":");

client.print(hum);

client.println("}");

Wecannowquicklytestthisproject.UploadthecodetotheArduinoboardagain,openyourwebbrowser,andgotothesameIPaddressyouusedbefore.Youshouldseethefollowinglineprintedonthepage:

{"temperature":24,"humidity":36}

Now,wealsohavetobuildtheserver-sidecodetoplotthedata.Thecodeisverysimilartothecodeofthepreviouschapter,soIwillonlydetailthedifferencesbetweenthetwoprojects.Inthepreviouschapter,itwastheboardthatwastryingtoreachouttheserverrunningonyourcomputer,andthedatalogger.phpfilewashandlingtherequests.Inthischapter,wearegoingtodothereverseandcalltheboardfromthewebserverrunningonyourcomputer.Todoso,wearegoingtouseamodulefromPHPcalledcURLtomakeGETrequeststoagivenURL;inthiscase,theURLoftheArduinoboard.

Thefirstthingwehavetodoismakechangestothedatalogger.phpfileandaddtheURLoftheArduinoboard,asshowninthefollowinglineofcode:

$url='http://192.168.1.103';

StartthecURLcall,asshowninthefollowinglineofcode:

$curl=curl_init();

WealsohavetosettheoptionsofthecURLcall.WewantthecalltoreturnthedatafromourArduinowebserver,andwealsowanttheURLtobetheonewedefinedbefore.Thisisdoneusingthefollowingcode:

curl_setopt_array($curl,array(

CURLOPT_RETURNTRANSFER=>1,

CURLOPT_URL=>$url,

));

Page 94: Arduino networking   marco schwartz

Wecannowexecutethecommand,asshowninthefollowinglineofcode::

$resp=curl_exec($curl);

ClosethecURLcall,asfollows:

curl_close($curl);

Wegettheanswerinavariablethatcontainsthedatainastring.InordertoopenitwithPHP,weneedtoconvertittotheJSONformatfirst,andthenextractthetemperatureandhumidityfields.Thisisdoneusingthefollowingpieceofcode:

$json=json_decode($resp,true);

$temperature=intval($json["temperature"]);

$humidity=intval($json["humidity"]);

Therestofthefileisstrictlyidenticaltothecodewedevelopedinthepreviouschapter.

Now,wealsoneedtomakeasmallmodificationintheplot.htmlfile.Inthepreviouschapter,thedatawasautomaticallyloggedinsidethedatabaseastheArduinoboardwasconstantlysendingdatatotheserver.Here,weneedtomakethecallontheserverside.Thisisdonebyaddingthefollowingsmallpieceofcodejustbeforethecodethatreadsoutthedatafromthedatabase:

$.ajax({

url:"datalogger.php",

type:"GET",

});

Thismeansthatjustbeforethedataisreadfromthedatabasetobeplotted,wearecallingtheArduinoboardtogetthetemperatureandhumiditymeasurements.

NoteAllthecodeforthissectioncanbefoundinsidetheGitHubrepositoryofthischapterathttps://github.com/openhomeautomation/arduino-networking/tree/master/chapter3.

Wecannowtestthispartofthechapter.NotethatthecodefromtheGitHubrepositoryincludesanexampledatabasesoyoucantesttheprojectrightaway,butIrecommenddeletingthefilejustbeforetestingtheproject,soyouwillplotyourownmeasureddatawhiletestingthecode.

Youcanjustputallthecodefortheplottingpartinsideafolderattherootofyourwebserver.Then,opentheplot.htmlfileviathelocalhostURLinyourwebserver.Youshouldimmediatelyseethatdataisbeingplottedinsideyourwebbrowser.Afterawhile,youshouldgetagraphsimilartothefollowinggraph:

Page 95: Arduino networking   marco schwartz

Ifyoucanseethisplotinyourbrowser,congratulations!ThismeansyoucanperformremotemeasurementsfromthewebserverrunningonyourArduinoboard.

Ifthisisnotthecase,thereareseveralthingsyoucancheck.ThisfirstthingyoucancheckismakingsurethattheArduinoboardcorrectlydisplaysthedatainaJSONformat.Todoso,youcansimplyentertheaddressofyourboardinabrowser.Then,checkwhetheryourwebserverisrunningonyourcomputerandthatyouhaveplacedallthefilesfromtheprojectinsidearepositoryinyourwebserver’smainfolder.Finally,makesurethatyouareaccessingtheHTMLfilefromthelocalhostURLinyourbrowserandnotbyclickingonitinsideyourfileexplorer.

Page 96: Arduino networking   marco schwartz
Page 97: Arduino networking   marco schwartz

SummaryLet’ssummarizewhatwedidinthischapter.WecreatedanindependentmeasurementstationwithArduinothatautomaticallymeasuresandservesthedatainsomeway.First,weloggedthedatalocallyonaSDcardandthenweservedthisdatausingawebserverrunningontheArduinoboard.

Thefollowingarethemajortakeawaysofthischapter:

1. First,webuilttherequiredhardwareforthischapter,andinsertedtheSDcardintotheEthernetshield.

2. Then,inthefirstpartoftheproject,weloggedthemeasureddataontheSDcardandusedaremotetimeservertoautomaticallygetthemeasurementtimes.

3. Finally,webuiltanewArduinosketchtohaveawebserverrunningontheArduinoboard.WethenmodifiedtheplottingcodefromthepreviouschaptersoitcancalltheserverontheArduinoboardtogetandplotthemeasureddata.

Thereare,ofcourse,manywaystoimprovethisproject.YoucanaddmoresensorstotheprojectandeitherlogthisadditionaldataonaSDcardorserveitonawebpageusingtheArduinowebserver.YoucanalsohavemanyoftheseboardsinyourhomeorevenoutsideandmakeyourcomputerpollalltheseArduinoserversataregularintervaltogettheirmeasurements.

Inthenextchapter,wearegoingtoworkagainwiththisideaofcreatinganindependentsystemwiththeArduinoEthernetshield.WearegoingtoconnectarelaytotheArduinoboard,soyoucanswitchalamponandoffremotely.Thisprojectwillcomeintwoflavors.First,wewillmakeasketchtocontroltherelayremotelyviayourwebbrowser.Inthesecondpartofthechapter,wewilluseaspeciallibrarysotherelaycanbecontrolledfromanywhereintheworld.

Page 98: Arduino networking   marco schwartz
Page 99: Arduino networking   marco schwartz

Chapter4.ControllingObjectsfromAnywhereInthischapter,wearegoingtodosomethingdifferenttowhatwedidintheotherchapters.WhatwedidsofarwasmeasuresomedataontheArduinoboardandtransmitthisdatabacktothenetworkusingtheEthernetshield.Inthischapter,wearegoingtocontroladeviceinsteadofmeasuringdata.

Todoso,wewillusearelayconnectedtotheArduinoboardwiththeEthernetshieldandcontrolthisrelayremotely.Wearealsogoingtoconnectasetofpowercablestothisrelaysoyoucandirectlyplugalampintoitsothatitcanbecontrolledremotely.

Inthefirstpartofthechapter,wearegoingtocontrolthisrelayremotelywithinyourlocalnetwork.Inthesecondpartofthechapter,wewilluseadedicatedwebservicetocontrolthisrelayfromanywhereintheworld.

Thefollowingwillbethemajortakeawaysfromthischapter:

First,wearegoingtoseehowtochoosethedifferentcomponentsforthisproject,includingtherelayandcablestoconnectadevicetotherelaysuchasalamp.Then,wewillassemblethedifferenthardwarecomponents,connecttherelaytotheArduinoboard,andthepowercablestotherelay.Afterthat,wewillwriteanArduinosketchtotestwhethertherelayisworkingcorrectlyandhasbeencorrectlyconnectedtothecircuit.Whenwearesurethattherelayisworking,wewillwriteanapplicationusingtheEthernetshieldalongwiththerelay.WearegoingtowriteasketchtocontroltherelayviaEthernetandthenbuildaninterfacetocontroltherelayfromyourwebserver.Finally,inthelastsectionofthechapter,wearegoingtouseadedicatedwebservicetocontroltherelayfromanywhereintheworld.Wearealsogoingtoadapttheinterfacewejustcreatedtocontroltherelayfromanywhere.

Page 100: Arduino networking   marco schwartz

HardwareandsoftwarerequirementsLet’sfirstseewhatweneedforthisproject.Aswithalltheotherchapters,youwillneedanArduinoboardandtheArduinoEthernetshield.

Youwillalsoneedarelaymodule.Ireallyrecommendusingarelaythatisintegratedonaboard,withalltherequiredcomponentsontheboardaswell.Itwillavoidyouhavingtobuildyourownrelaymoduleonabreadboard,anditisalsomuchsafer.Indeed,thereisnoriskinwiringtherelayandothercomponentsinanincorrectfashion.Simplymakesurethattherelayyouchooseiscompatiblewith5Vinputvoltagelevels.Also,youhavetomakesurethattherelaymodulecanhandlethepowerofthedeviceyouaregoingtouseforthisproject.Forexample,thelampIusedwasa30Wlamp,andtherelaycouldhandlemorethan1000W,justtobeonthesafeside.Ichosea5VrelaymodulefromPolulu,asshown:

Youcansimplyusetherelayasitisandcontrolitwiththecodewearegoingtodevelopinthisproject,butthegoalofhavingarelayistoconnectadevicetoit.Forthisproject,Ichosetoconnectalamptotherelay,butbyfollowingtheinstructionsinthischapter,youwillbeabletoconnectanydevicethatusesastandardpowerplug.

Todoso,Iusedasetofpowercables,onewithamalesocketandonewithafemalesocket,asshowninthefollowingimage:

Page 101: Arduino networking   marco schwartz

Themaleplugwillbeusedtoconnecttherelaytothemainpowerpluginthewallandthefemalesocketwillbeusedtoconnectthedevicetocontroltherelay.

NoteAlwaysbeverycarefulwhenconnectingwirestothemainelectricity.Makesurethatyoudon’ttouchanyoftheexposedpartsoftherelay,andmakesurethatthecablesthemselvesdon’thaveanyexposedcopper.Also,connecttheplugtotheelectricitylatestwhenassemblingtheproject.

Let’snowseethesoftwarerequirementsforthisproject.Asusual,youwillneedtohavetheArduinoIDEinstalled,alongwithawebserverrunningonyourcomputer.

Inthesecondpartofthechapter,wearegoingtouseaservicecalledTeleduinotocontroltheEthernetshieldfromanywhere.Tousethisservice,youwillneedtogetanAPIkey,whichyouwillhavetoinsertinsidetheArduinosketch.

Youcangetakeybyvisitingthefollowingaddress:

https://www.teleduino.org/tools/request-key

Youwillbetakentothefollowingpagewhereyoucangetyourkey:

Page 102: Arduino networking   marco schwartz

YouwillalsoneedtoinstallafewArduinolibrariesforthischapter.

ThefirstoneyouwillneedistheaRESTlibraryforArduino,whichyoucanfindatthefollowinglink:

https://github.com/marcoschwartz/aREST

Finally,youwillalsoneedtodownloadandinstalltheTeleduinolibrary,whichyoucanfindhere:

https://www.teleduino.org/downloads/

Toinstallagivenlibrary,simplyextractthefoldertoyourArduino/librariesfolder(orcreatethisfolderifitdoesn’texistyet).

Page 103: Arduino networking   marco schwartz

HardwareconfigurationNowlet’sseehowtoconnectthedifferentcomponentsoftheproject.Aswiththeotherchaptersofthebook,youwillneedtohavetheEthernetshieldpluggedintotheArduinoboard.YouwillalsoneedtoconnectanEthernetcablebetweentheEthernetshieldandyourrouter.

Then,youneedtoconnecttherelaymodule.Therelaymodulehasthreeinputpins:VCC,GND,andasignalpinusuallycalledSIG.YouneedtoconnecttheVCCpintoArduino5V,GNDtoArduinoGND,andfinallythesignalpintoArduinopinnumber7,whichisadigitalpin.Thefollowingimageshowsthesystematthispoint:

Then,youneedtoconnectthepowercablestotherelaymodule.Arelaymodulebasicallyhasthreeoutputpins:COM(forthecommonpin),NC(forthenormallyclosedpin),andNO(forthenormallyopenpin).

WhatwewantistohavetheCOMpinoftherelayconnectedtoonewireofthepowerplug,NCnotconnected,andNOconnectedtooneotherwireofthepowerplug.Thefollowingimagesummarizestheconnectionsatthisstage:

Page 104: Arduino networking   marco schwartz

First,connectonepinofthefemalepowerplugtotheCOMpin.Then,connectonepinofthemalepowerplugtotheNOpin.Finally,connectthetworemainingcablestogether,forexample,usingatypicalelectricalscrewterminal.

Oncethisisdone,youcanconnectthedeviceyouwanttocontroltherelay.Connectthelampinsidethefemalepowersocket,andthenconnectthemalepowerplugtothepowerpluginthewall.Thefollowingimagerepresentsthesystematthispoint,withoutthedevicetocontrolbeingconnected:

Ifyouhavesomethingsimilar,congratulations!Youaredonewiththehardwareconnectionsforthischapter.

Page 105: Arduino networking   marco schwartz
Page 106: Arduino networking   marco schwartz
Page 107: Arduino networking   marco schwartz

TestingtherelayWearenowgoingtobuildaverysimplesketchtotestthehardwareconnectionswejustmade.Thesketchwillsimplyswitchtherelayonandoffeverysecond.

Thesketchstartsbydeclaringtherightpinfortherelay:

constintrelay_pin=7;

Then,wesetthispinasanoutput:

pinMode(relay_pin,OUTPUT);

Then,intheloop()functionofthesketch,wesettherelaytoaHIGHstate:

digitalWrite(relay_pin,HIGH);

Wewaitfor5seconds:

delay(5000)

Then,weswitchtherelaypintoaLOWstateagain:

digitalWrite(relay_pin,LOW);

Wethenwaitagainfor5seconds:

delay(5000);

NoteThecodeforthissectioncanbefoundintheGitHubrepositoryforthischapterathttps://github.com/openhomeautomation/arduino-networking/tree/master/chapter4.

YoucannowuploadthecodetotheArduinoboard.Youshouldheartherelayswitchingonandoffeverysecond.Ifyouconnectalamptotheproject,forexample,youshouldalsoseeitswitchingonandoffeverysecond.

Page 108: Arduino networking   marco schwartz
Page 109: Arduino networking   marco schwartz

ControllingtherelayremotelyNow,wearegoingtobuildourfirstinterestingapplicationusingthesystemwejustassembled.WearegoingtobuildanArduinosketchtocontroltherelayfromanywherewithinyourlocalnetwork.Forexample,ifyourcomputerisconnectedviaWi-FitoyourrouterandtheEthernetshieldisconnectedtothesamerouter,youwillbeabletocontroltherelayviayourcomputer.TheadvantageofthisapproachinthissectionisthatevenifyourInternetconnectionisdown,youwillstillbeabletocontroltherelay.

Theapplicationstartsbyincludingthecorrectlibraries:

#include<SPI.h>

#include<Ethernet.h>

#include<aREST.h>

WesetuptheMACaddressoftheboard:

bytemac[]={0x90,0xA2,0xDA,0x0E,0xFE,0x40};

WealsodefineadefaultIPaddressfortheboardthatwillbeusedifDHCPfails:

IPAddressip(192,168,1,150);

WethencreateaninstanceoftheaRESTlibrary,whichwillhandletherequestthatcomestotheboard:

aRESTrest=aREST();

YoualsoneedtocreateaninstanceoftheEthernetserver:

EthernetServerserver(80);

Inthesetup()functionofthesketch,wegetanIPaddressusingDHCP,asshowninthefollowingcodesnippet:

if(Ethernet.begin(mac)==0){

Serial.println("FailedtoconfigureEthernetusingDHCP");

Ethernet.begin(mac,ip);

}

PrinttheIPaddressontheSerialMonitor,usingthefollowingcode:

server.begin();

Serial.print("Serverisat");

Serial.println(Ethernet.localIP());

Finally,intheloop()functionofthesketch,wecheckwhetherthereareincomingclientsandhandletheseclientswiththeaRESTinstance:

EthernetClientclient=server.available();

rest.handle(client);

NoteThecodeforthissectioncanbefoundintheGitHubrepositoryforthischapterat

Page 110: Arduino networking   marco schwartz

https://github.com/openhomeautomation/arduino-networking/tree/master/chapter4.

YoucannowuploadthecodetotheArduinoboardandopentheSerialMonitor.YoushouldseetheIPaddressoftheboardbeingprintedout:

Serverisat192.168.1.103

Youcannowgotoyourwebbrowserandstarttypingincommands.TheaRESTlibraryallowsyoutodirectlycommandallthepinsoftheArduinoboardviaEthernet.Youcanfindthecompletedocumentationofthelibraryathttps://github.com/marcoschwartz/aREST.Forexample,wefirstneedtosetpinnumber7asanoutput.Thisisdoneusingthefollowingcommand:

http://192.168.1.103/mode/7/o

Youwillbegreetedwiththefollowingmessageinthebrowser:

PinD7settooutput

Now,tosetthepintoaHIGHstate,youcansimplytype:

http://192.168.1.103/digital/7/1

Youwillgettheconfirmationinyourbrowser:

PinD7setto1

Youshouldalsoheartherelayswitchingfromonestatetotheotherwhenyouenterthecommand.

Nowwearegoingtobuildtheserver-sideinterfacetocontroltherelayfromyourcomputerwithouthavingtoentercommandsmanuallyinyourbrowser.

TheinterfaceisbasedonHTML,JavaScript,andPHP.IntheHTMLfile,therearebasicallytwobuttons:onetoturntherelayonandonetoturntherelayoff.Thefollowingisthecodeforoneofthebuttons:

<buttonclass="btnbtn-blockbtn-lgbtn-primary"type="button"id="1"

onClick="buttonClick(this.id)">On</button>

Youcanseethatthebuttoncallsafunction,whichisdefinedinaJavaScriptfile.Nowlet’shavealookatthisfile.Thefirstthingwehavetodowhenthepageloadsissettherelaypintobeanoutput,justaswedidwhenwetypedcommandsdirectlyinthebrowser.Thisisdoneusingthefollowingpieceofcode:

window.onload=function(){

$.get("command.php",{command:"/mode/7/o"});

}

Youcanseethatwearecallingafilenamedcommand.php.Wewillseethedetailsofthisfilelater.Now,wesawearlierthateverytimeabuttonisclicked,itcallsafunctioncalledbuttonClick.ThefollowingfunctionisalsodefinedintheJavaScriptfile:

functionbuttonClick(clicked_id){

Dependingonwhichbuttonwasclicked,wesendthecorrespondingcommandtothe

Page 111: Arduino networking   marco schwartz

Arduinoboard.Forexample,fortheOnbutton,weputaHIGHstateontherelaypin,asshowninthefollowingcode:

if(clicked_id=="1"){

$.get("command.php",{command:"/digital/7/1"});

}

Finally,wehavetolookatthePHPfilethatwillactuallysendthecommandtotheboard.WefirstneedtogetthecommandthatwassentbytheJavaScriptfileandstoreitinavariable:

$command=$_GET['command'];

Then,weneedtosettheURLtowhichwewillsendthecommand.Tosendthecommandtotheboard,wewilluseaPHPmodulecalledcURL,whichwilldoexactlythesameaswhatwejustdidfromthewebbrowser.

Atthispoint,youwillhavetomodifytheIPaddressdefinedinthePHPfileandreplaceitwiththeIPaddressofyourboard.Thefollowingpieceofcodedoesjustthat:

$service_url='http://192.168.1.103'.$command;

$curl=curl_init($service_url);

Then,wecanactuallyperformthecURLcallusingthefollowingpieceofcode:

curl_setopt($curl,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);

curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,0.5);

$curl_response=curl_exec($curl);

curl_close($curl);

NoteThecodeforthissectioncanbefoundintheGitHubrepositoryforthischapterathttps://github.com/openhomeautomation/arduino-networking/tree/master/chapter4.

Wecannowtesttheinterface.Makesurethatallthefilesofthisinterfacearestoredinsideafolderattherootofyourwebserverfolder,andalsomakesurethatthewebserverisrunning.Then,gotothisfolderviathelocalhostpathinyourbrowserandopentheHTMLfile.Youshouldseethefollowingscreenshot:

Trytoclickononeofthebuttons:youshouldhearthattherelayinstantlyswitches

Page 112: Arduino networking   marco schwartz

accordingtothebuttonyouclicked.

NoteWhenyouloadedtheinterfaceinyourbrowser,therelaypinwasalsoautomaticallysettobeanoutput.

Page 113: Arduino networking   marco schwartz
Page 114: Arduino networking   marco schwartz

ControllingtherelayfromanywhereInthelastsectionofthischapter,wearegoingtotakeanotherapproach.Sofar,wehaveaserverrunningonourArduinoboard,whichcanreceivecommandsfromanydeviceonyourlocalnetwork.However,thisisnotconvenientifyouwanttocontroladevicefromanywhereintheworld.Forexample,youwanttoactivatealampinyourhomeatgivenintervalswhenyouareawayfromyourhome.

Todoso,wearegoingtousetheTeleduinoservice,whichallowsyoutodoexactlythat.TheArduinoEthernetshieldwillbeconstantlyconnectedtothisservice,soyoucantransmitcommandstotheboardfromanywhereintheworldifyouhaveanInternetconnection.WearegoingtobuildanewsketchfortheArduinoboardandthenadapttheinterfaceaccordingly,soyoucancontroltherelayfromanywhereintheworldrightfromyourwebbrowser.

Youfirstneedtoincludetherequiredlibraries:

#include<EEPROM.h>

#include<Servo.h>

#include<Wire.h>

#include<Teleduino328.h>

#include<SPI.h>

#include<Ethernet.h>

ThenyouneedtodefinetheMACaddressofyourEthernetshield:

bytemac[]={0x90,0xA2,0xDA,0x0E,0xFE,0x40};

Then,definealotofparametersfortheTeleduinoservice.AswewilluseDHCPtogetanIPaddress,youdon’tneedtochangeanythinginthefollowingcode:

IPAddressdeviceIp(192,168,1,100);//OnlyifuseDhcpisfalse

IPAddressgatewayIp(192,168,1,1);//OnlyifuseDhcpisfalse

IPAddressdnsIp(192,168,1,1);//OnlyifuseDhcpisfalse

IPAddresssubnet(255,255,255,0);//OnlyifuseDhcpisfalse

IPAddressserverIp(173,230,152,173);//OnlyifuseDnsisfalse

charserverName[]="us01.proxy.teleduino.org";//OnlyifuseDnsistrue

unsignedintserverPort=5353;//Canbesettoeither53or5353

bytestatusLedPin=8;

Wealsoneedtoenterthekeythatyougotatthebeginningofthechapter.However,youwillneedtoconvertthiskeytothecorrectformatsothatyoucaninsertitinsidetheArduinosketch.

YoucandosobyvisitingthefollowingURL:

https://www.teleduino.org/tools/arduino-sketch-key

Youwillbepromptedtoinsertthekeyinsidethenewwindow,asshowninthefollowingscreenshot:

Page 115: Arduino networking   marco schwartz

YoucanthencopyandpastetheresultinsidetheArduinosketch:

bytekey[]={0x64,0x26,0xFF,0xC9,

0x20,0x4D,0xF1,0xCF,

0xAE,0x42,0xD4,0x1A,

0xED,0x6C,0xB0,0xB7};

YoualsoneedtodefinethefollowingvariablessothattheTeleduinoservicecanwork:

bytedata[257];

bytedataLength;

bytehexStage;

unsignedlonglastInstruction=0;

unsignedlonglastRefresh=0;

bytestage=0;

Finally,defineanEthernetclient:

EthernetClientClient;

TherestofthesketchcomesfromtheTeleduinoexampleandwon’tbedetailedhere.

NoteThecodeforthissectioncanbefoundintheGitHubrepositoryforthischapterathttps://github.com/openhomeautomation/arduino-networking/tree/master/chapter4.

It’snowtimetomakeafirsttestofthissketch.UploadthesketchtoyourArduinoboard,andthengotoyourwebbrowser.Youcannowdirectlysendcommandstoyourboard.First,wearegoingtosettherelaypinasanoutputasseenearlier.Thisisdoneusingthefollowingcommand(whereyouhavetoinsertyourownkeyatthekparameter):

http://us01.proxy.teleduino.org/api/1.0/328.php?k=yourKey

&r=definePinMode&pin=7&mode=1

Youwillbegreetedbyaconfirmationmessageinsideyourwebbrowser.YoucannowswitchtherelaypintoaHIGHstateusingthefollowingcommand:

http://us01.proxy.teleduino.org/api/1.0/328.php?

k=yourKey&r=setDigitalOutput&pin=7&output=1

Page 116: Arduino networking   marco schwartz

Bydoingso,youshouldheartheclickoftherelay,meaningthecommandwascorrectlysent.Youwillalsobegreetedbyaconfirmationmessageinsideyourbrowser.

Now,wearegoingtomodifytheinterfacesoyoucancommandtherelayfromanywhereusingyourwebbrowser.InsidetheJavaScriptfile,youwillthenneedtodefineyourTeleduinoAPIkey:

varkey="yourAPIkey";

Then,wehavetochangethecommandparameterstofittheTeleduinoAPIandmentionthekeyaswell,asshowninthefollowingcode:

window.onload=function(){

$.get("command.php",{

key:key,command:"definePinMode&pin=7&mode=1"});

}

Also,wehavetochangethecommandparametersandmentionthekeyforthefunctionthatiscalledwhenabuttonisclicked:

if(clicked_id=="1"){

$.get("command.php",{

key:key,command:"setDigitalOutput&pin=7&output=1"});

}

InsidethePHPfile,wenowhavetogettwoparameters,thecommandandAPIkeyfromTeleduino:

$key=$_GET['key'];

$command=$_GET['command'];

WealsoneedtomodifytheserviceURL,asshowninthefollowingcode:

$service_url='http://us01.proxy.teleduino.org/api/1.0/328.php?k='.

$key.'&r='.$command;

$curl=curl_init($service_url);

Therestofthefilesarestrictlyidentical,asseenintheprevioussection.

NoteThecodeforthissectioncanbefoundintheGitHubrepositoryforthischapterathttps://github.com/openhomeautomation/arduino-networking/tree/master/chapter4.

Youcannowputallthefilesforthismodifiedinterfaceinsideafolderattherootofyourwebserver.Also,makesurethatthewebserverisstillrunning.YoucanopentheHTMLfileandyoushouldseeexactlythesameinterfaceasbefore.

Youcannowtrytoclickonabuttonandyoushouldinstantlyheartherelayswitch.Theadvantageovertheprevioussectionofthechapteristhatthisinterfacecannowworkfromanywhere.YoucanbeinonepartoftheworldandhaveyourEthernetshieldinanotherpartoftheworldanditwouldstillwork.

Page 117: Arduino networking   marco schwartz
Page 118: Arduino networking   marco schwartz

SummaryInthischapter,weinterfacedarelaytotheArduinoboardandtheEthernetshieldsothatitcanbecontrolledremotely.Todoso,weusedtwodifferentapproaches,eachwiththeirownadvantagesanddisadvantages.First,wekeptthingslocalandcontrolledtherelayfromwithinyourlocalnetwork.ThissolutionhastheadvantagethatevenifyourInternetconnectionisdown,theprojectstillworks.

Then,weusedadedicatedwebservicetocontroltherelayfromanywhere.Thisisclearlyanadvantageofthelatterapproach;however,itwillnotworkifyourEthernetshieldisnotconnectedtotheweb.

Thefollowingwerethemajortakeawaysfromthischapter:

First,wechosethedifferentcomponentsfortheproject,andassembledthemsothatwecancontroladevicefromtheArduinoboardsuchasadesklamp.Then,wewrotethefirstsketchtotesttheprojectbysimplyswitchingtherelayonandoff.Afterthat,webuiltthefirstapplicationbasedonthehardwarewejustassembled.WeusedadedicatedlibrarysothattheArduinoboardcouldreceivecommandsfromthenetworkusingtheEthernetshield.Wealsobuiltasimpleweb-basedinterfacesothatyoucancontroltherelayfromagraphicalinterfacerunningonyourcomputer.Finally,weusedawebservicecalledTeleduinotocontroltherelayfromanywhereintheworld.Wealsomodifiedthegraphicalinterfacesothatwecancontroltherelayfromanywhere.

Inthenextchapter,wearegoingtotakeyetanotherapproachandusetheEthernetshieldtoconnectourArduinoprojectstotheInternetofThings.WearegoingtoperformsomemeasurementsontheArduinoboardandsendthisdatarighttoacloudservice.Usingthisservice,wewillbeabletomonitorthemeasurementsthatcomefromtheboardinrealtimeandfromanywhereintheworld.

Page 119: Arduino networking   marco schwartz
Page 120: Arduino networking   marco schwartz

Chapter5.InternetofThingswithXivelyInthepreviouschaptersofthebook,wemainlykeptthingslocalwhenperformingmeasurementsontheArduinoboardwiththeEthernetshield.Forexample,wesentsomemeasureddatabacktoadatabaseonyourcomputeranddisplayedthemeasurementsthere.

Inthischapter,wearegoingtotakeadifferentapproach.WearegoingtointegratetheEthernetshieldintoanInternetofThingsperspective.Thismeansthatinsteadofloggingmeasurementslocallywithinyourlocalnetwork,wearegoingtoautomaticallysendthemeasureddatatoacloudservicecalledXively.ThepurposeoftheXivelywebsiteistostoredatathatcomesfromyourdevicesanddisplaythisdataontheirwebsite.Thisway,yourdatawillbeavailableatanytimeandcanbeaccessedfromanywhere.

Thefollowingwillbethemajortakeawaysfromthischapter:

First,wearegoingtobuildthehardwareforthisprojectaroundtheEthernetshieldandtheDHT11temperatureandhumiditysensor.Then,wewillcreateanaccountontheXivelywebsite.WewillalsoconfigurethisaccountsothatwecansendthemeasureddatatoitusingtheArduinoEthernetshield.Whentheaccountiscorrectlyset,wewillusetheaccountinformationsuchastheXivelyAPIkeytobuildtheArduinosketchforthisproject.Finally,wewilluploadthesketchtotheArduinoboardandtestit.WewillcheckthatthedataiscorrectlysenttotheArduinoboardandvisualizetherecordeddatainrealtimeinyourbrowser.

Page 121: Arduino networking   marco schwartz

HardwareandsoftwarerequirementsOnthehardwareside,youwillofcourseneedtheArduinoEthernetshieldandanArduinoboardsuchastheArduinoUno.

Youwillalsoneedasensortomeasuresomedata.AsthisbookisabouthowtousetheEthernetshieldandnothowtomeasurefromsensors,youcanactuallyuseasensorofyourchoice.

IpickedaDHT11sensor,whichisadigitaltemperatureandhumiditysensor.IchosethissensorasitisaverycheapsensorandeasytointerfacewithArduino.AlongwiththeDHT11sensor,youwillalsoneeda4.7kohmresistor.

YouwillalsoneedabreadboardandsomejumperwirestomaketheconnectionsbetweenthesensorandtheEthernetshield.

Onthesoftwareside,thefirstthingyouwillneedisthelibrarytointerfacewiththesensoryouchosebefore.AsIchoseaDHT11sensorforthisproject,youwillneedtodownloadandinstalltheDHTlibraryfromhttps://github.com/adafruit/DHT-sensor-library.

ToinstallanArduinolibrary,simplyunzipthecontentsofthedownloadedfileintoyourlibrariesfolderofyourmainArduinofolder(orcreatethisfolderifitdoesn’texistalready).

Page 122: Arduino networking   marco schwartz

HardwareconfigurationIt’snowtimetosetupthehardwareforthisproject.Atthispoint,ifyoufollowedoneofthepreviouschapters,youshouldalreadyhaveyourArduinoEthernetshieldpluggedintotheArduinoboard,oneEthernetcableconnectingtheEthernetshield,andyourInternetrouter.Ifthat’snotthecasealready,pleasedoso.

TheonlythingyouwillhavetoconnectinthisprojectistheDHT11sensorandtheresistor.Youcanhaveanoverviewofthedifferentconnectionsyouhavetomakebylookingatthefollowingschematicdiagram:

First,plugtheDHT11sensortothebreadboard.Then,connectpinnumbers1and2ofthesensorusingthe4.7kohmresistor.

Nowcomesthepowersupply.Connectthepinnumber1ofthesensortotheArduino5Vandthepinnumber4totheArduinoGND.Finally,connectthepinnumber2oftheDHTsensortotheArduinopinnumber7.

Attheend,itshouldlooklikethefollowingimage:

Page 123: Arduino networking   marco schwartz

Youarenowdonewiththehardwareconfigurationofthisprojectandcanmovetothenextstep,whichiscreatinganaccountonXively.

Page 124: Arduino networking   marco schwartz
Page 125: Arduino networking   marco schwartz

CreatingyourXivelyaccountThefirstthingwehavetodotousetheXivelyserviceiscreateandconfigureaXivelyaccount.YouneedtocreateanaccountonXivelysothatwecansenddatatotheirservice.XivelyisbasicallyanonlineplatformforconnectedobjectssuchasourEthernetshield.Theservicewillautomaticallystorethedatathatwesend.Itwillalsodisplaythemeasureddataintheformofgraphsthatareupdatedinrealtimeasthedatacomesin.

TheveryfirststepistogoovertotheXivelysignuppageontheirwebsiteathttps://xively.com/signup/.Youwillarriveatapagewhereyoucanenteryourpersonaldetails:

Then,youwillneedtocreateadevice,whichisavirtualentityontheXivelywebsite.Thisdevicewillreceivethemeasureddata.Whenyoucreateanewdevice,youwillneedtoenteranameforyourdevice:

Page 126: Arduino networking   marco schwartz

Then,youcanaddchannelstoyourdevice.AchannelonXivelyislikeavariableorarowinadatabase;itistheentitythatwillreceiveaspecificmeasurementfromtheArduinoboard.Youcancreateanewchannelonthepageofyourdevicebyclickingonthebuttonshowninthefollowingscreenshot:

Page 127: Arduino networking   marco schwartz

Youwillneedtoentersomenameforyourchannels.Youwillhavetocreatetwoofthemforthisproject:onecalledTemperatureandonecalledHumidity.

Then,youwillneedtogetsomeinformationaboutyouraccount,whicharealllocatedonthedevicepage.

ThefirstoneisthefeedID,whichidentifiesthisspecificdevice.Youcanfinditinthefollowingsectionofthepage:

Then,youwillhavetogetyourAPIkey,whichisspecifictoyouraccount.Youcanalsofinditonthedevicepage,asshowninthefollowingscreenshot:

Page 128: Arduino networking   marco schwartz

YouwillneedtoenterthesetwokeysinsidetheArduinosketchthatwewillbuildinthischapter,sokeepthemathand.

Page 129: Arduino networking   marco schwartz
Page 130: Arduino networking   marco schwartz

SendingdatatoXivelyWearenowgoingtobuildtheArduinosketchforthisproject.ThegoalistomeasuredataontheArduinoboard,connectwiththeXivelyserver,andsendthedata.

Thefirststepistoincludethefollowingrequiredlibraries:

#include<SPI.h>

#include<Ethernet.h>

#include"DHT.h"

EntertheMACaddressofyourboard:

bytemac[]={0x90,0xA2,0xDA,0x0E,0xFE,0x40};

WecanthendefinethepinandthetypeoftheDHTsensorasfollows:

#defineDHTPIN7

#defineDHTTYPEDHT11

Createaninstanceonthesensor,asshowninthefollowingline:

DHTdht(DHTPIN,DHTTYPE);

CreateaninstanceoftheEthernetclient:

EthernetClientclient;

WealsodefineadefaultIPaddressfortheboard:

IPAddressip(192,168,1,50);

Inthesketch,wealsosettheaddressofthesecuredXivelyserverthatwewillconnecttousingtheEthernetshield:

IPAddressserver(216,52,233,120);

Now,wehavetomodifythesketchalittlebittoenteryourowninformationaboutyourXivelyaccount.ThisiswhereyouhavetoenteryourAPIkeyandfeedIDthatyougotintheprevioussection.Usingthefollowingcode,youcandefineyourAPIkeyandfeedID:

#defineWEBSITE"api.xively.com"

#defineAPI_key"yourAPIKey"

#definefeedID"yourFeedID"

Inthesetup()functionofthesketch,wecannowuseDHCPtogetanIPaddressforthesketch,asshowninthefollowingcode:

//StarttheEthernetconnection

if(Ethernet.begin(mac)==0){

Serial.println("FailedtoconfigureEthernetusingDHCP");

Ethernet.begin(mac,ip);

}

Fordebugpurposes,weprintthisIPaddressontheSerialMonitor:

Serial.print("IPaddress:");

Page 131: Arduino networking   marco schwartz

Serial.println(Ethernet.localIP());

Now,intheloop()functionofthesketch,wewillmakethemeasurementswiththeDHTsensor,formatthedataforXively,andsendthisdatatotheXivelyserver.

Thefirststepistomakethemeasurements.Thisisdonewiththefollowinglinesofcode:

floathumidity=dht.readHumidity();

floattemperature=dht.readTemperature();

WethenneedtoformatthismeasureddatasotheXivelyservercanunderstandit.Indeed,Xivelydefinesaspecificformattoreceivedata.Alltheformatsaredefinedathttps://xively.com/dev/docs/api/communicating/data_formats/.

Inourcase,wewillneedtoputthedatainaJSONstringaccordingtotheXivelyspecifications.Thisisdoneusingthefollowingpieceofcode:

intlength=0;

Stringdata="";

data=data+"\n"+"{\"version\":\"1.0.0\",\"datastreams\":[{\"id\":

\"Temperature\",\"current_value\":\""+String((int)temperature)+"\"},"

+"{\"id\":\"Humidity\",\"current_value\":\""+String((int)humidity)+

"\"}]}";

Serial.println(data);

length=data.length();

YouwillnotethatwealsogetthelengthofthestringthatwewillalsoneedinordertosendthedatatotheXivelyserver.Also,weareusingbackslashesbeforequotationsmarkstoindicatethatwewanttotransmitquotationmarksandnottheendofthestring.

Then,wewillactuallyconnecttotheXivelyserverandsendthedata.ThisisdonebyusingaPUTrequestandsendingaJSONfiletotheXivelyserver.Intheheaderoftherequest,wedefinethefeedIDoftheXivelydeviceandwealsotransmityourXivelyAPIkey.

Wealsoneedtosendthedatawedefinedbeforeinthebodyoftherequest.Thisisdoneusingthefollowingpieceofcode:

if(client.connect(server,80)){

if(client.connected()){

Serial.println("connected");

client.println("PUT/v2/feeds/"+String(feedID)+".jsonHTTP/1.1");

client.println("Host:api.xively.com");

client.println("X-ApiKey:"+String(API_key));

client.println("Content-Length:"+String(length));

client.print("Connection:close");

client.println();

client.print(data);

client.println();

}else{

Serial.println(F("Connectionfailed"));

return;

}

Then,afterthedataissent,wereadbackthedatacomingfromtheserverandprintthe

Page 132: Arduino networking   marco schwartz

answerontheSerialMonitorfordebuggingpurposes,usingthefollowingpieceofcode:

while(client.connected()){

while(client.available()){

charc=client.read();

Serial.print(c);

}

}

Finally,whenitisover,westoptheconnection.Thisisdonewiththefollowingcode:

if(!client.connected()){

Serial.println();

Serial.println("disconnecting.");

client.stop();

}

Werepeattheentireprocessevery10secondswiththefollowingline:

delay(10000);

NoteAllthecodeforthischaptercanbefoundontheGitHubrepositoryofthischapterathttps://github.com/openhomeautomation/arduino-networking/tree/master/chapter5.

ItisnowtimetotestthesketchanduploaddatatoXively.YoucanuploadthesketchtoXivelyatthispoint,andopentheSerialMonitorintheArduinoIDE.YoushouldseethattheIPaddressoftheboardisbeingprintedout,andthatthesketchisconnectedtotheXivelyserver:

IPaddress:192.168.1.104

Connecting…

YoushouldalsoseehowthedatawasformattedforXively:

{"version":"1.0.0","datastreams":[{"id":"Temperature","current_value"

:"24"},{"id":"Humidity","current_value":"37"}]}

Afteramoment,youshouldseetheanswercomingbackfromXively.IfthedatawassentcorrectlytotheXivelyserver,youshouldseea200OKcodebeingprintedouttotheSerialMonitor:

HTTP/1.1200OK

Date:Wed,21May201415:02:49GMT

Content-Type:application/json;charset=utf-8

Content-Length:0

Connection:close

X-Request-Id:e44becaa5231354568262013fa713d9f099ffc83

Cache-Control:max-age=0

Vary:Accept-Encoding

ThismeansthatthedatawascorrectlyreceivedbytheXivelyserver,andinanunderstandableformat.

Ifthatisnotthecase,thereareseveralthingsyoucancheck.First,makesurethatthe

Page 133: Arduino networking   marco schwartz

InternetconnectionofyourEthernetshieldisworking,andthattheshieldisindeedreceivinganIPaddress.Then,makesurethatyoucorrectlyenteredyourXivelyinformation,meaningtheAPIkeyandthefeedID.Also,checkthatyoucorrectlyformattedyourdataintheJSONformat,whichweintroducedwhilewritingthesketch.Finally,makesurethattheDHTsensoriscorrectlywiredandmeasuringdataproperly,asitcouldinterferewiththenormalbehavioroftherestofthesketch.

Page 134: Arduino networking   marco schwartz
Page 135: Arduino networking   marco schwartz

VisualizingtherecordeddataWearenowgoingtovisualizethedatawerecordedwithXively.YoucangooveragaintothedevicepageontheXivelywebsite.Youshouldseethatsomedatahasbeenrecordedindifferentchannels,asshowninthefollowingscreenshot:

Byclickingononeofthesechannels,youcanalsodisplaythedatagraphically.Forexample,thefollowingscreenshotshowsthetemperaturechannelafterafewmeasurements:

Page 136: Arduino networking   marco schwartz

Afterawhile,youwillhavemorepointsforthetemperaturemeasurements,asshowninthefollowingscreenshot:

Youcanalsodothesameforthehumiditymeasurements;thefollowingscreenshotshowsthehumiditymeasurements:

Page 137: Arduino networking   marco schwartz

Notethatbyclickingonthetimeicon,youcanchangethetimeaxisanddisplayalongerorshortertimerange.

Ifyoudon’tseeanydatabeingdisplayed,youneedtogobacktotheArduinoIDEandmakesurethattheanswercomingfromtheXivelyserverisa200OKmessage,likewesawintheprevioussection.

Page 138: Arduino networking   marco schwartz
Page 139: Arduino networking   marco schwartz

SummaryLet’ssummarizewhatwedidinthischapter.WeusedtheEthernetshieldtobuildanInternetofThingsproject,asweconnectedtheEthernetshielddirectlytoacloudservice.WemeasureddataontheArduinoboardandsentthisdatatothecloudserviceXivelysothatitcanbeaccessedanddisplayedfromanywhere.

TheadvantageofthissolutionisthatthedatarecordedonXivelyisaccessiblefromanywhere,andnotonlyfromyourlocalnetwork.YoucanalsousethedataandXivelytocreateautomatedtriggersbasedonthedata.Youcan,forexample,sendarequesttoanotherwebsitebasedontherecordeddata.Youcanalsosharethedatathatisrecordedbyyourdevicewithcolleaguesorfriendssothattheycanalsomonitorwhatyourprojectisrecordinginrealtime.

Ofcourse,oneofthedrawbacksfromthissolutionisthatifyourInternetconnectionisdown,thewholeprojectwon’tworkatall.

Thefollowingwerethemajortakeawaysfromthischapter:

Wefirstbuiltthehardwareofthisproject,includingtheEthernetshieldandtheDHT11sensortomeasuretemperatureandhumidity.Then,wewentovertotheXivelywebsiteandcreatedanaccountthere.WealsosetupadeviceontheXivelyinterface,andcreatedchannelssothatdatacanberecordedontheXivelywebsite.Finally,wealsogotafeedIDandAPIkeysothattheArduinosketchknowswheretosendthedata.WethendesignedtheArduinosketchforthisproject.TheArduinosketchwasresponsibleformeasuringdata,formattingitaccordingtotheXivelyguidelines,andsendingittoXively.WetestedthissketchandmadesurethatXivelyacceptedthedata.Finally,wewentagaintotheXivelywebsitetovisualizethedata.Welearnedhowtovisualizethisdatagraphically,andsawthedataarriveinrealtime.

Inthenextchapter,wearegoingtocontinuebuildingInternetofThingsapplications.WearegoingtouseanotherwebservicecalledTemboo,whichisaplatformthatcanbeinterfacedwithotherservicessuchasGmailorGoogleDocs.WearegoingtousethisservicetorecorddatadirectlyonaGoogleDocsspreadsheetandsendautomatede-mailsbasedontherecordeddata.

Page 140: Arduino networking   marco schwartz
Page 141: Arduino networking   marco schwartz

Chapter6.LoggingDatainGoogleDocsInthischapter,wearegoingtocontinuebuildingInternetofThingsapplicationsusingtheArduinoEthernetshield.Thistime,wearegoingtousethewebserviceTemboo,tobuildsomeusefulandinterestingapplications.TembooisdifferentfromXively,whichweusedinthepreviouschapter.Itisnotacloudplatforminitself,butitcanbeusedtointerfaceourArduinoprojectswithseveralotherapplicationsandservices.YoucanseeTembooasabridgebetweenyourEthernetshieldandawiderangeofwebservices,suchase-mailservices,textmessagingservices,orstorageservices.

Forexample,inthischapter,wearegoingseehowtointerfaceyourArduinoprojecttoyourGoogleAccountviaTemboo.WewillusethisfunctionalitytoautomaticallylogmeasurementsinsideaGoogleDocsspreadsheet.

TheadvantageofthissolutionisthatyoucanaccessyourGoogleDocsspreadsheetfromanywhere,thusmonitoringyourdatafromanywhereintheworldwhileyourEthernetshieldissendingdatafromhome.Wearealsogoingtosendautomatede-mailalertsusingGmailbasedonthemeasureddata.

Thefollowingwillbethemajortakeawaysofthischapter:

First,wearegoingtoconfigurethehardwarepartofthisprojectusingtheEthernetshieldandtheDHT11sensor.Wearealsogoingtodownloadandinstalltherequiredlibrariesfortheproject,includingtheTembooArduinolibrary.Then,wewillsetupthedifferentaccountsthatweneedforthischapter.First,wewillsetupyourGoogleAccountandcreateaspreadsheetwherethedatawillbelogged.WearealsogoingtosetupaTembooaccountandconfigureittousetheArduinoEthernetshield.Oncealltheaccountsareset,wearegoingtobuildthefirstapplicationofthisproject—automaticlogmeasureddatainaGoogleDocsspreadsheet.Youwillbeabletoseethemeasureddatarecordedliveinthespreadsheetandthedatabeingplottedautomaticallyinrealtime.Finally,wearegoingtosetupourArduinosystemtoautomaticallysende-mailswhenagivenmeasurementexceedsathreshold.

Page 142: Arduino networking   marco schwartz

HardwareandsoftwarerequirementsOnthehardwareside,youwillofcourseneedtheArduinoEthernetshieldandanArduinoboardsuchastheArduinoUno.

Youwillalsoneedasensortomeasuresomedata.AsthisbookisabouthowtousetheEthernetshieldandnothowtomeasurefromsensors,youcouldactuallytakeanysensorofyourchoice.

IusedaDHT11sensor,whichisadigitaltemperatureandhumiditysensor.IchosethissensorforthischapterandformanychaptersofthebookasitisaverycheapsensoranditiseasytointerfacewithArduino.AlongwiththeDHT11sensor,youwillalsoneeda4.7kohmresistor.

YouwillalsoneedabreadboardandsomejumperwirestocreatetheconnectionsbetweenthesensorandtheEthernetshield.

Onthesoftwareside,thefirstthingyouwillneedisthelibrarytointerfacewiththesensoryouchosebefore.AsIchoseaDHT11sensorforthisproject,youwillneedtodownloadandinstalltheDHTlibraryfromhttps://github.com/adafruit/DHT-sensor-libraryinordertousethis.

YouwillalsoneedtodownloadandinstalltheArduinoTemboolibraryfromhttps://www.temboo.com/arduino/others/library-installation.

ToinstallanArduinolibrary,simplyunzipthecontentsofthedownloadedfiletoyourlibrariesfolderofyourmainArduinofolder(orcreatethisfolderifitdoesn’texistalready).

Page 143: Arduino networking   marco schwartz

HardwareconfigurationIt’snowtimetosetupthehardwareforthisproject.Atthispoint,ifyoufollowedoneofthepreviouschapters,youshouldalreadyhaveyourArduinoEthernetshieldpluggedtotheArduinoboard,oneEthernetcableconnectingtheEthernetshield,andyourInternetrouter.Ifthat’snotthecasealready,pleasedoso.

TheonlythingyouwillhavetoconnectinthisprojectistheDHT11sensorandtheresistor.Youcanhaveanoverviewofthedifferentconnectionsyouhavetomakebylookingatthefollowingschematicdiagram:

First,plugtheDHT11sensortothebreadboard.Then,connectpinnumber1and2ofthesensorusingthe4.7kohmresistor.

Now,wearegoingtoconnectthepowersupply.Connectpinnumber1ofthesensortotheArduino5V,andpinnumber4totheArduinoGND.Finally,connectpinnumber2oftheDHTsensortotheArduinopinnumber7.

Attheend,theconnectionsshouldlooklikethefollowingscreenshot:

Page 144: Arduino networking   marco schwartz

Youarenowdonewiththehardwareconfigurationofthisprojectandyoucanmovetothenextstep,thatis,settingupyourGoogleAccountforthisproject.

Page 145: Arduino networking   marco schwartz
Page 146: Arduino networking   marco schwartz

SettingupyourGoogleAccountForthisproject,youwillneedtohaveaGoogleAccount.IfyouarealreadyusingaservicesuchasGmailorYouTube,itmeansyoualreadyhaveaGoogleAccount,andyouwillbeabletouseGoogleDocsimmediately.Ifthisisnotthecase,youcancreateanaccountatthefollowingaddress:

https://docs.google.com

Onceyouraccountiscreated,youwillbeabletocreateyourfirstspreadsheet.Todoso,justclickontheCreatebuttonandselectSpreadsheet.Youwillhavetoenteranameforthespreadsheet,whichisimportantasyouwillneedtoprovidethisnametoTemboolater.InamedmysheetsimplyEthernet.

Then,youwillneedtogivenamestothecolumnsthatwillreceivethedata.Wearegoingtomeasuretemperatureandhumidityandalsoaddatimestamptoeachmeasurement.Youwillneedtoenterthisinthefirstrow,asshowninthefollowingscreenshot:

WhenyouhaveaGooglespreadsheetthatlookslikethis,itmeansthatyouareallsetupforthispartandthatyoucanmovetothenextpart.

Page 147: Arduino networking   marco schwartz
Page 148: Arduino networking   marco schwartz

CreatingyourTembooaccountThenextstepistocreateanaccountonTemboo.Todothis,simplygotothefollowingaddress:

https://www.temboo.com/

Youwillbegreetedwithapagethatasksyoutoenteryoure-mailaddress.

Onceyouraccountiscreated,youwillbetakentotheTemboomainpage.Youwillhavemanychoicesatthisstage,buttheonewearelookingforisDevices,whichisdisplayedinthefollowingscreenshot:

Insidethedevicespage,TembooproposesatoolcalledDeviceCoder.ThistoolisintendedtogeneratemostofthecodeforuswhenweuseaplatformsuchastheArduinoYun,orinourcase,theArduinoEthernetshield.

Simplyclickontherightchoice,whichcorrespondstootherArduinodevicessuchastheEthernetshield,asshowninthefollowingscreenshot:

Page 149: Arduino networking   marco schwartz

Then,youwillbeaskedwhichkindofsensoryouwanttouse.Ofcourse,Temboocannotlisteverypossiblesensorwecoulduseforthiskindofproject.Therefore,theDHT11sensorisnotinthelistofpossibledevices.However,wewillfixthisbyrewritingpartofthegeneratedcode.Fornow,simplychooseGenericsensor.Theninthenextmenu,selectSpreadsheet.

Youwillthenbetakentoanewmenuwhereyoucanconfigureyourdevice.Asthisisyourfirsttimeconfiguringthedevice,youwillbeaskedtocreatenewTemboocredentialsforyourEthernetshield.ATemboocredentialisasetofparametersthatarestoredontheTembooserverssothatyoudon’thavetoenterthemlaterwhiledevelopingyourapplications.

EnterthedetailsaboutyourArduinoboardandEthernetshieldinthecredentialsbox,asshowninthefollowingscreenshot:

Page 150: Arduino networking   marco schwartz

Then,justasyouselectedtoworkwithaspreadsheet,youwillalsoneedtoenteryourGoogleAccountcredentials.WewilluseittoaccessGoogleDocsandalsointhefinalpartofthechaptertointerfacewithGmail.

EnterallyourGoogleAccountinformationinthebox,whichisshowninthefollowingscreenshot:

Page 151: Arduino networking   marco schwartz

ForthenameofmyGoogleAccountcredential,IusedEthernetGmail.

NotethatifyouhavetheGoogle2-Stepauthenticationmethodactivated,youwillneedtoprovideanapplication-specificpasswordhere.Thisisdoneforsecurityreasons,soyourGoogleAccountdoesn’tgetcompromisedifTemboogetscompromised.Youcanfindmoreinformationaboutapplication-specificpasswordsathttps://support.google.com/accounts/answer/185833?hl=en.

YoucanalsochoosenottoenteryourGoogleinformationatthispoint.However,inthatcase,youwillneedtoenteritinsidetheArduinosketchandmodifythissketchslightly.Tofindmoreinformationaboutthis,youcanvisithttps://www.temboo.com/arduino/yun/update-google-spreadsheet.

Youwillalsobeaskedtogiveanameofaspreadsheetyoupreparedbefore.Simplyenterthisnameinthecorrectbox,asshowninthefollowingscreenshot:

Forexample,InamedmyspreadsheetEthernet:

Page 152: Arduino networking   marco schwartz

Afterthat,youwillhavetoselectthedeviceyouwillbeworkingwithtologdatatothespreadsheet.Thisiswhereyouselectthecredentialsthatwecreatedbefore,asshowninthefollowingscreenshot:

YouwillalsoneedtogiveanametotheprojectyoujustcreatedsoyourArduinosketchwilllateronknowwheretosendthedata.InamedminearduinoTemperatureSpreadsheet.Ifyoudecidetouseanothername,youwillhavetomakeasmallmodificationinthecodelater.

Whenthisisdone,youwillbepromptedtodownloadacompressedfilethatcontainstwoArduinocodefiles.Downloadit,unzipit,andhavealookatit.Itwillappearlikethefollowingscreenshot:

ThereshouldbeanArduinofileandanotherfilecalledTembooAccount.h.Thislastfileisthemostimportantasitcontainsyourcredentialsfortheproject.YouwillneedtousethisfilefortherestoftheprojectinplaceofthefilethatisincludedintheGitHubrepositoryoftheproject.

Page 153: Arduino networking   marco schwartz
Page 154: Arduino networking   marco schwartz

LoggingdatainaspreadsheetAfterfinishingtheconfigurationofourdeviceontheTemboowebsite,wedownloadedabunchoffilesfromTemboo.However,theArduinofilethatwasdownloadedisforagenericsensor.Inthissection,wearegoingtoadaptthisfileforourownneedsandseethedetailsofhowthecodeworks.

NoteYouwillneedtoinsertyourownTembooAccount.hfileinthesamefolderastheArduinofilesothatthecodecanwork.

ThemainArduinosketchforthissectionstartsbyincludingallthelibrariesthatarerequiredfortheprojecttoworkwithTemboo.NotethatwewillalsoinserttheDHTlibrary.Addthefollowinglibrariesinthecode:

#include<SPI.h>

#include<Dhcp.h>

#include<Dns.h>

#include<Ethernet.h>

#include<EthernetClient.h>

#include<Temboo.h>

#include"TembooAccount.h"

#include"DHT.h"

WealsodefinethepinonwhichtheDHTsensorisconnectedandthetypeofthesensor:

#defineDHTPIN7

#defineDHTTYPEDHT11

Then,wewillcreateaninstanceofthesensor:

DHTdht(DHTPIN,DHTTYPE);

WealsoassigntheMACaddressoftheEthernetshield.Notethathereitisnotexplicitlyassigned,buttheinformationisdirectlytakenfromyourTembooaccountfile.TheMACaddressisassignedwiththefollowingline:

byteethernetMACAddress[]=ETHERNET_SHIELD_MAC;

WewillalsocreateaninstanceofanEthernetclientasfollows:

EthernetClientclient;

Now,inthesetup()functionofthesketch,wewillgetanIPaddressfortheEthernetshieldviaDHCP,asshowninthefollowingcode:

Serial.print("DHCP:");

if(Ethernet.begin(ethernetMACAddress)==0){

Serial.println("FAIL");

while(true);

}

Serial.println("OK");

delay(5000);

Page 155: Arduino networking   marco schwartz

StarttheDHTsensorwiththefollowingline:

dht.begin();

Then,intheloop()function,wewillmeasurethetemperatureandhumidityfromtheDHTsensorandconvertthemeasurementstostringswiththefollowingpieceofcode:

floath=dht.readHumidity();

floatt=dht.readTemperature();

inttemperature=(int)t;

inthumidity=(int)h;

Serial.println("Temperature:"+String(temperature));

Serial.println("Humidity:"+String(humidity));

Afterthemeasurementsaredone,wewillcallthefollowingfunctionthatwillactuallyconnecttothewebandlogthedatatoourGoogleDocsspreadsheet.WearegoingtoseethedetailsofthisfunctionthatwasautogeneratedbyTembooinamoment:

runAppendRow(temperature,humidity);

Finally,wewillalsoinsertsomedelaybetweeneachmeasurement.Irecommendusingalargedelay(Ichosetologdataeveryminutefordemonstrationpurposes)becausethenumberofcallsyoucanmaketoTembooislimited.Thedelayisinsertedwiththefollowingline:

delay(60000);

Youcanseethedifferentplansandpricingatthefollowinglink:

https://www.temboo.com/about/plans

Forexample,onthefreeplan,youarelimitedto1,000callspermonth,whichmeansthatyoucanlogmeasurementsapproximatelyevery44minutes.Onthefirstpaidplan,youcanlogonedatapointapproximatelyevery5minutes.Keeptheselimitationsinmindwhiledevelopingyourapplications.

Let’snowseethedetailsoftherunAppendRow()function.ItstartsbydeclaringthetypeofChoreowewanttouse.AChoreoistheequivalentofalibraryontheTembooservice.Forexample,wewilldeclarethatwewanttousethespecificlibrarytoinsertdatainarowintheGoogleDocsspreadsheet:

TembooChoreoAppendRowChoreo(client);

Wewillsetthedifferentinformationaboutyouraccount,suchasthenameoftheaccountandyourappkey.AllthesearealreadydefinedinyourTembooaccountfilethatyoudownloadedbefore,soyoudon’tneedtodefineanythingmore:

AppendRowChoreo.setAccountName(TEMBOO_ACCOUNT);

AppendRowChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);

AppendRowChoreo.setAppKey(TEMBOO_APP_KEY);

Then,youneedtosomehowspecifywherethedatashouldbelogged.Oncemore,alltheworkisdonebyTemboo:alltheinformationissavedontheTemboosideintheGoogle

Page 156: Arduino networking   marco schwartz

Accountcredentialsyouhavesetbefore.IfyouusedthesamenameasIdidforthisexample,youdon’thavetomodifyanythinginthefollowingline:

AppendRowChoreo.setSavedInputs("arduinoTemperatureSpreadsheet");

NotethatthenewwaytoovercometheTemboocalllimitationisalsototransmitseveraldatapointsateachcalloftheTembooAPI,forexample,byappendingseveralrowsateachcall.Youcanmodifythecodeaccordinglyasanexercise.

Now,weneedtoformatthedatasoitcanberecordedcorrectlyinGoogleDocs.Whatyouwanttoinsertinagivenrowisatimestamp,thetemperature,andthehumidity.Forthetimestamp,wearesimplygoingtousethetimethathaspassedsincethedevicewaspoweredonwiththemillis()function.

Thedataitselfwillbecontainedinsideastringvariable,wherethevalueofeachcolumnwillbeseparatedwithacomma,asshowninthefollowingcode:

StringRowDataValue=String(millis())+","+String(temperature)+","+

String(humidity);

AppendRowChoreo.addInput("RowData",RowDataValue);

WealsoneedtosetwhichChoreowewanttousewiththefollowingline:

AppendRowChoreo.setChoreo("/Library/Google/Spreadsheets/AppendRow");

Then,wecanfinallyexecuteChoreoandstoretheresultinavariablecalledreturnCodeusingthefollowingline:

unsignedintreturnCode=AppendRowChoreo.run();

Ifthiscodeisequalto0afterChoreohasbeenexecuted,itmeansthateverythingwentfine,andwewillprintthecorrespondingmessageontheSerialMonitorfordebuggingpurposesusingthefollowingpieceofcode:

if(returnCode==0){

Serial.println("Done!\n");

}else{

//Anon-zeroreturncodemeanstherewasanerror

//Readandprinttheerrormessage

while(AppendRowChoreo.available()){

charc=AppendRowChoreo.read();

Serial.print(c);

}

Serial.println();

}

Ifthat’snotthecase,wewillprintthecorrespondingerrormessageontheSerialMonitor.Finally,wecloseChoreowiththefollowingline:

AppendRowChoreo.close();

NoteYoucanfindallthecodeforthissectionontheGitHubrepositoryofthischapterathttps://github.com/openhomeautomation/arduino-networking/tree/master/chapter6.

Page 157: Arduino networking   marco schwartz

EvenifyoudecidetogetthecodedirectlyfromtheGitHubrepository,notethatyouwillneedtotakeyourownTembooaccountfileorenterthecorrectinformationintheTembooaccountfileprovidedonGitHub.

Wecannowtesttheproject.UploadthecodetotheArduinoboard,gotoGoogleDocs,andopenthespreadsheetoftheproject.Afteramoment,youshouldseethefirstmeasurementsbeingloggedinsidethespreadsheet,asshowninthefollowingscreenshot:

YoucanalsousetheintegratedplottingfunctionalitiesofGoogleDocstodisplaythemeasurementsonagraph.Youcansimplyselectthecolumnscorrespondingtothedata(A,B,andCintheexampledevelopedinthischapter),andclickontheInsertChartbuttoninsidethetoolbar.Youwillbepromptedtochoosethetypeofgraphyouwanttoplot.Isimplychosealinecharttoplotallthedataonasinglegraph.Thegraphwilllooksimilartothefollowingscreenshot:

Aseverythingisdynamic,youshouldseethatthegraphisupdatedinrealtimeasnewmeasurementscomein.NotethatasthisisaspreadsheetonGoogleDocs,itisaccessible

Page 158: Arduino networking   marco schwartz

fromanywhereyouareintheworld,youjustneedtologintoyourGoogleAccount.

Page 159: Arduino networking   marco schwartz
Page 160: Arduino networking   marco schwartz

Sendingautomatede-mailsInthislastpartofthechapter,wearegoingtobuildonwhatwealreadydid,butchangetheapplicationslightly.Thistime,wearegoingtousetheEthernetshieldandTembootoautomaticallysende-mailswhenaconditionisreached.Asanexample,wewillsetaconditiononthemeasuredtemperature.Wheneverthetemperaturereachesagivenvalue,wewillsendane-mailtotheaddressofyourchoice,forexample,yourprofessionale-mailtokeepyouupdatedwhenyouareatwork.

ItstartsbygoingagaintotheDeviceCoderontheTemboowebsiteathttps://www.temboo.com/library/Library/Devices/Arduino/Others/.

ClickonGenericsensorandthenonEmail.Thistimeyouwon’thavetoenterthatmuchinformation.YourGmailaccountshouldalreadybesetfromtheprevioussectionandtheDeviceCodershouldautomaticallyselectyourEthernetshield.

Yousimplyneedtoenterthedestinatione-mail(forexample,yourprofessionale-mailaddressorthee-mailaddressfromafamilymember)andtheSubjectfieldofthee-mail.Donotworrynowaboutthevalueofthebodyofthee-mail;wewillchangeitlater:

Whenitisfinished,clickonGenerate.Asfortheprevioussection,youwillbepromptedtoenteranameforthisprojectsothatTembooknowswheretosende-mails.InamedminearduinoTemperatureEmail,butifyoudecidetouseanothername,youwillsimplyhavetochangeonelineinthecodelater.

Youcannowdownloadthegeneratedcode,whichwewillmodifyabit.Asfortheprevioussection,wearegoingtomodifytheArduinocode,butitisimportantthatyougetyourownTembooAcccount.hfilethatcontainstheinformationrelativetoyourownaccountonTemboo.

TheArduinosketchissimilartotheoneintheprevioussection,soIwillonlydiscussthemainchanges.

Intheloop()functionofthesketch,youneedtosetthelimitatwhichthee-mailwillbesentbyTemboo.Fordemonstrationpurposes,Iwillsetthelimitto23,asshowninthefollowingcode:

Page 161: Arduino networking   marco schwartz

if(temperature>23){

Serial.println("\nTriggered!Calling/Library/Google/Gmail/SendEmail…");

//Sendemail

runSendEmail(temperature);

}

Youcanseethateverytimethetemperaturegoesabovethatlimit,analertwillbesentbyTembooviae-mail.Wewillseethedetailsofthisfunctioninamoment.Ialsoinserteda1-minutedelaybetweeneachmeasurement,sowedon’tcontinuouslysende-mailsifthethresholdiscrossed:

delay(60000);

Nowlet’slookatthedetailsoftherunSendEmail()function.ThisfunctionisresponsibleforcreatingthecorrectChoreotosendane-mail,setthebodyofthee-mail,andsenditviaTemboo.

ItstartsbycreatingthecorrectChoreotosendane-mailwiththefollowingline:

TembooChoreoSendEmailChoreo(client);

WealsodefinethedifferentinformationrelativetoyouraccountthatisdefinedintheTembooaccountfileyoujustdownloadedfromTemboo:

SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);

SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);

SendEmailChoreo.setAppKey(TEMBOO_APP_KEY);

Then,thisiswhereyouneedtoenterthenameofthee-mailprojectthatyoujustcreatedonTemboo.IfyouusethesamenameasIdid,thereisnoneedtomodifyanythinginthefollowingline:

SendEmailChoreo.setSavedInputs("arduinoTemperatureEmail");

Wewillnowbuildthebodyofthee-mail,whichwillbestoredinastringvariable.Wesimplyuseagenericmessagewhereweattachthevalueofthemeasuredtemperatureandstoreeverythinginastring.Finally,wewilladdthefollowinglinesasaninputtotheChoreousedtosende-mails:

StringMessageBodyValue=String("Alert!Thecurrentsensorvalueis:")+

String(sensorValue);

SendEmailChoreo.addInput("MessageBody",MessageBodyValue);

JustbeforeexecutingChoreo,wedefinethatwewanttouseSendEmailChoreofromGmailusingthefollowingline:

SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

WecanfinallyexecuteChoreoandstoretheresultinavariable:

unsignedintreturnCode=SendEmailChoreo.run();

Asintheprevioussection,iftheresultis0,itmeanseverythingwentfine.Ifthisisnotthecase,wewillprinttheerrormessageontheSerialportfordebuggingusingthefollowing

Page 162: Arduino networking   marco schwartz

pieceofcode:

if(returnCode==0){

Serial.println("Done!\n");

}else{

//Anon-zeroreturncodemeanstherewasanerror

//Readandprinttheerrormessage

while(SendEmailChoreo.available()){

charc=SendEmailChoreo.read();

Serial.print(c);

}

Serial.println();

}

Finally,wewillcloseChoreowiththefollowingline:

SendEmailChoreo.close();

NoteYoucanfindallthecodeforthissectionontheGitHubrepositoryofthischapterathttps://github.com/openhomeautomation/arduino-networking/tree/MASTER/chapter6.

Youcannowtestthesketch.ThefirstthingtodoistomakesurethatyouhaveyourownTembooaccountfileinthesamefolderastheArduinosketch.Then,uploadthesketchtotheArduinoboardandopentheSerialMonitor.Thefirstthingyoushouldseeistheconfirmationmessagethateverythingwentok:

DHCP:OK

Setupcomplete

Then,youshouldseethefirstmeasurementsontheSerialMonitor:

Temperature:21

Humidity:39

Dependingonthetemperaturevalue,youmightneedtopinchyoursensortotriggerthee-mailalert.Remember,intheexampleofthischapter,wesetavalueof23degreesforthetemperature.Afterawhile,ifthetemperaturereachesthethreshold,youshouldseethefollowingmessage:

Triggered!Calling/Library/Google/Gmail/SendEmail…

Afterawhile,thefollowingconfirmationmessageshouldappear:

Done!

YoucannowclosetheSerialMonitorandgocheckthee-mailaccountthatyousetonTemboo.YoushouldhavereceivedamessagewiththetitleyousetonTemboo,andyouwillalsoreceivethebodythatindicatesthegenericmessageyousetinthesketchalongwiththemeasuredtemperature.

Page 163: Arduino networking   marco schwartz
Page 164: Arduino networking   marco schwartz

SummaryInthischapter,wecreatedanotherInternetofThingsprojectusingthewebserviceTemboo.BasedonTemboo,webuilttwoexcitingapplications.ThefirstonewastoautomaticallylogmeasurementsinsideaGoogleDocsspreadsheet.Comparedtotheapproachwetookinthepreviouschapter,theadvantagehereisclearlythatGoogleDocsisthewidelyusedstandardtocreateandsharespreadsheets.Youcanaccessyourdatafromanywherejustbyusingawebbrowser,andyoucanalsoplotthedataandshareiteasilywithyourfriendsandfamily.

WealsobuiltanexcitingapplicationwhereweinterfacedourprojectwithGmailviaTemboo.Webuiltanautomatede-mailalertsystembasedonthemeasureddata.

Let’sseewhatthemajortakeawaysofthischapterwere.First,webuiltthehardwareoftheproject,withtheDHT11temperatureandhumiditysensorontopoftheArduinoEthernetshield.

Then,wesetupthedifferentaccountsthatwereneededfortheproject.WefirstcreatedaspreadsheetonGoogleDocsandconfigureditcorrectlysoitcanworkwithTemboo.Then,wealsocreatedaTembooaccountandconfigureditsothatyourEthernetshieldcansenddatatoTembooandlogmeasurementstoGoogleDocs.

Afterthesettingupphase,webuiltthefirstapplicationofthisproject,whichconsistedofloggingdatadirectlytoaGoogleDocsspreadsheet.WealsodisplayedthisdatausingtheGoogleDocsplottingcapabilities.

Finally,weusedTembooagaintocreateanautomatede-mailalertsystembysendingane-mailautomaticallytotheaddressofyourchoicewhenameasurementreachedagiventhreshold.

Asthisistheendofthisbook,let’sseewhatwelearnedabouttheArduinoEthernetshieldandwhatexcitingapplicationswecancreatewithit.

ThefirstpartofthebookwasallaboutrunningawebclientontheEthernetshield.WemadeafirsttestbyjusttryingouttheshieldandseeingwhetheritcouldconnecttotheInternetandgrabthecontentsofapage.Then,webuiltourfirstmeasurementsystem,wheretheEthernetshieldwasconnectingtoaserverrunningtoyourcomputertologsomedata.

Inthesecondpartofthebook,wegavemoreautonomytotheArduinoEthernetshieldbyrunningawebserverrightontheArduinoboard.Wemadethemeasurementprojectagain,butthistimebyhavingawebserverrunontheboardandloggingdatatoaSDcardinsertedintheshield.WealsoconnectedarelaytotheArduinoboardandwecontrolleditviaEthernet.

Finally,webuilttwoInternetofThingsprojectusingtheplatformsXivelyandTemboo.Inboththeseprojects,wesentdatatotheWebusingtheEthernetshieldsothatthisdatacanbeaccessedanddisplayedgraphicallyfromanywhereintheworld.

Toconcludethisbook,Ihopethatalltheinformationyoufoundinthedifferentchapters

Page 165: Arduino networking   marco schwartz

willgiveyouthewilltobuildevenmoreexcitingapplications.TheArduinoEthernetshieldisoneofthebestwaystobuildamazingconnectedapplicationswithArduino,andthereisnolimittowhatyoucandowiththeconceptsyoulearnedinthisbook.

Page 166: Arduino networking   marco schwartz

IndexA

account,Googlesettingup/SettingupyourGoogleAccount

account,Temboocreating/CreatingyourTembooaccount

application,buildingwithArduinoboardhardwarerequisites/Hardwareandsoftwarerequirementssoftwarerequisites/Hardwareandsoftwarerequirementshardwareconfiguration/Hardwareconfiguration

application,buildingwithArduinoEthernetshieldhardwarerequisites/Hardwareandsoftwarerequirementssoftwarerequisites/Hardwareandsoftwarerequirementshardwareconfiguration/Hardwareconfiguration

Arduinoboardwebserver,creatingon/CreatingawebserveronArduino

ArduinoEthernetShieldURL/Hardwareandsoftwarerequirements,Hardwareandsoftwarerequirements

ArduinoIDEURL/Hardwareandsoftwarerequirements

Arduinolibraryinstalling/Hardwareandsoftwarerequirements

ArduinoTemboolibraryURL/Hardwareandsoftwarerequirementsinstalling/Hardwareandsoftwarerequirements

ArduinoUnoURL/Hardwareandsoftwarerequirements,Hardwareandsoftwarerequirements

automatede-mailssending/Sendingautomatede-mails

Page 167: Arduino networking   marco schwartz

BBreadboard

URL/Hardwareandsoftwarerequirements,Hardwareandsoftwarerequirements

Page 168: Arduino networking   marco schwartz

CCOMpin,relay/Hardwareconfigurationconnection,ArduinoEthernetShield

testing/Testingyourconnection

Page 169: Arduino networking   marco schwartz

Ddata

sending,toserver/Sendingdatatoaserverlogging,onSDcard/LoggingdataonanSDcardplotting/Plottingthedatalocallysending,toXively/SendingdatatoXivelylogging,inGoogleDocsspreadsheet/Loggingdatainaspreadsheet

databaseincomingdata,logginginto/Logincomingdatainadatabase

delay()function/TestingyourconnectionDeviceCoder,Temboo/CreatingyourTembooaccount

URL/Sendingautomatede-mailsDHT11sensorArduinoEthernetShield

URL/Hardwareandsoftwarerequirements,Hardwareandsoftwarerequirements

DHTlibraryURL/Hardwareandsoftwarerequirements,Hardwareandsoftwarerequirements,Hardwareandsoftwarerequirements

Page 170: Arduino networking   marco schwartz

Ee-mails

sending/Sendingautomatede-mailsEasyPHP

URL/Hardwareandsoftwarerequirements

Page 171: Arduino networking   marco schwartz

Fflotlibrary

URL/Hardwareandsoftwarerequirements

Page 172: Arduino networking   marco schwartz

GGNDpin,relay/HardwareconfigurationGoogleAccount

settingup/SettingupyourGoogleAccountGoogleDocs

URL/SettingupyourGoogleAccountGoogleDocsspreadsheet

data,logging/Loggingdatainaspreadsheet

Page 173: Arduino networking   marco schwartz

Hhardwareconfiguration

fordata,logginginGoogleDocs/Hardwareconfigurationhardwareconfiguration,ArduinoEthernetShield/Hardwareconfigurationhardwareconfiguration,InternetofThingsproject/Hardwareconfigurationhardwarerequirements,ArduinoEthernetshield/Hardwareandsoftwarerequirementshardwarerequisites

application,buildingwithArduinoEthernetshield/Hardwareandsoftwarerequirementsforbuilding,applicationwithArduinoboard/Hardwareandsoftwarerequirementsforcontrollingobjectsremotely/HardwareandsoftwarerequirementsforInternetofThingsproject/Hardwareandsoftwarerequirementsfordata,logginginGoogleDocs/Hardwareandsoftwarerequirements

Page 174: Arduino networking   marco schwartz

Iinputpins,relay

VCCpin/HardwareconfigurationGNDpin/HardwareconfigurationSIGpin/Hardwareconfiguration

InternetofThingsprojecthardwarerequisites/Hardwareandsoftwarerequirementssoftwarerequisites/Hardwareandsoftwarerequirements

Page 175: Arduino networking   marco schwartz

JJSONformat

URL/LogincomingdatainadatabaseJumperwires

URL/Hardwareandsoftwarerequirements,Hardwareandsoftwarerequirements

Page 176: Arduino networking   marco schwartz

LLAMP

URL/HardwareandsoftwarerequirementsLINKLED/Hardwareconfiguration

Page 177: Arduino networking   marco schwartz

MMAMP

URL/HardwareandsoftwarerequirementsMicroSDcard

URL/HardwareandsoftwarerequirementsMongoDB

URL/Hardwareandsoftwarerequirements

Page 178: Arduino networking   marco schwartz

NNCpin,relay/HardwareconfigurationNOpin,relay/Hardwareconfiguration

Page 179: Arduino networking   marco schwartz

Ooutputpins,relay

COMpin/HardwareconfigurationNCpin/HardwareconfigurationNOpin/Hardwareconfiguration

Page 180: Arduino networking   marco schwartz

PPHP

used,forbuildingserver-sideapplication/Logincomingdatainadatabase

Page 181: Arduino networking   marco schwartz

Rrecordeddata

visualizing/Visualizingtherecordeddatarelay

testing/Testingtherelaycontrolling,remotely/Controllingtherelayremotelycontrolling,fromdistantlocation/Controllingtherelayfromanywhere

remoteobjects,controllinghardwarerequisites/Hardwareandsoftwarerequirementssoftwarerequisites/Hardwareandsoftwarerequirementshardwareconfiguration/Hardwareconfiguration

resultsdisplaying/Displayingtheresults

runAppendRow()function/Loggingdatainaspreadsheet

Page 182: Arduino networking   marco schwartz

SSDcard

data,loggingon/LoggingdataonanSDcardserver

data,sendingto/SendingdatatoaserverSIGpin,relay/Hardwareconfigurationsketch

writing,fortestingArduinoEthernetShieldconnection/Testingyourconnection

softwarerequirements,ArduinoEthernetshield/Hardwareandsoftwarerequirementssoftwarerequisites

forbuildingapplication,withArduinoEthernetshield/Hardwareandsoftwarerequirementsforbuilding,applicationwithArduinoboard/Hardwareandsoftwarerequirementsforcontrollingobjectsremotely/HardwareandsoftwarerequirementsforInternetofThingsproject/Hardwareandsoftwarerequirementsfordata,logginginGoogleDocs/Hardwareandsoftwarerequirements

SQLiteURL/Hardwareandsoftwarerequirements

Page 183: Arduino networking   marco schwartz

TTeleduinolibrary

URL/HardwareandsoftwarerequirementsTeleduinoservice

URL/ControllingtherelayfromanywhereTemboo

account,creating/CreatingyourTembooaccountTembooaccount

creating/CreatingyourTembooaccountURL/CreatingyourTembooaccount

TembooAccount.hfile/CreatingyourTembooaccountTimelibrary

URL/LoggingdataonanSDcard

Page 184: Arduino networking   marco schwartz

Uupdate()function/Displayingtheresults

Page 185: Arduino networking   marco schwartz

VVCCpin,relay/Hardwareconfiguration

Page 186: Arduino networking   marco schwartz

WWAMP

URL/Hardwareandsoftwarerequirementswebserver

creating,onArduinoboard/CreatingawebserveronArduino

Page 187: Arduino networking   marco schwartz

XXively

data,sendingto/SendingdatatoXivelyXivelyaccount

creating/CreatingyourXivelyaccountURL,forsignup/CreatingyourXivelyaccount