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:
Arduino được lập trình làm máy chủ web.
Bạn nhập địa chỉ IP của Arduino vào trình duyệt web trên điện thoại thông minh hoặc máy tính của bạn.
Arduino trả lời yêu cầu từ trình duyệt web bằng một trang web chứa nhiệt độ được đọc từ cảm biến DS18B20.
Chúng ta sẽ xem qua hai đoạn mã ví dụ:
Mã Arduino 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ễ hiểu cách nó hoạt động.
Mã Arduino cung cấp một trang web đồ họa hiển thị nhiệt độ từ cảm biến DS18B20.
| 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) | | |
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:

This image is created using Fritzing. Click to enlarge image
#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% °C</span>
</p>
</html>
)rawliteral";
const char WIFI_SSID[] = "YOUR_WIFI_SSID";
const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";
const int SENSOR_PIN = 6;
OneWire oneWire(SENSOR_PIN);
DallasTemperature tempSensor(&oneWire);
UnoR4WiFi_WebServer server;
float getTemperature() {
tempSensor.requestTemperatures();
float tempCelsius = tempSensor.getTempCByIndex(0);
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();
Serial.println("Arduino Uno R4 WiFi - Temperature via Web");
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());
server.addRoute("/", handleHome);
server.begin();
Serial.println("\n=== Web Server Ready! ===");
Serial.print("Visit: http://");
Serial.println(WiFi.localIP());
}
void loop() {
server.handleClient();
}
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.
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
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
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.
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
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.
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
#include <UnoR4WiFi_WebServer.h>
#include "index.h"
#include <OneWire.h>
#include <DallasTemperature.h>
const char WIFI_SSID[] = "YOUR_WIFI_SSID";
const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";
const int SENSOR_PIN = 6;
OneWire oneWire(SENSOR_PIN);
DallasTemperature tempSensor(&oneWire);
UnoR4WiFi_WebServer server;
float getTemperature() {
tempSensor.requestTemperatures();
float tempCelsius = tempSensor.getTempCByIndex(0);
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();
Serial.println("Arduino Uno R4 WiFi - Temperature via Web");
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());
server.addRoute("/", handleHome);
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:


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";
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();
}
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);
}
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.ino và index.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:
※ 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.