ESP8266 DHT11/DHT22 Temperature and Humidity Web Server with Arduino IDE

In this project you’ll create a standalone web server with an ESP8266 that displays the temperature and humidity with a DHT11 or DHT22 sensor using the Arduino IDE. The web server you’ll build can be accessed by any device that has a browser on your local network.

Recommended Resources:

If you like the ESP8266 and you want to build more projects, take a look at our course: Home Automation using ESP8266.

First, watch the video demonstration below

Installing Libraries

For this project you need to install the DHT Sensor library and the Adafruit Unified Sensor Driver. Follow the next steps to install the libraries.

Installing the DHT Sensor library

The DHT sensor library provides an easy way of using any DHT sensor to read temperature and humidity with your ESP8266 or Arduino boards.

Build home automation projects with the ESP8266 Wi-Fi dev board using Arduino IDE and Lua firmware DOWNLOAD »

Build home automation projects with the ESP8266 Wi-Fi dev board using Arduino IDE and Lua firmware DOWNLOAD »

1) Click here to download the DHT sensor library. You should have a .zip folder in your Downloads

zip

2) Unzip the .zip folder and you should get DHT-sensor-library-master folder

folder

3) Rename your folder from DHT-sensor-library-master to DHT

rename

4) Move the DHT folder to your Arduino IDE installation libraries folder

moving

5) Then re-open your Arduino IDE

Installing the Adafruit Unified Sensor library

You also need to install the Adafruit Unified Sensor Driver Library. Follow the next steps to install the library.

Download our Free eBooks and Resources

  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 DHT_sensor folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Uploading your ESP8266 code

Before uploading any code to the ESP8266, you need to have the ESP8266 add-on for the Arduino IDE installed (How to Install the ESP8266 Board in Arduino IDE).

Go to Tools and select “Generic ESP8266 Module”.

Copy the sketch below to your Arduino IDE. Replace the SSID and password with your own credentials.

After modifying my sketch upload it to your ESP8266 (if you can’t upload code to your ESP8266, read this troubleshooting guide).

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

// Including the ESP8266 WiFi library
#include <ESP8266WiFi.h>
#include "DHT.h"

// Uncomment one of the lines below for whatever DHT sensor type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

// Replace with your network details
const char* ssid = "YOUR_NETWORK_NAME";
const char* password = "YOUR_NETWORK_PASSWORD";

// Web Server on port 80
WiFiServer server(80);

// DHT Sensor
const int DHTPin = 5;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);

// Temporary variables
static char celsiusTemp[7];
static char fahrenheitTemp[7];
static char humidityTemp[7];

// only runs once on boot
void setup() {
  // Initializing serial port for debugging purposes
  Serial.begin(115200);
  delay(10);

  dht.begin();
  
  // Connecting to WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  
  // Starting the web server
  server.begin();
  Serial.println("Web server running. Waiting for the ESP IP...");
  delay(10000);
  
  // Printing the ESP IP address
  Serial.println(WiFi.localIP());
}

// runs over and over again
void loop() {
  // Listenning for new clients
  WiFiClient client = server.available();
  
  if (client) {
    Serial.println("New client");
    // bolean to locate when the http request ends
    boolean blank_line = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        
        if (c == '\n' && blank_line) {
            // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
            float h = dht.readHumidity();
            // Read temperature as Celsius (the default)
            float t = dht.readTemperature();
            // Read temperature as Fahrenheit (isFahrenheit = true)
            float f = dht.readTemperature(true);
            // Check if any reads failed and exit early (to try again).
            if (isnan(h) || isnan(t) || isnan(f)) {
              Serial.println("Failed to read from DHT sensor!");
              strcpy(celsiusTemp,"Failed");
              strcpy(fahrenheitTemp, "Failed");
              strcpy(humidityTemp, "Failed");         
            }
            else{
              // Computes temperature values in Celsius + Fahrenheit and Humidity
              float hic = dht.computeHeatIndex(t, h, false);       
              dtostrf(hic, 6, 2, celsiusTemp);             
              float hif = dht.computeHeatIndex(f, h);
              dtostrf(hif, 6, 2, fahrenheitTemp);         
              dtostrf(h, 6, 2, humidityTemp);
              // You can delete the following Serial.print's, it's just for debugging purposes
              Serial.print("Humidity: ");
              Serial.print(h);
              Serial.print(" %\t Temperature: ");
              Serial.print(t);
              Serial.print(" *C ");
              Serial.print(f);
              Serial.print(" *F\t Heat index: ");
              Serial.print(hic);
              Serial.print(" *C ");
              Serial.print(hif);
              Serial.print(" *F");
              Serial.print("Humidity: ");
              Serial.print(h);
              Serial.print(" %\t Temperature: ");
              Serial.print(t);
              Serial.print(" *C ");
              Serial.print(f);
              Serial.print(" *F\t Heat index: ");
              Serial.print(hic);
              Serial.print(" *C ");
              Serial.print(hif);
              Serial.println(" *F");
            }
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: text/html");
            client.println("Connection: close");
            client.println();
            // your actual web page that displays temperature and humidity
            client.println("<!DOCTYPE HTML>");
            client.println("<html>");
            client.println("<head></head><body><h1>ESP8266 - Temperature and Humidity</h1><h3>Temperature in Celsius: ");
            client.println(celsiusTemp);
            client.println("*C</h3><h3>Temperature in Fahrenheit: ");
            client.println(fahrenheitTemp);
            client.println("*F</h3><h3>Humidity: ");
            client.println(humidityTemp);
            client.println("%</h3><h3>");
            client.println("</body></html>");     
            break;
        }
        if (c == '\n') {
          // when starts reading a new line
          blank_line = true;
        }
        else if (c != '\r') {
          // when finds a character on the current line
          blank_line = false;
        }
      }
    }  
    // closing the client connection
    delay(1);
    client.stop();
    Serial.println("Client disconnected.");
  }
}   

View raw code

Note: if you’re using the DHT22 sensor comment the DHT11 line and uncomment the DHT22, as shown below:

// Uncomment one of the lines below for whatever DHT sensor type you're using!
//#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321

Schematics

To complete this project you need the following components:

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!

Note: Other DHT sensor types will also work with a small change in the code (as described in the sketch comments).

Here’s the schematic you need to follow to wire the DHT sensor to your ESP8266 board:

ESP8266_schematics_bb

Important: the DHT sensor requires 5V to operate properly, so make sure you use the Vin pin from your ESP8266 that outputs 5V.

ESP8266 IP Address

Open the Arduino IDE serial monitor at a baud rate of 115200. After a few seconds your IP address should appear. In my case it’s 192.168.1.95.

Arduino IDE

Demonstration

For the final demonstration open any browser from a device that is connected to the same router that your ESP is. Then type the IP address and click Enter!

web server

Now you can easily see the current temperature in Celsius and Fahrenheit and the humidity.

Wrapping Up

In this project we’ve shown you how to build a simple web server to display the temperature and humidity. You can easily modify this project to display other sensor readings. If you like the ESP8266 and IoT projects take a look at some of our most popular projects:

Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing our blog and our Facebook Page.

P.S. If you got stuck during this tutorial make sure you read “ESP8266 Troubleshooting Guide


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!

66 thoughts on “ESP8266 DHT11/DHT22 Temperature and Humidity Web Server with Arduino IDE”

  1. First, I wanted to thank you for your tutorials , already a real plaisur .
    However, I have a question about mounting. How can we provide power to the system for a long time . I believe a single AA battery couple is not enough for more than two or three days. I’ve heard of a solution about hibernation, but is applicable to an ESP- 01 ? And finally, what other kind of battery can be used (regardless of model lipo ? A link to Ebay to provide ? ) . Thank you for all your answers.

  2. Nice work here 🙂

    Any chance of doing more demos with Node MCU based ESP8266 projects. Running a Lua Script on the ESP8266 allows the ESp8266 to run standalone… Just a thought 🙂

  3. Rui
    If you change this line in your code, the web page will auto update every 5 seconds! Change the “5” to how many seconds you want to wait for the next update!!

    client.println(“ESP8266 – Temperature and HumidityTemperature in Celsius: “);

  4. Are you sure about the schematics? Vcc and Gnd connections to 4.7 kohm, tx pin connected to gnd rail?, nothing connected to gnd pin?

    Regards

      • Hi Rui, I am not sure if this reply will be duplicate or not, first draft was accidentally disappeared, so I write again.

        First of all thanks for your great postings, which help me a lot.

        This circuit schematics still has a mistake. 4.7 K should be a pull up resistor, whereas your sketch shows it as a pull down to GND. It does not work like this, I tried it.

        BR

  5. Great sketch!
    I need to refresh my browser to get the updated data.
    How to made the sketch to update my browser data automatically say every 5 minutes?
    Thanks.

  6. what is the problem if my esp isn’t react with the serial monitor?
    i use esp8266 as in the link below:
    encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwg3ohvTuCUk2iTloQKOVM0-tB3lT_7Ps_j3rrURKmV1_DMXIESg
    best regards and thanks for good tutorial !

  7. Hi Rui, I try your tutorial with this esp8266 banggood.com/ESP8266-Web-Server-Port-WiFi-Expansion-Board-ESP-13-Compatible-With-Arduino-p-1008124.html?rmmds=myorder

    but I have this error loading your script on esp8266 board:

    Arduino:1.6.12 (Windows 7), Scheda:”Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None”

    Lo sketch usa 236.389 byte (54%) dello spazio disponibile per i programmi. Il massimo è 434.160 byte.
    Le variabili globali usano 32.568 byte (39%) di memoria dinamica, lasciando altri 49.352 byte liberi per le variabili locali. Il massimo è 81.920 byte.
    C:\Users\user\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd ck -cb 115200 -cp COM13 -ca 0x00000 -cf C:\Users\user\AppData\Local\Temp\arduino_build_921673/remoteTemp.ino.bin
    esptool v0.4.9 – (c) 2014 Ch. Klippel
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM13
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
    opening bootloader
    resetting board

    trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 00 instead of C0
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

    Can you help me to understand what is the problem and to solve it? Thanks.

    • Hi,
      I’ve never used that board, but it sounds like your Arduino IDE is not establishing a serial communication with your ESP8266 board.
      To upload a new firmware/sketch to your ESP8266 GPIO 0 must be connected to GND on boot

      • Hi yes i connect the 2 GPIO on off and i think it means GND.
        Trying with esptool i have the error A fatal error occurred: Failed to connect to ESP8266..
        Any idea?
        Thanks.

  8. iam doing a small project with arduino uno with help of ultrasonic sensor and buzzer(home alaram system ) i need help to add esp8266 to my project so that i can get message if the buzzer goes on any idea how to movie on or anything u have did already

  9. Hi Rui. When trying to compile using IDE 1.6.8 I get the following error.

    WARNING: Spurious .github folder in ‘DHT sensor library’ library
    In file included from C:\Users\user\Documents\Arduino\libraries\DHT\DHT_U.cpp:22:0:

    C:\Users\user\Documents\Arduino\libraries\DHT\DHT_U.h:25:29: fatal error: Adafruit_Sensor.h: No such file or directory

    #include

    The only change I made was to Rem out the DHT11 define and replace it with DHT21.

    Thanks for any help

    ^

    compilation terminated.

    exit status 1
    Error compiling for board Generic ESP8266 Module.

  10. Hi Rui, I can connect to the IP address of my ESP8266 using the Arduino Serial Monitor but I keep getting the message:

    New client
    Failed to read from DHT sensor!
    Client disconnected.

    Any thoughts on why this might be?
    I’m using the NodeMCU V3 with the DH11 (3pin) connecting directly.

    • I’m using the V3 also. the V3’s Vin pin is not supplying power or enough power to the dht sensor. Mine is the AM2302 and I had to power it separately but it worked fine after that

    • I think on the V3 the Vin pin is at 5volts only if you power the board via that pin. if you power it via usb it wont power the dht sensor through that pin. when I applied an external 5 volts there it began to work.

  11. Hello, Thanks for a great tutorial. What do we need to do to make the web page automatically refresh or only refresh if there is a change in the temperature?

    • I added this line in the html code.

      client.println(“”);

      I dont know if its exactly the correct way to do it. I borrowed it from some of the example code that comes with the IDE. It works on my V3

  12. Great job!! I have a question about the deep sleep mode, if you already used it in an ESP project.
    What instructions you did use for deepsleep and to wake the esp up?
    Thanks.

  13. Hi Rui,

    Thanks for this tutorial.
    Despite it’s age 😉 I am now using it as a starting point and move on to programming the Arduino, ESP8266 and possibly Raspberry Pi using (Micro-)Python.

    I made a few personal modifications to your Code to better satisfy my “needs”, but one in particular might be useful for others as well.
    This one is NOT directly related to the ESP8266, the DHT11 etc, but it might be useful if people want to “monitor” the temperature.
    If you add (be aware of the twin double-quotes) in between the tags, the resulting WebPage will refresh every 5 seconds showing different readings of the temperature sensor 😉

    Thanks for providing these great tutorials!

    Regards,
    Rob.

  14. I keep getting error messages:

    Arduino: 1.8.2 (Mac OS X), Board: “Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None”

    Build options changed, rebuilding all
    Archiving built core (caching) in: /var/folders/m_/s61mbj4s2qx7k7y9xxntjvzr0000gn/T/arduino_cache_671719/core/core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____d36531614ebe222a45d35a594f73c3ee.a
    Sketch uses 236301 bytes (54%) of program storage space. Maximum is 434160 bytes.
    Global variables use 32472 bytes (39%) of dynamic memory, leaving 49448 bytes for local variables. Maximum is 81920 bytes.
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    I’ve tried this on a MAC and LINUX machine, same error. What am I doing wrong?

    • Hi Christopher.
      The following lines:
      warning: espcomm_sync failed
      error: espcomm_open failed
      error: espcomm_upload_mem failed
      error: espcomm_upload_mem failed
      Mean that your ESP8266 is not establishing a serial communication with your computer, or it’s not in flashing mode.
      If you’re using an ESP-01 make sure GPIO0 is connected to GND on power up.
      If you’re using another board, make sure you hold down the BOOT/FLASH button when uploading.
      I hope this helps,
      Regards,
      Sara

  15. First of all a big thanks to you. I almost completed. Nodemcu was connected to my mobile hotspot. But data is not displayed on the browser. Please help

  16. Hi!

    This is a great manual. But I faced some problem when I disconnect TLL converter form PC my esp8266 doesn’t connect to wifi, with converter everything works like a charm. Do you have an idea what it can be?

  17. “In file included from C:\Users\COMPUTER\Documents\Arduino\libraries\DHT_sensor_library\DHT_U.cpp:22:0:

    C:\Users\COMPUTER\Documents\Arduino\libraries\DHT_sensor_library\DHT_U.h:25:29: fatal error: Adafruit_Sensor.h: No such file or directory

    #include

    ^

    compilation terminated.”
    I use the esp8266-12 and faulty as above. Can you help me fix it?

    • Hi Phú.
      You need to install the Adafruit Sensor library.
      You can find the Adafruit Sensor library here: github.com/adafruit/Adafruit_Sensor
      Regards,
      Sara

  18. Hi, I have done everything that was written on this tutorial but when I enter in my IP address into a browser it says

    Temperature in Celsius: Failed *C
    Temperature in Fahrenheit: Failed *F
    Humidity: Failed %

    Is there any way to know the reason that it’s not working?

  19. HI,

    I found that if we place the sensor at a sudden change of temperature/humidity environment, we will require to refresh the webpage twice in order to receive the correct data.
    The first refresh data is not correct as the data shown did not update according to the environment change. It is still at old environment.
    Any suggestion?

    • Hi Mario.
      I think you have a DHT sensor module.
      In that case, you just need to take a look at the labels on the part. It should have VCC, OUT and GND.
      Connect VCC to the Vin pin, GND to GND, and out to D1. I think that with these modules you don’t need to add the 4.7kOhm resistor.
      I hope this helps,
      Regards,
      Sara 🙂

  20. I’m getting -999 in values (Failed to read from DHT sensor). Works great connected to my Arduino Uno, but the ESP8266 won’t read the DHT22. Any ideas? I’ve tried multiple libraries, all the same thing. I know the ESP8266 is working because it sends the -999 to Thingspeak.com. Thank you for any help.

    • Hi Al.
      Please check that the sensor is being properly powered (5V to the Vin pin of the sensor).
      Regards,
      Sara

  21. Hi Rui & Sara – this is a great tutorial, I usually find I have to tweak Arduino tutorials but this one just works! 🙂

    Best

    Andrew

Leave a Comment

Download our Free eBooks and Resources

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