Академический Документы
Профессиональный Документы
Культура Документы
ESP8266
IlovetobuildDIYhomeautomationsystemsusingopensourcehardware,especiallywiththe
amazingESP8266WiFichip.However,itcanbeabittrickytogetstarted,andyoumightfeel
lostinfrontofalltheoptionsthatareavailabletoyou.
ThisiswhyIwrotethisguidetohelpyoubuildyourfirsthomeautomationsystemusingthe
ESP8266:asimpleweathermeasurementstationthatworksviaWiFi.WewillconnectaDHT11
sensortotheESP8266board,andaccessthedataviaWiFi.
Todoso,wewillrunasimplewebserverontheESP8266chip,thatwilldisplaytheresults
insideawebpage.Wewillalsomakethiswebpageresponsive,soitlooksniceevenifyouare
usingasmartphone.Finally,wewillusethefactthattheESP8266isalreadyconnectedtothe
webtograbweathermeasurementsonline&displayitintheinterfaceaswell.
Hardware&SoftwareRequirements
Forthisproject,youwillofcourseneedaboardwiththeESP8266chip.Iwillforexampleuse
anAdafruitFeatherESP8266board,butyoucanofcourseuseanyboardbasedonthe
ESP8266chip.
However,IrecommendusingdevelopmentboardsthathaveUSBtoSerialconverteronboard
asyoujustneedtoplugthemtoyourcomputerviaaUSBcable.
Youwillalsoneedatemperaturesensor.IusedaDHT11sensor,whichischeap,veryeasyto
use&thatwillallowustomeasuretheambienttemperature&humidity.
Ifyouarenotusingadevelopmentboard,youwillalsoneeda3.3VFTDIUSBmoduleto
programtheESP8266chip,aswellasabreadboardpowersupplytopowerthechip.Finally,
youwillalsoneedsomejumperwires&abreadboard.
Thisisalistofallthecomponentsthatwillbeusedinthischapter:
AdafruitFeatherESP8266WiFiboard
DHT11sensor
Breadboard
Jumperwires
Onthesoftwareside,youwillneedthelatestversionoftheArduinoIDEthatyoucangetfrom:
http://www.arduino.cc/en/Main/Software
Then,followthisproceduretoaddtheESP8266boardtotheArduinoIDE:
StarttheArduinoIDEandopenthePreferenceswindow.
EnterthefollowingURLintotheAdditionalBoardManagerURLsfield:
http://arduino.esp8266.com/package_esp8266com_index.json
OpenBoardsManagerfromTools>Boardmenuandinstalltheesp8266platform.
YouwillalsoneedtheAdafruitDHTlibrarythatyoucangetfromtheArduinolibrarymanager.
HardwareConfiguration
WearefirstgoingtoseehowtoconfigurethehardwaretousetheESP8266board.Ifyouare
usingadevelopmentboard,yousimplyneedtoplugtheboardtoyourcomputerviaaUSB
cable.
Oncethisisdone,simplyinserttheDHT11sensoronthebreadboard.Then,connecttheleftpin
toVCCoftheboard,therightpintoGND,andthepinnexttoVCCtotheGPIO5pinonyour
ESP8266development.Thisisthefinalresult:
TestingtheSensor
Wearenowgoingtotestthesensor.Again,rememberthatweareusingtheArduinoIDE,so
wecancodejustlikewewoulddousinganArduinoboard.Here,wewillsimplyprintthevalue
ofthetemperatureinsidetheSerialmonitoroftheArduinoIDE.
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.Youcanseethatallthemeasurementpartiscontainedinside
theloop()function,whichmakesthecodeinsideitrepeatevery2seconds.
Then,wereaddatafromtheDHT11sensor,printthevalueofthetemperature&humidityon
theSerialport.
YoucannowpastethiscodeintheArduinoIDE.Then,goinTools>Boards,andselectthe
correctboardfromthelist.Ifyoucan'tfindtheboardyouareusing,select"GenericESP8266
Module".AlsoselectthecorrectSerialportthatcorrespondstotheboardorFTDIconverteryou
areusing.
Youshouldimmediatelyseethetemperature&humidityreadingsinsidetheSerialmonitor.My
sensorwasreadingaround24degreesCelsiuswhenItestedit,whichisarealisticvalue.
AccessingtheSensorviaWiFi
Atthispoint,wearesurethatthesensorisworkingandthatdatacanbereadbytheESP8266
chip.Now,wearegoingtobuildthesketchthatwillconnecttoyourWiFinetwork,andthen
serveawebpagethatwilldisplaytheresultsinlive.
Asthissketchisquitelong,Iwillonlydetailthemostimportantpartshere.Youcanofcourse
findthecompletecodeforthisprojectinsidetheGitHubrepositoryoftheproject:
https://github.com/openhomeautomation/esp8266weatherstation
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.Whatwewanthereistoservethedatatotheclientinanelegant
way.That'swhywewillusetheBootstrapCSSframework,thatwillmakeourpagelookspretty.
Itwillalsomakesitresponsive,soitwilllookgreatonmobiledevicesaswell.
ThefirstpartistosendtheHeadtagoftheHTMLpage,whichincludestheBootstrapCSSfile.
Wealsosetinthisparttherefreshrateofthepage,whichwillbeautomaticallyrefreshedevery
minute:
Strings="HTTP/1.1200OK\r\nContentType:text/html\r\n\r\n";
s+="<head>";
s+="<metaname=\"viewport\"content=\"width=devicewidth,initialscale=1\">";
s+="<metahttpequiv=\"refresh\"content=\"60\"/>";
s+="<scriptsrc=\"https://code.jquery.com/jquery2.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{fontsize:24px;}.voffset{margintop:30px;}</style>";
s+="</head>";
Then,wesendthecoreofthepage,whichconsistsinsimplydisplayingthetemperature&
humiditydata:
s+="<divclass=\"container\">";
s+="<h1>WiFiWeatherStation</h1>";
s+="<divclass=\"rowvoffset\">";
s+="<divclass=\"colmd3\">Temperature:</div>";
s+="<divclass=\"colmd3\">"+String(t)+"</div>";
s+="<divclass=\"colmd3\">Humidity:</div>"
s+="<divclass=\"colmd3\">"+String(h)+"</div>";
s+="</div>";
s+="</div>";
Finally,wesendthistotheclient,andwaituntiltheclientdisconnectsfromourboard:
client.print(s);
delay(1);
Serial.println("Clientdisconnected");
It'snowtimetotesttheproject.GetthecodefromtheGitHubrepositoryofthisproject:
https://github.com/openhomeautomation/esp8266weatherstation
Then,modifyitwithyourownparameters,anduploadthecodetotheboard,usingthe
instructionswesawearlier.
Afterthat,opentheSerialmonitoroftheArduinoIDE.YoushouldseethattheIPaddressis
displayedinsidetheSerialmonitor.
Then,simplygotoawebbrowserandtypethisIPaddress.Youshouldimmediatelyseethe
measureddatainyourbrowser:
Notethatyoucanalsodothesamefromyourmobilephoneortablet,anditwillworkjustas
well!
Thisisalreadytheendofthisguideaboutopensourcehomeautomation!Ihopethissimple
projectgaveyouanideaofwhatyoucandowiththeESP8266forhomeautomation
applications.
Ifthatsnotdoneyet,youcanofcoursefollowmywebsiteonFacebook&onTwitter.
Thanksagain,andallthebestforyourhomeautomationprojects!
MarcoSchwartz
contact@openhomeautomation.net