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 được lập trình như một web server.
Bạn nhập địa chỉ IP của ESP32 vào trình duyệt web trên smartphone hoặc PC.
ESP32 phản hồi yêu cầu từ trình duyệt web với một trang web chứa nhiệt độ đọc được từ cảm biến DS18B20.
Chúng ta sẽ đi qua hai ví dụ code:
Code ESP32 cung cấp một trang web rất đơn giản hiển thị nhiệt độ từ cảm biến DS18B20. Điều này giúp bạn dễ dàng hiểu cách hoạt động. Nội dung HTML được nhúng trong code ESP32
Code ESP32 cung cấp một trang web có đồ họa hiển thị nhiệt độ từ cảm biến DS18B20, nội dung HTML được tách riêng khỏi code ESP32.
Tiết lộ: Một số liên kết trong bài viết này là liên kết tiếp thị Amazon và có thể nhận hoa hồng theo chính sách của chương trình.
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:
/* * 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 credentialsconstchar WIFI_SSID[] = "YOUR_WIFI_SSID";constchar WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";// Create web server instanceDIYables_ESP32_WebServer server;OneWire oneWire(SENSOR_PIN); // setup a oneWire instanceDallasTemperature DS18B20(&oneWire); // pass oneWire to DallasTemperature libraryfloatgetTemperature() { DS18B20.requestTemperatures(); // send the command to get temperaturesfloat tempC = DS18B20.getTempCByIndex(0); // read temperature in °Creturn tempC;}// Page handlersvoid 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 sensorfloat temperature = getTemperature();// Format the temperature with two decimal placesString 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 += "°C</span>"; html += "</p>"; html += "</html>"; server.sendResponse(client, html.c_str());}voidsetup() {Serial.begin(9600);delay(1000); DS18B20.begin(); // initialize the DS18B20 sensorSerial.println("ESP32 Web Server");// Configure routes server.addRoute("/", handleHome);// Start web server with WiFi connection server.begin(WIFI_SSID, WIFI_PASSWORD);}voidloop() { server.handleClient();}
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.
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.
Bạn sẽ được yêu cầu cài đặt dependency. Click nút Install All để cài đặt thư viện OneWire.
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.
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
Connecting to WiFi...
Connected to WiFi
ESP32 Web Server's IP address: 192.168.0.2
Ln 11, Col 1
ESP32 Dev Module on COM15
2
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.
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
Connecting to WiFi...
Connected to WiFi
ESP32 Web Server's IP address: 192.168.0.2
ESP32 Web Server: New request received:
GET /
Ln 11, Col 1
ESP32 Dev Module on COM15
2
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:
※ 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 pinOneWire oneWire(SENSOR_PIN); // setup a oneWire instanceDallasTemperature DS18B20(&oneWire); // pass oneWire to DallasTemperature library// WiFi credentialsconstchar WIFI_SSID[] = "YOUR_WIFI_SSID";constchar WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";// Create web server instanceDIYables_ESP32_WebServer server;floatgetTemperature() { DS18B20.requestTemperatures(); // send the command to get temperaturesfloat tempC = DS18B20.getTempCByIndex(0); // read temperature in °Creturn tempC;}// Page handlersvoid 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 handlersvoid handleTemperature(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) {Serial.println("ESP32 Web Server: New request received"); // for debuggingfloat temperature = getTemperature();String temperatureStr = String(temperature, 2); server.sendResponse(client, temperatureStr.c_str(), "text/plain");}voidsetup() {Serial.begin(9600);delay(1000); DS18B20.begin(); // initialize the DS18B20 sensorSerial.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);}voidloop() { 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.
Đặt tên tệp là index.h và click nút OK
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_Hconst 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.ino và index.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:
※ 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....)