Ví dụ ESP32 WebRTC Hướng dẫn giao diện đồng hồ thời gian thực
Tổng quan
Ví dụ WebRTC cung cấp một giao diện đồng hồ thời gian thực toàn diện cho các dự án ESP32 của bạn. Được thiết kế cho nền tảng giáo dục ESP32 với khả năng RTC tích hợp, các tính năng quản lý thời gian được nâng cao và tích hợp liền mạch với hệ sinh thái giáo dục. Bạn có thể hiển thị thông tin đồng hồ thời gian thực, đồng bộ thời gian từ trình duyệt web sang Arduino, và theo dõi sự chênh lệch thời gian thông qua giao diện web trực quan.
Các tính năng
Hiển thị đồng hồ thời gian thực: Hiển thị thời gian RTC của ESP32 hiện tại với cập nhật tự động
So sánh thời gian thiết bị: Hiển thị thời gian của trình duyệt web và thiết bị cùng với thời gian ESP32
Đồng bộ thời gian bằng một cú nhấp chuột: Đồng bộ RTC ESP32 với thời gian của trình duyệt web ngay lập tức
Chỉ báo trực quan sự chênh lệch thời gian: Hiển thị sự lệch thời gian giữa các thiết bị bằng phút
Định dạng thời gian hai dòng: Định dạng 12 giờ theo AM/PM với hiển thị đầy đủ ngày tháng
Giao diện gradient hiện đại: Bố cục dạng thẻ với thiết kế đáp ứng
Giao tiếp WebSocket: Cập nhật thời gian thực hai chiều mà không cần làm mới trang
Đồng bộ theo múi giờ: Sử dụng thời gian của thiết bị địa phương để đồng bộ chính xác
Giám sát trạng thái kết nối: Dấu hiệu trực quan cho trạng thái kết nối WebSocket
Yêu cầu thời gian tự động: Yêu cầu thời gian ESP32 hiện tại khi tải trang
Nếu đây là lần đầu tiên bạn sử dụng ESP32, hãy tham khảo bài hướng dẫn về thiết lập môi trường cho ESP32 trong Arduino IDE (ESP32 - Cài Đặt Phần Mềm).
Kết nối board ESP32 với máy tính bằng cáp USB.
Mở Arduino IDE trên máy tính của bạn.
Chọn board ESP32 phù hợp (ví dụ ESP32 Dev Module) và cổng COM.
Đi tới biểu tượng Thư viện ở thanh bên trái của Arduino IDE.
Tìm kiếm "DIYables ESP32 WebApps", sau đó tìm thư viện DIYables ESP32 WebApps do DIYables
Nhấn nút Cài đặt để cài đặt thư viện.
Bạn sẽ được yêu cầu cài đặt một số phụ thuộc thư viện khác.
Nhấp vào nút Cài đặt Tất cả để cài đặt tất cả các phụ thuộc thư viện.
Tìm kiếm “RTClib”, sau đó tìm thư viện RTC của Adafruit.
Nhấn vào nút Cài đặt để cài đặt thư viện RTC.
Bạn có thể được yêu cầu cài đặt các phụ thuộc cho thư viện.
Cài đặt toàn bộ các phụ thuộc cho thư viện bằng cách nhấp vào nút Cài đặt Tất cả.
Trên Arduino IDE, Chuyển tới Tệp Ví dụ DIYables ESP32 WebApps WebRTC ví dụ, hoặc sao chép mã ở trên và dán nó vào trình soạn thảo của 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 objectRTC_DS3231 rtc;char daysOfWeek[7][12] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};// WiFi credentials - UPDATE THESE WITH YOUR NETWORKconstchar WIFI_SSID[] = "YOUR_WIFI_SSID";constchar WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";// Create WebApp server and page instancesESP32ServerFactory serverFactory;DIYablesWebAppServerwebAppsServer(serverFactory, 80, 81);DIYablesHomePage homePage;DIYablesWebRTCPage webRTCPage;voidsetup() {Serial.begin(9600);delay(1000);Serial.println("DIYables ESP32 WebApp - Web RTC Example");// Initialize RTCif (!rtc.begin()) {Serial.println("RTC module is NOT found");Serial.flush();while (1); }// Check if RTC lost power and if so, set the timeif (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 timeDateTime 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 serverwebAppsServer.addApp(&homePage);webAppsServer.addApp(&webRTCPage);// Optional: Add 404 page for better user experiencewebAppsServer.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 serverif (!webAppsServer.begin(WIFI_SSID, WIFI_PASSWORD)) {while (1) {Serial.println("Failed to connect to WiFi");delay(1000); } }}voidloop() {// Handle web serverwebAppsServer.loop();// Send current time to web clients and print to Serial every 1 secondstaticunsignedlong lastUpdate = 0;if (millis() - lastUpdate >= 1000) { lastUpdate = millis();// Get current RTC timeDateTime 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 MonitorSerial.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 commandvoid onTimeSyncReceived(unsignedlong unixTimestamp) {Serial.print("Time sync received: ");Serial.println(unixTimestamp);// Convert Unix timestamp to DateTime and set RTC timeDateTime newTime(unixTimestamp); rtc.adjust(newTime);Serial.println("ESP32 RTC synchronized!");}// Callback function called when web client requests current ESP32 timevoid onTimeRequested() {// Get current RTC time and send to web in human readable formatDateTime currentTime = rtc.now(); webRTCPage.sendTimeToWeb(currentTime.year(), currentTime.month(), currentTime.day(), currentTime.hour(), currentTime.minute(), currentTime.second());}
Cấu hình thông tin xác thực WiFi trong mã bằng cách cập nhật các dòng này:
Nhấp nút Tải lên trên Arduino IDE để tải mã lên Arduino.
Mở Trình theo dõi Serial trên Arduino IDE
Chờ kết nối với WiFi và các thông tin WiFi được in ra trên Serial Monitor.
Xem kết quả trên Serial Monitor. Nó trông như dưới đây
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
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
==========================================
Ln 11, Col 1
ESP32 Dev Module on COM15
2
Nếu bạn không thấy gì, hãy khởi động lại bo mạch ESP32.
Sử dụng Giao diện Web
Mở trình duyệt web trên máy tính hoặc thiết bị di động của bạn đang kết nối với cùng một mạng WiFi
Nhập địa chỉ IP được hiển thị trong Serial Monitor vào trình duyệt web
Ví dụ: http://192.168.1.100
Bạn sẽ thấy trang chủ như hình dưới đây:
Nhấp vào liên kết Web RTC, bạn sẽ thấy giao diện người dùng của ứng dụng Web RTC như dưới đây:
Hoặc bạn cũng có thể truy cập trang này trực tiếp bằng địa chỉ IP kèm theo /web-rtc. Ví dụ: http://192.168.1.100/web-rtc
Bạn sẽ thấy giao diện Web RTC được hiển thị:
Thời gian của Arduino: Thời gian hiện tại từ RTC của Arduino
Thời gian thiết bị của bạn: Thời gian hiện tại từ trình duyệt web/thiết bị của bạn
Hiệu thời gian: Sự khác biệt giữa hai thời điểm, tính bằng phút
Nút đồng bộ thời gian ESP32: Nhấn để đồng bộ thời gian ESP32 với thiết bị của bạn
Đồng bộ hóa thời gian
Nhấp vào nút "Đồng bộ thời gian ESP32" để đồng bộ thời gian RTC của Arduino với thời gian địa phương trên thiết bị của bạn
Quá trình đồng bộ hóa:
Lấy thời gian địa phương hiện tại của thiết bị bạn (không phải UTC)
Điều chỉnh cho lệch múi giờ để đảm bảo đồng bộ thời gian địa phương chính xác
Gửi dấu thời gian tới Arduino thông qua WebSocket
Arduino cập nhật RTC của nó bằng thời gian nhận được
Giao diện web cập nhật để hiển thị thời gian đã đồng bộ
Sau khi đồng bộ, sự chênh lệch thời gian nên tối thiểu (thường từ 0-1 phút)
ESP32 sẽ duy trì thời gian chính xác ngay cả khi giao diện web đã đóng
Giải thích mã nguồn
Các Thành Phần Chính
#include <DIYablesWebApps.h>#include <RTClib.h>// Initialize RTC object and web serverRTC_DS3231 rtc;DIYablesWebAppServer server;DIYablesWebRTCPage rtcPage;// Days of week array for displaychar daysOfWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday"};
Hàm Thiết Lập
voidsetup() {Serial.begin(9600);// Initialize DS3231 RTC moduleif (!rtc.begin()) {Serial.println("RTC module is NOT found");Serial.flush();while (1); }// Check if RTC lost power and set time if neededif (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();}
Các hàm gọi lại
Hàm gọi lại đồng bộ thời gian:
// Called when web interface sends time sync commandvoid onTimeSyncReceived(unsignedlong unixTimestamp) {Serial.print("Time sync received: ");Serial.println(unixTimestamp);// Convert Unix timestamp to DateTime and set RTC timeDateTime newTime(unixTimestamp); rtc.adjust(newTime);Serial.println("ESP32 RTC synchronized!");}
Gọi lại cho yêu cầu thời gian:
// Called when web interface requests current ESP32 timevoid 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() );}
Vòng lặp chính
voidloop() { server.handleClient();// Send current time to web clients every 1 secondstaticunsignedlong 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 MonitorSerial.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);}
Các phương thức API
Các phương thức của lớp DIYablesWebRTCPage
onTimeSyncFromWeb(callback)
Thiết lập hàm gọi lại để xử lý đồng bộ thời gian từ trình duyệt web
Tham số: void (*callback)(unsignedlong unixTimestamp)
Cách sử dụng: Được gọi khi người dùng nhấp vào nút "Đồng bộ thời gian ESP32"
yêu cầu đúng giờ tới Web (callback)
Thiết lập hàm gọi lại để xử lý các yêu cầu thời gian từ trình duyệt web
Tham số: void (*callback)()
Cách sử dụng: Được gọi khi giao diện web yêu cầu thời gian hiện tại của ESP32
sendTimeToWeb(năm, tháng, ngày, giờ, phút, giây)
Gửi thời gian hiện tại của ESP32 tới giao diện web
Thông số:
year: Năm hiện tại (ví dụ: 2025)
month: Tháng hiện tại (1-12)
day: Ngày hiện tại của tháng (1-31)
hour: Giờ hiện tại (0-23)
minute: Phút hiện tại (0-59)
second: Giây hiện tại (0-59)
Giao tiếp WebSocket
Tin nhắn từ Web đến Arduino
RTC:GET_TIME - Yêu cầu thời gian hiện tại của ESP32
RTC:SYNC:[timestamp] - Đồng bộ thời gian ESP32 với Unix timestamp
Các tin nhắn từ ESP32 đến Web
DATETIME:YYYY,MM,DD,HH,MM,SS - Gửi các thành phần thời gian hiện tại của ESP32
Khắc phục sự cố
Các vấn đề phổ biến
Chênh lệch thời gian kéo dài vài giờ
Vấn đề: ESP32 hiển thị thời gian lệch vài giờ so với thời gian của thiết bị
Nguyên nhân: Thường là vấn đề về múi giờ hoặc RTC chưa được khởi tạo đúng
Giải pháp:*
Nhấp vào nút "Sync ESP32 Time" để đồng bộ lại thời gian.
Kiểm tra xem RTC có được khởi tạo đúng trong setup() không?
Kiểm tra xem kết nối WiFi có ổn định không
Lỗi "Mô-đun RTC không được tìm thấy"
Vấn đề: mô-đun RTC không được phát hiện trong quá trình khởi tạo
Nguyên nhân: Mô-đun DS3231 được kết nối không đúng hoặc bị hỏng
Giải pháp:
Kiểm tra kết nối I2C (SDA tới GPIO 21, SCL tới GPIO 22)
Kiểm tra kết nối nguồn (VCC đến 3.3V/5V, GND về GND)
Kiểm tra bằng máy quét I2C để phát hiện địa chỉ của mô-đun
Hãy thử các mô-đun DS3231 khác nếu có.
Lỗi "Không kết nối với Arduino"
Vấn đề: Lỗi khi nhấn nút đồng bộ
Nguyên nhân: Kết nối WebSocket thất bại
Giải pháp:
Kiểm tra xem địa chỉ IP của ESP32 có đúng không
Làm mới trang web
Xác nhận ESP32 đã được kết nối với cùng một mạng WiFi
Kiểm tra cài đặt tường lửa
Thời gian ngừng cập nhật
Lỗi: Hiển thị thời gian bị treo hoặc không cập nhật
Nguyên nhân: Kết nối WebSocket bị mất hoặc RTC ngừng hoạt động
Giải pháp:
Làm mới trang web
Kiểm tra trạng thái kết nối WebSocket
Khởi động lại ESP32 nếu RTC ngừng phản hồi
4. Sự chênh lệch thời gian lớn (ngày/tháng)
Vấn đề: Chênh lệch thời gian hiển thị lên tới hàng nghìn phút
Nguyên nhân: RTC chưa được thiết lập đúng hoặc đã lệch đáng kể
Giải pháp: Nhấn nút đồng bộ nhiều lần và kiểm tra các hàm gọi lại
Mẹo gỡ lỗi
Bật gỡ lỗi nối tiếp:
void onTimeSyncReceived(unsignedlong unixTimestamp) {Serial.print("Time sync received: ");Serial.println(unixTimestamp);// ... rest of function}void onTimeRequested() {Serial.println("Time request received from web");// ... rest of function}
Kiểm tra khởi tạo RTC:
voidsetup() {// ... other setup codeif (!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__))); }}
void checkScheduledActions() {DateTime currentTime = rtc.now();// Turn on LED every day at 6:00 AMif (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 PMif (currentTime.hour() == 22 && currentTime.minute() == 0 && currentTime.second() == 0) {digitalWrite(LED_BUILTIN, LOW);Serial.println("Evening LED deactivated!"); }}
Tích hợp nhiều ứng dụng web
// Combine WebRTC with other web appsserver.addWebApp(rtcPage); // Real-time clockserver.addWebApp(monitorPage); // Serial monitor with timestampsserver.addWebApp(plotterPage); // Data plotting with time axis
Ứng dụng và các trường hợp sử dụng
Các dự án giáo dục
Học quản lý thời gian: Dạy cho học sinh về RTC (đồng hồ thời gian thực), việc theo dõi thời gian và đồng bộ hóa
Các khái niệm thời gian IoT: Trình diễn đồng bộ hóa thời gian mạng trong các hệ thống IoT
Các dự án ghi nhật ký dữ liệu: Thêm dấu thời gian cho các phép đo của cảm biến và các thí nghiệm
Các hệ thống lập lịch: Tạo các hệ thống tự động hóa và điều khiển dựa trên thời gian
Các ứng dụng thực tế
Tự động hóa tại nhà: Lên lịch cho đèn, hệ thống tưới nước, hoặc các thiết bị khác
Thu thập dữ liệu: Ghi nhận dấu thời gian của các phép đo cảm biến để phân tích
Ghi nhận sự kiện: Ghi lại thời điểm xảy ra các sự kiện cụ thể một cách chính xác
Giám sát từ xa: Kiểm tra trạng thái thiết bị và thời gian cập nhật lần cuối từ xa
Lợi ích của giáo dục STEM
Khái niệm múi giờ: Hiểu thời gian địa phương so với UTC và cách xử lý múi giờ
Giao tiếp mạng: Học cách giao tiếp qua WebSocket và cập nhật thời gian thực
Tích hợp phần cứng: Kết hợp giao diện web với chức năng RTC của phần cứng
Giải quyết vấn đề: Gỡ lỗi các vấn đề về thời gian và đồng bộ hóa
Thông số kỹ thuật
Sử dụng bộ nhớ
Bộ nhớ Flash: ~8KB dành cho chức năng WebRTC
SRAM: ~2KB trong quá trình vận hành
Bộ đệm WebSocket: ~1KB cho xử lý tin nhắn
Đặc tính hiệu suất
Tần suất cập nhật: Cập nhật thời gian thực qua WebSocket
Độ chính xác đồng bộ: Thông thường trong khoảng 1-2 giây
Chi phí mạng: ~50 byte cho mỗi tin nhắn cập nhật thời gian
Thời gian phản hồi: <100 ms cho các thao tác đồng bộ thời gian
Tương thích
Các bo mạch ESP32: ESP32, Ứng dụng Web ESP32
Các trình duyệt: Tất cả các trình duyệt hiện đại có hỗ trợ WebSocket
Các thiết bị: Máy tính để bàn, máy tính bảng và thiết bị di động
Các mạng: Các mạng WiFi có kết nối Internet
Video hướng dẫn
Video demo bên dưới sử dụng đoạn mã bên dưới:
/* * Mã ESP32 này được phát triển bởi newbiely.vn * Mã ESP32 này được cung cấp để sử dụng công khai, không có ràng buộc. * Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: * https://newbiely.vn/tutorials/esp32/diyables-esp32-web-apps-web-rtc *//** * @file SmartPillReminder_ESP32.ino * @brief IoT Medication Reminder System using ESP32 and an external I2C DS3231 RTC module. * * This firmware integrates an asynchronous Web Server for RTC synchronization, * a MAX7219 8x32 LED Matrix driven via SPI, and a discrete GPIO active buzzer peripheral. * Memory safety is enforced via static char buffer allocation to prevent runtime heap corruption. * * Hardware Connections: * - DS3231 SDA -> ESP32 GPIO 21 (Default I2C SDA pin) * - DS3231 SCL -> ESP32 GPIO 22 (Default I2C SCL pin) * - MAX7219 VCC -> 5V * - MAX7219 GND -> GND * - MAX7219 DIN -> ESP32 MOSI (Default GPIO 23) * - MAX7219 CLK -> ESP32 SCK (Default GPIO 18) * - MAX7219 CS -> GPIO 25 (Configured SPI Chip Select pin) * - Active Buzzer -> GPIO 15 (Configured Digital Output pin) */#include <DIYables_ESP32_Platform.h>#include <DIYablesWebApps.h>#include <RTClib.h>#include <MD_Parola.h>#include <MD_MAX72xx.h>// --- PERIPHERAL INSTANTIATION ---RTC_DS3231 rtc;// --- NETWORK CONFIGURATION ---constchar WIFI_SSID[] = "YOUR_WIFI_SSID";constchar WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";// --- WEB SERVER ROUTING ENGINE ---ESP32ServerFactory serverFactory;DIYablesWebAppServerwebAppsServer(serverFactory, 80, 81);DIYablesHomePage homePage;DIYablesWebRTCPage webRTCPage;// --- DISPLAY SUBSYSTEM CONFIGURATION ---#define HARDWARE_TYPE MD_MAX72XX::FC16_HW// Hardware register layout variant for physical modules#define MAX_DEVICES 4 // Number of cascaded 8x8 matrix blocks#define CS_PIN 25 // SPI Chip Select active-low hardware pinMD_Parola ledMatrix = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);// --- ALARM SUBSYSTEM ARCHITECTURE ---constint BUZZER_PIN = 15;bool isAlarming = false; // State flag to prevent redundant re-initialization of display bufferstypedefstruct {inthour;intminute;} AlarmTime;// Scheduled alarm arrays for validationconstint TOTAL_ALARMS = 3;AlarmTime medicationAlarms[TOTAL_ALARMS] = { {9, 9}, // Slot 1 {9, 11}, // Slot 2 {9, 12} // Slot 3};// Fixed-size static allocation to prevent dangling pointers during stack deallocationchar AlertMsg[50] = "";char daysOfWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};// --- CALLBACK FUNCTION PROTOTYPES ---void onTimeSyncReceived(unsignedlong unixTimestamp);void onTimeRequested();/** * @brief Hardware initialization routine. */voidsetup() {Serial.begin(115200); // Updated to match default ESP32 bootloader speed to eliminate garbage textdelay(1000);// Configure GPIO peripheralspinMode(BUZZER_PIN, OUTPUT);digitalWrite(BUZZER_PIN, LOW);// Initialize SPI-driven LED Matrix ledMatrix.begin(); ledMatrix.setIntensity(8); // Brightness optimization register value to prevent camera sensor overexposure ledMatrix.displayClear();// Set initial boot token into display queue ledMatrix.displayText("Medicine Reminder System READY", PA_LEFT, 60, 2000, PA_SCROLL_LEFT, PA_SCROLL_LEFT);Serial.println("[SYS] Starting firmware initialization pipeline...");// Initialize I2C clock communication busif (!rtc.begin()) {Serial.println("[ERR] Fatal: DS3231 hardware module not detected on I2C bus.");Serial.flush();while (1); }// Verify internal register state; apply fallback parameters if compile parameters mismatchif (rtc.lostPower()) {Serial.println("[RTC] Power down event detected. Aligning internal clock parameters to compile time."); rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); }// Construct Web App HTTP server routing layerswebAppsServer.addApp(&homePage);webAppsServer.addApp(&webRTCPage);webAppsServer.setNotFoundPage(DIYablesNotFoundPage());// Attach synchronization service event hooks webRTCPage.onTimeSyncFromWeb(onTimeSyncReceived); webRTCPage.onTimeRequestToWeb(onTimeRequested);// Initialize network link layer socket connectionif (!webAppsServer.begin(WIFI_SSID, WIFI_PASSWORD)) {while (1) {Serial.println("[NET] Fatal: Network connection timed out.");delay(1000); } }Serial.print("[NET] Infrastructure active. Resource path accessible via: http://");Serial.println(WiFi.localIP());}/** * @brief Infinite loop processing task pipelines. */voidloop() {// Service inbound network sockets and data frame handshakeswebAppsServer.loop();// Non-blocking shift engine: Calculates next step pixel translations on every passif (ledMatrix.displayAnimate()) { ledMatrix.displayReset(); }// Time-sliced task execution block running at a strict 1000ms polling intervalstaticunsignedlong lastUpdate = 0;if (millis() - lastUpdate >= 1000) { lastUpdate = millis();// Query immediate system states from the DS3231 tracking registersDateTime currentTime = rtc.now();int currentH = currentTime.hour();int currentM = currentTime.minute();int currentS = currentTime.second();// Output status parameters to local tracking streamSerial.print("[LOG] Time Status: ");Serial.print(currentH); Serial.print(":");Serial.print(currentM); Serial.print(":");Serial.println(currentS);// SEQUENTIAL SEARCH SCAN ACROSS ACTIVE ALARM VECTORSfor (int i = 0; i < TOTAL_ALARMS; i++) {if (currentH == medicationAlarms[i].hour && currentM == medicationAlarms[i].minute && currentS == 0) {// Conditional block protecting display memory boundaries from re-entrant override bugsif (!isAlarming) { isAlarming = true;// Print safe formatted characters straight to locked char index slots// %02d ensures leading zeros are preserved flawlessly (e.g. [23:43]) sprintf(AlertMsg, "TAKE MEDICATION ! [%02d:%02d] ", currentH, currentM); ledMatrix.displayClear(); // Link structural char reference space to the active render queue ledMatrix.displayText(AlertMsg, PA_LEFT, 60, 0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);Serial.print("[ALARM] Trigger event confirmed at slot ID: ");Serial.println(i + 1); } } }// Auto-timeout block: Clears active alert metrics after 20 elapsed secondsif (currentS >= 20 && isAlarming) { isAlarming = false; ledMatrix.displayClear(); ledMatrix.displayText("Medicine Reminder System With WEB RTC", PA_LEFT, 60, 0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);Serial.println("[ALARM] Trigger window expired. Display registers reset to default state."); }// Synchronize network clock states with browser clients (Executed at bottom to shield SPI lines) webRTCPage.sendTimeToWeb(currentTime.year(), currentTime.month(), currentTime.day(), currentH, currentM, currentS); }// Asynchronous Active Buzzer Duty Cycle Control (50% duty cycle, 1Hz rate square-wave generator)if (isAlarming) {staticunsignedlong lastBuzzerToggle = 0;if (millis() - lastBuzzerToggle >= 500) { lastBuzzerToggle = millis();digitalWrite(BUZZER_PIN, !digitalRead(BUZZER_PIN)); // Invert state logic } } else {digitalWrite(BUZZER_PIN, LOW); // Enforce noise suppression when system state is idle }delay(10); // System cycle stabilizer trashing delay}/** * @brief Processes epoch update queries coming down from external browser UI sync commands. * @param unixTimestamp Incoming epoch time tracking token. */void onTimeSyncReceived(unsignedlong unixTimestamp) {Serial.print("[NET] Inbound synchronization frame detected: ");Serial.println(unixTimestamp);DateTime newTime(unixTimestamp); rtc.adjust(newTime); // Write updated parameters straight to external RTC register cellsSerial.println("[RTC] External DS3231 synchronization routine complete.");}/** * @brief Processes outbound interface frame payload requests from polling web hosts. */void onTimeRequested() {DateTime currentTime = rtc.now(); webRTCPage.sendTimeToWeb(currentTime.year(), currentTime.month(), currentTime.day(), currentTime.hour(), currentTime.minute(), currentTime.second());}
Tóm tắt
Ví dụ WebRTC minh họa cách thực hiện:
Tạo giao diện đồng hồ thời gian thực dựa trên web
Đồng bộ hóa RTC của ESP32 với thời gian của trình duyệt web
Hiển thị thông tin thời gian ở định dạng thân thiện với người dùng
Giám sát sự chênh lệch thời gian và trạng thái kết nối
Tích hợp chức năng thời gian với các ứng dụng web khác
Xây dựng các dự án IoT giáo dục với các tính năng quản lý thời gian
Ví dụ này rất phù hợp với các dự án yêu cầu thời gian chính xác, ghi dữ liệu có dấu thời gian, tự động hóa theo lịch trình và các minh họa giáo dục về khái niệm đồng bộ hóa thời gian trong các hệ thống IoT.