ESP32 Kiểm tra Nhiệt độ qua Web

Trong hướng dẫn này, chúng ta sẽ khám phá quá trình lập trình ESP32 để hoạt động như một web server, cho phép bạn truy cập dữ liệu nhiệt độ qua giao diện web. Sử dụng cảm biến nhiệt độ DS18B20 được kết nối, bạn có thể dễ dàng kiểm tra nhiệt độ hiện tại bằng cách dùng smartphone hoặc PC để truy cập trang web do ESP32 cung cấp. Dưới đây là tổng quan ngắn gọn về cách hoạt động:

ESP32 ds18b20 cảm biến nhiệt độ web server

Chúng ta sẽ đi qua hai ví dụ code:

Phần Cứng Cần Thiết

1×mô-đun phát triển ESP-WROOM-32
1×Alternatively, ESP32 Uno-form board
1×Alternatively, ESP32 S3 Uno-form board
1×Cáp USB Type-C
1×Cảm biến nhiệt độ DS18B20 (CÓ Adapter)
1×Cảm biến nhiệt độ DS18B20 (KHÔNG Adapter)
1×Dây nối Jumper
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)

Về ESP32 Web Server và Cảm biến nhiệt độ DS18B20

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

Sơ đồ Kết nối

ESP32 web server ds18b20 cảm biến nhiệt độ sơ đồ đấu dây

This image is created using Fritzing. Click to enlarge image

Nếu bạn chưa rõ cách cấp nguồn cho ESP32 và các linh kiện khác, xem: Cách Cung Cấp Nguồn Điện Cho ESP32.

Code ESP32 - Trang Web Đơn giản

/* * 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/esp32-temperature-via-web */ #include <DIYables_ESP32_WebServer.h> #include <OneWire.h> #include <DallasTemperature.h> #define SENSOR_PIN 17 // ESP32 pin GPIO17 connected to DS18B20 sensor's DATA pin // WiFi credentials const char WIFI_SSID[] = "YOUR_WIFI_SSID"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // Create web server instance DIYables_ESP32_WebServer server; OneWire oneWire(SENSOR_PIN); // setup a oneWire instance DallasTemperature DS18B20(&oneWire); // pass oneWire to DallasTemperature library float getTemperature() { DS18B20.requestTemperatures(); // send the command to get temperatures float tempC = DS18B20.getTempCByIndex(0); // read temperature in °C return tempC; } // Page handlers void handleHome(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { Serial.println("ESP32 Web Server: New request received"); // for debugging // get temperature from sensor float temperature = getTemperature(); // Format the temperature with two decimal places String temperatureStr = String(temperature, 2); String html = "<!DOCTYPE HTML>"; html += "<html>"; html += "<head>"; html += "<link rel=\"icon\" href=\"data:,\">"; html += "</head>"; html += "<p>"; html += "Temperature: <span style=\"color: red;\">"; html += temperature; html += "&deg;C</span>"; html += "</p>"; html += "</html>"; server.sendResponse(client, html.c_str()); } void setup() { Serial.begin(9600); delay(1000); DS18B20.begin(); // initialize the DS18B20 sensor Serial.println("ESP32 Web Server"); // Configure routes server.addRoute("/", handleHome); // Start web server with WiFi connection server.begin(WIFI_SSID, WIFI_PASSWORD); } void loop() { server.handleClient(); }

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

  • Nếu đây là lần đầu bạn sử dụng ESP32, hãy xem ESP32 - Cài Đặt Phần Mềm.
  • Thực hiện kết nối như hình trên.
  • Kết nối bo mạch ESP32 với PC của bạn qua cáp micro USB
  • Mở Arduino IDE trên PC.
  • Chọn đúng bo mạch ESP32 (ví dụ: ESP32 Dev Module) và cổng COM.
  • Mở Library Manager bằng cách click vào biểu tượng Library Manager trên thanh điều hướng bên trái của Arduino IDE.
  • Tìm kiếm "DIYables ESP32 WebServer", sau đó tìm thư viện Web Server được tạo bởi DIYables.
  • Click nút Install để cài đặt thư viện Web Server.
ESP32 web server thư viện
  • Tìm kiếm "DallasTemperature" trong ô tìm kiếm, sau đó tìm thư viện DallasTemperature của Miles Burton.
  • Click nút Install để cài đặt thư viện DallasTemperature.
ESP32 dallas temperature thư viện
  • Bạn sẽ được yêu cầu cài đặt dependency. Click nút Install All để cài đặt thư viện OneWire.
ESP32 onewire thư viện
  • Sao chép code trên và mở bằng Arduino IDE
  • Thay đổi thông tin wifi (SSID và password) trong code thành thông tin của bạn
  • Click nút Upload trên Arduino IDE để upload code lên ESP32
  • Mở Serial Monitor
  • Kiểm tra kết quả trên Serial Monitor.
COM6
Send
Connecting to WiFi... Connected to WiFi ESP32 Web Server's IP address: 192.168.0.2
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 smartphone hoặc PC.
  • Bạn sẽ thấy kết quả sau trên Serial Monitor.
COM6
Send
Connecting to WiFi... Connected to WiFi ESP32 Web Server's IP address: 192.168.0.2 ESP32 Web Server: New request received: GET /
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • Bạn sẽ thấy một trang web rất đơn giản của bo mạch ESP32 trên trình duyệt web như dưới đây:
ESP32 temperature web server

※ Lưu ý:

Với code được cung cấp ở trên, để có được cập nhật nhiệt độ, bạn phải reload lại trang trên trình duyệt web. Trong phần tiếp theo, chúng ta sẽ học cách làm cho trang web cập nhật giá trị nhiệt độ ở chế độ nền mà không cần reload lại trang web.

Code ESP32 - Trang Web có Đồ họa

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

  • Code ESP32 sẽ được đặt trong tệp .ino.
  • Code HTML (bao gồm HTML, CSS, và Javascript) sẽ được đặt trong tệp .h.

Để biết chi tiết về cách tách code HTML khỏi code ESP32, vui lòng tham khảo hướng dẫn ESP32 - Web Server.

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

  • Mở Arduino IDE và tạo sketch mới, Đặt tên cho nó, ví dụ: newbiely.com.ino
  • Sao chép code dưới đây và mở bằng Arduino IDE
/* * 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/esp32-temperature-via-web */ #include <DIYables_ESP32_WebServer.h> #include "index.h" // Include the index.h file #include <OneWire.h> #include <DallasTemperature.h> #define SENSOR_PIN 17 // ESP32 pin GPIO17 connected to DS18B20 sensor's DATA pin OneWire oneWire(SENSOR_PIN); // setup a oneWire instance DallasTemperature DS18B20(&oneWire); // pass oneWire to DallasTemperature library // WiFi credentials const char WIFI_SSID[] = "YOUR_WIFI_SSID"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // Create web server instance DIYables_ESP32_WebServer server; float getTemperature() { DS18B20.requestTemperatures(); // send the command to get temperatures float tempC = DS18B20.getTempCByIndex(0); // read temperature in °C return tempC; } // Page handlers void handleHome(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { Serial.println("ESP32 Web Server: New request received"); // for debugging server.sendResponse(client, webpage); // webpage is from index } // Page handlers void handleTemperature(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { Serial.println("ESP32 Web Server: New request received"); // for debugging float temperature = getTemperature(); String temperatureStr = String(temperature, 2); server.sendResponse(client, temperatureStr.c_str(), "text/plain"); } void setup() { Serial.begin(9600); delay(1000); DS18B20.begin(); // initialize the DS18B20 sensor Serial.println("ESP32 Web Server"); // Define a route to get the web page server.addRoute("/", handleHome); // Define a route to get the temperature data server.addRoute("/temperature", handleTemperature); // Start web server with WiFi connection server.begin(WIFI_SSID, WIFI_PASSWORD); } void loop() { server.handleClient(); }
  • Thay đổi thông tin WiFi (SSID và password) trong code thành thông tin của bạn
  • Tạo tệp index.h trên Arduino IDE bằng cách:
    • Click vào nút ngay dưới biểu tượng serial monitor và chọn New Tab, hoặc sử dụng phím tắt Ctrl+Shift+N.
    Arduino ide 2 adds file
    • Đặt tên tệp là index.h và click nút OK
    Arduino ide 2 adds file index.h
    • Sao chép code dưới đây và dán vào index.h.
    /* * 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/esp32-temperature-via-web */ #ifndef WEBPAGE_H #define WEBPAGE_H const char* webpage = R"=====( <!DOCTYPE html> <html> <head> <title>ESP32 - 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); fetchTemperature(); setInterval(fetchTemperature, 4000); // Update temperature every 4 seconds } function fetchTemperature() { fetch("/temperature") .then(response => response.text()) .then(data => {update_view(data);}); } 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, -cvs_height + 80, cvs_width, cvs_height + 50); 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>ESP32 - Web Temperature</h1> <canvas id="cvs"></canvas> </body> </html> )====="; #endif
    • Bây giờ bạn có code trong hai tệp: newbiely.com.inoindex.h
    • Click nút Upload trên Arduino IDE để upload code lên ESP32
    • Truy cập trang web của bo mạch ESP32 qua trình duyệt web trên PC hoặc smartphone như trước. Bạn sẽ thấy như dưới đây:
    ESP32 temperature web browser server

    ※ Lưu ý:

    • Nếu bạn sửa đổi nội dung HTML trong index.h và không thay đổi gì trong tệp newbiely.com.ino, khi bạn compile và upload code lên ESP32, Arduino IDE sẽ không cập nhật nội dung HTML.
    • Để Arduino IDE cập nhật nội dung HTML trong trường hợp này, hãy thực hiện một thay đổi trong tệp newbiely.com.ino (ví dụ: thêm dòng trống, thêm comment....)