Web based Weather Station with ESP32 and DHT11 Sensor

Introduction

In this project, we’ll create a simple, real-time weather station using ESP32 and DHT11 sensor to monitor temperature and humidity. The ESP32 will operate in Access Point (AP) mode, allowing it to host a web interface that displays temperature and humidity readings in real-time, which can be accessed by any nearby device without an internet connection. Our weather station reads data from the DHT11 sensor every second, displays the readings on an ESP32-hosted webpage, and updates automatically. This project is great for beginners looking to understand IoT and web-based projects with ESP32.


COMPONENTS REQUIRED

  • ESP32 Development Board
  • DHT11 Temperature and Humidity Sensor
  • Jumper Wires
  • Breadboard (optional for easy connections)

PROJECT FEATURES

  • Responsive UI: The webpage is designed to be user-friendly and responsive, providing a seamless experience on both mobile and desktop devices.
  • Real-Time Monitoring: The ESP32 and DHT11 sensor enable real-time temperature and humidity monitoring, updating every second.
  • Wi-Fi Connectivity: The ESP32 connects to your existing Wi-Fi network, allowing you to access data from any device on the same network.
  • Automatic Data Updates: The webpage refreshes every second to display the latest data, ensuring real-time monitoring.

WIRING DIAGRAM

The ESP32 connects to the DHT11 sensor as follows:

DHT11 PinConnection to ESP32
VCCVIN
GNDGND
DATAGPIO 27
ESP32 and DHT11 Wiring Diagram

Note: GPIO 27 is used for this example, but you can use any other GPIO pin by adjusting the code.


CODE WALKTHROUGH

Let’s walk through the main sections of the code.

Setting up the ESP32 Web Server

The ESP32 and DHT11 sensor work together seamlessly in this setup, with the ESP32 hosting a web server to display real-time data from the DHT11. The ESP32 operates in Wi-Fi station mode, connecting to your existing network. Once connected, you can access a simple HTML-based dashboard through a browser, displaying real-time temperature and humidity data.

HTML User Interface

The HTML interface, which the ESP32 serves, includes icons for temperature and humidity to make the data visually appealing. JavaScript is used to fetch and display updated data every second, providing a near real-time user experience.

Code Listing

Here’s the complete code for the project:

// Web based Weather Station with ESP32 and DHT11 Sensor by ArduinoYard
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <DHT.h>

// DHT11 setup
#define DHTPIN  27       // DHT11 data pin
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// Replace with your network credentials
const char* ssid = "Your_SSID";
const char* password = "Your_Pass";

AsyncWebServer server(80);

float temperature = 0;
float humidity = 0;

// Webpage for ESP32 and DHT11 Sensor
// HTML webpage with inline CSS styling for icons and layout
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather Station</title>
  <style>
    /* Custom CSS mimicking Bootstrap styles */
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      background-color: #f2f2f2;
      margin: 0;
      padding: 0;
    }
    
    .container {
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .row {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
    }
    .col-md-4 {
      flex: 0 0 100%;
      max-width: 100%;
      padding: 10px;
    }
    @media (min-width: 768px) {
      .col-md-4 {
        flex: 0 0 33.3333%;
        max-width: 33.3333%;
      }
    }
    .card {
      background-color: #ffffff;
      border-radius: 8px;
      box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
      padding: 20px;
      margin: 10px;
      text-align: center;
    }
    .icon {
      font-size: 80px;
      color: #f39c12;
    }
    .data {
      font-size: 2em;
      color: #333;
    }
    h1 {
      font-size: 2em;
      color: #333;
      margin-top: 20px;
    }
  </style>
</head>
<body>

  <div class="container">
    <h1>ESP32 Weather Station</h1>
    <div class="row">
      <div class="col-md-4">
        <div class="card">
          <div class="icon">🌡</div> <!-- Thermometer icon -->
          <div class="data" id="temperature">%TEMPERATURE% ℃</div>
          <p>Temperature</p>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card">
          <div class="icon">💧</div> <!-- Water drop icon -->
          <div class="data" id="humidity">%HUMIDITY% %</div>
          <p>Humidity</p>
        </div>
      </div>
    </div>
  </div>

  <script>
    setInterval(() => {
      fetch('/data').then(response => response.text()).then(data => {
        const [temperature, humidity] = data.split(',');
        document.getElementById('temperature').textContent = `${temperature}`;
        document.getElementById('humidity').textContent = `${humidity} %`;
      });
    }, 1000); // Fetch data every second
  </script>
</body>
</html>
)rawliteral";

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

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("\nWi-Fi connected");
  Serial.println(WiFi.localIP());
  
  // Serve the main page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    String html = index_html;
    html.replace("%TEMPERATURE%", String(temperature, 1));
    html.replace("%HUMIDITY%", String(humidity, 1));
    request->send(200, "text/html", html);
  });

  // Serve data as plain text
  server.on("/data", HTTP_GET, [](AsyncWebServerRequest *request) {
    String data = String(temperature, 1) + "," + String(humidity, 1);
    request->send(200, "text/plain", data);
  });

  // Start server
  server.begin();
}

void loop() {

  // Read DHT11 sensor data every second
  static unsigned long lastRead = 0;
  if (millis() - lastRead >= 1000) {
    lastRead = millis();
    temperature = dht.readTemperature();
    humidity = dht.readHumidity();
    if (isnan(temperature) || isnan(humidity)) {
      Serial.println("Failed to read from DHT sensor!");
      temperature = 0;
      humidity = 0;
    }
    Serial.printf("Temperature: %.1f°C, Humidity: %.1f%%\n", temperature, humidity);
  }
}

Explanation of the Code

  1. WiFi Access Point: The ESP32 operates as a Wi-Fi access point, creating a network named WeatherStation.
  2. Web Server: The ESPAsyncWebServer library serves an HTML file with CSS and JavaScript.
  3. Data Fetching: Every second, the JavaScript fetches updated sensor data from /data.
  4. Captive Portal Redirect: Any attempt to access an undefined page redirects the user to the main dashboard.

REQUIRED LIBRARIES

  1. DHT Sensor Library
    • Library Name: DHT sensor library by Adafruit
    • Purpose: Reads temperature and humidity from the DHT11 sensor.
    • Installation: Search for DHT sensor library in the Arduino Library Manager (Tools > Manage Libraries).
    • Additional Requirement: This library also requires the Adafruit Unified Sensor library, so install that as well if you haven’t already.
  2. ESPAsyncWebServer
    • Library Name: ESPAsyncWebServer by ESP32Async
    • Purpose: Simplifies the creation of a web server on the ESP32, handling client requests and serving HTML/CSS/JavaScript.
    • Installation: This library is not available in the Library Manager by default. You need to download it manually from ESPAsyncWebServer GitHub Repository and install it by placing it in the libraries folder in your Arduino IDE directory.
  3. AsyncTCP
    • Library Name: AsyncTCP by ESP32Async
    • Purpose: Required for ESPAsyncWebServer to handle asynchronous requests.
    • Installation: Download from the AsyncTCP GitHub Repository and place it in the libraries folder.

DEMONSTRATION

Hardware

ESP32 and DHT11 hardware image

Serial Monitor Output

Open the Serial Monitor and wait for the ESP32 to connect to Wi-Fi. Once connected, the ESP32 web server’s IP address will be displayed on the Serial Monitor, as shown below:

Web Dashboard

Copy the IP address from the Serial Monitor and enter it in your browser to access the weather station webpage.

The ESP32 web dashboard shows live temperature and humidity data collected from the ESP32 and DHT11 sensor, making it easy to monitor environmental conditions.


CONCLUSION

This project demonstrates how the ESP32, combined with a few lines of HTML and JavaScript, can create an interactive, real-time weather station. Using Wi-Fi station mode, it can be accessed from any device on the same network, enabling you to monitor environmental data anytime.

This project can be expanded with more sensors, or the design can be customized further with your unique styles. Whether you’re a beginner or experienced with ESP32 projects, this weather station utilizing ESP32 and DHT11 is a fun way to explore IoT and web-based interactions!

Thank You!!!


You can find more amazing ESP32 projects on this website:

YouTube Channel Statistics Display With NodeMCU(ESP8266) And I2C OLED Display – Easy – ArduinoYard

DHT11 With Adafruit.IO: Temp And Hum Monitoring With NodeMCU – ArduinoYard

Leave a Comment