Arduino WebMonitor Example Hướng Dẫn Web-Based Serial Monitor

Tổng Quan

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

Arduino webmonitor example - hướng dẫn web-based serial monitor

Tính Năng

  • Hiển Thị Serial Thời Gian Thực: Xem thông điệp Arduino ngay lập tức trên trình duyệt
  • Nhập 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ễ nhìn
  • Tự Động Cuộn: Tự động cuộn đến thông điệp mới nhất
  • Đánh Dấu Thời Gian: Tất cả thông điệp đều có timestamp
  • Lịch Sử Lệnh: Duyệt 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 monitor
  • Copy/Paste: Hỗ trợ đầy đủ việc chọn và copy văn bản
  • Mở Rộng Nền Tảng: Hiện tại được triển khai cho Arduino Uno R4 WiFi, nhưng có thể mở rộng cho các nền tảng phần cứng khác. Xem DIYables_WebApps_ESP32

Linh Kiện Cần Thiết

1×Arduino UNO R4 WiFi
1×Alternatively, DIYables STEM V4 IoT
1×(Tùy chọn) DIYables STEM V4 IoT
1×Cáp USB Type-C
1×(Khuyến nghị) Screw Terminal Block Shield for Arduino UNO R4
1×(Khuyến nghị) Breadboard Shield for Arduino UNO R4
1×(Khuyến nghị) Enclosure for Arduino UNO R4
1×(Khuyến nghị) Power Splitter for Arduino UNO R4
1×(Khuyến nghị) 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)

Hướng Dẫn Cài Đặt

Các Bước Nhanh

Thực hiện theo hướng dẫn từng bước:

  • Mới sử dụng Arduino Uno R4 WiFi/DIYables STEM V4 IoT? Hãy tham khảo hướng dẫn về Arduino UNO R4 - Cài Đặt Phần Mềm.
  • Kết nối bo mạch Arduino Uno R4/DIYables STEM V4 IoT với máy tính bằng cáp USB.
  • Khởi động Arduino IDE trên máy tính của bạn.
  • Chọn bo mạch Arduino Uno R4 phù hợp (ví dụ: Arduino Uno R4 WiFi) và cổng COM.
  • Điều hướng đến biểu tượng Libraries trên thanh bên trái của Arduino IDE.
  • Tìm kiếm "DIYables WebApps", sau đó tìm thư viện DIYables WebApps của DIYables
  • Nhấp nút Install để cài đặt thư viện.
Arduino UNO R4 diyables webapps thư viện
  • Bạn sẽ được hỏi về việc cài đặt một số thư viện phụ thuộc khác
  • Nhấp nút Install All để cài đặt tất cả thư viện phụ thuộc.
Arduino UNO R4 diyables webapps dependency
  • Trong Arduino IDE, đi đến File Examples DIYables WebApps WebMonitor example, hoặc copy đoạn code trên và dán vào editor 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: 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]/webmonitor */ #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 UnoR4ServerFactory 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 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 WiFi trong code bằng cách cập nhật các dòng này:
const char WIFI_SSID[] = "YOUR_WIFI_NETWORK"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";
  • Nhấp nút Upload trên Arduino IDE để upload code lên Arduino UNO R4/DIYables STEM V4 IoT
  • Mở Serial Monitor
  • Kiểm tra kết quả trên Serial Monitor. Nó sẽ giống như dưới đây
COM6
Send
DIYables WebApp - Web Monitor Example INFO: Added app / INFO: Added app /web-monitor 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 Monitor: http://192.168.0.2/web-monitor ==========================================
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • Nếu bạn không thấy gì, hãy khởi động lại bo mạch Arduino.
  • Ghi lại đị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 web trên điện thoại hoặc PC của bạn.
  • Ví dụ: http://192.168.0.2
  • Bạn sẽ thấy trang chủ như hình dưới đây:
Arduino UNO R4 diyables webapp home page với web monitor app
  • Nhấp vào liên kết Web Monitor, bạn sẽ thấy giao diện của ứng dụng Web Monitor như dưới đây:
Arduino UNO R4 diyables webapp web monitor app
  • Hoặc bạn cũng có thể truy cập trang trực tiếp bằng địa chỉ IP theo sau bởi /web-monitor. Ví dụ: http://192.168.0.2/web-monitor
  • Thử gửi lệnh đến Arduino của bạn thông qua giao diện web monitor và xem đầu ra serial thời gian thực từ Arduino của bạn.

Cách Sử Dụng

Xem Đầu Ra Serial

  1. Mở giao diện web monitor
  2. Arduino tự động gửi thông điệp trạng thái mỗi 5 giây
  3. Tất cả đầu ra Serial.println() xuất hiện trong monitor
  4. Thông điệp được đánh dấu thời gian tự động

Gửi Lệnh

  1. Nhập lệnh trong trường nhập liệu ở cuối
  2. Nhấn Enter hoặc nhấp nút Send
  3. Arduino xử lý lệnh và phản hồi

Lệnh Tích Hợp

Ví dụ này bao gồm các lệnh minh họa sau:

Điều Khiển LED

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

Lệnh Hệ Thống

  • "status" → Hiển thị trạng thái Arduino 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 thông điệp
  • "memory" → Hiển thị thông tin bộ nhớ trống

Lệnh Debug

  • "test" → Gửi thông điệp thử nghiệm
  • "echo [message]" → Lặp lại thông điệp của bạn
  • "repeat [n] [message]" → Lặp lại thông điệp n lần

Tính Năng Giao Diện

Phím Tắt

  • Enter → Gửi lệnh
  • ↑/↓ Phím Mũi Tên → Duyệt lịch sử lệnh
  • Ctrl+L → Xóa monitor (nếu được triển khai)
  • Ctrl+A → Chọn tất cả văn bản

Điều Khiển Monitor

  • Auto-scroll → Tự động cuộn đến thông điệp mới
  • Clear → Xóa màn hình monitor
  • Copy → Copy văn bản đã chọn vào clipboard

Tùy Chỉnh Sáng Tạo - Xây Dựng Công Cụ Debug Nâng Cao

Mở rộng ví dụ web monitor này để tạo giao diện debug và điều khiển mạnh mẽ cho các dự án của bạn! Thêm lệnh tùy chỉnh, giám sát cảm biến, và trực quan hóa dữ liệu 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 Code

Thành Phần Chính

  1. WebApp Server: Xử lý kết nối HTTP và WebSocket
  2. Monitor Page: Cung cấp giao diện web kiểu terminal
  3. Message Handler: Xử lý các lệnh đến
  4. Serial Bridge: Chuyển tiếp đầu ra Serial đến giao diện web

Hàm Chính

// Xử lý lệnh từ giao diện web void handleWebCommand(String command, String clientId) { // Xử lý lệnh và thực hiện hành động } // Gửi thông điệp đến web monitor void sendToWebMonitor(String message) { // Chuyển tiếp thông điệp qua WebSocket }

Thêm Lệnh Tùy Chỉnh

Để thêm lệnh mới, sửa đổi hàm handleWebCommand:

if (command.startsWith("your_command")) { // Trích xuất tham số String param = command.substring(12); // Sau "your_command" // Thực hiện hành động của bạn digitalWrite(LED_BUILTIN, HIGH); // Gửi phản hồi sendToWebMonitor("Command executed: " + param); }

Ứng Dụng Thực Tiễn

Phát Triển và Debug

void loop() { // Debug các giá trị cảm biến int sensorValue = analogRead(A0); sendToWebMonitor("Sensor A0: " + String(sensorValue)); // Debug biến sendToWebMonitor("Loop count: " + String(loopCount++)); delay(1000); }

Giám Sát Hệ Thống Từ Xa

void checkSystemHealth() { // Giám sát bộ nhớ int freeMemory = getFreeMemory(); sendToWebMonitor("Free memory: " + String(freeMemory) + " bytes"); // Giám sát cảm biến float temperature = getTemperature(); sendToWebMonitor("Temperature: " + String(temperature) + "°C"); // Giám sát kết nối if (WiFi.status() == WL_CONNECTED) { sendToWebMonitor("WiFi: Connected (RSSI: " + String(WiFi.RSSI()) + ")"); } else { sendToWebMonitor("WiFi: Disconnected"); } }

Quản Lý Cấu Hình

// Xử lý lệnh cấu hình if (command.startsWith("config ")) { String setting = command.substring(7); if (setting.startsWith("interval ")) { int interval = setting.substring(9).toInt(); updateInterval = interval * 1000; // Chuyển đổi sang milliseconds sendToWebMonitor("Update interval set to " + String(interval) + " seconds"); } if (setting == "save") { saveConfigToEEPROM(); sendToWebMonitor("Configuration saved to EEPROM"); } }

Tính Năng Nâng Cao

Lọc Thông Điệp

Thêm 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 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); // Phân tích tham số... } else { cmd.name = input; cmd.paramCount = 0; } return cmd; }

Ghi Log Dữ Liệu

Ghi log dữ liệu monitor 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ố

Vấn Đề Thường Gặp

1. Không có đầu ra trong web monitor

  • Kiểm tra Serial.begin() được gọi trong setup()
  • Xác minh kết nối WebSocket (chỉ báo trạng thái xanh)
  • Kiểm tra console của trình duyệt để tìm lỗi

2. Lệnh không hoạt động

  • Đảm bảo lệnh chính xác như được chỉ định
  • Kiểm tra độ nhạy cảm về chữ hoa/thường của lệnh
  • Tìm thông điệp phản hồi trong monitor

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

  • Kiểm tra cường độ tín hiệu WiFi
  • Giảm tần suất thông điệp
  • Xóa cache trình duyệt

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

  • Kiểm tra tính ổn định của mạng
  • Giảm kích thước thông điệp
  • Triển khai logic kết nối lại

Mẹo Debug

Bật debug 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

Giám sát trạng thái WebSocket:

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

Cân Nhắc Bảo Mật

Xác Thực Lệnh

Luôn xác thực lệnh đến:

bool isValidCommand(String command) { // Kiểm tra độ dài lệnh if (command.length() > 100) return false; // Kiểm tra ký tự nguy hiểm if (command.indexOf("\\") >= 0 || command.indexOf("/") >= 0) return false; // Kiểm tra với danh sách cho phép 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) { // Kiểm tra ủy quyền client return authorizedClients.indexOf(clientId) >= 0; }

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) { // Đọc nhiều cảm biến int light = analogRead(A0); int temp = analogRead(A1); int humidity = analogRead(A2); // Gửi dữ liệu được định dạng String data = "Sensors - Light: " + String(light) + ", Temp: " + String(temp) + ", Humidity: " + String(humidity); sendToWebMonitor(data); lastSensorRead = millis(); } }

Giám Sát Nhà Thông Minh

void monitorHome() { // Cảm biến cửa if (digitalRead(DOOR_SENSOR) == HIGH) { sendToWebMonitor("ALERT: Front door opened"); } // Phát hiện chuyển động if (digitalRead(PIR_SENSOR) == HIGH) { sendToWebMonitor("Motion detected in living room"); } // Giám sát môi trường float temp = dht.readTemperature(); if (temp > 25.0) { sendToWebMonitor("WARNING: Temperature high (" + String(temp) + "°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 API Reference
  • Truy cập hướng dẫn DIYables: https://newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-diyables-webapps
  • Diễn đàn cộng đồng Arduino