ESP32 DHT11/DHT22 Web Server – Temperature and Humidity using Arduino IDE

In this project, you’ll learn how to build an asynchronous ESP32 web server with the DHT11 or DHT22 that displays temperature and humidity using Arduino IDE

The web server we’ll build updates the readings automatically without the need to refresh the web page.

With this project you’ll learn:

  • How to read temperature and humidity from DHT sensors (DHT11 and DHT22).
  • Build an asynchronous web server using the ESPAsyncWebServer library;
  • Update the sensor readings automatically without the need to refresh the web page.

For a more in-depth explanation on how to use the DHT22 and DHT11 temperature and humidity sensors with the ESP32, read our complete guide: ESP32 with DHT11/DHT22 Temperature and Humidity Sensor using Arduino IDE

Watch the Video Tutorial

You can watch the video tutorial or keep reading this page for the written instructions.

Asynchronous Web Server

To build the web server we’ll use the ESPAsyncWebServer library that provides an easy way to build an asynchronous web server. Building an asynchronous web server has several advantages as mentioned in the library GitHub page, such as:

  • “Handle more than one connection at the same time”;
  • “When you send the response, you are immediately ready to handle other connections while the server is taking care of sending the response in the background”;
  • “Simple template processing engine to handle templates”;
  • And much more.

Take a look at the library documentation on its GitHub page.

Parts Required

To complete this tutorial you need the following parts:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Schematic

Before proceeding to the web server, you need to wire the DHT11 or DHT22 sensor to the ESP32 as shown in the following schematic diagram.

In this case, we’re connecting the data pin to GPIO 27, but you can connect it to any other digital pin. You can use this schematic diagram for both DHT11 and DHT22 sensors.

(This schematic uses the ESP32 DEVKIT V1 module version with 36 GPIOs – if you’re using another model, please check the pinout for the board you’re using.)

Note: if you’re using a module with a DHT sensor, it normally comes with only three pins. The pins should be labeled so that you know how to wire them. Additionally, many of these modules already come with an internal pull up resistor, so you don’t need to add one to the circuit.

Installing Libraries

You need to install a couple of libraries for this project:

Follow the next instructions to install those libraries:

Installing the DHT Sensor Library

To read from the DHT sensor using Arduino IDE, you need to install the DHT sensor library. Follow the next steps to install the library.

  1. Click here to download the DHT Sensor library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get DHT-sensor-library-master folder
  3. Rename your folder from DHT-sensor-library-master to  DHT_sensor
  4. Move the DHT_sensor folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Installing the Adafruit Unified Sensor Driver

You also need to install the Adafruit Unified Sensor Driver library to work with the DHT sensor. Follow the next steps to install the library.

  1. Click here to download the Adafruit Unified Sensor library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get Adafruit_sensor-master folder
  3. Rename your folder from Adafruit_sensor-master to Adafruit_sensor
  4. Move the Adafruit_sensor folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Installing the ESPAsyncWebServer library

Follow the next steps to install the ESPAsyncWebServer library:

  1. Click here to download the ESPAsyncWebServer library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get ESPAsyncWebServer-master folder
  3. Rename your folder from ESPAsyncWebServer-master to ESPAsyncWebServer
  4. Move the ESPAsyncWebServer folder to your Arduino IDE installation libraries folder

Installing the Async TCP Library for ESP32

The ESPAsyncWebServer library requires the AsyncTCP library to work. Follow the next steps to install that library:

  1. Click here to download the AsyncTCP library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get AsyncTCP-master folder
  3. Rename your folder from AsyncTCP-master to AsyncTCP
  4. Move the AsyncTCP folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Code

We’ll program the ESP32 using Arduino IDE, so make sure you have the ESP32 add-on installed before proceeding:

Open your Arduino IDE and copy the following code.

/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

// Import required libraries
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include <Adafruit_Sensor.h>
#include <DHT.h>

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

#define DHTPIN 27     // Digital pin connected to the DHT sensor

// Uncomment the type of sensor in use:
//#define DHTTYPE    DHT11     // DHT 11
#define DHTTYPE    DHT22     // DHT 22 (AM2302)
//#define DHTTYPE    DHT21     // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

String readDHTTemperature() {
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  //float t = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  if (isnan(t)) {    
    Serial.println("Failed to read from DHT sensor!");
    return "--";
  }
  else {
    Serial.println(t);
    return String(t);
  }
}

String readDHTHumidity() {
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  if (isnan(h)) {
    Serial.println("Failed to read from DHT sensor!");
    return "--";
  }
  else {
    Serial.println(h);
    return String(h);
  }
}

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 { font-size: 3.0rem; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .dht-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 15px;
    }
  </style>
</head>
<body>
  <h2>ESP32 DHT Server</h2>
  <p>
    <i class="fas fa-thermometer-half" style="color:#059e8a;"></i> 
    <span class="dht-labels">Temperature</span> 
    <span id="temperature">%TEMPERATURE%</span>
    <sup class="units">&deg;C</sup>
  </p>
  <p>
    <i class="fas fa-tint" style="color:#00add6;"></i> 
    <span class="dht-labels">Humidity</span>
    <span id="humidity">%HUMIDITY%</span>
    <sup class="units">%</sup>
  </p>
</body>
<script>
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("temperature").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}, 10000 ) ;

setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("humidity").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/humidity", true);
  xhttp.send();
}, 10000 ) ;
</script>
</html>)rawliteral";

// Replaces placeholder with DHT values
String processor(const String& var){
  //Serial.println(var);
  if(var == "TEMPERATURE"){
    return readDHTTemperature();
  }
  else if(var == "HUMIDITY"){
    return readDHTHumidity();
  }
  return String();
}

void setup(){
  // Serial port for debugging purposes
  Serial.begin(115200);

  dht.begin();
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  // Print ESP32 Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html, processor);
  });
  server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readDHTTemperature().c_str());
  });
  server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readDHTHumidity().c_str());
  });

  // Start server
  server.begin();
}
 
void loop(){
  
}

View raw code

Insert your network credentials in the following variables and the code will work straight away.

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

How the Code Works

In the following paragraphs we’ll explain how the code works. Keep reading if you want to learn more or jump to the Demonstration section to see the final result.

Importing libraries

First, import the required libraries. The WiFi, ESPAsyncWebServer and the ESPAsyncTCP are needed to build the web server. The Adafruit_Sensor and the DHTlibraries are needed to read from the DHT11 or DHT22 sensors.

#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include <ESPAsyncTCP.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>

Setting your network credentials

Insert your network credentials in the following variables, so that the ESP32 can connect to your local network.

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Variables definition

Define the GPIO that the DHT data pin is connected to. In this case, it’s connected to GPIO 27.

#define DHTPIN 27  // Digital pin connected to the DHT sensor

Then, select the DHT sensor type you’re using. In our example, we’re using the DHT22. If you’re using another type, you just need to uncomment your sensor and comment all the others.

#define DHTTYPE DHT22   // DHT 22 (AM2302)

Instantiate a DHTobject with the type and pin we’ve defined earlier.

DHT dht(DHTPIN, DHTTYPE);

Create an AsyncWebServerobject on port 80.

AsyncWebServer server(80);

Read Temperature and Humidity Functions

We’ve created two functions: one to read the temperature (readDHTTemperature()) and the other to read humidity (readDHTHumidity()).

String readDHTTemperature() {
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  //float t = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  if (isnan(t)) {    
    Serial.println("Failed to read from DHT sensor!");
    return "--";
  }
  else {
    Serial.println(t);
    return String(t);
  }
}

Getting sensor readings is as simple as using the readTemperature() and readHumidity() methods on the dht object.

float t = dht.readTemperature();
float h = dht.readHumidity();

We also have a condition that returns two dashes (–) in case the sensor fails to get the readings.

if (isnan(t)) {    
  Serial.println("Failed to read from DHT sensor!");
  return "--";
}

The readings are returned as string type. To convert a float to a string, use the String() function.

return String(t);

By default, we’re reading the temperature in Celsius degrees. To get the temperature in Fahrenheit degrees, comment the temperature in Celsius and uncomment the temperature in Fahrenheit, so that you have the following:

//float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float t = dht.readTemperature(true);

Building the Web Page

Proceeding to the web server page.

As you can see in the above figure, the web page shows one heading and two paragraphs. There is a paragraph to display the temperature and another to display the humidity. There are also two icons to style our page.

Let’s see how this web page is created.

All the HTML text with styles included is stored in the index_html variable. Now we’ll go through the HTML text and see what each part does.

The following <meta> tag makes your web page responsive in any browser.

<meta name="viewport" content="width=device-width, initial-scale=1">

The <link> tag is needed to load the icons from the fontawesome website.

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

Styles

Between the <style></style> tags, we add some CSS to style the web page.

<style>
 html {
   font-family: Arial;
   display: inline-block;
   margin: 0px auto;
   text-align: center;
  }
  h2 { font-size: 3.0rem; }
  p { font-size: 3.0rem; }
  .units { font-size: 1.2rem; }
  .dht-labels{
    font-size: 1.5rem;
    vertical-align:middle;
    padding-bottom: 15px;
  }
</style>

Basically, we’re setting the HTML page to display the text with Arial font in block without margin, and aligned at the center.

html {
  font-family: Arial;
  display: inline-block;
  margin: 0px auto;
  text-align: center;
 }

We set the font size for the heading (h2), paragraph (p) and the units(.units) of the readings.

h2 { font-size: 3.0rem; }
p { font-size: 3.0rem; }
.units { font-size: 1.2rem; }

The labels for the readings are styled as shown below:

dht-labels{
    font-size: 1.5rem;
    vertical-align:middle;
    padding-bottom: 15px;
}

All of the previous tags should go between the <head> and </head> tags. These tags are used to include content that is not directly visible to the user, like the <meta> , the <link> tags, and the styles.

HTML Body

Inside the <body></body> tags is where we add the web page content.

The <h2></h2> tags add a heading to the web page. In this case, the “ESP32 DHT server” text, but you can add any other text.

<h2>ESP32 DHT Server</h2>

Then, there are two paragraphs. One to display the temperature and the other to display the humidity. The paragraphs are delimited by the <p> and </p> tags. The paragraph for the temperature is the following:

<p>
  <i class="fas fa-thermometer-half" style="color:#059e8a;"</i> 
  <span class="dht-labels">Temperature</span> 
  <span id="temperature">%TEMPERATURE%</span>
  <sup class="units">°C</sup>
</p>

And the paragraph for the humidity is on the following snipet:

<p>
  <i class="fas fa-tint" style="color:#00add6;"></i> 
  <span class="dht-labels">Humidity</span>
  <span id="humidity">%HUMIDITY%</span>
  <sup class="units">%</sup>
</p>

The <i> tags display the fontawesome icons.

How to display icons

To chose the icons, go to the Font Awesome Icons website.

Search the icon you’re looking for. For example, “thermometer”.

Click the desired icon. Then, you just need to copy the HTML text provided.

<i class="fas fa-thermometer-half">

To chose the color, you just need to pass the style parameter with the color in hexadecimal, as follows:

<i class="fas fa-tint" style="color:#00add6;"></i> 

Proceeding with the HTML text…

The next line writes the word “Temperature” into the web page.

<span class="dht-labels">Temperature</span>

The TEMPERATURE text between % signs is a placeholder for the temperature value.

<span id="temperature">%TEMPERATURE%</span>

This means that this %TEMPERATURE% text is like a variable that will be replaced by the actual temperature value from the DHT sensor. The placeholders on the HTML text should go between % signs.

Finally, we add the degree symbol.

<sup class="units">°C</sup>

The <sup></sup> tags make the text superscript.

We use the same approach for the humidity paragraph, but it uses a different icon and the %HUMIDITY% placeholder.

<p>
  <i class="fas fa-tint" style="color:#00add6;"></i> 
  <span class="dht-labels">Humidity</span>
  <span id="humidity">%HUMIDITY%</span>
  <sup class="units">%</sup>
</p>

Automatic Updates

Finally, there’s some JavaScript code in our web page that updates the temperature and humidity automatically, every 10 seconds.

Scripts in HTML text should go between the <script></script> tags.

<script>
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("temperature").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}, 10000 ) ;

setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("humidity").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/humidity", true);
  xhttp.send();
}, 10000 ) ;
</script>

To update the temperature on the background, we have a setInterval() function that runs every 10 seconds.

Basically, it makes a request in the /temperature URL to get the latest temperature reading.

  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}, 10000 ) ;

When it receives that value, it updates the HTML element whose id is temperature.

if (this.readyState == 4 && this.status == 200) {
  document.getElementById("temperature").innerHTML = this.responseText;
}

In summary, this previous section is responsible for updating the temperature asynchronously. The same process is repeated for the humidity readings.

Important: since the DHT sensor is quite slow getting the readings, if you plan to have multiple clients connected to an ESP32 at the same time, we recommend increasing the request interval or remove the automatic updates.

Processor

Now, we need to create the processor() function, that will replace the placeholders in our HTML text with the actual temperature and humidity values.

String processor(const String& var){
  //Serial.println(var);
  if(var == "TEMPERATURE"){
    return readDHTTemperature();
  }
  else if(var == "HUMIDITY"){
    return readDHTHumidity();
  }
  return String();
}

When the web page is requested, we check if the HTML has any placeholders. If it finds the %TEMPERATURE% placeholder, we return the temperature by calling the readDHTTemperature() function created previously.

if(var == "TEMPERATURE"){
  return readDHTTemperature();
}

If the placeholder is %HUMIDITY%, we return the humidity value.

else if(var == "HUMIDITY"){
  return readDHTHumidity();
}

setup()

In the setup(), initialize the Serial Monitor for debugging purposes.

Serial.begin(115200);

Initialize the DHT sensor.

dht.begin();

Connect to your local network and print the ESP32 IP address.

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.println("Connecting to WiFi..");
}

Finally, add the next lines of code to handle the web server.

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send_P(200, "text/html", index_html, processor);
});
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send_P(200, "text/plain", readDHTTemperature().c_str());
});
server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send_P(200, "text/plain", readDHTHumidity().c_str());
});

When we make a request on the root URL, we send the HTML text that is stored on the index_html variable. We also need to pass the processorfunction, that will replace all the placeholders with the right values.

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send_P(200, "text/html", index_html, processor);
});

We need to add two additional handlers to update the temperature and humidity readings. When we receive a request on the /temperature URL, we simply need to send the updated temperature value. It is plain text, and it should be sent as a char, so, we use the c_str() method.

server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send_P(200, "text/plain", readDHTTemperature().c_str());
});

The same process is repeated for the humidity.

server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send_P(200, "text/plain", readDHTHumidity().c_str());
});

Lastly, we can start the server.

server.begin();

Because this is an asynchronous web server, we don’t need to write anything in the loop().

void loop(){
  
}

That’s pretty much how the code works.

Upload the Code

Now, upload the code to your ESP32. Make sure you have the right board and COM port selected.

After uploading, open the Serial Monitor at a baud rate of 115200. Press the ESP32 reset button. The ESP32 IP address should be printed in the serial monitor.

Web Server Demonstration

Open a browser and type the ESP32 IP address. Your web server should display the latest sensor readings.

Notice that the temperature and humidity readings are updated automatically without the need to refresh the web page.

Troubleshooting

If your DHT sensor fails to get the readings, read our DHT Troubleshooting Guide to help you fix the issue.

Wrapping Up

In this tutorial we’ve shown you how to build an asynchronous web server with the ESP32 to display sensor readings from a DHT11 or DHT22 sensor and how to update the readings automatically.

If you liked this project, you may also like:

This tutorial is a preview of the “Learn ESP32 with Arduino IDE” course. If you like this project, make sure you take a look at the ESP32 course page where we cover this and a lot more topics with the ESP32.


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

74 thoughts on “ESP32 DHT11/DHT22 Web Server – Temperature and Humidity using Arduino IDE”

  1. Hello. I keep getting this error when I compile.

    Board nodemcuv2 (platform esp8266, package esp8266) is unknown
    Error compiling for board NodeMCU 1.0 (ESP-12E Module).

    It compiles OK when I select Arduino Nano, but not the ESP8266. Can you give me any suggestions on how to solve this problem?
    Thanks,
    Steve Tripoli

    • I changed these lines and it now compiles and uploads.
      This is the orignial
      // Replace with your network credentials
      const char* ssid = “YOUR_SSID”;
      const char* password = “YOUR_PASSWORD”;

      All I did was to remove the const in both lines.

  2. Will this work using an ESP8266? I am trying, but this all I get from the serial monitor.

    ets Jan 8 2013,rst cause:4, boot mode:(3,6)

    wdt reset
    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v4ceabea9
    ~ld

    Connecting to MyHome36

  3. Hi,
    This work perfectly, thank you.
    I just wants to connect more sensors with the esp32 , for example the DHT11 for temperature and humidity and the PIR motion sensor. It is possible to do it ? and witch pins use to collect data ?

    • Hi.
      Yes, you can do that.
      You can use the PIR motion sensor with any GPIO of the ESP32 (except GPIOs 6, 7, 8, 9, 10, and 11).
      I hope this helps.
      Regards
      sara 🙂

      • Found it, got it to compile. However, on runtime, upon going to browser, it displays the page, but it always goes to “FAILED” on ALL readings. I’m trying to find out why it can’t read the DHT11 🙁

        • It may be a power issue. If you’re supplying 3.3V to the DTH11, try to supply 5V instead, and see if that fixes your issue.
          Also, make sure you have everything wired correctly with the 4.7K Ohm pull-up resistor.
          Also test powering up the sensor using an external power suppky.
          I hope this helps debugging your problem.
          Regards,
          Sara 🙂

  4. Hi, Suppose I have my sensors outside the house, how to supply power to the ESP8266 module without the USB port? Can batteries do this job?

  5. hello

    I loaded this on a esp32, and it works… for a while, then the browser can`t access the web server until I restart the ESP32 again. Any thoughts ?

    • Hi Martin.
      Sometimes the DHT sensor fails to read the temperature, but I have no idea why that happens?
      But do you get good results without failures with that new library?
      We need to try that library as see what we get.
      Regards,
      Sara 🙂

  6. It looks like you now also need the Adafruit_Sensor-master repo to get the DHT repo to work right. It can be found here: https://github.com/adafruit/Adafruit_Sensor.

    Without it I was getting a “multiple libraries were found for “wifi.h”” error that wouldn’t allow for a compile.

    Or did I miss a step when following the instructions?

    • Hi Michael.
      You are right. You also need to install the adafruit sensor library.
      I’ve updated the post to include that.
      Thanks for telling us.
      Regards,
      Sara 🙂

  7. Hi, just wondering how can I save the reading data from the website to a text file for every 30 seconds? I added a line of client.println(“Content-Disposition: attachment; filename=\”test.txt\””); under the line of client.println(“Content-Type: text/html”); , but the webpage stop refreshing after the first text file has been downloaded. Please advise.

  8. Will this work on an ESP8266? I am trying to find what to change to make this work on an 8266 and I cant find anything in the code. I tried just setting the board (under tools->board) to my model ESP8266 (adafruit feather Huzzah esp8266) but it wont take the code.

  9. Hi,

    I adapted this code to send a key status to the browser, but the 30 seconds of auto refresh is to long… Is there a way to send (and show on browser) the data right after the key is pressed or not?

  10. Sara, it is always the dht11 or dht22 sensors which are limited to low temperatures. Why not do a project that uses the MAX31865 RTD and MAX31855 Thermocouple amplifier boards with the ESP8266. These devices offer outstanding accuracy over an extremely long range of temperatures.

    • Hi Carl.
      Thank you for the suggestion.
      We have to try those in the future and maybe come up with a tutorial.
      Regards,
      Sara

  11. Hi all, good post, but i’ve suggestion.
    this app contains 2 async separated calls, for temperature and humidity: why not a single xhr call to read these values then returning an object (ie {“T”:”25,32″, “H”:”76.54″})?
    regards

  12. Finally a new project that isn’t MicroPython, thanks, very cool.
    Question: is it possible to insert the icons local, that is on my local network that doesn’t have internet access? (Where I live way out in the country internet is VERY expensive so have to go into town and use library internet about once a week)
    Can they be downloaded elsewhere and stored on the esp32?
    Thanks for all the great tutorials.
    dp

  13. Bonjour. impossible de compiler le programme. il m’indique:’tcp’p_api_call_data’ incomplete .exit status 1.à vous lire salutations; toutes les librairies sont bien instalés le “SSID” et le “Passeword ” sont OK ,alors?

  14. Hi. when compiling I get this error:

    int begin(char* ssid, const char *passphrase);
    ^
    exit status 1
    invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]

    Do you know what may be happening?
    Thank you

    • Hi.
      This project only works with the ESP32.
      But you can change the code to include the right libraries to make it compatible with the ESP8266. However, we don’t have that documented at the moment.
      You need to use the ESP8266WiFi library instead of the WiFi library, and the ESPAsyncTCP instead of the Async TCP.
      Regards,
      Sara

  15. Hii
    I keep getting this error when I compile.
    “invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]”
    Can you give me any suggestions on how to solve this problem?
    Thanks,
    Udayana

  16. Hi, Sara and Rui,
    I have realized this project with the ESP32 and everything was perfect.
    I’wanted to try with an ESP8266-01 (1Mb) and I changed the library WiFi.h with the ESP8266WiFi.h
    I have also in my library folder the ESPAsyncTCP.h, but is not used directly in the sketch.
    But can’t read the sensor (DFH11 or DHT22) with the error “Failed to read from DHT sensor!”.
    I have insert the display of the Temp and Humidity at the beginning of the Setup, and run perfectly.
    I have also changed the interval time in the Javascript from 10.000 to 20.000.
    The sensor is powered with 5v with a pullup resistor of 4.7k.
    Also a display after the “dht.readTemperature()” shows “nan” (Not a Number) and a “delay(200)” or more added after the “dht.readTemperature()d” can’t run better.

    It’s not so important, but I’d like to understand why.
    One time out of twenty I have a correct display of the Temp and Humidity at the beginnig after a “reset”.
    I have put a counter instead the Temp value and run correctly also on the Smartphone.

    Thanks for any suggestion. I start also to try yours intersting projects with MicroPython.
    This project is the best project with ESP and C++ I ever found. Really!!
    Roberto
    Graz
    Austria

    • Hi Roberto.
      Thank you so much for your nice words.
      When you get “Failed to read from DHT sensor!” it usually means that the sensor is not wired properly, or it is not being powered properly. If you’re powering your ESP32 using an USB cable directly through your computer USB port, that can be the problem, and that’s why you sometimes get readings and others don’t.
      Try power it from a USB hub powered by an external source. Also helps to replace the USB cable with a stronger and/or shorter one.
      If you get a “nan” error, it usually means that the sensor didn’t have enough time to get the readings. If you’re using a DHT22, you can only request readings every 2 seconds.

      I hope this helps.
      Regards,
      Sara

  17. I have installed the AsyncTCP-master library but I get the error:

    C:\Users\marti\Documents\Arduino\sketchbook\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:36:25: fatal error: ESPAsyncTCP.h: No such file or directory

    #include

    ^

    I see the file AsyncTCP.h in the library but not ESPAsyncTCP.h Is there another library I need that wasn’t in the article?

  18. Hi Sara,
    following the detailed (thank you!) instructions in “installing ESP32 board …” second part “deleting the espressif folder ..” to get the latest version of it I successful could test the WiFiscan example.
    Great!
    However:
    I failed to compile the “ESP32 DHT11/DHT21 webserver temp & hum …” example from your Web site. Got a whole bunch of error messages, first read as:
    … AsyncTCP-952b7eb6ba62f7071f7da2a274d36e06b97de572\src\AsyncTCP.cpp:259:27: error: field ‘call’ has incomplete type ‘tcpip_api_call’
    etc. etc.
    Searching the WEB I found a lot of comments concerning this issue totaly unintelligble to me :-((
    Please give advice how to fix the problen or public a new – compatible – version of the Web-server sketch.
    Thank you

      • Sara, thank you for the very fast response!
        As I’m using the latest arduino IDE and the latest espressive file may I ask you for a very short cross check before I have to dig deeper into installation details?

        I’m using IDE 1.8.9 and have – according to the instruction – deleted the espressive file in my sketchbook folder to compile the sourcecode from your Web-side.

        Thank you so much for your support

        • Unfortunately, I don’t know what to do from here as I’ve never experienced that problem.
          You can also check if you have more than one Arduino IDE installed in your computer that may be conflicting…

      • Thank you Sara for your hint. I gone thru all the steps in https://github.com/me-no-dev/AsyncTCP/issues/21 as adviced. Afterwards I could sucessfull compile and run the ESP32 examples WiFiScan, getChipID, LEDCSoftwarefade etc. but still not the async. Webserver sketch.
        Did you suceed in compiling the code?
        Maybe there is someone out here who can try to compile – no hardware neede for the test just compile.
        Thank you for support!

          • Sara
            it looks like an incompabilty of older an newer async tcpip libs:
            field ‘call’ has incomplete type ‘tcpip_api_call’ struct tcpip_api_call call;

            If you ever update arduino IDE et all pls try to compil again and report the result here. It’s allways a mess with incompatible updates I know.

            Thank you for your support!

  19. Thanks so much for this tutorial, it’s fantastic and just what I was looking for.
    Do you know if there a way to display a graph of the data on the website so you can view the changes in temp & humidity over the course of a day, instead of just at a point in time??

  20. There is a compilation error that seems to be linked to one of the libraries:
    C:\Users\ik\Documents\Arduino\libraries\ESPAsyncWebServer\src\WebAuthentication.cpp:23:17: fatal error: md5.h: No such file or directory

    I have the ESPAsyncWebserver installed and there is a WebAuthentication.cpp file.
    What could be wrong here

  21. Hey thanks for the awesome guide!

    I know this is a bit old but there were a few issues.

    The link to the AsyncTCP might be incorrect or outdated, I googled and found the files from a different source.

    There was a problem with multiple wifi.h locations, but this seems like a general esp32 issue.

    Also the credentials for wifi showed errors, I removed the ‘const’ and it worked.

    I have one question, the website randomly gets assigned to an local ip address.
    Is there any way to keep the ip static so it will be the same?

    Thank you for the guide

  22. hi there I’m getting this error how do I fix it

    Serial port /dev/cu.Bluetooth-Incoming-Port
    Connecting…….._____….._____….._____….._____….._____….._____…..____An error occurred while uploading the sketch
    _

    A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header

  23. Hi there,
    thanks for the fine tutorial.
    It’s working, but I’ve little issues:
    I set the interval to 12000, both t and h.
    Now the h updates every 8 seconds, the t only when I reload the page.
    Not so comfortable and I don’t understand – both parts have similar code.

    So I thought, it would be nice to display the date and time of the readings too. Unfortunately I don’t know how to integrate this function.

    Another question for ESP32: If I interrupt the voltage and connect again, starts it working by itself or must I press the boot- and/or the en-button?

    Thanks for your applied time
    Siegfried

  24. Update:
    After changing interval time and uploading, it doesn’t connect to wifi anymore.
    Everything else is the same.
    Help!!!

  25. Maybe I should have added this:
    18:47:16.866 -> rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    18:47:16.866 -> configsip: 0, SPIWP:0xee
    18:47:16.866 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    18:47:16.912 -> mode:DIO, clock div:1
    18:47:16.912 -> load:0x3fff0018,len:4
    18:47:16.912 -> load:0x3fff001c,len:928
    18:47:16.912 -> ho 0 tail 12 room 4
    18:47:16.912 -> load:0x40078000,len:8424
    18:47:16.912 -> ho 0 tail 12 room 4
    18:47:16.912 -> load:0x40080400,len:5868
    18:47:16.912 -> entry 0x4008069c
    18:47:18.316 -> Connecting to WiFi..
    18:47:19.299 -> Connecting to WiFi..
    18:47:20.282 -> Connecting to WiFi..
    18:47:21.313 -> Connecting to WiFi..
    18:47:22.295 -> Connecting to WiFi.. and so on
    I tried again and again.

    • Hi.
      Did you introduced your network credentials?
      It is common to get that error when we upload the code without the credentials. It continuously tries to connect to wifi.
      Regards,
      Sara

  26. Hi Sara,
    I did! It worked before. The code is the same, I only changed interval time. The problem is still after I undid the change.
    I tried the ‘const char* ssid = “W…’ lines without ‘const’, wich hint I found somewhere – no other result.
    Regards,
    Siegfried

  27. I’m sorry to be flashy but I can’t solve the problem.
    I made a new sketch, copying your code, only changing the network credentials, did the upload. It started the same way as before: continuously tries to connect to wifi.
    I can’t understand because it worked about ten days ago for about one weak. It’s the same computer and other hardware (Win7, DOIT ESP32 Devkit V1, Router WLAN adjustment).
    Would you have any suggestions?
    Regards,
    Siegfried

    • Hi.
      I’m sorry, but I don’t know what can be wrong.
      If you are inserting your network credentials properly, it is very difficult to figure out what is wrong.
      Can you try any other wi-fi sketch example and see if the ESP32 connects to wi-fi?
      In the Arduino IDE, you can select a file from the examples folder.
      Regards,
      Sara

  28. Hi,
    as the ESP32 to google sheets project works fine since may, 19. on the same wifi, I finally
    changed the DHT22 to another one – no better result
    put it to 5V as I read somewhere – no better result
    put it back to 3.3V – miraculously it w o r k s !!!
    I don’t understand but obviously sometimes you have to try some crazy things with the computer stuff.

    How could I display date and time on the web page too?

    Is there any workshop for learning how to get access to my WiFi.localIP from www? After reading the whole google (nearly), all I tried till now failed.

    Thanks so much for helping,
    Siegfried

  29. I’m going to connect two ultrasonic sensors with ESP module is there anything to change or can I just replacer the coding part which is related to the ultrasonic sensor part?
    help me

    • Hi.
      It depends on your application. But if you just add the ultrasonic sensor part, it should work.
      Regards,

      Sara

    • Hi Igor.
      After uploading the code, open the Serial Monitor and make sure you have the right baud rate selected. In this case 115200.
      Then, press the ESP32 on-board RESET button. It should display the IP address.
      I hope this helps.
      Regards,
      Sara

  30. hi..i am facing an error after uploading the code.i open the serial monitor and there was an error message…BROWNOUT DETECTOR WAS TRIGGERED.pls help me to solve this

Leave a Reply to David Pope Cancel reply

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.