portfolio

Adding a Web Interface

Course Content
Session 1: Introduction to ESP32
Objective: Get familiar with the ESP32 microcontroller and set up the development environment.
0/5
Session 2: Interfacing with Sensors and Displays
Learn how to connect a DHT22 sensor and an OLED display to the ESP32.
0/4
Session 4: Programming the OLED Display
Objective: Write code to display information on the OLED display.
0/4
Session 5: Integrating Sensor Data with OLED Display
Objective: Combine sensor readings with OLED display functionality.
0/1
Session 6: Setup WIFI Capability
0/1
Session 7: Adding a Webserver
0/1
Session 8: Wrap-up
0/1
ESP32 Basics
About Lesson

To add a web interface to the previous code, we can use the built-in web server on the ESP32. The web interface will allow you to view the temperature and humidity data via a web browser on any device connected to the same Wi-Fi network.

We’ll use the ESPAsyncWebServer library, which is efficient and handles web requests asynchronously.

Key Steps:

  1. Set up the ESPAsyncWebServer to serve a simple HTML page showing the DHT22 sensor data.
  2. Use JavaScript and AJAX to periodically update the temperature and humidity values on the web interface without needing to refresh the page.

Install Required Libraries:

  1. ESPAsyncWebServer library
  2. AsyncTCP library (required by ESPAsyncWebServer)

Complete Code with Web Interface:

C++
#include <WiFiManager.h>         // WiFiManager for easy Wi-Fi configuration
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#include <ESPAsyncWebServer.h>   // For the web server

// OLED display settings
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET    -1 // We don't use reset pin on most OLEDs
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// DHT22 settings
#define DHTPIN 4          // GPIO pin for DHT22
#define DHTTYPE DHT22     // DHT22 sensor type
DHT dht(DHTPIN, DHTTYPE);

// Create an AsyncWebServer object on port 80
AsyncWebServer server(80);

// Variables to store DHT22 data
float temperatureF;
float humidity;

void setup() {
  // Start the Serial Monitor
  Serial.begin(115200);

  // Initialize DHT22
  dht.begin();

  // Initialize the OLED display
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }

  // Clear display buffer
  display.clearDisplay();

  // Start WiFiManager to auto-connect to Wi-Fi
  WiFiManager wifiManager;
  wifiManager.autoConnect("ESP32_DHT22_OLED");

  // Once connected, show success message on OLED
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.println("Connected to Wi-Fi");
  display.display();
  delay(2000);  // Wait for 2 seconds
  
  // Clear the screen for sensor data
  display.clearDisplay();

  // Define the root page handler to show HTML interface
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    String html = "<html><head><meta http-equiv='refresh' content='5'/>"
                  "<title>ESP32 DHT22</title></head><body>"
                  "<h1>ESP32 DHT22 Sensor Data</h1>"
                  "<p>Temperature: " + String(temperatureF) + " °F</p>"
                  "<p>Humidity: " + String(humidity) + " %</p>"
                  "</body></html>";
    request->send(200, "text/html", html);
  });

  // Start the server
  server.begin();
}

void loop() {
  // Read temperature and humidity from DHT22
  humidity = dht.readHumidity();
  temperatureF = dht.readTemperature(true);  // Fahrenheit

  // Check if readings are valid
  if (isnan(humidity) || isnan(temperatureF)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // Clear the OLED display before showing new data
  display.clearDisplay();

  // Display temperature on OLED
  display.setCursor(0, 10);
  display.setTextSize(2);
  display.println("Temp:");
  display.setTextSize(2);
  display.setCursor(0, 30);
  display.print(temperatureF);
  display.println(" F");

  // Display humidity on OLED
  display.setCursor(0, 50);
  display.setTextSize(2);
  display.print("Hum:");
  display.setCursor(0, 70);
  display.print(humidity);
  display.println(" %");

  // Update the OLED display with new values
  display.display();

  // Print the same data to Serial Monitor for debugging
  Serial.print("Temperature: ");
  Serial.print(temperatureF);
  Serial.print(" F, Humidity: ");
  Serial.print(humidity);
  Serial.println(" %");

  // Wait a few seconds between measurements
  delay(2000);
}

How This Code Works:

  1. WiFiManager: Automatically connects to the Wi-Fi network using a portal for initial configuration.
  2. OLED Display: Displays the current temperature and humidity values on the OLED screen.
  3. Web Server: Hosts a basic web interface that shows the temperature and humidity values. The HTML page refreshes every 5 seconds to fetch the latest data.
    • server.on("/", HTTP_GET, ...) sets up the root endpoint (“/”) to respond with a basic HTML page showing the current temperature and humidity values.

Web Interface:

When you access the ESP32’s IP address (printed on the serial monitor after connecting to Wi-Fi), the web page will display the DHT22 data. The page refreshes every 5 seconds to display the updated data.

Example Web Page Output:

HTML
ESP32 DHT22 Sensor Data

Temperature: 75.4 °F
Humidity: 60 %

You can adjust the HTML page in the server.on() function to customize how the data is displayed. This setup allows real-time monitoring of the sensor data over Wi-Fi.