DIYables ESP32 Web Apps Web Rtc

Overview

The WebRTC example provides a comprehensive real-time clock interface for your ESP32 projects. Designed for ESP32 educational platform with built-in RTC capabilities, enhanced time management features, and seamless integration with the educational ecosystem. You can display real-time clock information, synchronize time from web browser to Arduino, and monitor time differences through an intuitive web interface.

Arduino WebRTC Example - Real-Time Clock Interface Tutorial

Features

  • Real-time Clock Display: Shows current ESP32 RTC time with automatic updates
  • Device Time Comparison: Display web browser/device time alongside ESP32 time
  • One-click Time Synchronization: Sync ESP32 RTC with web browser time instantly
  • Visual Time Difference Indicator: Shows time drift between devices in minutes
  • Two-line Time Format: 12-hour AM/PM format with full date display
  • Modern Gradient UI: Card-style layout with responsive design
  • WebSocket Communication: Real-time bidirectional updates without page refresh
  • Timezone-aware Synchronization: Uses local device time for accurate sync
  • Connection Status Monitoring: Visual indicators for WebSocket connection state
  • Automatic Time Requests: Requests current ESP32 time on page load

Hardware Used In This Tutorial

1×ESP-WROOM-32 Dev Module
1×USB Cable Type-A to Type-C (for USB-A PC)
1×USB Cable Type-C to Type-C (for USB-C PC)
1×Real-Time Clock DS3231 Module
1×CR2032 battery
1×Jumper Wires
1×Breadboard
1×Recommended: Screw Terminal Expansion Board for ESP32
1×Recommended: Breakout Expansion Board for ESP32
1×Recommended: Power Splitter for ESP32

Or you can buy the following kits:

1×DIYables ESP32 Starter Kit (ESP32 included)
1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links in this section are Amazon affiliate links, meaning we may earn a commission at no additional cost to you if you make a purchase through them. Additionally, some links direct you to products from our own brand, DIYables .

Wiring Diagram

ESP32 Real-Time Clock DS3231 Wiring Diagram

This image is created using Fritzing. Click to enlarge image

ESP32 - DS3231 RTC Module

DS1307 RTC Module ESP32
Vin 3.3V
GND GND
SDA GPIO21
SCL GPIO22

If you're unfamiliar with how to supply power to the ESP32 and other components, you can find guidance in the following tutorial: The best way to Power ESP32 and sensors/displays.

Quick Instructions

Follow these instructions step by step:

  • If this is your first time using the ESP32, refer to the tutorial on setting up the environment for ESP32 in the Arduino IDE.
  • Connect the ESP32 board to your computer using a USB cable.
  • Launch the Arduino IDE on your computer.
  • Select the appropriate ESP32 board (e.g. ESP32 Dev Module) and COM port.
  • Navigate to the Libraries icon on the left bar of the Arduino IDE.
  • Search "DIYables ESP32 WebApps", then find the DIYables ESP32 WebApps Library by DIYables
  • Click Install button to install the library.
DIYables ESP32 WebApps Library
  • You will be asked for installing some other library dependencies
  • Click Install All button to install all library dependencies.
DIYables ESP32 WebApps dependency
  • Search “RTClib”, then find the RTC library by Adafruit
  • Click Install button to install RTC library.
ESP32 RTC library
  • You may be asked to install dependencies for the library
  • Install all dependencies for the library by clicking on Install All button.
ESP32 Adafruit BusIO library
  • On Arduino IDE, Go to File Examples DIYables ESP32 WebApps WebRTC example, or copy the above code and paste it to the editor of Arduino IDE
/* * DIYables WebApp Library - Web RTC Example * * This example demonstrates the Web RTC feature: * - Real-time clock display for both ESP32 and client device * - One-click time synchronization from web browser to ESP32 * - Hardware RTC integration for persistent timekeeping * - Visual time difference monitoring * * Hardware Required: * - ESP32 development board * - DS3231 RTC module (connected via I2C) * * Required Libraries: * - RTClib library (install via Library Manager) * * Setup: * 1. Connect DS3231 RTC module to ESP32 I2C pins (SDA/SCL) * 2. Install RTClib library in Arduino IDE * 3. Update WiFi credentials below * 4. Upload the sketch to your ESP32 * 5. Open Serial Monitor to see the IP address * 6. Navigate to http://[IP_ADDRESS]/web-rtc */ #include <DIYables_ESP32_Platform.h> #include <DIYablesWebApps.h> #include <RTClib.h> // RTC object RTC_DS3231 rtc; char daysOfWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; // WiFi credentials - UPDATE THESE WITH YOUR NETWORK const char WIFI_SSID[] = "YOUR_WIFI_SSID"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // Create WebApp server and page instances ESP32ServerFactory serverFactory; DIYablesWebAppServer webAppsServer(serverFactory, 80, 81); DIYablesHomePage homePage; DIYablesWebRTCPage webRTCPage; void setup() { Serial.begin(9600); delay(1000); Serial.println("DIYables ESP32 WebApp - Web RTC Example"); // Initialize RTC if (!rtc.begin()) { Serial.println("RTC module is NOT found"); Serial.flush(); while (1); } // Check if RTC lost power and if so, set the time if (rtc.lostPower()) { Serial.println("RTC lost power, setting time!"); // When time needs to be set on a new device, or after a power loss, the // following line sets the RTC to the date & time this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // This line sets the RTC with an explicit date & time, for example to set // January 21, 2021 at 3am you would call: // rtc.adjust(DateTime(2021, 1, 21, 3, 0, 0)); } // Print initial RTC time DateTime initialTime = rtc.now(); Serial.print("Initial RTC Time: "); Serial.print(initialTime.year(), DEC); Serial.print("/"); Serial.print(initialTime.month(), DEC); Serial.print("/"); Serial.print(initialTime.day(), DEC); Serial.print(" ("); Serial.print(daysOfWeek[initialTime.dayOfTheWeek()]); Serial.print(") "); if (initialTime.hour() < 10) Serial.print("0"); Serial.print(initialTime.hour(), DEC); Serial.print(":"); if (initialTime.minute() < 10) Serial.print("0"); Serial.print(initialTime.minute(), DEC); Serial.print(":"); if (initialTime.second() < 10) Serial.print("0"); Serial.print(initialTime.second(), DEC); Serial.println(); // Add pages to server webAppsServer.addApp(&homePage); webAppsServer.addApp(&webRTCPage); // Optional: Add 404 page for better user experience webAppsServer.setNotFoundPage(DIYablesNotFoundPage()); // Set callback for time sync from web webRTCPage.onTimeSyncFromWeb(onTimeSyncReceived); // Set callback for time request from web webRTCPage.onTimeRequestToWeb(onTimeRequested); // Start the WebApp server if (!webAppsServer.begin(WIFI_SSID, WIFI_PASSWORD)) { while (1) { Serial.println("Failed to connect to WiFi"); delay(1000); } } } void loop() { // Handle web server webAppsServer.loop(); // Send current time to web clients and print to Serial every 1 second static unsigned long lastUpdate = 0; if (millis() - lastUpdate >= 1000) { lastUpdate = millis(); // Get current RTC time DateTime currentTime = rtc.now(); // Send time to web clients in human readable format webRTCPage.sendTimeToWeb(currentTime.year(), currentTime.month(), currentTime.day(), currentTime.hour(), currentTime.minute(), currentTime.second()); // Print time to Serial Monitor Serial.print("RTC Time: "); Serial.print(currentTime.year(), DEC); Serial.print("/"); Serial.print(currentTime.month(), DEC); Serial.print("/"); Serial.print(currentTime.day(), DEC); Serial.print(" ("); Serial.print(daysOfWeek[currentTime.dayOfTheWeek()]); Serial.print(") "); if (currentTime.hour() < 10) Serial.print("0"); Serial.print(currentTime.hour(), DEC); Serial.print(":"); if (currentTime.minute() < 10) Serial.print("0"); Serial.print(currentTime.minute(), DEC); Serial.print(":"); if (currentTime.second() < 10) Serial.print("0"); Serial.print(currentTime.second(), DEC); Serial.println(); } delay(10); } // Callback function called when web client sends time sync command void onTimeSyncReceived(unsigned long unixTimestamp) { Serial.print("Time sync received: "); Serial.println(unixTimestamp); // Convert Unix timestamp to DateTime and set RTC time DateTime newTime(unixTimestamp); rtc.adjust(newTime); Serial.println("ESP32 RTC synchronized!"); } // Callback function called when web client requests current ESP32 time void onTimeRequested() { // Get current RTC time and send to web in human readable format DateTime currentTime = rtc.now(); webRTCPage.sendTimeToWeb(currentTime.year(), currentTime.month(), currentTime.day(), currentTime.hour(), currentTime.minute(), currentTime.second()); }
  • Configure WiFi credentials in the code by updating these lines:
const char WIFI_SSID[] = "YOUR_WIFI_NETWORK"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";
  • Click Upload button on Arduino IDE to upload the code to Arduino.
  • Open the Serial Monitor on Arduino IDE
  • Wait for the connection to WiFi and the prints of WiFi information on Serial Monitor.
  • Check out the result on Serial Monitor. It looks like the below
COM6
Send
DIYables ESP32 WebApp - Web RTC Example Initial RTC Time: 2025/8/28 (Thursday) 12:00:08 INFO: Added app / INFO: Added app /web-rtc DIYables WebApp Library Platform: ESP32 Network connected! IP address: 192.168.0.2 HTTP server started on port 80 Configuring WebSocket server callbacks... WebSocket server started on port 81 WebSocket URL: ws://192.168.0.2:81 WebSocket server started on port 81 ========================================== DIYables WebApp Ready! ========================================== 📱 Web Interface: http://192.168.0.2 🔗 WebSocket: ws://192.168.0.2:81 📋 Available Applications: 🏠 Home Page: http://192.168.0.2/ 🕐 Web RTC: http://192.168.0.2/web-rtc ==========================================
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • If you do not see anything, reboot ESP32 board.

Using the Web Interface

  • Open a web browser on your computer or mobile device connected to the same WiFi network
  • Type the IP address shown in the Serial Monitor to the web browser
  • Example: http://192.168.1.100
  • You will see the home page like below image:
ESP32 DIYables WebApp Home page with Web RTC app
  • Click to the Web RTC link, you will see the Web RTC app's UI like the below:
ESP32 DIYables WebApp Web RTC app
  • Or you can also access the page directly by IP address followed by /web-rtc. For example: http://192.168.1.100/web-rtc
  • You will see the Web RTC interface showing:
    • Arduino Time: Current time from the Arduino's RTC
    • Your Device Time: Current time from your web browser/device
    • Time Difference: Difference between the two times in minutes
    • Sync ESP32 Time Button: Click to synchronize ESP32 time with your device

Time Synchronization

  • Click the "Sync ESP32 Time" button to synchronize the Arduino's RTC with your device's local time
ESP32 DIYables WebApp Web RTC app
  • The synchronization process:
    1. Gets your device's current local time (not UTC)
    2. Adjusts for timezone offset to ensure accurate local time sync
    3. Sends timestamp to Arduino via WebSocket
    4. Arduino updates its RTC with the received time
    5. Web interface updates to show the synchronized time
  • After synchronization, the time difference should be minimal (usually 0-1 minutes)
  • The ESP32 will maintain accurate time even after the web interface is closed
  • Code Explanation

    Key Components

    #include <DIYablesWebApps.h> #include <RTClib.h> // Initialize RTC object and web server RTC_DS3231 rtc; DIYablesWebAppServer server; DIYablesWebRTCPage rtcPage; // Days of week array for display char daysOfWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

    Setup Function

    void setup() { Serial.begin(9600); // Initialize DS3231 RTC module if (!rtc.begin()) { Serial.println("RTC module is NOT found"); Serial.flush(); while (1); } // Check if RTC lost power and set time if needed if (rtc.lostPower()) { Serial.println("RTC lost power, setting time!"); rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } // Setup WiFi connection server.setupWiFi(WIFI_SSID, WIFI_PASSWORD); // Add RTC page to server server.addWebApp(rtcPage); // Set up callback functions rtcPage.onTimeSyncFromWeb(onTimeSyncReceived); rtcPage.onTimeRequestToWeb(onTimeRequested); // Start the server server.begin(); }

    Callback Functions

    Time Synchronization Callback:

    // Called when web interface sends time sync command void onTimeSyncReceived(unsigned long unixTimestamp) { Serial.print("Time sync received: "); Serial.println(unixTimestamp); // Convert Unix timestamp to DateTime and set RTC time DateTime newTime(unixTimestamp); rtc.adjust(newTime); Serial.println("ESP32 RTC synchronized!"); }

    Time Request Callback:

    // Called when web interface requests current ESP32 time void onTimeRequested() { DateTime currentTime = rtc.now(); // Send current time to web interface rtcPage.sendTimeToWeb( currentTime.year(), currentTime.month(), currentTime.day(), currentTime.hour(), currentTime.minute(), currentTime.second() ); }

    Main Loop

    void loop() { server.handleClient(); // Send current time to web clients every 1 second static unsigned long lastUpdate = 0; if (millis() - lastUpdate >= 1000) { lastUpdate = millis(); DateTime currentTime = rtc.now(); // Send time to web clients rtcPage.sendTimeToWeb(currentTime.year(), currentTime.month(), currentTime.day(), currentTime.hour(), currentTime.minute(), currentTime.second()); // Print time to Serial Monitor Serial.print("RTC Time: "); Serial.print(currentTime.year(), DEC); Serial.print("/"); Serial.print(currentTime.month(), DEC); Serial.print("/"); Serial.print(currentTime.day(), DEC); Serial.print(" ("); Serial.print(daysOfWeek[currentTime.dayOfTheWeek()]); Serial.print(") "); if (currentTime.hour() < 10) Serial.print("0"); Serial.print(currentTime.hour(), DEC); Serial.print(":"); if (currentTime.minute() < 10) Serial.print("0"); Serial.print(currentTime.minute(), DEC); Serial.print(":"); if (currentTime.second() < 10) Serial.print("0"); Serial.print(currentTime.second(), DEC); Serial.println(); } delay(10); }

    API Methods

    DIYablesWebRTCPage Class Methods

    onTimeSyncFromWeb(callback)

    • Sets the callback function to handle time synchronization from web browser
    • Parameter: void (*callback)(unsigned long unixTimestamp)
    • Usage: Called when user clicks "Sync ESP32 Time" button

    onTimeRequestToWeb(callback)

    • Sets the callback function to handle time requests from web browser
    • Parameter: void (*callback)()
    • Usage: Called when web interface requests current ESP32 time

    sendTimeToWeb(year, month, day, hour, minute, second)

    • Sends current ESP32 time to web interface
    • Parameters:
      • year: Current year (e.g., 2025)
      • month: Current month (1-12)
      • day: Current day of month (1-31)
      • hour: Current hour (0-23)
      • minute: Current minute (0-59)
      • second: Current second (0-59)

    WebSocket Communication

    Messages from Web to Arduino

    • RTC:GET_TIME - Request current ESP32 time
    • RTC:SYNC:[timestamp] - Sync ESP32 time with Unix timestamp

    Messages from ESP32 to Web

    • DATETIME:YYYY,MM,DD,HH,MM,SS - Send current ESP32 time components

    Troubleshooting

    Common Issues

    1. Time Difference of Several Hours

    • Issue: ESP32 shows time several hours different from device time
    • Cause: Usually a timezone issue or RTC not properly initialized
    • Solution:
      • Click "Sync ESP32 Time" button to resynchronize
      • Check if RTC is properly initialized in setup()
      • Verify WiFi connection is stable

      2. "RTC module is NOT found" Error

      • Issue: RTC module not detected during initialization
      • Cause: DS3231 module not properly connected or faulty
      • Solution:
        • Check I2C wiring (SDA to GPIO 21, SCL to GPIO 22)
        • Verify power connections (VCC to 3.3V/5V, GND to GND)
        • Test with I2C scanner to detect module address
        • Try different DS3231 module if available

        3. "Not connected to Arduino" Error

        • Issue: Error when clicking sync button
        • Cause: WebSocket connection failed
        • Solution:
          • Check if ESP32 IP address is correct
          • Refresh the web page
          • Verify ESP32 is connected to same WiFi network
          • Check firewall settings

          3. Time Stops Updating

          • Issue: Time display freezes or doesn't update
          • Cause: WebSocket connection lost or RTC stopped
          • Solution:
            • Refresh the web page
            • Check WebSocket connection status
            • Restart ESP32 if RTC stops responding

            4. Large Time Differences (Days/Months)

            • Issue: Time difference shows thousands of minutes
            • Cause: RTC wasn't properly set or has drifted significantly
            • Solution: Click sync button multiple times and verify callback functions

            Debug Tips

            Enable Serial Debugging:

            void onTimeSyncReceived(unsigned long unixTimestamp) { Serial.print("Time sync received: "); Serial.println(unixTimestamp); // ... rest of function } void onTimeRequested() { Serial.println("Time request received from web"); // ... rest of function }

            Check RTC Initialization:

            void setup() { // ... other setup code if (!rtc.begin()) { Serial.println("RTC module is NOT found"); Serial.println("Check I2C wiring:"); Serial.println("SDA -> GPIO 21"); Serial.println("SCL -> GPIO 22"); Serial.println("VCC -> 3.3V or 5V"); Serial.println("GND -> GND"); while (1); } Serial.println("DS3231 RTC initialized successfully"); if (rtc.lostPower()) { Serial.println("RTC lost power, will set to compile time"); rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } }

    Advanced Usage

    Data Logging with Timestamps

    void logSensorData(float temperature, float humidity) { DateTime currentTime = rtc.now(); String logEntry = String(currentTime.year()) + "-" + String(currentTime.month()) + "-" + String(currentTime.day()) + " " + String(currentTime.hour()) + ":" + String(currentTime.minute()) + ":" + String(currentTime.second()) + " (" + String(daysOfWeek[currentTime.dayOfTheWeek()]) + ") - " + "Temp: " + String(temperature) + "°C, " + "Humidity: " + String(humidity) + "%"; Serial.println(logEntry); // Save to SD card, send to database, etc. }

    Scheduled Actions

    void checkScheduledActions() { DateTime currentTime = rtc.now(); // Turn on LED every day at 6:00 AM if (currentTime.hour() == 6 && currentTime.minute() == 0 && currentTime.second() == 0) { digitalWrite(LED_BUILTIN, HIGH); Serial.print("Morning LED activated! Time: "); Serial.print(daysOfWeek[currentTime.dayOfTheWeek()]); Serial.print(" "); Serial.print(currentTime.hour()); Serial.print(":"); Serial.println(currentTime.minute()); } // Turn off LED every day at 10:00 PM if (currentTime.hour() == 22 && currentTime.minute() == 0 && currentTime.second() == 0) { digitalWrite(LED_BUILTIN, LOW); Serial.println("Evening LED deactivated!"); } }

    Multiple Web Apps Integration

    // Combine WebRTC with other web apps server.addWebApp(rtcPage); // Real-time clock server.addWebApp(monitorPage); // Serial monitor with timestamps server.addWebApp(plotterPage); // Data plotting with time axis

    Applications and Use Cases

    Educational Projects

    • Time Management Learning: Teach students about RTC, timekeeping, and synchronization
    • IoT Time Concepts: Demonstrate network time synchronization in IoT systems
    • Data Logging Projects: Add timestamps to sensor readings and experiments
    • Scheduling Systems: Create time-based automation and control systems

    Real-World Applications

    • Home Automation: Schedule lights, irrigation, or other devices
    • Data Acquisition: Timestamp sensor readings for analysis
    • Event Logging: Record when specific events occur with accurate timing
    • Remote Monitoring: Check device status and last update times remotely

    STEM Education Benefits

    • Time Zone Concepts: Understand local time vs. UTC and timezone handling
    • Network Communication: Learn WebSocket communication and real-time updates
    • Hardware Integration: Combine web interfaces with hardware RTC functionality
    • Problem Solving: Debug timing issues and synchronization problems

    Technical Specifications

    Memory Usage

    • Flash Memory: ~8KB for WebRTC functionality
    • SRAM: ~2KB during operation
    • WebSocket Buffer: ~1KB for message handling

    Performance Characteristics

    • Update Frequency: Real-time updates via WebSocket
    • Sync Accuracy: Typically within 1-2 seconds
    • Network Overhead: ~50 bytes per time update message
    • Response Time: <100ms for time sync operations

    Compatibility

    • ESP32 boards: ESP32, ESP32 Web Apps
    • Browsers: All modern browsers with WebSocket support
    • Devices: Desktop, tablet, and mobile devices
    • Networks: WiFi networks with internet access

    Summary

    The WebRTC example demonstrates how to:

    • Create a web-based real-time clock interface
    • Synchronize ESP32 RTC with web browser time
    • Display time information in user-friendly format
    • Monitor time differences and connection status
    • Integrate time functionality with other web applications
    • Build educational IoT projects with time management features

    This example is perfect for projects requiring accurate timekeeping, data logging with timestamps, scheduled automation, and educational demonstrations of time synchronization concepts in IoT systems.

    ※ OUR MESSAGES