Arduino UNO R4 Web Server

Trong hướng dẫn này, chúng tôi sẽ chỉ bạn cách làm cho Arduino UNO R4 R4 WiFi hoạt động như một web server. Bạn có thể truy cập các trang web trên Arduino UNO R4 Web Server bằng trình duyệt web trên máy tính hoặc điện thoại thông minh. Điều này sẽ cho phép bạn xem và thay đổi giá trị trên Arduino UNO R4. Chúng ta sẽ học các bước sau để lập trình Arduino UNO R4 WiFi cho mục đích này:

Arduino UNO R4 web server

Phần Cứng 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)

Đọc giá trị cảm biến từ Arduino UNO R4 qua Web

Code Arduino UNO R4 thực hiện các nhiệm vụ sau:

  • Xây dựng web server nhận các yêu cầu HTTP từ trình duyệt web.
  • Khi trình duyệt web gửi yêu cầu, Arduino UNO R4 phản hồi với:
    • HTTP header
    • HTTP body: Chứa nội dung HTML và dữ liệu cảm biến.

    Đây là code Arduino UNO R4 thực hiện các nhiệm vụ đã đề cập ở trên:

    /* * Mã Arduino UNO R4 này được phát triển bởi newbiely.vn * Mã Arduino UNO R4 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/arduino-uno-r4/arduino-uno-r4-web-server */ #include <UnoR4WiFi_WebServer.h> const char HTML_CONTENT[] PROGMEM = R"rawliteral( <!DOCTYPE HTML> <html> <head> <link rel="icon" href="data:,"> </head> <p> Temperature: <span style="color: red;">%TEMP_PLACE_HOLDER% &deg;C</span> </p> </html> )rawliteral"; // WiFi credentials const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // change your network SSID (name) const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // change your network password // Create web server instance UnoR4WiFi_WebServer server; float getTemperature() { return 26.9456; // YOUR SENSOR IMPLEMENTATION HERE // simulate the temperature value float temp_x100 = random(0, 10000); // a ramdom value from 0 to 10000 return temp_x100 / 100; // return the simulated temperature value from 0 to 100 in float } void handleHome(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { float tempC = getTemperature(); String response = HTML_CONTENT; response.replace("%TEMP_PLACE_HOLDER%", String(tempC, 1)); server.sendResponse(client, response.c_str()); } void setup() { Serial.begin(9600); delay(1000); Serial.println("Arduino Uno R4 WiFi - Web Server"); // Connect to WiFi Serial.print("Connecting to "); Serial.println(WIFI_SSID); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("connected!"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // Configure routes server.addRoute("/", handleHome); // Start server server.begin(); Serial.println("\n=== Web Server Ready! ==="); Serial.print("Visit: http://"); Serial.println(WiFi.localIP()); } void loop() { server.handleClient(); }

    Các Bước Thực Hiện

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

    • Nếu đây là lần đầu tiên bạn sử dụng Arduino Uno R4 WiFi/Minima, 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 với máy tính của bạn 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.
    • Mở Library Manager bằng cách nhấp vào biểu tượng Library Manager ở phía bên trái của Arduino IDE.
    • Tìm kiếm Web Server for Arduino Uno R4 WiFi và tìm thư viện Web Server được tạo bởi DIYables.
    • Nhấp vào nút Install để thêm thư viện Web Server.
    Arduino UNO R4 web server thư viện
    • Sao chép code và mở nó trong Arduino IDE.
    • Thay thế thông tin wifi (SSID và password) trong code bằng thông tin của bạn.
    • Nhấp vào nút Upload trong Arduino IDE để tải code lên Arduino UNO R4.
    • Mở Serial Monitor.
    • Xem kết quả trên Serial Monitor.
    COM6
    Send
    Arduino Uno R4 WiFi - Web Server Connecting to YOUR_WIFI_SSID connected! IP address: 192.168.0.254 Starting web server on IP: 192.168.0.254 === Web Server Ready! === Visit: http://192.168.0.254
    Autoscroll Show timestamp
    Clear output
    9600 baud  
    Newline  
    • Xem địa chỉ IP được hiển thị và nhập nó vào thanh địa chỉ của trình duyệt web trên điện thoại thông minh hoặc máy tính của bạn.
    • Sau đó, bạn sẽ thấy thông tin này trên Serial Monitor.
    COM6
    Send
    Arduino Uno R4 WiFi - Web Server Connecting to YOUR_WIFI_SSID connected! IP address: 192.168.0.254 Starting web server on IP: 192.168.0.254 === Web Server Ready! === Visit: http://192.168.0.254 Method: GET Requested path: / Client disconnected
    Autoscroll Show timestamp
    Clear output
    9600 baud  
    Newline  
    • Khi bạn nhập địa chỉ IP vào trình duyệt web, bạn sẽ thấy một trang web đơn giản hiển thị thông tin về bo mạch Arduino UNO R4. Trang sẽ hiển thị như sau:
    Arduino UNO R4 r4 temperature web browser

    Để tạo trang web có giao diện đồ họa (UI) đẹp mắt, hãy xem phần cuối của hướng dẫn này.

Điều khiển Arduino UNO R4 qua Web

Quản lý thiết bị kết nối với Arduino UNO R4 phức tạp hơn một chút so với việc chỉ kiểm tra giá trị. Sự phức tạp này phát sinh bởi vì Arduino UNO R4 phải diễn giải lệnh nhận được từ trình duyệt web để xác định phản hồi thích hợp. Đây là cách code Arduino UNO R4 xử lý tình huống này:

  • Xây dựng web server nhận các yêu cầu HTTP từ trình duyệt web.
  • Xử lý yêu cầu từ trình duyệt bằng cách:
    • Đọc HTTP request header.
    • Kiểm tra HTTP request header để hiểu rõ lệnh điều khiển cần thiết.
    • Điều khiển thiết bị hoặc vật phẩm kết nối sử dụng Arduino UNO R4 theo lệnh điều khiển.
    • Gửi phản hồi HTTP.
    • Tùy chọn, nó cũng có thể gửi HTTP response body chứa nội dung HTML để hiển thị chi tiết về trạng thái điều khiển (nếu cần).

    Để có ví dụ tốt hơn và chi tiết hơn, tôi đề xuất xem các hướng dẫn dưới đây:

Tách nội dung HTML vào file khác trong Arduino IDE

Để tạo trang web cơ bản với chỉ vài nội dung, bạn có thể bao gồm HTML trong code Arduino UNO R4 như đã đề cập trước đó.

Nếu bạn muốn tạo trang web phức tạp và ấn tượng hơn với nhiều nội dung, việc đặt tất cả HTML, CSS và JavaScript trực tiếp vào code Arduino UNO R4 là không dễ dàng. Trong trường hợp này, bạn có thể sử dụng phương pháp khác để xử lý code.

  • Code Arduino UNO R4 nên được lưu trong file có tên .ino.
  • Code HTML, bao gồm HTML, CSS và Javascript, nên được lưu trong file khác có tên .h. Điều này giúp tách biệt nội dung trang web khỏi code Arduino UNO R4, làm cho việc xử lý và thay đổi trở nên đơn giản hơn.

Chúng ta cần thực hiện hai bước chính:

  • Tạo Nội Dung HTML
  • Lập Trình Arduino UNO R4

Chuẩn bị nội dung HTML

  1. Tạo file HTML trên máy tính của bạn. File này nên bao gồm thiết kế giao diện người dùng của bạn sử dụng HTML, CSS và JavaScript.
  2. Trong file HTML, đặt một placeholder tại nơi bạn muốn dữ liệu từ Arduino UNO R4 xuất hiện. Hiện tại, hãy sử dụng bất kỳ giá trị mẫu nào.
  3. Kiểm tra và điều chỉnh thiết kế của file cho đến khi bạn hài lòng với nó.
  4. Thay thế giá trị placeholder trong file HTML của bạn bằng nhãn duy nhất, chẳng hạn như TEMPERATURE_MARKER. Sau này, bạn sẽ sử dụng lệnh String.replace("TEMPERATURE_MARKER", real_value); trong script Arduino UNO R4 để hiển thị dữ liệu thực tế từ Arduino.
  5. Tiếp theo, chúng ta sẽ chuyển nội dung HTML này vào file .h trong Arduino IDE.

Lập trình Arduino UNO R4

  • Khởi động Arduino IDE và tạo file mới. Đặt tên như thế này: newbiely.com.ino.
  • Lấy code được cung cấp dưới đây và đặt nó vào file mới bạn đã tạo.
/* * Mã Arduino UNO R4 này được phát triển bởi newbiely.vn * Mã Arduino UNO R4 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/arduino-uno-r4/arduino-uno-r4-web-server */ #include <UnoR4WiFi_WebServer.h> #include "index.h" const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // change your network SSID (name) const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // change your network password UnoR4WiFi_WebServer server; float getTemperature() { return 26.9456; // YOUR SENSOR IMPLEMENTATION HERE // simulate the temperature value float temp_x100 = random(0, 10000); // a ramdom value from 0 to 10000 return temp_x100 / 100; // return the simulated temperature value from 0 to 100 in float } void handleHome(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { float tempC = getTemperature(); String response = HTML_CONTENT; response.replace("TEMPERATURE_MARKER", String(tempC, 1)); server.sendResponse(client, response.c_str()); } void setup() { Serial.begin(9600); delay(1000); Serial.println("Arduino Uno R4 WiFi - Web Server"); // Connect to WiFi Serial.print("Connecting to "); Serial.println(WIFI_SSID); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("connected!"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // Configure routes server.addRoute("/", handleHome); // Start server server.begin(); Serial.println("\n=== Web Server Ready! ==="); Serial.print("Visit: http://"); Serial.println(WiFi.localIP()); } void loop() { server.handleClient(); }
  • Cập nhật code với thông tin WiFi của bạn (SSID và password)
  • Trong Arduino IDE, tạo file có tên index.h
Arduino ide 2 adds file
  • Nhấp vào nút bên dưới biểu tượng serial monitor và chọn New Tab, hoặc nhấn Ctrl+Shift+N.
  • Đặt tên file là index.h và nhấn nút OK.
Arduino ide 2 adds file index.h
  • Sao chép code dưới đây và dán nó vào file có tên index.h.
/* * Mã Arduino UNO R4 này được phát triển bởi newbiely.vn * Mã Arduino UNO R4 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/arduino-uno-r4/arduino-uno-r4-web-server */ const char *HTML_CONTENT = R""""( REPLACE_YOUR_HTML_CONTENT_HERE )"""";
  • Chèn nội dung HTML đã chuẩn bị của bạn tại REPLACE_YOUR_HTML_CONTENT_HERE. Không sao nếu sử dụng ký tự xuống dòng. Đây là ví dụ về file index.h:
/* * Mã Arduino UNO R4 này được phát triển bởi newbiely.vn * Mã Arduino UNO R4 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/arduino-uno-r4/arduino-uno-r4-web-server */ const char *HTML_CONTENT = R""""( <!DOCTYPE html> <html> <head> <title>Arduino Uno R4 - Web Temperature</title> <meta name="viewport" content="width=device-width, initial-scale=0.7, maximum-scale=0.7"> <meta charset="utf-8"> <link rel="icon" href="https://diyables.io/images/page/diyables.svg"> <style> body { font-family: "Georgia"; text-align: center; font-size: width/2pt;} h1 { font-weight: bold; font-size: width/2pt;} h2 { font-weight: bold; font-size: width/2pt;} button { font-weight: bold; font-size: width/2pt;} </style> <script> var cvs_width = 200, cvs_height = 450; function init() { var canvas = document.getElementById("cvs"); canvas.width = cvs_width; canvas.height = cvs_height + 50; var ctx = canvas.getContext("2d"); ctx.translate(cvs_width/2, cvs_height - 80); update_view(TEMPERATURE_MARKER); } function update_view(temp) { var canvas = document.getElementById("cvs"); var ctx = canvas.getContext("2d"); var radius = 70; var offset = 5; var width = 45; var height = 330; ctx.clearRect(-cvs_width/2, -350, cvs_width, cvs_height); ctx.strokeStyle="blue"; ctx.fillStyle="blue"; //5-step Degree var x = -width/2; ctx.lineWidth=2; for (var i = 0; i <= 100; i+=5) { var y = -(height - radius)*i/100 - radius - 5; ctx.beginPath(); ctx.lineTo(x, y); ctx.lineTo(x - 20, y); ctx.stroke(); } //20-step Degree ctx.lineWidth=5; for (var i = 0; i <= 100; i+=20) { var y = -(height - radius)*i/100 - radius - 5; ctx.beginPath(); ctx.lineTo(x, y); ctx.lineTo(x - 25, y); ctx.stroke(); ctx.font="20px Georgia"; ctx.textBaseline="middle"; ctx.textAlign="right"; ctx.fillText(i.toString(), x - 35, y); } // shape ctx.lineWidth=16; ctx.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.stroke(); ctx.beginPath(); ctx.rect(-width/2, -height, width, height); ctx.stroke(); ctx.beginPath(); ctx.arc(0, -height, width/2, 0, 2 * Math.PI); ctx.stroke(); ctx.fillStyle="#e6e6ff"; ctx.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.rect(-width/2, -height, width, height); ctx.fill(); ctx.beginPath(); ctx.arc(0, -height, width/2, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle="#ff1a1a"; ctx.beginPath(); ctx.arc(0, 0, radius - offset, 0, 2 * Math.PI); ctx.fill(); temp = Math.round(temp * 100) / 100; var y = (height - radius)*temp/100.0 + radius + 5; ctx.beginPath(); ctx.rect(-width/2 + offset, -y, width - 2*offset, y); ctx.fill(); ctx.fillStyle="red"; ctx.font="bold 34px Georgia"; ctx.textBaseline="middle"; ctx.textAlign="center"; ctx.fillText(temp.toString() + "°C", 0, 100); } window.onload = init; </script> </head> <body> <h1>Arduino - Web Temperature</h1> <canvas id="cvs"></canvas> </body> </html> )"""";
  • Bây giờ bạn có code trong hai file: newbiely.com.inoindex.h
  • Nhấp vào nút Upload trong Arduino IDE để chuyển code lên Arduino UNO R4
  • Mở trang web của bo mạch Arduino UNO R4 trong trình duyệt web, tương tự như những lần trước. Nó sẽ hiển thị như sau:
Arduino UNO R4 temperature web browser

Để có hướng dẫn chi tiết, vui lòng kiểm tra hướng dẫn Arduino UNO R4 - DS18B20 Temperature Sensor qua Web.

※ Lưu ý:

Nếu bạn thay đổi HTML trong file có tên "index.h" nhưng không thực hiện thay đổi trong file "newbiely.com.ino", Arduino IDE sẽ không cập nhật HTML khi bạn biên dịch và tải code lên ESP32.

Để làm cho Arduino IDE cập nhật HTML, bạn phải thay đổi thứ gì đó trong file "newbiely.com.ino". Bạn có thể thêm dòng trống hoặc một comment. Điều này cho IDE biết rằng dự án đã thay đổi, do đó nó bao gồm HTML mới của bạn khi tải lên.

Arduino UNO R4 Web Server - Nhiều Trang

Hãy xem hướng dẫn này về Arduino UNO R4 - Web Server Multiple Pages.