DIYables Web Apps Web Rtc

WebRTC Example - Setup Instructions

Overview

The WebRTC example provides a comprehensive real-time clock interface for your Arduino projects. Designed for Arduino Uno R4 WiFi and DIYables STEM V4 IoT 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 Arduino RTC time with automatic updates
  • Device Time Comparison: Display web browser/device time alongside Arduino time
  • One-click Time Synchronization: Sync Arduino 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 Arduino time on page load
  • Platform Extensible: Currently implemented for Arduino Uno R4 WiFi, but can be extended for other hardware platforms. See DIYables_WebApps_ESP32

Hardware Preparation

1×Arduino UNO R4 WiFi
1×Alternatively, DIYables STEM V4 IoT
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×Recommended: Screw Terminal Block Shield for Arduino UNO R4
1×Recommended: Breadboard Shield for Arduino UNO R4
1×Recommended: Enclosure for Arduino UNO R4
1×Recommended: Power Splitter for Arduino UNO R4
1×Recommended: Prototyping Base Plate & Breadboard Kit for Arduino UNO

Or you can buy the following kits:

1×DIYables STEM V4 IoT Starter Kit (Arduino included)
1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

Setup Instructions

Detailed Instructions

Follow these instructions step by step:

  • If this is your first time using the Arduino Uno R4 WiFi/DIYables STEM V4 IoT, refer to the tutorial on setting up the environment for Arduino Uno R4 WiFi/DIYables STEM V4 IoT in the Arduino IDE.
  • Connect the Arduino Uno R4/DIYables STEM V4 IoT board to your computer using a USB cable.
  • Launch the Arduino IDE on your computer.
  • Select the appropriate Arduino Uno R4 board (e.g., Arduino Uno R4 WiFi) and COM port.
  • Navigate to the Libraries icon on the left bar of the Arduino IDE.
  • Search "DIYables WebApps", then find the DIYables WebApps library by DIYables
  • Click Install button to install the library.
Arduino UNO R4 DIYables WebApps library
  • You will be asked for installing some other library dependencies
  • Click Install All button to install all library dependencies.
Arduino UNO R4 DIYables WebApps dependency
  • On Arduino IDE, Go to File Examples DIYables 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 Arduino and client device * - One-click time synchronization from web browser to Arduino * - Hardware RTC integration for persistent timekeeping * - Visual time difference monitoring * * Hardware: Arduino Uno R4 WiFi or DIYables STEM V4 IoT * * Setup: * 1. Update WiFi credentials below * 2. Upload the sketch to your Arduino * 3. Open Serial Monitor to see the IP address * 4. Navigate to http://[IP_ADDRESS]/web-rtc */ #include <DIYablesWebApps.h> #include "RTC.h" // 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 UnoR4ServerFactory serverFactory; DIYablesWebAppServer webAppsServer(serverFactory, 80, 81); DIYablesHomePage homePage; DIYablesWebRTCPage webRTCPage; void setup() { Serial.begin(9600); delay(1000); Serial.println("DIYables WebApp - Web RTC Example"); // Initialize RTC RTC.begin(); // Check if RTC is running and set initial time if needed RTCTime savedTime; RTC.getTime(savedTime); if (!RTC.isRunning() || savedTime.getYear() == 2000) { Serial.println("RTC is NOT running, setting initial time..."); // Set a default time - you can modify this to match current time RTCTime startTime(28, Month::AUGUST, 2025, 12, 0, 0, DayOfWeek::THURSDAY, SaveLight::SAVING_TIME_ACTIVE); RTC.setTime(startTime); Serial.println("RTC initialized with default time"); } else { Serial.println("RTC is already running"); } // Print initial RTC time RTCTime initialTime; RTC.getTime(initialTime); Serial.print("Initial RTC Time: "); Serial.print(initialTime.getYear()); Serial.print("/"); Serial.print(Month2int(initialTime.getMonth())); Serial.print("/"); Serial.print(initialTime.getDayOfMonth()); Serial.print(" - "); if (initialTime.getHour() < 10) Serial.print("0"); Serial.print(initialTime.getHour()); Serial.print(":"); if (initialTime.getMinutes() < 10) Serial.print("0"); Serial.print(initialTime.getMinutes()); Serial.print(":"); if (initialTime.getSeconds() < 10) Serial.print("0"); Serial.print(initialTime.getSeconds()); 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 RTCTime currentTime; RTC.getTime(currentTime); // Send time to web clients in human readable format webRTCPage.sendTimeToWeb(currentTime.getYear(), Month2int(currentTime.getMonth()), currentTime.getDayOfMonth(), currentTime.getHour(), currentTime.getMinutes(), currentTime.getSeconds()); // Print time to Serial Monitor Serial.print("RTC Time: "); Serial.print(currentTime.getYear()); Serial.print("/"); Serial.print(Month2int(currentTime.getMonth())); Serial.print("/"); Serial.print(currentTime.getDayOfMonth()); Serial.print(" - "); if (currentTime.getHour() < 10) Serial.print("0"); Serial.print(currentTime.getHour()); Serial.print(":"); if (currentTime.getMinutes() < 10) Serial.print("0"); Serial.print(currentTime.getMinutes()); Serial.print(":"); if (currentTime.getSeconds() < 10) Serial.print("0"); Serial.print(currentTime.getSeconds()); 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 RTCTime RTCTime newTime; newTime.setUnixTime(unixTimestamp); // Set RTC time RTC.setTime(newTime); Serial.println("Arduino RTC synchronized!"); } // Callback function called when web client requests current Arduino time void onTimeRequested() { // Get current RTC time and send to web in human readable format RTCTime currentTime; RTC.getTime(currentTime); webRTCPage.sendTimeToWeb(currentTime.getYear(), Month2int(currentTime.getMonth()), currentTime.getDayOfMonth(), currentTime.getHour(), currentTime.getMinutes(), currentTime.getSeconds()); }
  • 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 WebApp - Web RTC Example RTC is already running Initial RTC Time: 2025/8/28 - 12:00:08 INFO: Added app / INFO: Added app /web-rtc DIYables WebApp Library Platform: Arduino Uno R4 WiFi 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 Arduino 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:
Arduino UNO R4 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:
Arduino UNO R4 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 Arduino Time Button: Click to synchronize Arduino time with your device

    Time Synchronization

    • Click the "Sync Arduino Time" button to synchronize the Arduino's RTC with your device's local time
    Arduino UNO R4 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 Arduino will maintain accurate time even after the web interface is closed

Code Explanation

Key Components

#include <DIYablesWebApps.h> #include <RTC.h> // Initialize web server and RTC page DIYablesWebAppServer server; DIYablesWebRTCPage rtcPage;

Setup Function

void setup() { Serial.begin(9600); // Initialize RTC RTC.begin(); // 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 RTCTime RTCTime newTime; newTime.setUnixTime(unixTimestamp); // Set RTC time RTC.setTime(newTime); Serial.println("Arduino RTC synchronized!"); }

Time Request Callback:

// Called when web interface requests current Arduino time void onTimeRequested() { RTCTime currentTime; RTC.getTime(currentTime); // Send current time to web interface rtcPage.sendTimeToWeb( currentTime.getYear(), currentTime.getMonth(), currentTime.getDayOfMonth(), currentTime.getHour(), currentTime.getMinutes(), currentTime.getSeconds() ); }

Main Loop

void loop() { server.handleClient(); // Optional: Print current time every 10 seconds static unsigned long lastPrint = 0; if (millis() - lastPrint > 10000) { RTCTime currentTime; RTC.getTime(currentTime); Serial.print("Current Arduino Time: "); Serial.print(currentTime.getHour()); Serial.print(":"); if (currentTime.getMinutes() < 10) Serial.print("0"); Serial.print(currentTime.getMinutes()); Serial.print(":"); if (currentTime.getSeconds() < 10) Serial.print("0"); Serial.println(currentTime.getSeconds()); lastPrint = millis(); } 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 Arduino 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 Arduino time

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

  • Sends current Arduino 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 Arduino time
    • RTC:SYNC:[timestamp] - Sync Arduino time with Unix timestamp

    Messages from Arduino to Web

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

    Troubleshooting

    Common Issues

    1. Time Difference of Several Hours

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

      2. "Not connected to Arduino" Error

      • Issue: Error when clicking sync button
      • Cause: WebSocket connection failed
      • Solution:
        • Check if Arduino IP address is correct
        • Refresh the web page
        • Verify Arduino 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 Arduino 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 initialized successfully"); } else { Serial.println("RTC initialization failed!"); } }

          Advanced Usage

          Data Logging with Timestamps

          void logSensorData(float temperature, float humidity) { RTCTime currentTime; RTC.getTime(currentTime); String logEntry = String(currentTime.getYear()) + "-" + String(currentTime.getMonth()) + "-" + String(currentTime.getDayOfMonth()) + " " + String(currentTime.getHour()) + ":" + String(currentTime.getMinutes()) + ":" + String(currentTime.getSeconds()) + " - " + "Temp: " + String(temperature) + "°C, " + "Humidity: " + String(humidity) + "%"; Serial.println(logEntry); // Save to SD card, send to database, etc. }

          Scheduled Actions

          void checkScheduledActions() { RTCTime currentTime; RTC.getTime(currentTime); // Turn on LED every day at 6:00 AM if (currentTime.getHour() == 6 && currentTime.getMinutes() == 0) { digitalWrite(LED_BUILTIN, HIGH); Serial.println("Morning LED activated!"); } // Turn off LED every day at 10:00 PM if (currentTime.getHour() == 22 && currentTime.getMinutes() == 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

          • Arduino Boards: Arduino Uno R4 WiFi, DIYables STEM V4 IoT
          • 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 Arduino 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

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!