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

Real-Time Monitoring: The ESP32 and DHT11 sensor combination allows real-time temperature and humidity monitoring every second.

Wi-Fi Access Point Mode: The ESP32 creates its own Wi-Fi network, allowing you to access the data locally without internet.

Automatic Data Updates: The webpage refreshes every second to display the latest data, making it feel real-time.

Responsive UI: The webpage layout is responsive and user-friendly for both mobile and desktop devices.


WIRING DIAGRAM

The ESP32 connects to the DHT11 sensor as follows:

DHT11 PinConnection to ESP32
VCCVIN
GNDGND
DATAGPIO 27

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 data from the DHT11 in real-time. The ESP32 operates in Access Point mode, creating its own network with a specific SSID and password. When you connect a device to this network, opening the default browser will lead you to a simple HTML-based dashboard that displays 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 <DNSServer.h>
#include <DHT.h>

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

// Wi-Fi and Server
const char* ssid = "WeatherStation";
const char* password = "";
DNSServer dnsServer;
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();

  // Set ESP32 as an access point
  WiFi.softAP(ssid, password);
  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

  // DNS Server setup for redirection
  dnsServer.start(53, "*", IP);  // Redirect all DNS queries to the ESP32's IP address

  // Redirect all requests to the main index page
  server.onNotFound([](AsyncWebServerRequest *request){
    request->redirect("/index");
  });

  // Serve the main page
  server.on("/index", 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() {
  dnsServer.processNextRequest();

  // 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 me-no-dev
    • 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 me-no-dev
    • Purpose: Required for ESPAsyncWebServer to handle asynchronous requests.
    • Installation: Download from the AsyncTCP GitHub Repository and place it in the libraries folder.
  4. DNSServer
    • Library Name: DNSServer (part of the ESP32 core)
    • Purpose: Handles DNS requests and allows the ESP32 to redirect clients to a captive portal.
    • Installation: No additional installation is required, as it is included in the ESP32 Arduino core.

DEMONSTRATION

Hardware

esp32-and-dht11

Serial Monitor Output

Web Dashboard

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 showcases how the ESP32, along with a few lines of HTML and JavaScript, can be used to create an interactive, real-time weather station. With Wi-Fi AP mode, it’s accessible from any nearby device, allowing you to monitor the environment data at any time.

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