ESP32 DHT11 Weather Station with Web Server (Code + Wiring)

Build an ESP32 DHT11 weather station that shows live temperature and humidity on a web page. Wiring table, complete Arduino code and troubleshooting.

  • DifficultyEasy
  • Build time1–2 hours
  • Board / MCUESP32 DevKit
  • Parts5 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

In this project we build a Wi-Fi weather station with an ESP32 and a DHT11 sensor. The ESP32 reads temperature and humidity every two seconds and hosts its own web server, so you can open a live dashboard from any phone or laptop on the same Wi-Fi network – no cloud account, no app and no monthly fee. It also serves the readings as JSON at /data, which makes it easy to connect to Node-RED, Home Assistant or your own scripts later.

This is one of the best first IoT projects: it teaches sensor reading, Wi-Fi connection, HTML generation on a microcontroller and basic error handling, all in under 100 lines of code.

How It Works

The DHT11 contains a capacitive humidity element and a thermistor, plus a tiny chip that converts the readings into a digital signal on a single data wire. The ESP32 asks for a reading, the sensor answers with 40 bits of data, and the DHT library decodes it into °C and %RH. The ESP32 then joins your Wi-Fi as a station, gets an IP address from your router and listens on port 80. When a browser requests /, the sketch builds an HTML page containing the latest values; the page refreshes itself every 10 seconds.

Components Required

  • ESP32 DevKit V1 (ESP32-WROOM-32) – 1
  • DHT11 temperature & humidity sensor (3-pin module with built-in pull-up, or bare 4-pin sensor) – 1
  • 10 kΩ resistor – only if you use the bare 4-pin DHT11
  • Breadboard and jumper wires
  • USB data cable and a 2.4 GHz Wi-Fi network

Wiring Table (Pin-to-Pin)

DHT11 PinESP32 PinNotes
VCC (+)3V3DHT11 works from 3.3–5.5 V; 3.3 V keeps the data line ESP32-safe
DATA (OUT / S)GPIO4Matches #define DHTPIN 4
GND (−)GNDCommon ground
(bare sensor only) 10 kΩbetween DATA and 3V3Pull-up resistor; 3-pin modules already have it
(bare sensor only) pin 3not connectedNC pin

Libraries Used

  • DHT sensor library by Adafruit – adafruit/DHT-sensor-library (MIT license).
  • Adafruit Unified Sensor – required dependency – adafruit/Adafruit_Sensor (Apache-2.0).
  • WiFi.h and WebServer.h come with the ESP32 Arduino core: espressif/arduino-esp32 (LGPL-2.1).
  • The sketch itself is original code written for this tutorial; the DHT read pattern follows the library’s DHTtester example.

Complete Code

// ESP32 DHT11 Weather Station with Web Server
// Libraries: "DHT sensor library" + "Adafruit Unified Sensor" (Adafruit)
// Board: ESP32 Dev Module
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>

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

#define DHTPIN  4        // DHT11 DATA -> GPIO4
#define DHTTYPE DHT11    // change to DHT22 if you use a DHT22
DHT dht(DHTPIN, DHTTYPE);
WebServer server(80);

float temperature = NAN, humidity = NAN;
unsigned long lastRead = 0;

void readSensor() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();   // Celsius
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;                          // keep last good values
  }
  humidity = h;
  temperature = t;
  Serial.printf("Temp: %.1f C  Humidity: %.1f %%\n", t, h);
}

String valueOrDash(float v) { return isnan(v) ? String("--") : String(v, 1); }

void handleRoot() {
  String html = "<!DOCTYPE html><html><head><meta charset='utf-8'>"
                "<meta name='viewport' content='width=device-width,initial-scale=1'>"
                "<meta http-equiv='refresh' content='10'>"
                "<title>ESP32 Weather Station</title>"
                "<style>body{font-family:Arial;text-align:center;background:#0f172a;color:#fff}"
                ".card{display:inline-block;margin:12px;padding:20px 30px;border-radius:12px;background:#1e293b}"
                ".v{font-size:2.5em;color:#22c55e}</style></head><body>"
                "<h1>ESP32 Weather Station</h1>";
  html += "<div class='card'><div>Temperature</div><div class='v'>" + valueOrDash(temperature) + " &deg;C</div></div>";
  html += "<div class='card'><div>Humidity</div><div class='v'>" + valueOrDash(humidity) + " %</div></div>";
  html += "<p>Auto-refresh every 10 s</p></body></html>";
  server.send(200, "text/html", html);
}

void handleJson() {
  String json = "{\"temperature\":" + valueOrDash(temperature) +
                ",\"humidity\":" + valueOrDash(humidity) + "}";
  if (isnan(temperature)) json = "{\"error\":\"sensor not ready\"}";
  server.send(200, "application/json", json);
}

void setup() {
  Serial.begin(115200);
  dht.begin();
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
  Serial.print("\nConnected! Open http://");
  Serial.println(WiFi.localIP());
  server.on("/", handleRoot);
  server.on("/data", handleJson);
  server.begin();
  readSensor();
}

void loop() {
  server.handleClient();
  if (millis() - lastRead > 2000) {   // DHT11: max 1 reading per second
    lastRead = millis();
    readSensor();
  }
}

Code Explanation

  • Credentials: replace YOUR_WIFI_SSID and YOUR_WIFI_PASSWORD. The ESP32 only supports 2.4 GHz networks.
  • readSensor() reads humidity and temperature. If either value is NAN (failed read), the old values are kept, so the web page never shows garbage.
  • Non-blocking timing: instead of delay(2000), the loop uses millis(), so the web server keeps answering requests instantly.
  • handleRoot() builds a mobile-friendly HTML page with two cards; meta refresh reloads it every 10 seconds.
  • handleJson() returns {"temperature":27.0,"humidity":61.0} for other apps.

Step-by-Step Instructions

  1. Install the ESP32 board package (Boards Manager → “esp32” by Espressif).
  2. Install “DHT sensor library” and “Adafruit Unified Sensor” from Library Manager.
  3. Wire the DHT11 exactly as in the table: VCC → 3V3, DATA → GPIO4, GND → GND.
  4. Paste the code and enter your Wi-Fi name and password.
  5. Select ESP32 Dev Module and the correct port, then Upload (hold BOOT if it is stuck at “Connecting…”).
  6. Open Serial Monitor at 115200 baud. After “Connected!” note the IP address, e.g. 192.168.1.45.
  7. On your phone (same Wi-Fi) open http://192.168.1.45. You will see live temperature and humidity.
  8. Breathe gently on the sensor – humidity should rise within a few seconds, which confirms everything works.

Troubleshooting

ProblemFix
“Failed to read from DHT sensor!”Check DATA is on GPIO4, add the 10 kΩ pull-up for bare sensors, make sure DHTTYPE matches your sensor (DHT11 vs DHT22).
Stuck on “Connecting to WiFi…..”Check SSID/password spelling, use a 2.4 GHz network, move closer to the router.
Page does not openPhone must be on the same network; type http:// not https; check the IP in Serial Monitor.
Temperature reads 1–2 °C highThe ESP32 warms up; keep the sensor a few cm away from the board.
Compile error “Adafruit_Sensor.h not found”Install the Adafruit Unified Sensor library.

Upgrade Ideas

  • Swap to a DHT22 or BME280 for better accuracy (and pressure on BME280).
  • Log data to ThingSpeak or Google Sheets for graphs.
  • Add an OLED display for a standalone readout.
  • Use deep sleep and a battery for an outdoor station.

Frequently Asked Questions

DHT11 vs DHT22 – which is better?

DHT11 measures 0–50 °C (±2 °C) and 20–80 % RH (±5 %). DHT22 covers −40–80 °C (±0.5 °C) and 0–100 % RH (±2–5 %). For a few rupees more, DHT22 is more accurate; just change DHTTYPE to DHT22.

Can I view it from outside my home?

Not directly; the server is on your local network. Use port forwarding (not recommended), a VPN, or a cloud service such as Blynk, ThingSpeak or MQTT.

Why read only every 2 seconds?

The DHT11 cannot be read faster than about once per second; faster reads return errors.

Does it work with ESP8266?

Yes – replace WiFi.h/WebServer.h with ESP8266WiFi.h/ESP8266WebServer.h, use ESP8266WebServer server(80);, and connect DATA to D2 (GPIO4).

Related Projects

Browse more ESP32 Projects on Arduino Project Hub.

3 thoughts on “ESP32 DHT11 Weather Station with Web Server (Code + Wiring)”

Leave a Comment