ESP8266: How to Monitor Temperature and Humidity

93

2

Posted in TechnologyMicrocontrollers

Introduction: ESP8266: How to Monitor Temperature and Humidity

About: Do you like technology? Follow my channel on Youtube and my Blog. In them I put videos every week of microcontrollers, arduinos, networks, among other subjects. New tutorials on Tuesdays and Fridays.

In today's tutorial, we will use an ESP-01, which is the ESP8266 in configuration 01 (with only 2 GPIO), for temperature and humidity readings of the DHT22 sensor. I will show you an electrical schematic and the ESP programming part with an Arduino. The example is simple, easy to understand, and also comes with the PDF used in the video to aid in assembly.

In the design, we have then the ESP01, the source that converts 110 or 220 into 5 volts, a voltage regulator of 3v3, and the DHT22, which is the sensor. On the smartphone screen, you will have the local IP address in addition to the JavaScript code provided by the ESP. This screen will therefore receive the parameters of temperature and humidity and will print these values, which will be updated every five seconds. To do this, you won’t need any apps on phones and tablets, and this applies for both the Android OS and IOS.

Step 1: Assembly

The electrical scheme is quite simple, as is the part about the assembly, which will involve the ESP01 as a server. The ESPO1 will be programmed as if it were an Arduino: through the C language. I point out that part of the code is printed from the browser. This means that it sends JavaScript code to the browser. Below, I’ll explain better about how this works.

Returning to the wiring diagram, I put a 5-volt switched source connected to a 3v3 voltage regulator to power the ESP01. We still have the DHT22 with four pins. One of these, data, is not used. However, it takes a pull up resistor.

Step 2: Code

The first step is to include the libs that we will use. The DHT lib can be added by the Sketch option> Include Library> Manage Libraries ...

In the window that opens, look for the DHT sensor library.

After that, we created a variable of the type ESP8266WebServer that will be our server and will respond to HTTP requests (port 80).

We also create a DHT variable with parameters 0 (which is the GPIO pin 0) and the type (in our case DHT22).

#include <ESP8266WiFi.h>
#include <WiFiClient.h> #include <ESP8266WebServer.h> #include <DHT.h> //Criamos uma variável do tipo ESP8266WebServer que já possui funções //que auxiliam na criação das rotas que o ESP8266 vai responder ESP8266WebServer server(80); //Variável do tipo DHT que possui funções para controlarmos o módulo dht //permitindo ler a temperatura e a umidade DHT dht(0, DHT22);

Step 3: ​Setup

In the setup, we will initialize the Serial only so that we have a log. This will occur if the ESP8266 is connected to the computer through the serial to use the serial monitor.

We'll make the ESP8266 connect to our network. In our case, we use the network TesteESP with the password 87654321, but you will have to change this according to the network that you use.

//Inicialize a Serial apenas caso esteja com o ESP8266 conectado ao computador pela serla queira ter um log
//para facilitar saber o que está acontecendo com o ESP8266 Serial.begin(115200); //Instrução para o ESP8266 se conectar à rede. //No nosso caso o nome da rede é TesteESP e a senha é 87654321. //Você deve alterar com as informações da sua rede WiFi.begin("TesteESP", "87654321" ); //Feedback caso esteja usando o Monitor Serial Serial.println(""); Serial.print("Conectando");

We wait for the ESP8266 to connect to the network, and after it connects, we send the network settings. Change according to your network.

//Esperamos até que o módulo se conecte à rede
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } //Configurações do IP fixo. Você pode alterar conforme a sua rede IPAddress ip(192, 168, 3, 11); IPAddress gateway(192, 168, 3, 1); IPAddress subnet(255, 255, 255, 0); Serial.print("Configurando IP fixo para : "); Serial.println(ip); //Envia a configuração WiFi.config(ip, gateway, subnet);

The next commands are only in the case that you have ESP8266 connected to the computer through the serial, so that you have feedback from the Serial Monitor.

You can check the IP that the ESP8266 received to see if it is the same as in the settings.

//Mostramos no Monitor Serial o ip com o qual o esp8266 se conectou para ver se está de acordo com o que configuramos
Serial.println(""); Serial.println("Connectado"); Serial.print ("IP: "); Serial.println(WiFi.localIP());

Here, we begin to define which functions will be executed for each request.

In the instruction below, every time ESP8266 receives an HTTP request of the type GET in the path / temperature, the getTemperature function will be executed.

//Aqui definimos qual a função será executada para o caminho e tipo dado.
//Nesse caso quando houver uma requisição http do tipo GET no caminho http://192.168.2.8/temperature //(pode ser outro ip dependendo da sua configuração) a função getTemperature será executada server.on("/temperature", HTTP_GET, getTemperature);

In this other statement, every time ESP8266 receives an HTTP request of type GET in the path / humidity, the getHumidity function will be executed.

//Nesse outo caso quando houver uma requisição http do tipo GET no caminho http://192.168.2.8/humidity
//(pode ser outro ip dependendo da sua configuração) a função getHumidity será executada server.on("/humidity", HTTP_GET, getHumidity);

In this instruction, every time ESP8266 receives an HTTP request of type GET in the path / monitor, the function showMonitor will be executed.

The showMonitor function is responsible for returning the main html that will display the values of temperature and humidity.

//Nesse caso quando houver uma requisição http do tipo GET no caminho http://192.168.2.8/monitor
//(pode ser outro ip dependendo da sua configuração) a função showMonitor será executada. //Esta função retornará a página principal que mostrará os valores //da temperatura e da umidade e recarregará essas informações de tempos em tempos server.on("/monitor", HTTP_GET, showMonitor);

Here is the function definition that should be executed when the requested path is not found.

//Aqui definimos qual função será executada caso o caminho que o cliente requisitou não tenha sido registrado
server.onNotFound(onNotFound);

Here we initialize our server that we previously declared on port 80.

This is the end of setup.

//Inicializamos o server que criamos na porta 80
server.begin(); Serial.println("Servidor HTTP iniciado"); }

Step 4: Loop

Thanks to the lib ESP8266WebServer, we don’t need to be checking in the loop if there are clients and for what the request path is. We just need to call handleClient (), and the object will check if any client is making any requests and will redirect to the corresponding function that we registered before.

void loop()
{ //Verifica se há alguma requisição de algum cliente server.handleClient(); }

Step 5: Request Not Found

This is the function we previously logged to execute when the client makes any requests that have not been registered.

The function only returns code 404 (default code for when a resource is not found), the returned data type (in the case of plain text), and a text with the words "Not Found.”

//Função que definimos para ser chamada quando o caminho requisitado não foi registrado
void onNotFound() { server.send(404, "text/plain", "Not Found" ); }

Step 6: Returning the Temperature

This is the function that will return a json with the temperature data when the client makes a GET request at / temperature.

//Função que definimos que será executada quando o cliente fizer uma requisição
//do tipo GET no caminho http://192.168.2.8/temperature (pode ser outro ip dependendo da sua configuração) void getTemperature() { //Fazemos a leitura da temperatura através do módulo dht float t = dht.readTemperature(); //Cria um json com os dados da temperatura String json = "{\"temperature\":"+String(t)+"}"; //Envia o json para o cliente com o código 200, que é o código quando a requisição foi realizada com sucesso server.send (200, "application/json", json); }

Step 7: Returning Humidity

This is the function that will return a json with the moisture data when the client makes a GET request in / humidity.

//Função que definimos que será executada quando o cliente fizer uma requisição
//do tipo GET no caminho http://192.168.2.8/humidity (pode ser outro ip dependendo da sua configuração) void getHumidity() { //Fazemos a leitura da umidade através do módulo dht float h = dht.readHumidity(); //Cria um json com os dados da umidade String json = "{\"humidity\":"+String(h)+"}"; //Envia o json para o cliente com o código 200, que é o código quando a requisição foi realizada com sucesso server.send(200, "application/json", json); }

Step 8: HTML

This is the function that will return the html when the client goes to access / monitor. This page will show the temperature and humidity values, and it will reload the data from time to time. The part that is between <style type = 'text / ccs'> and </ style> and style>

defines the appearance of the page, and you can change it as you like.

//Função que definimos que será executada quando o cliente fizer uma requisição
//do tipo GET no caminho http://192.168.2.8/monitor (pode ser outro ip dependendo da sua configuração) void showMonitor() { String html = "<html>" "<head>" "<meta name=1viewport' content=meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'/>"

"<title>DHT Monitor</title>" "<style type='text/css'>"

"body{"

"padding:35px;"

"background-color: #222222;"
"}"

Step 9: HTML Style Continuation

"h1{"
"color: #FFFFFF;" "font-family: sans-serif;" "}" "p{" "color: #EEEEEE;" "font-family: sans-serif;" "font-size:18px;" "}" "</style>"

"</head>"

Here we have the main part of html. In it, we have two paragraphs that will show the temperature and the humidity. Pay attention to the ids of the paragraphs, because it is through them that we will recover these paragraphs to enter the values of temperature and humidity after the requisitions.

"<body>"
	"<h1>DHT Monitor</h1>"
	"<p id='temperature'>Temperature: </p>"
	"<p id='humidity'>Humidity: </p>
"<body>"

Step 10: JavaScript

Here we begin to define the script that will from time to time read the values of temperature and humidity. The refresh () function calls the refreshTemperature () and refreshHumdity () functions, and setInterval calls the refresh function every 5000 milliseconds (5 seconds).

"<script type='text/javascript'>"

"refresh();"
"setInterval(refresh, 5000);" "function refresh()" "{" "refreshTemperature()" "refreshHumidity();" "}"

The function refreshTemperature () makes a request at / temperature, parses the information contained in json, and adds into the paragraph the id temperature.

"function refreshTemperature()"
"{" "var xmlhttp = new XMLHttpRequest();" "xmlhttp.onreadystatechange = function() {" "if (xmlhttp.readyState == XMLHttpRequest.DONE && xmlhttp.status == 200){" "document.getElementById('temperature').innerHTML = 'Temperature: ' + JSON.parse(xmlhttp.responseText).temperature + 'C';" "}" "};" "xmlhttp.open('GET', 'http://192.168.2.8/temperature', true);" "xmlhttp.send();" "}"

The refreshHumidity () function makes a request to / humidity, parses the information contained in json, and adds into the paragraph the id humidity. And with that, we finish the html that we’ll send in the requests in / monitor.

"function refreshHumidity()"
"{" "var xmlhttp = new XMLHttpRequest();" "xmlhttp.onreadystatechange = function() {" "if (xmlhttp.readyState == XMLHttpRequest.DONE && xmlhttp.status == 200){" "document.getElementById('humidity').innerHTML = 'Humidity: ' + JSON.parse(xmlhttp.responseText).humidity + '%';" "}" "};" "xmlhttp.open('GET', 'http://192.168.2.8/humidity', true);" "xmlhttp.send();" "}"

"</script>"

"</html>";

Step 11: Finishing ShowMonitor

Now that the string with the html that we will send is ready, we can send it to the client. This completes the showMonitor function and the code.

//Envia o html para o cliente com o código 200, que é o código quando a requisição foi realizada com sucesso
server.send(200, "text/html", html); }

Step 12: Testing

Now open your browser and enter http://192.168.2.8/monitor (you may need a different ip depending on your configuration).

Share

    Recommendations

    • Make it Move Contest

      Make it Move Contest
    • Woodworking Contest

      Woodworking Contest
    • Microcontroller Contest

      Microcontroller Contest
    user

    We have a be nice policy.
    Please be positive and constructive.

    Tips

    Questions

    Comments