Post on 11-Jan-2016
HomeAutomationWiththeESP8266BuildHomeAutomationSystemsUsingthePowerfuland
CheapESP8266WiFiChip
MarcoSchwartz,PhD
ContentsLegalAbouttheauthorAboutthecompanionwebsite
Chapter1 Introduction
Chapter2 ESP8266HardwareConfiguration2.1 HowtoChooseYourESP8266Module2.2 HardwareRequirements2.3 HardwareConfiguration
Chapter3 GettingStartedWiththeESP8266ArduinoIDE3.1 InstallingtheArduinoIDEfortheESP82663.2 ConnectingYourModuletoYourWiFiNetwork
Chapter4 FirstProjectsWiththeESP82664.1 ControlaLED4.2 ReadDataFromaGPIOPin4.3 GrabtheContentFromaWebPage
Chapter5 WiFiWeatherMeasurementStation5.1 Hardware&SoftwareRequirements5.2 HardwareConfiguration5.3 TestingtheSensor5.4 AccessingtheSensorviaWiFi5.5 IntegratingtheOpenWeatherMapAPI5.6 HowtoGoFurther
Chapter6 ControlaLampRemotely6.1 Hardware&SoftwareRequirements6.2 HardwareConfiguration6.3 ControllingtheLampRemotely6.4 HowtoGoFurther
Chapter7 CreateaSimpleWiFiAlarmSystem7.1 Hardware&SoftwareRequirements7.2 HardwareConfiguration7.3 WritingtheMotionSensorCode7.4 CreatingOurAlarmSystem7.5 HowtoGoFurther
Chapter8 BuildanHomeAutomationSystemBasedontheESP82668.1 Hardware&SoftwareRequirements8.2 HardwareConfiguration8.3 WritingtheSketches8.4 CreatingtheInterface8.5 HowtoGoFurther
Chapter9 Conclusion
Chapter10 Resources10.1 LearnMoreAbouttheESP8266Chip10.2 Components
LegalCopyright©2015byMarc-OlivierSchwartz
Allrightsreserved. Nopartofthisbookmaybeusedorreproducedinanymannerwhatsoeverwithoutpermissionexceptinthecaseofbriefquotationsembodiedincriticalarticlesorreviews.
FirsteBookedition:April2015
AbouttheauthorIamMarcoSchwartz,andIamanelectricalengineer,entrepreneurandauthor. IhaveaMaster’sdegreeinElectricalEngineering&ComputerSciencefromoneofthetopElectricalEngineeringschoolinFrance,andaMaster’sdegreeinMicroEngineeringfromtheEPFLuniversityinSwitzerland.
Ihavemorethan5yearsofexperienceworkinginthedomainofelectricalengineering.Myinterestsgravitatearoundelectronics,homeautomation,theArduinoplatform,open-sourcehardwareprojects,and3Dprinting.
Since2011Ihavebeenworkingfull-timeasanentrepreneur,runningwebsiteswithinformationaboutopen-sourcehardwareandbuildingmyownopen-sourcehardwareproducts.
AboutthecompanionwebsiteThisbookhasacompanionwebsite,OpenHomeAutomation,whichyoucaneasilyfindbygoingathttp://www.openhomeautomation.net. Onthiswebsiteyouwillfindevenmoreprojectsandresourcesaroundhomeautomationandopen-sourcehardware.
Allthecodethatcanbefoundinthisbookcanalsobeaccessedonlineathttps://github.com/openhomeautomation/home-automation-esp8266. ThisGitHubrepositoryforthebookcontainsallthelatestup-to-datecodeforalltheprojectsyouwillfindinthisbook.
Chapter1
IntroductionIfirstheardabouttheESP8266WiFichipin2014. WhenIheardaboutit,IwasbuildingDIYhomeautomationsystemsalready,mainlyusingtheArduinoplatform. Atfirst,Iwasreluctanttousethischip:yes,itwascheap($5),butitwasverydifficulttouseandtoconnecttoArduinoforexample.
However,everythingchangedin2015withtheintroductionofamodifiedversionoftheArduinoIDEfortheESP8266. Withthissoftware,notonlyitwasreallyeasytousetheESP8266,butitalsoworkedwiththeonboardprocessoroftheESP8266,thereforeremovingtheneedofanArduinoboardnexttothechip.
ThismadeittheperfectbasetobuildDIYhomeautomationsystems. WiFiisveryconvenienttousetobuildconnectedapplicationsinyourhome,andatthisprice,itisano-brainertouseitineverydeviceinyourhome. Inthisbook,Iwillshowyouhowyoucandothat.
WearegoingtostartbysettinguptheESP8266chip. Youwilllearnhowtochoosetherightmoduleforyourproject,andgetalltheadditionalhardwareyouneedtousethechip. WewillalsoseehowtoconnecttheESP8266toyourcomputersoyoucanprogramitusinganUSBcable.
Then,wearegoingtoseehowtoconfigure&uploadcodetotheESP8266chip. Forthat,wewillbeusingamodifiedversionoftheArduinoIDE.ThismakesusingtheESP8266somucheasier,aswewillbeusingawell-knowninterface&languagetoconfigurethechip. WewillalsobeabletousemostofthealreadyexistingArduinolibrariesforourprojects.
Then,wewillmakethreesimpleprojectsusingtheESP8266chipthatyoujustconfigured,soyoucanlearnthebasicsofthischip.
Afterthat,we’lldiveintohomeautomationwiththeESP8266WiFichip:wewillconnectatemperature&humiditysensortoyourESP8266WiFichip,andthendisplaythemeasurementsonawebserverranontheESP8266itself! Thiswillallowyoutoaccess
measurementsfromanywhereinyourhome,forexampleonyoursmartphone.
Then,wearegoingtoseehowtocontrolalampremotelyviaWiFi. WewillalsohosttheinterfaceontheESP8266itself,tobuildacompletelyautonomouslampcontroller. Wewillalsomaketheinterfaceresponsive,soitcanbeusedeasilyfromasmartphoneortablet.
Afterthat,wewillconnectamotionsensortotheESP8266,andcreateasimplealarmsystemwithyourcomputerasthecentralalarmcontroller.
Finally,wewilluseeverythingwelearnedinthebooktocreateasmallhomeautomationsystembasedontheESP8266WiFichip. Wewilllearnhowtointegrateseveralcomponentsintoacentralinterface,soyoucancontroleverythingfromthesameplace.
Youdon’tneedtohavepreviousexperiencewiththeESP8266chiptousethecontentsofthisbook. However,abasicknowledgeofelectronicsandprogrammingisrequired. IfyoualreadyknowabitaboutArduino,itwillalsohelpyoutounderstandtheexamplesofthisbook.
Chapter2
ESP8266HardwareConfigurationInthischapter,wearegoingtoseehowtosetuptheESP8266soitiscorrectlypowered.Wearealsogoingtoconnectittoyourcomputersoyoucanprogramit. Finally,wearegoingtoseehowtochoosetherightmoduleforyourproject.
2.1 HowtoChooseYourESP8266Module
WearefirstgoingtoseehowtochoosetherightESP8266moduleforyourproject.Indeed,therearemanymodulesavailableonthemarket,anditisquiteeasytogetlostbetweenallthechoices.
ThefirstonethatyouprobablyheardofisthesmallESP8266SerialWirelessTransceivermodule:
Thismoduleisthemostfamousone,asitisreallysmallandonlycosts$5. However,thenumberofaccessibleGPIOpins(input/outputpins)arequitelimited. Itisalsodifficulttoplugitonastandardbreadboard.
Ifyouchoosethismodule,therearesomeprojectsofthisbookthatyoumightnotbeabletodo. Forexample,youwon’tbeabletodotheprojectsusinganalogsensorsastheanaloginputpinisnotaccessible.
Buttherearemanyothermodulesonthemarket,thatgivesyouaccesstoallthepinsoftheESP8266. Forexample,IreallyliketheESP8266Olimexmodulewhichisalsocheap(around$10):
Thismodulecaneasilybemountedonabreadboard,andyoucaneasilyaccessallthepinsoftheESP8266. ThisistheoneIwillusefortherestofthisbook,andthereforeIalsorecommendthatyouuseasimilarmodule. YoucanalsousemodulesbasedontheESP-12board,whichisverysimilartotheOlimexmodule.
AnothersolutionistousetheNodeMCUdevelopmentkit,whichissimilartotheOlimexboardbutalsohaveanintegratedUSBtoSerialconverter,aswellasanonboardpowersupply. Itiseveneasiertouse,buthardtofindatthetimethisguidewaswritten. YoucangetmoreinformationontheNodeMCUwebsite:
http://nodemcu.com/index_en.html
2.2 HardwareRequirements
Let’snowseewhatweneedtomaketheESP8266chipwork. Indeed,itisusuallywronglyassumedthatyoujustneedthislittlechipandnothingelsetomakeitwork,andwearegoingtoseethatitisnottrue.
First,youwillneedsomewaytoprogramtheESP8266. YoucanuseanArduinoboardforthat,butformethereallygreatthingabouttheESP8266isthatitcanfunctioncompletelyautonomously,usingtheonboardprocessor.
Sofortoprogramthechip,IwilluseaUSBFTDIprogrammer. NotethatithastobecompatiblewiththelogicleveloftheESP8266chip,so3.3V.Iusedamodulethatcanbeswitchedbetween3.3Vand5V:
Youwillalsoneedadedicatedpowersupplytopowerthechip. Thisisapointthatisoftenforgottenandthatleadstoalotofissues. Indeed,ifyouareforexampletryingtopowertheESP8266chipfromthe3.3VcomingfromtheFTDIboardorfromanArduinoboard,itsimplywon’tworkcorrectly.
Therefore,youneedadedicatedpowersupplythatcandeliveratleast300mAtobesafe.Iusedabreadboardpowersupplythatcandeliverupto500mAat3.3V:
ThisisalistofallthecomponentsthatyouwillneedtousetheESP8266chip:
ESP8266Olimexmodule(https://www.olimex.com/Products/IoT/MOD-WIFI-ESP8266-DEV/)Breadboard3.3Vpowersupply(https://www.sparkfun.com/products/13032)3.3VFTDIUSBmodule(https://www.sparkfun.com/products/9873)Breadboard(https://www.sparkfun.com/products/12002)Jumperwires(https://www.sparkfun.com/products/9194)
2.3 HardwareConfiguration
WearenowgoingtoseehowtoconfigurethehardwareforthefirstuseofyourESP8266board. Thisishowtoconnectthedifferentcomponents:
Andthisishowitwilllooklikeattheend:
Makesurethatyouconnectedeverythingaccordingtotheschematics,oryouwon’tbeabletocontinue. Alsomakesurethatalltheswitchesofyourcomponents(FTDImodule&powersupply)aresetto3.3V,oritwilldamageyourchip.
YourESP8266isnowready,andyoucannowmoveontothenextstep:usingthemodifiedversionoftheArduinoIDEtoconfigureyourchip.
Chapter3
GettingStartedWiththeESP8266ArduinoIDENowthatwecompletelysetupthehardwarearoundtheESP8266,wearereadytoconfigureitusingamodifiedversionoftheArduinoIDE.
Indeed,themostbasicwaytousetheESP8266moduleistouseserialcommands,asthechipisbasicallyaWiFi/Serialtransceiver. However,thisisnotconvenient,andthisisnotwhatIrecommenddoing.
WhatIrecommendisusingtheverycoolArduinoESP8266project,whichisamodifiedversionoftheArduinoIDEthatyouneedtoinstallonyourcomputer. ThismakesitveryconvenienttousetheESP8266chipaswewillbeusingthewell-knownArduinoIDE.Thisisthereforethemethodwewilluseinthiswholebook.
3.1 InstallingtheArduinoIDEfortheESP8266
WearenowgoingtoinstalltheArduinoIDEthathasbeenmodifiedfortheESP8266.Youcanfindallthedetailsoftheprojecton:
https://github.com/esp8266/Arduino
InstallingtheIDEisreallyeasyaswell. Youjustneedtodownloadthecorrespondingreleaseforyourplatform,andthenfollowtheonscreeninstructions. Youcangetthelatestreleasefrom:
https://github.com/esp8266/Arduino/releases
OncetheIDEisinstalled,congratulations,younowhaveaESP8266chipreadytobeusedwiththeArduinoIDE!
3.2 ConnectingYourModuletoYourWiFiNetwork
Now,wearegoingtocheckthattheArduinoIDEiscorrectlyworking,andconnectyourchiptoyourlocalWiFinetwork.
Todoso,weneedtowritethecodefirst,andthenuploadittotheboard. Thecodeiswillbequitesimple:wejustwanttoconnecttothelocalWiFinetwork,andprinttheIPaddressoftheboard. Thisisthecodetoconnecttothenetwork:
//Importrequiredlibraries
#include<ESP8266WiFi.h>
//WiFiparameters
constchar*ssid="your_wifi_name";
constchar*password="your_wifi_password";
voidsetup(void)
{
//StartSerial
Serial.begin(115200);
//ConnecttoWiFi
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFiconnected");
//PrinttheIPaddress
Serial.println(WiFi.localIP());
}
voidloop(){
}
Youcansimplycopythelinesofcodeabove,andcopythemintotheESP8266ArduinoIDEthatyoudownloadedbefore. Ofcourse,putyourownWiFiname&passwordinthecode. Savethisfilewithanameofyourchoice.
Now,alsogoinTools>Boards,andselect“GenericESP8266Module”. AlsoselectthecorrectSerialportthatcorrespondstotheFTDIconverteryourareusing.
Afterthat,uploadthecodetotheboard,andopentheSerialmonitorwhenthisisdone.AlsosettheSerialmonitorspeedto115200. Youshouldseethefollowingmessage:
WiFiconnected
192.168.1.103
IfyoucanseethismessageandanIP,congratulations,yourboardisnowconnectedto
yourWiFinetwork! YouarenowreadytobuildyourfirstprojectsusingtheESP8266chip.
Chapter4
FirstProjectsWiththeESP8266NowthatyourESP8266chipisreadytobeused&thatwecouldconnectittoyourWiFinetwork,wecannowbuildsomebasicprojectswithit. ThiswillhelpyouunderstandthebasicsoftheESP8266.
Wearegoingtoseethreeprojectsinthischapter:howtocontrolaLED,howtoreaddatafromofaGPIOpin,andfinallyhowtograbthecontentsfromawebpage.
4.1 ControlaLED
First,wearegoingtoseehowtocontrolasimpleLED.ThiswillteachyouhowtousetheGPIOpinsofthechipasoutputs.
ThefirststepistoaddanLEDtoourproject. Thesearetheextracomponentsyouwillneedforthisproject:
5mmLED(https://www.sparkfun.com/products/9590)330Ohmresistor(https://www.sparkfun.com/products/8377)
ThenextstepistoconnecttheLEDwiththeresistortotheESP8266board. Todoso,thefirstthingtodoistoplacetheresistoronthebreadboard. Then,placetheLEDonthebreadboardaswell,connectingthelongestpinoftheLED(theanode)toonepintheresistor.
Then,connecttheotherendoftheresistortotheGPIOpin5oftheESP8266,andtheotherendoftheLEDtotheground.
Thisishowitshouldlooklikeattheend:
WearenowgoingtolightuptheLEDbyprogrammingtheESP8266chip,justaswedidbeforebyconnectingittotheWiFinetwork.
Thisisthecompletecodeforthissection:
//Importrequiredlibraries
#include<ESP8266WiFi.h>
voidsetup(void)
{
//SetGPIO5asoutput
pinMode(5,OUTPUT);
//SetGPIO5onaHIGHstate
digitalWrite(5,HIGH);
}
voidloop(){
}
ThiscodesimplysetstheGPIOpinasanoutput,andthenapplyaHIGHstateonit.
YoucannowcopythiscodeandpasteitintheArduinoIDE.Then,uploadthecodetotheboard. YoushouldimmediatelyseethattheLEDislightingup. YoucanshutitdownagainbyusingdigitalWrite(5,LOW)inthecode.
4.2 ReadDataFromaGPIOPin
Asasecondprojectinthischapter,wearegoingtoreadthestateofaGPIOpin. Forthis,wewillusethesamepinasinthepreviousproject. YoucanthereforeremovetheLED&theresistorthatweusedinthepreviousproject.
Now,simplyconnectthispin(GPIO5)oftheboardtothepositivepowersupplyonyourbreadboardwithawire.
Readingdatafromapinisreallysimple. Thisisthecompletecodeforthispart:
//Importrequiredlibraries
#include<ESP8266WiFi.h>
voidsetup(void)
{
//StartSerial
Serial.begin(115200);
//SetGPIO5asinput
pinMode(5,INPUT);
}
voidloop(){
//ReadGPIO5andprintitonSerialport
Serial.print("StateofGPIO5:");
Serial.println(digitalRead(5));
//Wait1second
delay(1000);
}
Wesimplysetthepinasaninput,andthenreadthevalueofthispin,andprintitouteverysecond. Copy&pastethiscodeintotheArduinoIDE,thenuploadittotheboard.
ThisistheresultyoushouldgetintheSerialmonitor:
StateofGPIO5:1
Wecanseethatthereturnedvalueis1(digitalstateHIGH),whichiswhatweexpected,becauseweconnectedthepintothepositivepowersupply. Asatest,youcanalsoconnectthepintotheground,andthestateshouldgoto0.
4.3 GrabtheContentFromaWebPage
Asalastprojectinthischapter,wearefinallygoingtousetheWiFiconnectionofthechip,tograbthecontentofapage. Wewillsimplyusethewww.example.compage,asit’sabasicpagelargelyusedfortestpurposes.
Thisisthecompletecodeforthisproject:
//Importrequiredlibraries
#include<ESP8266WiFi.h>
//WiFiparameters
constchar*ssid="your_wifi_network";
constchar*password="your_wifi_password";
//Host
constchar*host="www.example.com";
voidsetup(){
//StartSerial
Serial.begin(115200);
delay(10);
//WestartbyconnectingtoaWiFinetwork
Serial.println();
Serial.println();
Serial.print("Connectingto");
Serial.println(ssid);
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFiconnected");
Serial.println("IPaddress:");
Serial.println(WiFi.localIP());
}
intvalue=0;
voidloop(){
Serial.print("Connectingto");
Serial.println(host);
//UseWiFiClientclasstocreateTCPconnections
WiFiClientclient;
constinthttpPort=80;
if(!client.connect(host,httpPort)){
Serial.println("connectionfailed");
return;
}
//Thiswillsendtherequesttotheserver
client.print(String("GET/")+"HTTP/1.1\r\n"+
"Host:"+host+"\r\n"+
"Connection:close\r\n\r\n");
delay(10);
//ReadallthelinesofthereplyfromserverandprintthemtoSerial
while(client.available()){
Stringline=client.readStringUntil('\R');
Serial.print(line);
}
Serial.println();
Serial.println("closingconnection");
delay(5000);
}
Thecodeisreallybasic:wefirstopenaconnectiontotheexample.comwebsite,andthensendaGETrequesttograbthecontentofthepage. Usingthewhile(client.available())code,wealsolistenforincomingdata,andprintitallinsidetheSerialmonitor.
YoucannowcopythiscodeandpasteitintotheArduinoIDE.Then,uploadittotheboard. ThisiswhatyoushouldseeintheSerialmonitor:
Thisisbasicallythecontentofthepage,inpureHTMLcode.
Congratulations,youjustcompletedyourveryfirstprojectsusingtheESP8266chip!
Chapter5
WiFiWeatherMeasurementStationInthisfirstchapterofthebook,wearegoingtomakeatypicalhomeautomationproject:aWiFiweathermeasurementstation. WewillconnectaDHT11sensortotheESP8266board,andaccessthedataviaWiFi.
Todoso,wewillrunasimplewebserverontheESP8266chip,thatwilldisplaytheresultsinsideawebpage. Wewillalsomakethiswebpageresponsive,soitlooksniceevenifyouareusingasmartphone. Finally,wewillusethefactthattheESP8266isalreadyconnectedtothewebtograbweathermeasurementsonline&displayitintheinterfaceaswell.
5.1 Hardware&SoftwareRequirements
Forthisproject,youwillofcourseneedanESP8266chip. YoucanforexampleuseanOlimexESP8266module.
Youwillalsoneedatemperaturesensor. IusedaDHT11sensor,whichischeap,veryeasytouse&thatwillallowustomeasuretheambienttemperature&humidity.
Youwillalsoneeda3.3VFTDIUSBmoduletoprogramtheESP8266chip. Finally,youwillalsoneedsomejumperwires&abreadboard.
Thisisalistofallthecomponentsthatwillbeusedinthischapter:
ESP8266Olimexmodule(https://www.olimex.com/Products/IoT/MOD-WIFI-ESP8266-DEV/)Breadboard3.3Vpowersupply(https://www.sparkfun.com/products/13032)3.3VFTDIUSBmodule(https://www.sparkfun.com/products/9873)DHT11sensor(https://www.adafruit.com/products/386)Breadboard(https://www.sparkfun.com/products/12002)Jumperwires(https://www.sparkfun.com/products/9194)
Onthesoftwareside,pleaserefertotheGettingStartedwiththeESP8266book(ortothefirstchaptersofthisbook)toknowwhatsoftwarecomponentsyouneedtoget.
YouwillalsoneedtheDHTlibrarythatyoucangetfrom:
https://github.com/adafruit/DHT-sensor-library
ToinstallanArduinolibrary,simplyputthelibrary’sfolderinsideyourArduino‘libraries’folder.
5.2 HardwareConfiguration
Again,formostofthehardwareconfigurationpleaserefertotheGettingStartedwiththeESP8266book(ortothefirstchaptersofthisbook). Attheend,youwillneedtohaveanESP8266chipreadytobeusedwiththeESP8266ArduinoIDE.
Oncethisisdone,simplyinserttheDHT11sensoronthebreadboard. Then,connecttheleftpintoVCC(redpowerrail),therightpintoGND(bluepowerrail),andthepinnexttoVCCtotheGPIO5pinonyourESP8266chip. Thisisthefinalresult,notshowingtheUSB-to-SerialFTDIcables:
5.3 TestingtheSensor
Wearenowgoingtotestthesensor. Again,rememberthatweareusingthemodifiedversionoftheArduinoIDE,sowecancodejustlikewewoulddousinganArduinoboard. Here,wewillsimplyprintthevalueofthetemperatureinsidetheSerialmonitoroftheArduinoIDE.
Thisisthecompletecodeforthispart:
//Libraries
#include"DHT.h"
//Pin
#defineDHTPIN5
//UseDHT11sensor
#defineDHTTYPEDHT11
//InitializeDHTsensor
DHTdht(DHTPIN,DHTTYPE,15);
voidsetup(){
//StartSerial
Serial.begin(115200);
//InitDHT
dht.begin();
}
voidloop(){
//Readingtemperatureandhumidity
floath=dht.readHumidity();
//ReadtemperatureasCelsius
floatt=dht.readTemperature();
//Displaydata
Serial.print("Humidity:");
Serial.print(h);
Serial.print("%\t");
Serial.print("Temperature:");
Serial.print(t);
Serial.println("*C");
//Waitafewsecondsbetweenmeasurements.
delay(2000);
}
Let’sseethedetailsofthecode. Youcanseethatallthemeasurementpartiscontainedinsidetheloop()unction,whichmakesthecodeinsideitrepeatevery2seconds.
Then,wereaddatafromtheDHT11sensor,printthevalueofthetemperature&humidityontheSerialport.
NotethatthecompletecodecanalsobefoundinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-esp8266
YoucannowpastethiscodeintheArduinoIDE,anduploadittoyourboard. Then,opentheSerialmonitor. Youshouldimmediatelyseethetemperature&humidityreadingsinsidetheSerialmonitor. Mysensorwasreadingaround24degreesCelsiuswhenItestedit,whichisarealisticvalue.
5.4 AccessingtheSensorviaWiFi
Atthispoint,wearesurethatthesensorisworkingandthatdatacanbereadbytheESP8266chip. Now,wearegoingtobuildthesketchthatwillconnecttoyourWiFinetwork,andthenserveawebpagethatwilldisplaytheresultsinlive.
Asthissketchisquitelong,Iwillonlydetailthemostimportantpartshere. YoucanofcoursefindthecompletecodeforthisprojectinsidetheGitHubrepositoryofthebook.
First,youneedtosetupyourownWiFinetworkname&passwordinthecode:
constchar*ssid="your_wifi_network_name";
constchar*password="your_wifi_network_password";
Afterthat,wecreateawebserveronport80:
WiFiServerserver(80);
Then,insidethesetup()functionofthesketch,weconnecttheESP8266totheWiFinetwork:
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFiconnected");
Then,westarttheserver,andprinttheIPaddressontheSerialport:
//Starttheserver
server.begin();
Serial.println("Serverstarted");
//PrinttheIPaddress
Serial.println(WiFi.localIP());
Insidetheloop()functionofthesketch,wecheckifaclientisconnectedtotheESP8266:
WiFiClientclient=server.available();
Then,wereaddatafromthesensor:
//Readingtemperatureandhumidity
floath=dht.readHumidity();
//ReadtemperatureasCelsius
floatt=dht.readTemperature();
Afterthat,wereadtheincomingrequestfromtheclient:
Stringreq=client.readStringUntil('\R');
Serial.println(req);
client.flush()
Then,weprepareouranswer. Whatwewanthereistoservethedatatotheclientinanelegantway. That’swhywewillusetheBootstrapCSSframework,thatwillmakeourpagelookspretty. Itwillalsomakesitresponsive,soitwilllookgreatonmobiledevicesaswell.
ThefirstpartistosendtheHeadtagoftheHTMLpage,whichincludestheBootstrapCSSfile. Wealsosetinthisparttherefreshrateofthepage,whichwillbeautomaticallyrefreshedeveryminute:
Strings="HTTP/1.1200OK\r\nContent-Type:text/html\r\n\r\n";
s+="<head>";
s+="<metaname=\"viewport\"content=\"width=device-width,initial-scale=1\">";
s+="<metahttp-equiv=\"refresh\"content=\"60\"/>";
s+="<scriptsrc=\"https://code.jquery.com/jquery-2.1.3.min.js\"></script>";
s+="<linkrel=\"stylesheet\"href=";
s+="\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\">";
s+="<style>body{font-size:24px;}.voffset{margin-top:30px;}</style>";
s+="</head>";
Then,wesendthecoreofthepage,whichconsistsinsimplydisplayingthetemperature&humiditydata:
s+="<divclass=\"container\">";
s+="<h1>WiFiWeatherStation</h1>";
s+="<divclass=\"rowvoffset\">";
s+="<divclass=\"col-md-3\">Temperature:</div>";
s+="<divclass=\"col-md-3\">"+String(t)+"</div>";
s+="<divclass=\"col-md-3\">Humidity:</div>"
s+="<divclass=\"col-md-3\">"+String(h)+"</div>";
s+="</div>";
s+="</div>";
Finally,wesendthistotheclient,andwaituntiltheclientdisconnectsfromourboard:
client.print(s);
delay(1);
Serial.println("Clientdisconnected");
NotethatyoucanfindallthecodeforthisprojectinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-esp8266
It’snowtimetotesttheproject. GetthecodefromtheGitHubrepository,modifyitwithyourownparameters,andthenuploadthecodetotheboard.
Afterthat,opentheSerialmonitoroftheArduinoIDE.YoushouldseethattheIPaddressisdisplayedinsidetheSerialmonitor.
Then,simplygotoawebbrowserandtypethisIPaddress. Youshouldimmediatelyseethemeasureddatainyourbrowser:
Notethatyoucanalsodothesamefromyourmobilephoneortablet,anditwillworkjustaswell!
5.5 IntegratingtheOpenWeatherMapAPI
Wearegoingtopushthisprojectalittlefurthernow. Someweatherstationsthatyoucangetfromastoreincorporateanexternalsensorthatyoucanforexampleputoutside,andthenitwilldisplaybothinside&outsidetemperaturesonthestation.
Here,wewillusethefactthatourprojectisalreadyconnectedtothewebtogetthelocaloutsidetemperature&humidityfromtheweb. Todoso,wewillusetheOpenWeatherMapAPI:
http://openweathermap.org/api
It’sveryeasytotest. Forexample,youcanjustvisitthefollowinglinktogetthecurrentweatherdataforLondon,UK:
http://api.openweathermap.org/data/2.5/weather?q=London,uk
YouwillgetananswerinaJSONcontainer:
{
"coord":{
"lon":-0.13,
"lat":51.51
},
"sys":{
"message":0.0323,
"country":"GB",
"sunrise":1428384087,
"sunset":1428432222
},
"weather":[
{
"id":800,
"main":"Clear",
"description":"SkyisClear",
"icon":"01d"
}
],
"base":"stations",
"main":{
"temp":272.73,
"temp_min":272.73,
"temp_max":272.73,
"pressure":1042.28,
"sea_level":1050.54,
"grnd_level":1042.28,
"humidity":87
},
"wind":{
"speed":0.96,
"deg":43.0004
},
"clouds":{
"all":0
},
"dt":1428388195,
"id":2643743,
"name":"London",
"cod":200
}
That’sgood,becauseitwillbereallyeasytousebyoursimpleHTTPserverrunningontheESP8266chip. Wewillonlyneedtomodifythesketchabit. Thisiswhatweneedtoaddfortheinterface:
s+="<divclass=\"rowvoffset\">";
s+="<divclass=\"col-md-3\">Exteriortemperature:</div>";
s+="<divid=\"ext_temp\"class=\"col-md-3\"></div>";
s+="<divclass=\"col-md-3\">Exteriorhumidity:</div>";
s+="<divid=\"ext_humidity\"class=\"col-md-3\"></div>";
s+="</div>";
Andafterthat,weneedtoaddsomeJavaScriptintotheanswertotheclient,sotheESP8266constantlyfetchesdatafromtheOpenWeatherMapwebsite:
s+="<script>$.ajax({url:";
s+="\"http://api.openweathermap.org/data/2.5/weather?q=London,uk\",";
s+="crossDomain:true})";
s+=".done(function(result){";
s+="$(\"#ext_temp\").html((result.main.temp-273.15).toFixed(2));";
s+="$(\"#ext_humidity\").html(result.main.humidity);})";
s+="</script>";
Ofcourse,youwillneedtomodifythecodeaccordinglyforyourowncity&country.
NotethatyoucanfindallthecodeforthisprojectinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-esp8266
It’snowtimetotesttheproject. GetthecodefromtheGitHubrepository,modifyitwithyourownparameters,andthenuploadthecodetotheboard.
Now,gotothesameIPaddressasbeforewithyourwebbrowser,andthisiswhatyouwillsee:
5.6 HowtoGoFurther
Let’ssummarizewhatweachievedinthisproject. WebuiltaWiFiweatherstationbasedontheESP8266WiFichip. Weusedasensortomeasurethelocaltemperature&humidity,andalsofetcheddatafromthewebtogettheoutsidetemperature. Then,wedisplayedeverythingonawebpagethatcanalsobeaccessedonmobiledevices.
Therearemanythingsyoucandotoimprovethisproject. YoucanforexampleusemoredatathatyoureceivefromtheOpenWeatherMapAPI&displaythisdataaswellonthewebpage,likethelocalbarometricpressure,ortheweatherpredictions. YoucanalsoconnectmoresensorstotheESP8266chip,likeanambientlightsensor.
Chapter6
ControlaLampRemotelyInthischapter,wearegoingtousetheESP8266chiptocontrolalampremotelyviaWiFi. However,wewon’tdowhatyouusuallyseeontheweb. Indeed,peopleusuallyuseaserverrunningontheircomputerstocontroldevicesremotely.
Here,wearegoingtousetheonboardprocessoroftheESP8266tohostasmallwebserver,thatwillgenerateasimpleinterfaceonawebpagefromwhichyouwillbeabletocontrolthelamp. Andwewillevenmakethisinterfaceresponsive,soitcanalsobeusedwithyourphoneortablet!
6.1 Hardware&SoftwareRequirements
Forthisproject,youwillofcourseneedanESP8266chip. Asforthewholebook,IusedtheOlimexESP8266module,butanyESP8266modulewillworkfinehere.
Youwillalsoneedsomewaytocontrolyourlamporotherdevices. Ioriginallyusedasimplerelayformytests,butIquicklymovedtoaPowerSwitchTailKitwhichallowstosimply&safelyplughighvoltagedevicestoyourprojects.
Youwillalsoneeda3.3VFTDIUSBmoduletoprogramtheESP8266chip.
Finally,youwillalsoneedsomejumperwires&abreadboard.
Thisisalistofallthecomponentsthatwillbeusedinthisproject:
ESP8266Olimexmodule(https://www.olimex.com/Products/IoT/MOD-WIFI-ESP8266-DEV/)Breadboard3.3Vpowersupply(https://www.sparkfun.com/products/13032)3.3VFTDIUSBmodule(https://www.sparkfun.com/products/9873)PowerSwitchTailKit(https://www.sparkfun.com/products/10747)Breadboard(https://www.sparkfun.com/products/12002)Jumperwires(https://www.sparkfun.com/products/9194)
Notethatyouwillalsoneedadevicetocontrol. Iusedasimple30Wdesklampasatestdevice,butyoucanalsouseanyotherdeviceinyourhome(ifthepowerratingislowerthanthemaximumpoweracceptedbythePowerSwitchTailKit). Youcanalsojustuseasimplerelayfortestpurposes.
Onthesoftwareside,pleaserefertotheGettingStartedwiththeESP8266book(ortothefirstchaptersofthisbook)toknowwhichsoftwarecomponentsyouneedtogettomaketheESP8266chipwork.
Attheend,youwillneedtohaveanESP8266chipreadytoworkwiththeESP8266ArduinoIDE.
6.2 HardwareConfiguration
Again,pleaserefertotheGettingStartedwiththeESP8266book(ortothefirstchaptersofthisbook)
TheonlythingyouneedtoaddtothisbasicconfigurationisthePowerSwitchTailKit.Connectthetwopinsontheright(-inandGround)onthegroundofourproject(bluepowerrail),andthe+inpintotheGPIO5pin. Ifyourboarddoesn’thavethispin,youcanplugittothefreeGPIOpinofyourchoice,youwilljustneedtomodifyyourcodeaccordingly.
Then,alsoconnectalamporanyelectricaldevicetothePowerSwitch,andtheotherendofthePowerSwitchtothemainselectricity.
Thisistheassembledproject,withouttheFTDImoduletoconfigurethemodule:
AndthisistheprojectdeployedclosetothelampIusedasatest:
6.3 ControllingtheLampRemotely
Wearenowgoingtowritethecoderequiredtocontrolourlampremotely. Notethatwewantacompletelyautonomousoperationofthedevice. TheESP8266willhavetohandlerequestscomingfromyourbrowser,displayasimpleHTMLpagewithtwobuttons(On&Off),andthencontroltherelayaccordingly. AsweareusingtheArduinoIDEtoprogramourESP8266wewillalsobeusingthewell-knownArduinolanguageforthispart.
Asthecodeisquitelong,Iwillonlycovertheimportantpartshere. Ofcourse,youcanfindallthecodeinsidetheGitHubrepositoryofthebook.
Itstartsbyincludethecorrectlibrary:
#include<ESP8266WiFi.h>
Then,youneedtoenteryourWiFinetwork&password:
constchar*ssid="your_wifi_network";
constchar*password="your_wifi_password";
Wealsodeclareawebserverrunningonport80:
WiFiServerserver(80);
WealsodeclarethatwewilluseGPIOpin5. OfcourseifyouareusinganotherGPIOpinyouwillneedtomodifythisvalue:
intoutput_pin=5;
Inthesetup()function,wedeclarethepinonwhichtherelay/PowerSwitchisconnected:
pinMode(output_pin,OUTPUT);
Afterthat,weconnecttotheWiFinetworkandstarttheserver:
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFiconnected");
//Starttheserver
server.begin();
Serial.println("Serverstarted");
Now,intheloop()function,welistentoincomingconnectionsonport80:
WiFiClientclient=server.available();
Whenwereceivesomedata,wefirstcheckifitdoesn’tcontaintheonoroffvalues. Ifitdoes,wechangethestateoftheoutputpinaccordingly:
if(req.indexOf("/on")!=-1){
digitalWrite(output_pin,1);
}
elseif(req.indexOf("/off")!=-1){
digitalWrite(output_pin,0);
}
Now,weneedtoserveanddisplayabasicinterfaceeverytimeweaccesstheboardviaourbrowser. WewillactuallysendalltheHTMLpage,linebyline. Let’sstartwiththe<head>element:
Strings="HTTP/1.1200OK\r\nContent-Type:text/html\r\n\r\n";
s+="<head>";
s+="<metaname=\"viewport\"content=\"width=device-width,initial-scale=1\">";
s+="<scriptsrc=\"https://code.jquery.com/jquery-2.1.3.min.js\"></script>";
s+="<linkrel=\"stylesheet\"href=\"https://maxcdn.bootstrapcdn.com/";
s+="bootstrap/3.3.4/css/bootstrap.min.css\">";
s+="</head>";
YoucanseethatweevenimportmoduleslikejQuery(tohandletheclicksonourbuttons)andBootstrap(togetaniceresponsiveinterface). ThisispossibleonthesmallESP8266chipbecauseweareusingthehostedversionsoftheseframeworks,andthereforeitdoesn’ttakeextramemoryspaceonthechip.
Then,wesendtheinterfaceitselfwithtwobuttons:
s+="<divclass=\"container\">";
s+="<h1>RelayControl</h1>";
s+="<divclass=\"row\">";
s+="<divclass=\"col-md-2\"><inputclass=\"btnbtn-blockbtn-lgbtn-primary\"";
s+="type=\"button\"value=\"On\"onclick=\"on()\"></div>";
s+="<divclass=\"col-md-2\"><inputclass=\"btnbtn-blockbtn-lgbtn-danger\"";
s+="type=\"button\"value=\"Off\"onclick=\"off()\"></div>";
s+="</div></div>";
Thisisalsowhereyoucangiveanametoourproject. Iputsimply‘RelayControl’asIwasdoingallthetestswithasimplerelay.
Finally,wesendsomeJavaScriptcodeaswelltohandletheclicksonthebuttons:
s+="<script>functionon(){$.get(\"/on\");}</script>";
s+="<script>functionoff(){$.get(\"/off\");}</script>";
NotethatyoucanfindallthecodeforthisprojectonthecorrespondingGitHubrepository:
https://github.com/openhomeautomation/home-automation-esp8266
IusedagaintheESP8266ArduinoIDEsoftwaretouploadfilestotheESP8266board.Then,opentheSerialmonitortogettheIPaddressofyourboard.
Finally,simplyopenyourfavoritewebbrowser,andtypeintheboardIPaddress. Youshouldseetheinterfacebeingdisplayed:
Youcannowtrythebuttons:youshouldnoticethatthestateofthePowerSwitchortherelayischanginginstantly,andthatthelampisturningon&off. AndnotethatthisisonlyusingtheESP8266chiphere:it’scompletelyindependentfromyourcomputer!
Theinterfaceisalsoresponsive,thankstotheBootstrapframework. Thismeansitwillautomaticallyadapttothedeviceonwhichitisused. Thisisforexampletheresultonmyphone:
6.4 HowtoGoFurther
Inthisproject,webuiltacompletelyautonomousremotelampcontrollerusingtheESP8266WiFichip. Wemadethislittlechipcontrolalamp(oranyotherdevice)byservinganice&responsiveinterface,allowingyoutocontrolthedevicefromanyterminalwithinyourlocalWiFinetwork,likeaphoneortablet.
Ofcourse,youcanusewhatyoulearnedinthisprojecttobuildotherhomeautomationsystems. Youcanforexampleusethesameprinciplestoaddsensorstotheprojectthatmeasuredataanddisplayitallinasingleinterface,alsoservedbytheESP8266module.
Chapter7
CreateaSimpleWiFiAlarmSystemInthischapter,wearegoingtobuildasimplealarmsystembasedontheESP8266. ItwillbecomposedofoneorseveralESP8266modulescoupledwithmotionsensors,andacentralalarminterfacerunningonyourcomputer.
Typically,motiondetectorsareusinglow-costradiostocommunicatewithacentralalarmsystems,andneverWiFi. However,theESP8266chipissocheapthatitalsomakessenseheretouseWiFiformotionsensors. Let’sdiveintotheproject!
7.1 Hardware&SoftwareRequirements
Forthisproject,youwillofcourseneedanESP8266chip. Asforthewholebook,IusedtheOlimexESP8266module,butanyESP8266modulewillworkfinehere.
Youwillalsoneedamotionsensor. Iusedasimple&cheapPIRmotionsensorforthisproject. Theseareexactlythesamekindofsensorthatareusedincommercialhomeautomationsystems:
Thisisalistofallthecomponentsthatwillbeusedinthisproject:
ESP8266Olimexmodule(https://www.olimex.com/Products/IoT/MOD-WIFI-ESP8266-DEV/)Breadboard3.3Vpowersupply(https://www.sparkfun.com/products/13032)3.3VFTDIUSBmodule(https://www.sparkfun.com/products/9873)PIRmotionsensor(https://www.adafruit.com/product/189)Breadboard(https://www.sparkfun.com/products/12002)
Jumperwires(https://www.sparkfun.com/products/9194)
Alsonotethatifyouwanttohaveseveralmotionsensorsliketheonewearegoingtobuildhere,youwillneedseveralESP8266chips&PIRsensorsaswell. Asanexample,wewillonlyuseonemotionsensorfortheproject.
Onthesoftwareside,pleaserefertotheGettingStartedwiththeESP8266book(ortothefirstchaptersofthisbook)toknowwhichsoftwarecomponentsyouneedtogettomaketheESP8266chipwork.
Attheend,youwillneedtohaveanESP8266chipreadytoworkwiththeESP8266ArduinoIDE.
7.2 HardwareConfiguration
Again,pleaserefertotheGettingStartedwiththeESP8266book(ortothefirstchaptersofthisbook). Theonlythingyouwillneedtoaddinthisprojectisthemotionsensor.
ThePIRmotionsensorisreallyeasytoconnecttotheESP8266chip. First,connectthepowersupply:theVCCpingoestotheredpowerrailonthebreadboard,andtheGNDpinofthesensorgoestothebluepowerrail. Finally,connecttheSIGpinofthesensortotheGPIOpin5oftheESP8266WiFichip. Thisisthefinalresult:
Ofcourse,youcanalsouseanotherpinfortheSIGpin,especiallyincaseyouareusinganESP8266WiFithatdoesn’thaveallthepinsexposed. Inthatcase,youwillneedtomodifythecodeslightly.
7.3 WritingtheMotionSensorCode
Wearefirstgoingtowritethesketchforthemotionsensor. Thiscodewillbasicallyconstantlycheckthestatusofthemotionsensor. Ifitdetectsthatthestatechanged(whichmeansmotionhasbeendetected),itwillsendamessagetoawebserverrunningonyourcomputer(thatwewillcodelater).
Asthecodeisquitelong,Iwillonlycovertheimportantpartshere. Ofcourse,youcanfindallthecodeinsidetheGitHubrepositoryofthebook.
Westartbyincludingtherequiredlibraryfortheproject:
#include<ESP8266WiFi.h>
Then,wedefinetheIPaddressoftheserverthatwillrunthealarmsystem. Inthiscase,itistheIPaddressofyourcomputer:
constchar*host="192.168.1.100";
Therearemanywaysyoucangetitdependingonyouroperatingsystem,butitisusuallyfoundunderamenuorpanelcalled“NetworkPreferences”.
Wealsoinitializethemotionsensorstateto0:
intmotion_sensor_state=0;
Then,intheloop()functionofthesketch,wereaddatafromthepinonwhichthemotionsensorisconnected:
intnew_motion_sensor_state=digitalRead(5);
Then,wecomparethisreadingtotheoldreading,toseeifthestatechanged:
if(new_motion_sensor_state!=motion_sensor_state)
Ifthisisthecase,wefirstassignthenewstatetotheoldstate:
motion_sensor_state=new_motion_sensor_state;
Then,wecreateaclientinstanttoconnecttotheserverrunningonourcomputer:
WiFiClientclient;
constinthttpPort=3000;
if(!client.connect(host,httpPort)){
Serial.println("connectionfailed");
return;
}
Afterthat,wesendaPOSTrequesttotheserverthatcontainsthestateofthesensor:
client.print(String("POST/motion?state=")+String(new_motion_sensor_state)+
"HTTP/1.1\r\n"+"Host:"+host+"\r\n"+"Connection:close\r\n\r\n");
delay(10);
Afterthat,wereadtheanswerfromtheserver:
while(client.available()){
Stringline=client.readStringUntil('\R');
Serial.print(line);
}
NotethatyoucanfindthewholesketchinsidetheGitHubrepositoryofthebook:
https://github.com/openhomeautomation/home-automation-esp8266
It’snowtimetotesttheproject. GetthecodefromtheGitHubrepository,modifyitwithyourownparameters,andthenuploadthecodetotheboard.
Now,wecanmovetocodingthealarmsystemitself.
7.4 CreatingOurAlarmSystem
Wearenowgoingtowritethecodeforthealarmsystem,thatwillrunonyourcomputer.Theserverwillbereallybasic:youwillbeabletomonitorthestateofthemotionsensorfromaninterface,andalsoactivateordeactivatethealarmmode.
Whenthealarmmodewillbeactivated,ifmotionisdetectedtherewillbealoudsoundcomingoutofyourcomputer. Ifitisdeactivated,thesensorwillkeeponcommunicatingwiththeserver,butnosoundwillbeemittedbythecomputer.
WewillusetheverypopularNode.jsframeworktocodeourserver. Youcannowdownloaditandinstallitfrom:
https://nodejs.org/
Therewillbasicallybe3filesinthisproject:
Theapp.jsfile,thatwillcontainthecodefortheserveritselfTheinterface.jadefile,thatwilldefinetheinterfaceTheinterface.jsfile,thatwillmakethelinkbetweentheinterface&theserver
Asthecodeisquitelong,Iwillonlycovertheimportantpartshere. Ofcourse,youcanfindallthecodeinsidetheGitHubrepositoryofthebook.
Let’sstartwiththemainfile,whichiscalledapp.js. ItstartsbyincludingtheExpressframework(http://expressjs.com/),whichwillmakeiteasiertocodeourwebserver:
varexpress=require('express');
varapp=express();
Then,wedefinesomeglobalvariables:oneforthestateofthesensor,andforthestateofthealarm:
//Globalvariableformotionsensor
varmotion=0;
//Alarmstate
varalarm=0;
Then,wehavetodefinevariousroutestoget&tosetthestateofthesevariables:
//Changemotionsensorstate
app.post('/motion',function(req,res){
motion=req.query.state;
res.send('Datareceived:'+motion);
});
//Getmotionsensorstate
app.get('/motion',function(req,res){
res.json({state:motion});
});
//Getalarmstate
app.get('/alarm',function(req,res){
res.json({state:alarm});
});
//Setalarmstate
app.post('/alarm',function(req,res){
alarm=req.query.state;
res.send('Datareceived:'+alarm);
});
Finally,westartthewebserverwith:
app.listen(port);
console.log("Listeningonport"+port);
Now,let’sseetheinterface.jsfile. Thisfilewillmakethelinkbetweentheinterfaceandtheserver.
Wefirstdefineafunctiontoquerythevalueofthemotionsensor,andchangetheinterfaceaccordingly. Ifmotionisdetectedandthealarmisnoton,wesimplychangethestateoftheindicatorintheinterface. Ifthealarmison,wealsoplayasound.
Thisisthecompletecodeforthisfunction:
functionrefresh_motion(){
$.getq('queue','/motion',function(data){
if(data.state==0){$('#motion').html("Nomotiondetected");}
if(data.state==1){
//Changetext
$('#motion').html("Motiondetected");
//Playsoundifalarmison
$.get('/alarm',function(data){
if(data.state==1){$.playSound('/audio/alarm');}
});
}
});
}
Now,werunthisfunctionevery500milliseconds:
refresh_motion();
setInterval(refresh_motion,500);
Wealsoneedtoinitializeabuttonforthealarm,andchangethetext&colorofthisbuttondependingofthestateofthealarm:
$.get('/alarm',function(data){
varalarm_state=data.state;
if(alarm_state==1){
$('#alarm').html("AlarmOn");
$('#alarm').attr('class','btnbtn-blockbtn-lgbtn-success');
}
if(alarm_state==0){
$('#alarm').html("AlarmOff");
$('#alarm').attr('class','btnbtn-blockbtn-lgbtn-danger');
}
});
Finally,wehandletheclicksonthealarmbutton,andchangethestateofthealarmaccordingly:
$('#alarm').click(function(){
//Getalarmstate
$.get('/alarm',function(data){
varalarm_state=data.state;
if(alarm_state==0){
$.post('/alarm?state=1');
$('#alarm').html("AlarmOn");
$('#alarm').attr('class','btnbtn-blockbtn-lgbtn-success');
}
if(alarm_state==1){
$.post('/alarm?state=0');
$('#alarm').html("AlarmOff");
$('#alarm').attr('class','btnbtn-blockbtn-lgbtn-danger');
}
});
});
NotethatyoucanfindallthecodeforthisprojectinsidethecorrespondingGitHubrepository:
https://github.com/openhomeautomation/home-automation-esp8266
It’snowtimetotesttheproject. GetthecodefromtheGitHubrepository,andplaceallthefilesintoagivenfolder. Then,gotothisfolderwithaterminal. Afterthat,type:
sudonpminstallexpressjade
Andthen:
nodeapp.js
Then,simplygotoyourfavoritewebbrowser,andtype:
http://localhost:3000/
Youshouldseetheinterfaceofyoursimplealarmsystem,withthealarmoffbydefault:
Youcanalsonowtestthemotionsensor. Justwaveyourhandinfrontofit,andyoushouldseethetextchanginginsidetheinterface.
Now,trytoclickonthebutton. Youshouldseethatthebuttonisturninggreen:
Now,trytowaveyourhandinfrontofthesensoragain. Thistime,youshouldhearaloudalarmsoundcomingfromyourcomputer.
Congratulations,younowbuiltasimplealarmsystemwiththeESP8266chip!
7.5 HowtoGoFurther
Let’ssummarizewhatweachievedinthischapter. WeconnectedaPIRmotionsensortotheESP8266chip,andthenbuiltasimplealarmsystemwithit.
Therearemanythingsyoucandotoimprovethisproject. Onewayistomodifythecodeofthisprojectslightlytoaccommodateformoremotionsensors. OntheESP8266side,youwillneedtoforexampleassignanuniqueIDtoeachsensorandtransmitthisIDalongwiththestateofthemotionsensor.
Then,ontheserverside,youwilljustneedtogettheIDofthesensoraswell,anddisplaythestateofthedifferentsensorsinsidetheinterface. YoucouldalsoimagineconnectingthisprojecttoTwitter,soyoureceiveaTweeteverytimemotionisdetectedinyourhome.
Chapter8
BuildanHomeAutomationSystemBasedontheESP8266Forthefinalchapterofthisbook,wearegoingtointegratealltheknowledgeweacquiredinthebooksofartobuildasmallhomeautomationsystemthatintegratesseveralcomponents.
Asanexample,wewilluseagainthetemperature&humiditysensorprojectandthelampcontrolproject,andintegratetheseprojectsintoasingleinterface. Thiswillallowyoutomonitoryourhomefromasingleinterface. Youwillalsobeabletousewhatyoulearnedinthisprojectandaddmorecomponentsinthefuture.
8.1 Hardware&SoftwareRequirements
Forthisproject,youbasicallyneedthesamehardwarethatweusedintwootherprojectsofthisbook.
Forthetemperature&humiditysensormodulerequirements,pleasecheckagainChapter5. Forthelampcontrolmodulerequirements,pleasecheckagainChapter6.
8.2 HardwareConfiguration
Again,toconfigurethehardwareforthisproject,Iwillredirectyoutothecorrespondingchaptersofthebook.
Forthetemperature&humiditysensormoduleconfiguration,pleasecheckagainChapter5. Forthelampcontrolmoduleconfiguration,pleasecheckagainChapter6.
8.3 WritingtheSketches
Wearenowgoingtowritetwosketches:oneforthelampcontrolproject,andoneforthetemperature&humiditysensormodule.
Comparedtopreviouschapters,wedon’twanttohavetheESP8266WiFiservingit’sowninterface. Here,wejustwantthesemodulestorespondtocommandssentbyacentralserver,thatwillrunonourcomputer.
Tomakethingseasier,wearegoingtousetheaRESTAPI,whichimplementsaRESTfulinterfacefortheESP8266board. Basically,itmeansthatyourboardwillbefullycontrollableviaHTTPcommands,forexamplecomingfromawebserver. Youcanfindmoredetailsabouttheprojecthere:
http://arest.io
Now,wearegoingtostartwiththesketchtocontrolthelamp. Thisisthecompletesketchforthismodule:
//Importrequiredlibraries
#include<ESP8266WiFi.h>
#include<aREST.h>
//CreateaRESTinstance
aRESTrest=aREST();
//WiFiparameters
constchar*ssid="your_wifi_name";
constchar*password="your_wifi_password";
//TheporttolistenforincomingTCPconnections
#defineLISTEN_PORT80
//Createaninstanceoftheserver
WiFiServerserver(LISTEN_PORT);
voidsetup(void)
{
//StartSerial
Serial.begin(115200);
//GivenameandIDtodevice
rest.set_id("1");
rest.set_name("lamp_control");
//ConnecttoWiFi
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFiconnected");
//Starttheserver
server.begin();
Serial.println("Serverstarted");
//PrinttheIPaddress
Serial.println(WiFi.localIP());
}
voidloop(){
//HandleRESTcalls
WiFiClientclient=server.available();
if(!client){
return;
}
while(!client.available()){
delay(1);
}
rest.handle(client);
}
Let’snowseetheimportantpartsofthissketch. First,weneedtoincludetheESP8266WiFilibraryandtheaRESTlibrary:
#include<ESP8266WiFi.h>
#include<aREST.h>
Then,wecreateaninstanceoftheaRESTlibrary:
aRESTrest=aREST();
Intheloop()functionofthesketch,wecheckifwehaveaclientconnectedtotheESP8266. Ifthat’sthecase,wehandletherequestwiththeaRESTlibrary:
//HandleRESTcalls
WiFiClientclient=server.available();
if(!client){
return;
}
while(!client.available()){
delay(1);
}
rest.handle(client);
It’snowtimetotesttheproject. GetthecodefromtheGitHubrepository,modifyitwithyourownparameters,andthenuploadthecodetotheboard.
Now,opentheSerialmonitortogettheIPaddressoftheboard. We’llassumefortherestofthissectionthatitis192.168.1.103. Then,gotoyourfavoritewebbrowser,andtype:
http://192.168.1.103/mode/5/o
ThiscommandwillsettheGPIOpin5toanoutput. Then,type:
http://192.168.1.103/digital/5/1
ThisisthecommandtoturntheGPIOpin5toaHIGHstate. Assoonasyoupressthiscommand,theLEDshouldturnon. Youshouldalsoreceiveaconfirmationmessageinyourbrowser. Youcanofcoursejustputa0attheendofthecommandtoturnitoffagain.
Wearenowgoingtoseethesketchforthetemperature&humiditysensormodule. Thisisthecompletesketchforthispart:
//Importrequiredlibraries
#include<ESP8266WiFi.h>
#include<aREST.h>
#include"DHT.h"
//Pin
#defineDHTPIN5
//UseDHT11sensor
#defineDHTTYPEDHT11
//InitializeDHTsensor
DHTdht(DHTPIN,DHTTYPE,15);
//CreateaRESTinstance
aRESTrest=aREST();
//WiFiparameters
constchar*ssid="your_wifi_name";
constchar*password="your_wifi_password";
//TheporttolistenforincomingTCPconnections
#defineLISTEN_PORT80
//Createaninstanceoftheserver
WiFiServerserver(LISTEN_PORT);
//Variables
floattemperature;
floathumidity;
voidsetup(void)
{
//StartSerial
Serial.begin(115200);
//GivenameandIDtodevice
rest.set_id("2");
rest.set_name("sensor");
//ExposevariablestoAPI
rest.variable("temperature",&temperature);
rest.variable("humidity",&humidity);
//ConnecttoWiFi
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFiconnected");
//Starttheserver
server.begin();
Serial.println("Serverstarted");
//PrinttheIPaddress
Serial.println(WiFi.localIP());
//InitDHT
dht.begin();
}
voidloop(){
//Readingtemperatureandhumidity
humidity=dht.readHumidity();
//ReadtemperatureasCelsius
temperature=dht.readTemperature();
//HandleRESTcalls
WiFiClientclient=server.available();
if(!client){
return;
}
while(!client.available()){
delay(1);
}
rest.handle(client);
}
Asthecodeisquitelong,Iwillonlygothroughtheimportantpartsthatweaddedcomparedtotheprevioussketch.
Justasbefore,weneedtogiveanIDandanametoourmodule:
rest.set_id("2");
rest.set_name("sensor");
Here,whatwewanttodoistoqueryforthevalueofthetemperature&humidityoftheboard. Thisisdonewiththevariable()function:
rest.variable("temperature",&temperature);
rest.variable("humidity",&humidity);
It’snowtimetotesttheproject. GetthecodefromtheGitHubrepository,modifyitwithyourownparameters,andthenuploadthecodetotheboard.
Then,opentheSerialmonitortogettheIPaddressofthismodule. Let’sassumehereitis192.168.1.102. Now,gotoawebbrowserandtype:
http://192.168.1.102/temperature
Youwillthenreceiveananswerfromtheboardwiththevalueofthetemperature:
{"temperature":22,"id":"2","name":"sensor","connected":true}
Youcanofcoursedothesamewiththehumidity. Congratulations,younowhavetwoworkingmodulesinyourhomeautomationsystembasedontheESP8266!
8.4 CreatingtheInterface
Wearenowgoingtocodetheinterfacethatyouwillusetocontrolallthemodulesfromacentralinterface.
Asinthepreviouschapter,wewillusetheverypopularNode.jsframeworktocodeourserver. Youcannowdownloaditandinstallitfrom:
https://nodejs.org/
Therewillbasicallybe3filesinthisproject:
Theapp.jsfile,thatwillcontainthecodefortheserveritselfTheinterface.jadefile,thatwilldefinetheinterfaceTheinterface.jsfile,thatwillmakethelinkbetweentheinterface&theserver
Let’sfirstseetheapp.jsfile. WestartbydeclaringtheExpressframework:
varexpress=require('express');
varapp=express();
Wealsosettheportto3000:
varport=3000;
Afterthat,wesettheviewenginetoJade,whichwewillusetocodetheinterfaceinaverysimpleway:
app.set('viewengine','jade');
Then,wedefinethemainrouteoftheinterface,whichwewillusetoaccesstheinterfaceofthehomeautomationsystem:
app.get('/',function(req,res){
res.render('interface');
});
InthisprojectwillalsousetheaRESTNode.jsmodule,thatwillmakethelinkbetweentheserverrunningonyourcomputerandallthemoduleswecreatedbefore. Thisishowtouseitintheapp:
varrest=require("arest")(app);
Then,weaddbothdevicesintotheapp:
rest.addDevice('http','192.168.1.103');
rest.addDevice('http','192.168.1.104');
Ofcourse,youwillneedtochangetheseIPaddressesdependingontheIPaddressesofyourmodules.
Finally,westarttheappwith:
app.listen(port);
console.log("Listeningonport"+port);
Now,let’sseethecontentoftheinterface.jadefile. Thiswilldefinetheinterfaceandallthecomponentsinit.
First,weneedtoincludetheBootstrapCSSframeworkthatweusedinpreviouschaptersofthisbook. WealsoincludejQuery. Thisisalldefinedinthispieceofcode:
head
titleInterface
link(rel='stylesheet',
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css")
link(rel='stylesheet',href="/css/interface.css")
meta(name='viewport',content='width=device-width,initial-scale=1')
script(src="https://code.jquery.com/jquery-2.1.1.min.js")
script(src="/js/ajaxq.js")
script(src="/js/interface.js")
Then,wedefinetheinterfaceitselfinthebodytag. WebasicallycreatetwobuttonstocontrolthemodulewiththeLED(calledlampcontrolhere),andthenwecreatetwoindicatorsforthetemperature&humiditymodule:
body
.container
h1Dashboard
.row.voffset
.col-md-4
divLampControl
.col-md-4
button.btn.btn-block.btn-lg.btn-primary#1On
.col-md-4
button.btn.btn-block.btn-lg.btn-danger#2Off
.row.voffset
.col-md-4
div#temperatureTemperature:
.col-md-4
div#humidityHumidity:
Let’snowseetheinterface.jsfile,whichwillmakethelinkbetweentheinterfaceandtheserver. WefirstneedtosettheGPIOpin5asanoutputwiththefollowingcommand:
$.getq('queue','/lamp_control/mode/5/o');
Then,wecreatetwofunctionsthatwillhandletheclicksonthebuttonsintheinterface:
$("#1").click(function(){
$.getq('queue','/lamp_control/digital/5/1');
});
$("#2").click(function(){
$.getq('queue','/lamp_control/digital/5/0');
});
Finally,wedefineafunctiontorefreshthetemperature&humidityreadings. Wealsorepeatthisfunctionevery10seconds:
functionrefresh_dht(){
$.getq('queue','/sensor/temperature',function(data){
$('#temperature').html("Temperature:"+data.temperature+"C");
});
$.getq('queue','/sensor/humidity',function(data){
$('#humidity').html("Humidity:"+data.humidity+"%");
});
}
refresh_dht();
setInterval(refresh_dht,10000);
It’snowtimetotesttheproject. GetthecodefromtheGitHubrepository,modifyitwithyourownparameters,andthenuploadthecodetotheboard.
Then,gotothefolderwheretheapp.jsfileislocated,andtype:
sudonpminstallarestjadeexpress
Then,launchtheappwith:
nodeapp.js
Afterthat,gotoyourfavoritebrowserandtype:
http://locahost:3000
Youshouldimmediatelyseetheinterfaceofyourhomeautomationsystem:
Youcanalreadytrypressingthebutton,itshouldswitchtheLEDonyourESP8266projecton&off. Ofcourse,youcanusetheexactsameinterfacetocontrolalampthatwouldbeconnectedtoitforexample.
Notethatthisinterfaceisalsofullyresponsive,whichmeansyoucanaccessitfromyourphoneortablet. Thisistheresultonmyphone:
8.5 HowtoGoFurther
Let’ssummarizewhatweachievedinthisproject. WecreatedmodulesbasedontheESP8266chip,usingaRESTAPIthatallowsustocontrolthesemodulesviaWiFi. Then,weintegratedthismoduleintoanhomeautomationserverrunningonacomputer,sowecancontrolallmodulesremotelyfromasingleplace.
Therearemanythingsyoucandotoimprovethisproject. Thefirstthingtodoistointegratemoremodulesintotheproject. Forexample,youcouldperfectlyadaptthealarmsystemprojectintothisinterface.
Youcanalsointegratewebservicesintothesameinterface,forexampletodisplaytheoutsidetemperatureorbarometricpressure,justaswedidinChapter5.
Chapter9
ConclusionIfyoufollowedalltheprojectsofthisbook,congratulations,younowknowhowtocreateDIYhomeautomationssystemsbasedontheESP8266WiFichip! YoulearnedhowtocreateyourownWiFihomeautomationdevices,forexamplearemotelampcontrollerthatyoucanusewithyourmobilephone.
Rightnow,Irecommendthatyougoagainthroughalltheprojectsofthebook,soyoucanreallygetalltheknowledgethatiscontainedinthebook. Then,justexperiment! TherearevirtuallynolimitsonwhatyoucancreateusingtheESP8266WiFichip. Youcancreategreathomeautomationsystemsbyusingthis$5WiFichiptoautomateeveryaspectsohyourhome. Havefun!
Chapter10
ResourcesThefollowingisalistofthebestressourcesconcerningopen-sourcehomeautomationwiththeESP8266chip. Iorganizedthischapterindifferentcategoriessoitiseasierforyoutofindtheinformationyouneed.
10.1 LearnMoreAbouttheESP8266Chip
OpenHomeAutomation:Thecompanionwebsiteofthisbook,whereyouwillfindothertutorials&ideasabouthowtousetheESP8266forhomeautomationprojects.ESP8266.com:ThereferencewebsitefortheESP8266chip,whereyouwillfindhelpfulinformationabouthowtousethechip. Youwillalsofindalargecommunitytherethatcanhelpyououtwithanyproblemsyouhavewiththischip.
10.2 Components
SparkFun:Awebsitesellingmanysensors&componentsthatcanbeusedwiththeESP8266. Alltheirproductsareopen-sourceandyoucandownloadthesourcefilesdirectlyfromtheirproductdescriptions.Adafruit:AcompanybasedinNewYorkthatsellshighqualityproductsthatcanbeusedwiththeESP8266.SeeedStudio:AChinesecompanythatsellsmanyoriginalproductsthatwillalsobecompatiblewiththeESP8266. TheyalsooffertheirownPCBproduction&assemblyservices.
TableofContents
FrontmatterChapter1Chapter2Chapter3Chapter4Chapter5Chapter6Chapter7Chapter8Chapter9Chapter10