0% found this document useful (0 votes)
203 views7 pages

Wifi Weather Station Esp 8266

This document provides instructions to build a WiFi weather station using an ESP8266 chip and a DHT11 temperature and humidity sensor. It connects the sensor to an ESP8266 development board and runs a web server to display the sensor readings on a webpage. The webpage is responsive and refreshes automatically every minute. Code examples are provided to test the sensor, connect to WiFi, and serve the sensor data on a webpage using HTML and CSS. Complete code for the project is available in a GitHub repository.

Uploaded by

Moog
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
203 views7 pages

Wifi Weather Station Esp 8266

This document provides instructions to build a WiFi weather station using an ESP8266 chip and a DHT11 temperature and humidity sensor. It connects the sensor to an ESP8266 development board and runs a web server to display the sensor readings on a webpage. The webpage is responsive and refreshes automatically every minute. Code examples are provided to test the sensor, connect to WiFi, and serve the sensor data on a webpage using HTML and CSS. Complete code for the project is available in a GitHub repository.

Uploaded by

Moog
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Build a WiFi Weather Station with the

ESP8266

by Marco Schwartz of Open Home Automation


http://www.openhomeautomation.net/

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
[email protected]

You might also like