Arduino Nhiệt độ qua Web

Trong bài hướng dẫn này, chúng ta sẽ học cách lập trình Arduino để trở thành một máy chủ web cung cấp nhiệt độ cho bạn qua web. Bạn có thể truy cập trang web do Arduino cung cấp để xem nhiệt độ từ cảm biến DS18B20. Dưới đây là cách nó hoạt động:

máy chủ web cảm biến nhiệt độ ds18b20 cho Arduino UNO R4

Chúng ta sẽ xem qua hai đoạn mã ví dụ:

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

1×Arduino UNO R4 WiFi
1×Alternatively, DIYables STEM V4 IoT
1×(Tùy chọn) 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×DS18B20 Temperature Sensor (WITH Adapter)
1×DS18B20 Temperature Sensor (WITHOUT Adapter)
1×dây jumper
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)

Về Arduino Uno R4 và cảm biến nhiệt độ DS18B20

Nếu bạn chưa biết về Arduino Uno R4 và cảm biến nhiệt DS18B20 (bố trí các chân, cách hoạt động, cách lập trình ...), hãy tìm hiểu về chúng trong các bài hướng dẫn sau:

Sơ đồ đấu dây

sơ đồ nối dây cảm biến nhiệt ds18b20 cho Arduino UNO R4 WiFi

This image is created using Fritzing. Click to enlarge image

Mã Arduino - Trang web đơn giản

/* * Mã Arduino này được phát triển bởi newbiely.vn * Mã Arduino 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/arduino-temperature-via-web */ #include <UnoR4WiFi_WebServer.h> #include <OneWire.h> #include <DallasTemperature.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"; const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // change your network SSID (name) const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // change your network password const int SENSOR_PIN = 6; // Arduino pin connected to DS18B20 sensor's DQ pin OneWire oneWire(SENSOR_PIN); // setup a oneWire instance DallasTemperature tempSensor(&oneWire); // pass oneWire to DallasTemperature library UnoR4WiFi_WebServer server; float getTemperature() { tempSensor.requestTemperatures(); // send the command to get temperatures float tempCelsius = tempSensor.getTempCByIndex(0); // read temperature in Celsius return tempCelsius; } 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); tempSensor.begin(); // initialize the temperature sensor Serial.println("Arduino Uno R4 WiFi - Temperature via Web"); // 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(); }

Hướng dẫn từng bước

  • Nếu đây là lần đầu bạn sử dụng Arduino Uno R4, hãy xem Cách bắt đầu với Arduino UNO R4.
  • Mở Library Manager bằng cách nhấn vào biểu tượng Library Manager ở 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 do DIYables tạo ra.
  • Nhấn vào nút Install để thêm thư viện Web Server.
thư viện máy chủ web cho Arduino UNO R4
  • Sao chép mã ở trên và mở bằng Arduino IDE
  • Thay đổi thông tin wifi (SSID và mật khẩu) trong mã thành của bạn
  • Nhấp nút Tải lên trên Arduino IDE để tải mã lên Arduino
  • Mở Serial Monitor
  • Xem kết quả trên Serial Monitor
COM6
Send
Arduino Uno R4 WiFi - Temperature via Web 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  
  • Bạn sẽ tìm thấy một địa chỉ IP.
  • Nhập địa chỉ IP này 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.
  • Bạn sẽ thấy đầu ra như sau trên Serial Monitor.
COM6
Send
Arduino Uno R4 WiFi - Temperature via Web 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  
  • Bạn sẽ thấy một trang web rất đơn giản về bo mạch Arduino trên trình duyệt web như dưới đây:
trình duyệt web nhiệt cho Arduino UNO R4

Mã Arduino - Trang web đồ họa

Vì một trang web đồ họa chứa một lượng lớn nội dung HTML, việc nhúng nó vào mã Arduino như trước đây trở nên bất tiện. Để giải quyết vấn đề này, chúng ta cần tách mã Arduino và mã HTML thành các tệp riêng biệt:

  • Mã Arduino sẽ được đặt vào một tệp .ino.
  • Mã HTML (bao gồm HTML, CSS và JavaScript) sẽ được đặt vào tệp .h.

Hướng dẫn từng bước

  • Mở Arduino IDE và tạo một sketch mới. Đặt tên cho nó, ví dụ ArduinoGetStarted.com.ino
  • Sao chép mã dưới đây và mở bằng Arduino IDE
/* * Mã Arduino này được phát triển bởi newbiely.vn * Mã Arduino 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/arduino-temperature-via-web */ #include <UnoR4WiFi_WebServer.h> #include "index.h" #include <OneWire.h> #include <DallasTemperature.h> const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // change your network SSID (name) const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // change your network password const int SENSOR_PIN = 6; // Arduino pin connected to DS18B20 sensor's DQ pin OneWire oneWire(SENSOR_PIN); // setup a oneWire instance DallasTemperature tempSensor(&oneWire); // pass oneWire to DallasTemperature library UnoR4WiFi_WebServer server; float getTemperature() { tempSensor.requestTemperatures(); // send the command to get temperatures float tempCelsius = tempSensor.getTempCByIndex(0); // read temperature in Celsius return tempCelsius; } 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); tempSensor.begin(); // initialize the temperature sensor Serial.println("Arduino Uno R4 WiFi - Temperature via Web"); // 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(); }
  • Thay đổi thông tin WiFi (SSID và mật khẩu) trong mã thành của bạn
  • Tạo tệp index.h trong Arduino IDE bằng cách:
    • Nhấp vào nút ngay bên dưới biểu tượng Serial Monitor và chọn New Tab, hoặc dùng phím Ctrl+Shift+N.
    Arduino ide 2 thêm tệp tin
    • Hãy đặt tên cho tệp tin là index.h và nhấp nút OK
    Arduino ide 2 thêm tệp index.h
    • Sao chép mã ở dưới đây và dán vào index.h.
    /* * Mã Arduino này được phát triển bởi newbiely.vn * Mã Arduino 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/arduino-temperature-via-web */ const char *HTML_CONTENT = R""""( <!DOCTYPE html> <html> <head> <title>Arduino - 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ó mã trong hai tệp: ArduinoGetStarted.com.inoindex.h
    • Nhấp Tải lên nút trên Arduino IDE để tải mã lên Arduino
    • Truy cập trang web của bo mạch Arduino thông qua trình duyệt web như trước. Bạn sẽ thấy nó như dưới đây:
    nhiệt độ Arduino trên trình duyệt web

    ※ Lưu ý:

    • Nếu bạn thực hiện thay đổi nội dung HTML bên trong tệp index.h nhưng không chỉnh sửa bất kỳ điều gì trong tệp ArduinoGetStarted.com.ino, IDE Arduino sẽ không làm mới hoặc cập nhật nội dung HTML khi bạn biên dịch và tải mã lên ESP32.
    • Để buộc IDE Arduino cập nhật nội dung HTML trong tình huống này, bạn cần thực hiện một chỉnh sửa trong tệp ArduinoGetStarted.com.ino. Ví dụ, bạn có thể thêm một dòng trống hoặc chèn một chú thích. Hành động này kích hoạt IDE nhận ra rằng có sự thay đổi trong dự án, đảm bảo nội dung HTML được cập nhật của bạn được đưa vào lần tải lên.