Ví dụ ESP32 WebMonitor Hướng dẫn Serial Monitor dựa trên Web

Tổng quan

Ví dụ WebMonitor thay thế Serial Monitor truyền thống bằng một giao diện dựa trên web có thể truy cập từ mọi thiết bị trên mạng của bạn. Được thiết kế cho nền tảng giáo dục ESP32 với khả năng IoT được nâng cao, giám sát cảm biến tích hợp sẵn và tích hợp liền mạch với hệ sinh thái giáo dục.

ví dụ Arduino webmonitor - hướng dẫn trình giám sát nối tiếp dựa trên web

Các tính năng

  • Đầu ra nối tiếp thời gian thực: Xem các thông điệp ESP32 ngay lập tức trong trình duyệt
  • Đầu vào lệnh: Gửi lệnh từ giao diện web đến Arduino
  • Giao diện tối: Giao diện kiểu Terminal dễ mắt
  • Tự cuộn: Tự động cuộn đến các tin nhắn mới nhất
  • Dấu thời gian: Tất cả các tin nhắn đều có dấu thời gian
  • Lịch sử lệnh: Điều hướng các lệnh trước bằng phím mũi tên
  • Chức năng Xóa: Xóa màn hình hiển thị
  • Sao chép/Dán: Hỗ trợ chọn và sao chép toàn bộ văn bản

Phần cứng cần chuẩn bị

1×mô-đun phát triển ESP-WROOM-32
1×Alternatively, ESP32 Uno-form board
1×Alternatively, ESP32 S3 Uno-form board
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×(Khuyến nghị) Screw Terminal Expansion Board for ESP32
1×(Khuyến nghị) Breakout Expansion Board for ESP32
1×(Khuyến nghị) 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)

Hướng dẫn cài đặt

Các bước nhanh

Hãy làm theo các hướng dẫn này theo từng bước.

  • Nếu đây là lần đầu tiên bạn sử dụng ESP32, hãy tham khảo hướng dẫn về ESP32 - Cài Đặt Phần Mềm.
  • Kết nối bo mạch ESP32 với máy tính của bạn bằng cáp USB.
  • Mở Arduino IDE trên máy tính của bạn.
  • Chọn bo mạch 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 phát hành.
  • Nhấn nút Cài đặt để cài đặt thư viện.
thư viện ESP32 webapps của diyables
  • Bạn sẽ được yêu cầu cài đặt một số phụ thuộc thư viện khác
  • Nhấp nút Cài đặt Tất cả để cài đặt tất cả các phụ thuộc thư viện.
phụ thuộc ESP32 webapps của diyables
  • Trên Arduino IDE, vào Tệp Ví dụ DIYables ESP32 WebApps WebMonitor ví dụ, hoặc sao chép mã ở trên và dán vào trình soạn thảo của Arduino IDE
/* * DIYables WebApp Library - Web Monitor Example * * This example demonstrates the Web Monitor feature: * - Real-time serial monitor in web browser * - Send commands from browser to Arduino * - Automatic message timestamping * * Hardware: ESP32 Boards * * 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]/webmonitor */ #include <DIYables_ESP32_Platform.h> #include <DIYablesWebApps.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 ESP32ServerFactory serverFactory; DIYablesWebAppServer webAppsServer(serverFactory, 80, 81); DIYablesHomePage homePage; DIYablesWebMonitorPage webMonitorPage; // Demo variables unsigned long lastMessage = 0; int messageCount = 0; void setup() { Serial.begin(9600); delay(1000); Serial.println("DIYables ESP32 WebApp - Web Monitor Example"); // Add home and web monitor pages webAppsServer.addApp(&homePage); webAppsServer.addApp(&webMonitorPage); // Optional: Add 404 page for better user experience webAppsServer.setNotFoundPage(DIYablesNotFoundPage()); // Initialize LED for status indication pinMode(LED_BUILTIN, OUTPUT); // Start the WebApp server if (!webAppsServer.begin(WIFI_SSID, WIFI_PASSWORD)) { while (1) { Serial.println("Failed to start WebApp server!"); delay(1000); } } // Set up monitor callback for incoming commands webMonitorPage.onWebMonitorMessage([](const String& message) { Serial.println("Command from web: " + message); // Process simple commands if (message == "LED_ON") { digitalWrite(LED_BUILTIN, HIGH); webMonitorPage.sendToWebMonitor("LED turned ON"); return; } if (message == "LED_OFF") { digitalWrite(LED_BUILTIN, LOW); webMonitorPage.sendToWebMonitor("LED turned OFF"); return; } if (message == "STATUS") { String status = "Arduino Status: LED=" + String(digitalRead(LED_BUILTIN) ? "ON" : "OFF"); webMonitorPage.sendToWebMonitor(status); return; } if (message == "HELP") { webMonitorPage.sendToWebMonitor("Available commands: LED_ON, LED_OFF, STATUS, HELP"); return; } webMonitorPage.sendToWebMonitor("Unknown command: " + message); }); // Send welcome message webMonitorPage.sendToWebMonitor("Arduino Web Monitor ready!"); webMonitorPage.sendToWebMonitor("Type HELP for available commands"); } void loop() { // Handle WebApp server communications webAppsServer.loop(); // Send periodic updates to web monitor if (millis() - lastMessage > 5000) { // Every 5 seconds messageCount++; // Send sensor readings or status updates String message = "Message #" + String(messageCount) + " - Uptime: " + String(millis() / 1000) + "s"; webMonitorPage.sendToWebMonitor(message); lastMessage = millis(); } // Add your main application code here delay(10); }
  • Cấu hình thông tin đăng nhập WiFi trong mã bằng cách cập nhật các dòng sau:
const char WIFI_SSID[] = "YOUR_WIFI_NETWORK"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";
  • Nhấp vào nút Tải lên trên Arduino IDE để tải mã nguồn lên ESP32
  • Mở Serial Monitor
  • Xem kết quả trên Serial Monitor. Nó trông như dưới đây
COM6
Send
DIYables WebApp - Web Monitor Example INFO: Added app / INFO: Added app /web-monitor 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 Monitor: http://192.168.0.2/web-monitor ==========================================
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • Nếu bạn không nhìn thấy gì, hãy khởi động lại bo mạch ESP32.
  • Ghi nhận địa chỉ IP được hiển thị, và nhập địa chỉ này vào thanh địa chỉ của trình duyệt trên điện thoại thông minh hoặc máy tính của bạn.
  • Ví dụ: http://192.168.0.2
  • Bạn sẽ thấy trang chủ như hình dưới đây:
trang chủ webapp ESP32 diyables với ứng dụng web monitor
  • Nhấp vào liên kết Web Monitor, bạn sẽ thấy giao diện người dùng của ứng dụng Web Monitor như dưới đây:
Ứng dụng giám sát web cho ESP32 diyables webapp
  • 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-monitor. Ví dụ: http://192.168.0.2/web-monitor
  • Hãy thử gửi các lệnh tới ESP32 của bạn thông qua giao diện web monitor và xem đầu ra nối tiếp theo thời gian thực từ Arduino của bạn.

Cách Sử Dụng

Xem đầu ra của cổng nối tiếp

  1. Mở giao diện giám sát trên web
  2. ESP32 tự động gửi thông điệp trạng thái mỗi 5 giây
  3. Tất cả đầu ra từ Serial.println() xuất hiện trên màn hình giám sát
  4. Các thông điệp được gắn dấu thời gian tự động

Gửi Các Lệnh

  1. Gõ lệnh vào ô nhập ở dưới cùng
  2. Nhấn phím Enter hoặc bấm nút Gửi
  3. ESP32 xử lý lệnh và phản hồi

Các lệnh tích hợp sẵn

Ví dụ này bao gồm các lệnh trình diễn sau đây:

Điều khiển LED

  • "led on" → Bật đèn LED tích hợp
  • "led off" → Tắt đèn LED tích hợp
  • "led toggle" → Chuyển đổi trạng thái đèn LED
  • "blink" → Nháy đèn LED 3 lần

Các lệnh hệ thống

  • "status" → Hiển thị trạng thái ESP32 và thời gian hoạt động
  • "help" → Liệt kê các lệnh có sẵn
  • "reset counter" → Đặt lại bộ đếm tin nhắn
  • "memory" → Hiển thị thông tin bộ nhớ khả dụng

Các lệnh gỡ lỗi

  • "test" → Gửi tin nhắn kiểm tra
  • "echo [message]" → In lại tin nhắn của bạn
  • "repeat [n] [message]" → Lặp lại tin nhắn n lần

Các tính năng của giao diện

Phím tắt

  • Phím Enter → Gửi lệnh
  • ↑/↓ Phím mũi tên → Điều hướng lịch sử lệnh
  • Ctrl+L → Xóa màn hình (nếu được triển khai)
  • Ctrl+A → Chọn toàn bộ văn bản

Điều khiển màn hình

  • Auto-scroll → Tự động cuộn đến tin nhắn mới
  • Clear → Xóa màn hình
  • Copy → Sao chép văn bản được chọn vào khay nhớ tạm

Tùy biến sáng tạo - Xây dựng công cụ gỡ lỗi nâng cao của bạn

Mở rộng ví dụ về trình giám sát web này để tạo giao diện gỡ lỗi và điều khiển mạnh mẽ cho các dự án của bạn! Thêm các lệnh tùy chỉnh, giám sát cảm biến và trực quan hóa dữ liệu theo thời gian thực để phù hợp với nhu cầu sáng tạo của bạn.

Cấu trúc mã nguồn

Các Thành Phần Chính

  1. Máy chủ WebApp: Xử lý các kết nối HTTP và WebSocket
  2. Trang giám sát: Cung cấp giao diện web kiểu terminal
  3. Bộ xử lý tin nhắn: Xử lý các lệnh đến
  4. Cầu nối Serial: Chuyển tiếp đầu ra Serial tới giao diện web

Các chức năng chính

// Handle commands from web interface void handleWebCommand(String command, String clientId) { // Process command and execute actions } // Send message to web monitor void sendToWebMonitor(String message) { // Forward message via WebSocket }

Thêm các lệnh tùy chỉnh

Để thêm các lệnh mới, hãy chỉnh sửa hàm handleWebCommand:

if (command.startsWith("your_command")) { // Extract parameters String param = command.substring(12); // After "your_command" // Execute your action digitalWrite(LED_BUILTIN, HIGH); // Send response sendToWebMonitor("Command executed: " + param); }

Ứng dụng thực tế

Phát triển và gỡ lỗi

void loop() { // Debug sensor readings int sensorValue = analogRead(A0); sendToWebMonitor("Sensor A0: " + String(sensorValue)); // Debug variables sendToWebMonitor("Loop count: " + String(loopCount++)); delay(1000); }

Giám sát hệ thống từ xa

void checkSystemHealth() { // Monitor memory int freeMemory = getFreeMemory(); sendToWebMonitor("Free memory: " + String(freeMemory) + " bytes"); // Monitor sensors float temperature = getTemperature(); sendToWebMonitor("Temperature: " + String(temperature) + "°C"); // Monitor connectivity if (WiFi.status() == WL_CONNECTED) { sendToWebMonitor("WiFi: Connected (RSSI: " + String(WiFi.RSSI()) + ")"); } else { sendToWebMonitor("WiFi: Disconnected"); } }

Quản lý cấu hình

// Handle configuration commands if (command.startsWith("config ")) { String setting = command.substring(7); if (setting.startsWith("interval ")) { int interval = setting.substring(9).toInt(); updateInterval = interval * 1000; // Convert to milliseconds sendToWebMonitor("Update interval set to " + String(interval) + " seconds"); } if (setting == "save") { saveConfigToEEPROM(); sendToWebMonitor("Configuration saved to EEPROM"); } }

Các tính năng nâng cao

Lọc tin nhắn

Thêm các loại thông điệp và lọc:

enum MessageType { INFO, WARNING, ERROR, DEBUG }; void sendToWebMonitor(String message, MessageType type = INFO) { String prefix; switch(type) { case WARNING: prefix = "[WARN] "; break; case ERROR: prefix = "[ERROR] "; break; case DEBUG: prefix = "[DEBUG] "; break; default: prefix = "[INFO] "; } webMonitorPage.sendMessage(prefix + message); }

Phân tích Lệnh

Triển khai phân tích cú pháp lệnh phức tạp:

struct Command { String name; String parameters[5]; int paramCount; }; Command parseCommand(String input) { Command cmd; int spaceIndex = input.indexOf(' '); if (spaceIndex > 0) { cmd.name = input.substring(0, spaceIndex); // Parse parameters... } else { cmd.name = input; cmd.paramCount = 0; } return cmd; }

Ghi nhật ký dữ liệu

Ghi dữ liệu giám sát vào thẻ SD hoặc EEPROM:

#include <SD.h> void logMessage(String message) { File logFile = SD.open("monitor.log", FILE_WRITE); if (logFile) { logFile.print(millis()); logFile.print(": "); logFile.println(message); logFile.close(); } }

Khắc phục sự cố

Các sự cố phổ biến

1. Không có đầu ra trong trình giám sát web

  • Kiểm tra Serial.begin() được gọi trong setup()
  • Kiểm tra kết nối WebSocket (biểu tượng trạng thái xanh)
  • Kiểm tra bảng điều khiển trình duyệt để xem lỗi

2. Các lệnh không hoạt động

  • Đảm bảo các lệnh chính xác như đã chỉ định
  • Kiểm tra phân biệt chữ hoa chữ thường của lệnh
  • Tìm các thông điệp phản hồi trên màn hình

3. Giao diện tải chậm

  • Kiểm tra cường độ tín hiệu WiFi
  • Giảm tần suất tin nhắn
  • Xóa bộ nhớ cache của trình duyệt

4. Ngắt kết nối WebSocket

  • Kiểm tra độ ổn định của mạng
  • Giảm kích thước tin nhắn
  • Triển khai logic tái kết nối

Mẹo gỡ lỗi

Bật gỡ lỗi chi tiết:

#define DEBUG_WEBMONITOR 1 #if DEBUG_WEBMONITOR #define DEBUG_PRINT(x) Serial.print(x) #define DEBUG_PRINTLN(x) Serial.println(x) #else #define DEBUG_PRINT(x) #define DEBUG_PRINTLN(x) #endif

Theo dõi trạng thái WebSocket:

void checkWebSocketStatus() { if (server.getClientCount() > 0) { sendToWebMonitor("WebSocket clients connected: " + String(server.getClientCount())); } }

Các yếu tố bảo mật

Xác thực lệnh

Luôn kiểm tra các lệnh đến:

bool isValidCommand(String command) { // Check command length if (command.length() > 100) return false; // Check for dangerous characters if (command.indexOf("\\") >= 0 || command.indexOf("/") >= 0) return false; // Check against whitelist String allowedCommands[] = {"led", "status", "help", "test"}; String cmdName = command.substring(0, command.indexOf(' ')); for (String allowed : allowedCommands) { if (cmdName.equals(allowed)) return true; } return false; }

Kiểm soát truy cập

Triển khai xác thực cơ bản:

bool isAuthorized(String clientId) { // Check client authorization return authorizedClients.indexOf(clientId) >= 0; }

Các ví dụ tích hợp

Hệ thống Giám sát Cảm biến

void monitorSensors() { static unsigned long lastSensorRead = 0; if (millis() - lastSensorRead > 5000) { // Read multiple sensors int light = analogRead(A0); int temp = analogRead(A1); int humidity = analogRead(A2); // Send formatted data String data = "Sensors - Light: " + String(light) + ", Temp: " + String(temp) + ", Humidity: " + String(humidity); sendToWebMonitor(data); lastSensorRead = millis(); } }

Giám sát Tự động hóa Gia đình

void monitorHome() { // Door sensors if (digitalRead(DOOR_SENSOR) == HIGH) { sendToWebMonitor("ALERT: Front door opened"); } // Motion detection if (digitalRead(PIR_SENSOR) == HIGH) { sendToWebMonitor("Motion detected in living room"); } // Environmental monitoring float temp = dht.readTemperature(); if (temp > 25.0) { sendToWebMonitor("WARNING: Temperature high (" + String(temp) + "°C)"); } }

Các bước tiếp theo

Sau khi thành thạo ví dụ WebMonitor, hãy thử:

  1. Chat - Để giao tiếp tương tác
  2. DigitalPins - Để điều khiển đầu ra
  3. Slider - Để điều khiển giá trị analog
  4. MultipleWebApps - Kết hợp giám sát với điều khiển

Hỗ trợ

Để được hỗ trợ thêm:

  • Kiểm tra tài liệu tham khảo API
  • Truy cập các hướng dẫn DIYables: https://esp32io.com/tutorials/diyables-esp32-webapps
  • Diễn đàn cộng đồng ESP32