ApplicationsHardware & Boards

ESP32 Weather Station: Live Temperature & Humidity with a DHT22 Sensor

After learning how to control an LED through an ESP32 web server, reading sensor data and displaying it online serves as the perfect next project. In this tutorial, you will connect a DHT22 sensor to your ESP32 board. Consequently, you will build a clean web page that displays live temperature and humidity readings directly from the device without requiring any third-party cloud services.

What You Will Learn

  • Wire and read environmental data directly from a DHT22 sensor.
  • Install and configure the required Adafruit DHT sensor libraries in Arduino IDE.
  • Display live sensor readings on a self-hosted web page.
  • Auto-refresh web page content automatically using simple HTML meta tags.

Project Prerequisites

  • Difficulty: Beginner
  • Time Required: 25–35 minutes
  • Estimated Cost: Under $8 (DHT22 sensor + ESP32)

Components Needed

  • 1x ESP32 development board
  • 1x DHT22 temperature & humidity sensor (or DHT11 as a cheaper alternative)
  • 1x 10kΩ pull-up resistor (only needed if your DHT22 module lacks a built-in resistor)
  • Breadboard and jumper wires
  • USB cable

Circuit Wiring Diagram

Most DHT22 breakout modules feature three pins: VCC, GND, and DATA. However, if you use a bare 4-pin sensor, you must add a 10kΩ resistor between the VCC and DATA pins.

ESP32 PinConnected Component
3.3VDHT22 VCC (+)
GNDDHT22 GND (–)
GPIO 4DHT22 DATA (signal)

Pro Tip: Always power your DHT22 sensor using 3.3V rather than 5V when connecting directly to an ESP32 to prevent damaging the GPIO pins.

Step-by-Step Setup Guide

Step 1: Install the Required Libraries

  1. Open Arduino IDE and navigate to Sketch → Include Library → Manage Libraries.
  2. Search for DHT sensor library by Adafruit and click install.
  3. When prompted by the library manager, install its required dependency: Adafruit Unified Sensor.

Step 2: Wire the Sensor Circuit

Connect your DHT22 sensor to the ESP32 following the pin connections listed in the reference table above.

Step 3: Upload the ESP32 Weather Station Code

Copy the full sketch below into your Arduino IDE, update the network credentials with your Wi-Fi name and password, and upload it to your board.

C++

#include <WiFi.h>
#include "DHT.h"

const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";

#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  dht.begin();

  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  server.begin();
}

void loop() {
  WiFiClient client = server.available();
  if (client) {
    String currentLine = "";
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (c == '\n') {
          if (currentLine.length() == 0) {
            float temp = dht.readTemperature();
            float hum = dht.readHumidity();

            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            client.println("<!DOCTYPE html><html><head>");
            client.println("<meta http-equiv='refresh' content='5'>");
            client.println("</head><body>");
            client.println("<h1>ESP32 Weather Station - iotjournal.net</h1>");

            if (isnan(temp) || isnan(hum)) {
              client.println("<p>Failed to read from DHT sensor!</p>");
            } else {
              client.println("<p>Temperature: " + String(temp) + " &deg;C</p>");
              client.println("<p>Humidity: " + String(hum) + " %</p>");
            }

            client.println("</body></html>");
            client.println();
            break;
          } else {
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
        }
      }
    }
    client.stop();
  }
}

Step 4: Obtain the ESP32 IP Address

Open the Serial Monitor by selecting Tools → Serial Monitor and set the baud rate to 115200. Once the device connects to Wi-Fi, note the assigned IP address printed in the console.

Step 5: View Live Readings in Your Browser

  1. Connect your smartphone or computer to the same Wi-Fi network as the ESP32.
  2. Open a browser and type the board’s IP address (e.g., [http://192.168.1.55](http://192.168.1.55)).
  3. The dashboard displays live temperature and humidity values, updating automatically every 5 seconds.

How It Works

The DHT22 sensor transmits temperature and humidity data over a single digital pin using a timing-based protocol. The Adafruit DHT library manages this low-level timing automatically through readTemperature() and readHumidity() functions. Every time a user accesses the webpage, the ESP32 fetches a fresh reading and constructs an HTML page. The included <meta http-equiv='refresh' content='5'> tag forces the browser to reload every 5 seconds, maintaining an auto-refreshing dashboard.

Troubleshooting Common Issues

  • Readings show ‘nan’ or fail: Verify your physical wiring to the DATA pin and confirm that your code specifies the correct sensor type (DHT11 vs DHT22).
  • Sensor reads inconsistently: The DHT22 requires a 2-second sampling interval. Avoid requesting data faster than the sensor can process.
  • Web page fails to auto-refresh: Confirm that browser caching isn’t blocking updates. Perform a hard refresh to clear cached assets.
  • No IP address displays in Serial Monitor: Re-check your Wi-Fi credentials and ensure your router provides adequate signal strength.

Next Steps and Project Extensions

  • Log historical readings directly to an SD card or external dashboard.
  • Add visual thresholds that activate a physical buzzer or indicator LED when temperature rises.
  • Customize the web interface using custom CSS styles and vector icons.
  • Check out our preliminary project on Building a Simple ESP32 Web Server for a complete introduction to web controls, or review the Official Espressif Documentation to learn more about GPIO pin capabilities.

Published on iotjournal.net — part of the ‘Practical ESP32 Projects’ series.

Tags
Show More

IoT Journal

Technical Product Manager focused on enterprise IoT and digital transformation.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Close