Tải bản đầy đủ (.pdf) (26 trang)

Cảm biến nhiệt độ ESP8266 DS18B20 với Arduino IDE (Máy chủ Web, Đơn, Nhiều)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (910.23 KB, 26 trang )

Cảm biến nhiệt độ ESP8266 DS18B20 với Arduino IDE
(Máy chủ Web, Đơn, Nhiều)
Đây là hướng dẫn chuyên sâu về cảm biến nhiệt độ DS18B20 với ESP8266 sử dụng
Arduino IDE. Chúng tôi sẽ đề cập đến cách nối dây cảm biến, cài đặt các thư viện cần
thiết và viết mã để đọc cảm biến từ một và nhiều cảm biến. Cuối cùng, chúng ta sẽ xây
dựng một máy chủ web đơn giản để hiển thị các chỉ số cảm biến.

Trong suốt hướng dẫn này, chúng tôi sẽ đề cập đến các chủ đề sau:
1. Đọc nhiệt độ từ một cảm biến nhiệt độ DS18B20;
2. Đọc nhiệt độ từ nhiều cảm biến nhiệt độ DS18B20;
3. Hiển thị số đọc cảm biến DS18B20 trên máy chủ web.
Bạn cũng có thể thích đọc các hướng dẫn DS18B20 khác:
Tìm hiểu thêm về ESP8266 với khóa học của chúng tơi: Tự động hóa gia đình bằng
ESP8266.

Giới thiệu cảm biến nhiệt độ DS18B20
Cảm biến nhiệt độ DS18B20 là cảm biến nhiệt độ kỹ thuật số một dây. Điều này có nghĩa
là nó chỉ u cầu một dịng dữ liệu (và GND) để giao tiếp với ESP8266 của bạn.

1/26


Nó có thể được cung cấp năng lượng bởi nguồn điện bên ngồi hoặc nó có thể lấy năng
lượng từ đường dữ liệu (được gọi là "chế độ ký sinh trùng"), giúp loại bỏ sự cần thiết của
nguồn điện bên ngồi.

Mỗi cảm biến nhiệt độ DS18B20 có một mã sê-ri 64-bit duy nhất. Điều này cho phép bạn
nối nhiều cảm biến vào cùng một dây dữ liệu. Vì vậy, bạn có thể nhận nhiệt độ từ nhiều
cảm biến chỉ bằng một GPIO.
Cảm biến nhiệt độ DS18B20 cũng có sẵn trong phiên bản chống thấm nước.


2/26


Dưới đây là tóm tắt các thơng số kỹ thuật phù hợp nhất của cảm biến nhiệt độ DS18B20:
Giao tiếp qua bus một dây
Phạm vi cung cấp điện: 3.0V đến 5.5V
Phạm vi nhiệt độ hoạt động: -55ºC đến + 125ºC
Độ chính xác +/-0,5 ºC (giữa phạm vi -10ºC đến 85ºC)
Để biết thêm thông tin, hãy tham khảo bảng dữ liệu DS18B20.

Các bộ phận cần thiết
Để hoàn thành hướng dẫn này, bạn cần các thành phần sau:
ESP8266 - đọc Bảng phát triển Wi-Fi ESP8266 tốt nhất
Cảm biến nhiệt độ DS18B20 (một hoặc nhiều cảm biến) – phiên bản chống thấm
nước
Điện trở 4.7k Ohm
Breadboard
Dây nhảy

ESP8266 với sơ đồ DS18B20
Như đã đề cập trước đây, cảm biến nhiệt độ DS18B20 có thể được cấp nguồn thơng qua
chân VDD (chế độ bình thường) hoặc nó có thể lấy sức mạnh từ đường dữ liệu (chế độ
ký sinh trùng). Bạn có thể chọn một trong hai chế độ.

Chế độ ký sinh trùng

3/26


Chế độ bình thường


4/26


Lưu ý: trong hướng dẫn này, chúng tôi đang kết nối đường dữ liệu DS18B20 với GPIO
4, nhưng bạn có thể sử dụng bất kỳ GPIO phù hợp nào khác.
Đọc Hướng dẫn tham khảo GPIO ESP8266 của chúng tôi để tìm hiểu thêm về các GPIO
ESP8266.
Lưu ý: nếu bạn đang sử dụng ESP-01, GPIO 2 là chân phù hợp nhất để kết nối với chân
dữ liệu DS18B20.

Chuẩn bị Arduino IDE của bạn
5/26


Chúng tơi sẽ lập trình ESP8266 bằng Arduino IDE, vì vậy hãy đảm bảo bạn đã cài đặt
tiện ích bổ sung ESP8266 trước khi tiếp tục:
Cài đặt bảng ESP8266 trong Arduino IDE (hướng dẫn Windows, Mac OS X và
Linux)

Cài đặt thư viện cho DS18B20
Để giao tiếp với cảm biến nhiệt độ DS18B20, bạn cần cài đặt thư viện One Wire của Paul
Stoffregen và thư viện Nhiệt độ Dallas. Làm theo các bước tiếp theo để cài đặt các thư
viện đó.
1. Mở Arduino IDE của bạn và đi tới Sketch > Include Library > Manage Libraries.
Trình quản lý thư viện sẽ mở.
2. Nhập "onewire" vào hộp tìm kiếm và cài đặt thư viện OneWire của Paul Stoffregen.

3. Sau đó, tìm kiếm "Dallas" và cài đặt thư viện Nhiệt độ Dallas của Miles Burton.


6/26


Sau khi cài đặt các thư viện, hãy khởi động lại Arduino IDE của bạn.

Mã (Đơn DS18B20)
Sau khi cài đặt các thư viện cần thiết, bạn có thể tải mã sau lên ESP8266. Mã đọc nhiệt
độ từ cảm biến nhiệt độ DS18B20 và hiển thị số đọc trên Màn hình nối tiếp Arduino IDE.

7/26


/*********

Rui Santos

Complete project details at
*********/





#include <OneWire.h>

#include <DallasTemperature.h>

// GPIO where the DS18B20 is connected to

const int oneWireBus = 4;



// Setup a oneWire instance to communicate with any OneWire devices

OneWire oneWire(oneWireBus);

// Pass our oneWire reference to Dallas Temperature sensor

DallasTemperature sensors(&oneWire);

void setup() {

// Start the Serial Monitor

Serial.begin(115200);

// Start the DS18B20 sensor

sensors.begin();

}

void loop() {

sensors.requestTemperatures();

float temperatureC = sensors.getTempCByIndex(0);

float temperatureF = sensors.getTempFByIndex(0);


Serial.print(temperatureC);

Serial.println("ºC");

Serial.print(temperatureF);

Serial.println("ºF");

delay(5000);

}


Xem mã thơ
Có nhiều cách khác nhau để có được nhiệt độ từ cảm biến nhiệt độ DS18B20. Tuy nhiên,
nếu bạn chỉ sử dụng một cảm biến duy nhất, đây là một trong những cách dễ nhất và
đơn giản nhất.

8/26


Mã hoạt động như thế nào
Bắt đầu bằng cách bao gồm các thư viện OneWire và DallasTemperature.
#include <OneWire.h>

#include <DallasTemperature.h>

Tạo các phiên bản cần thiết cho cảm biến nhiệt độ. Cảm biến nhiệt độ được kết nối với
GPIO 4.
// GPIO where the DS18B20 is connected to


const int oneWireBus = 4;

// Setup a oneWire instance to communicate with any OneWire devices

OneWire oneWire(oneWireBus);

// Pass our oneWire reference to Dallas Temperature sensor

DallasTemperature sensors(&oneWire);

Trong setup(), khởi tạo Serial Monitor với tốc độ truyền là 115200.
Serial.begin(115200);

Khởi tạo cảm biến nhiệt độ DS18B20:
sensors.begin();

Trước khi thực sự nhận được nhiệt độ, bạn cần gọi phương thức requestTemperatures().
sensors.requestTemperatures();

Sau đó, lấy nhiệt độ tính bằng Celsius bằng cách sử dụng phương thức
getTempCByIndex() như hình dưới đây:
float temperatureC = sensors.getTempCByIndex(0);

9/26


Hoặc sử dụng getTempFByIndex() để lấy nhiệt độ tính bằng Fahrenheit.
float temperatureF = sensors.getTempFByIndex(0);


Các phương thức getTempCByIndex() và getTempFByIndex() chấp nhận chỉ số của cảm
biến nhiệt độ. Bởi vì chúng tôi chỉ sử dụng một cảm biến, chỉ số của nó là 0. Nếu bạn
muốn đọc nhiều cảm biến, bạn sử dụng chỉ số 0 cho một cảm biến, chỉ mục 1 cho cảm
biến khác, v.v.
Cuối cùng, in kết quả trong Serial Monitor.
Serial.print(temperatureC);

Serial.println("ºC");

Serial.print(temperatureF);

Serial.println("ºF");

Chỉ số nhiệt độ mới được yêu cầu cứ sau 5 giây.
delay(5000);

Cuộc biểu tình
Sau khi tải mã lên, hãy mở Màn hình nối tiếp Arduino IDE với tốc độ truyền 9600. Bạn sẽ
nhận được nhiệt độ hiển thị ở cả độ C và độ F:

10/26


Lấy nhiệt độ từ nhiều cảm biến nhiệt độ DS18B20

Cảm biến nhiệt độ DS18B20 giao tiếp bằng giao thức một dây và mỗi cảm biến có một
mã sê-ri 64 bit duy nhất, vì vậy bạn có thể đọc nhiệt độ từ nhiều cảm biến chỉ bằng một
chân kỹ thuật số duy nhất.



Để đọc nhiệt độ từ nhiều cảm biến, bạn chỉ cần nối tất cả các dòng dữ liệu lại với nhau
như thể hiện trong sơ đồ tiếp theo:

11/26


Mã (Nhiều DS18B20)
Sau đó, tải lên mã sau. Nó quét tất cả các thiết bị trên GPIO 4 và in nhiệt độ cho từng
thiết bị. Bản phác thảo này dựa trên ví dụ được cung cấp bởi thư viện
DallasTemperature.

12/26


/*********

Rui Santos

Complete project details at
*********/





#include <OneWire.h>

#include <DallasTemperature.h>

// Data wire is plugged TO GPIO 4


#define ONE_WIRE_BUS 4

// Setup a oneWire instance to communicate with any OneWire devices (not just
Maxim/Dallas temperature ICs)

OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.

DallasTemperature sensors(&oneWire);

// Number of temperature devices found

int numberOfDevices;

// We'll use this variable to store a found device address

DeviceAddress tempDeviceAddress;

void setup(){

// start serial port

Serial.begin(115200);

// Start up the library

sensors.begin();


// Grab a count of devices on the wire

numberOfDevices = sensors.getDeviceCount();

// locate devices on the bus

Serial.print("Locating devices...");

Serial.print("Found ");

Serial.print(numberOfDevices, DEC);

Serial.println(" devices.");

// Loop through each device, print out address

for(int i=0;i
// Search the wire for address

if(sensors.getAddress(tempDeviceAddress, i)){

Serial.print("Found device ");

Serial.print(i, DEC);

Serial.print(" with address: ");

printAddress(tempDeviceAddress);


Serial.println();

} else {

Serial.print("Found ghost device at ");

Serial.print(i, DEC);

Serial.print(" but could not detect address. Check power and cabling");

}

}

}

13/26


void loop(){

sensors.requestTemperatures(); // Send the command to get temperatures

// Loop through each device, print out temperature data

for(int i=0;i
// Search the wire for address

if(sensors.getAddress(tempDeviceAddress, i)){


// Output the device ID

Serial.print("Temperature for device: ");

Serial.println(i,DEC);

// Print the data

float tempC = sensors.getTempC(tempDeviceAddress);

Serial.print("Temp C: ");

Serial.print(tempC);

Serial.print(" Temp F: ");

Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to
Fahrenheit

}

}

delay(5000);

}

// function to print a device address


void printAddress(DeviceAddress deviceAddress) {

for (uint8_t i = 0; i < 8; i++){

if (deviceAddress[i] < 16) Serial.print("0");

Serial.print(deviceAddress[i], HEX);

}

}


Xem mã thô

Cách mã hoạt động
Mã sử dụng một số phương pháp hữu ích để xử lý nhiều cảm biến DS18B20.
Bạn sử dụng phương thức getDeviceCount() để lấy số lượng cảm biến DS18B20 trên
dịng dữ liệu.
numberOfDevices = sensors.getDeviceCount();

Phương thức getAddress() tìm các địa chỉ cảm biến:
if(sensors.getAddress(tempDeviceAddress, i)){

Địa chỉ là duy nhất cho mỗi cảm biến. Vì vậy, mỗi cảm biến có thể được xác định bởi địa
chỉ của nó.
Sau đó, bạn sử dụng phương thức getTempC() chấp nhận làm đối số địa chỉ thiết bị. Với
phương pháp này, bạn có thể lấy nhiệt độ từ một cảm biến cụ thể:
float tempC = sensors.getTempC(tempDeviceAddress);


14/26


Để có được nhiệt độ ở độ Fahrenheit, bạn có thể sử dụng getTemF(). Ngồi ra, bạn có
thể chuyển đổi nhiệt độ tính bằng C sang Fahrenheit như sau:
DallasTemperature::toFahrenheit(tempC)

Cuộc biểu tình
Sau khi tải mã lên, hãy mở Màn hình nối tiếp của bạn với tốc độ truyền là 115200. Bạn sẽ
nhận được tất cả các bài đọc cảm biến của bạn được hiển thị như hình dưới đây:

Hiển thị chỉ số nhiệt độ DS18B20 trong máy chủ web
Để xây dựng máy chủ web, chúng tôi sẽ sử dụng thư viện ESPAsyncWebServer cung
cấp một cách dễ dàng để xây dựng một máy chủ web không đồng bộ. Xây dựng một máy
chủ web khơng đồng bộ có một số lợi thế. Chúng tôi khuyên bạn nên xem nhanh tài liệu
thư viện trên trang GitHub của nó.

Cài đặt thư viện ESPAsyncWebServer
Thư viện ESPAsyncWebServer khơng có sẵn để cài đặt trong Trình quản lý thư viện
Arduino IDE. Vì vậy, bạn cần cài đặt nó bằng tay.
Làm theo các bước tiếp theo để cài đặt thư viện ESPAsyncWebServer:
1. Bấm vào đây để tải xuống thư viện ESPAsyncWebServer. Bạn sẽ có một thư mục
.zip trong thư mục Tải xuống của mình
2. Giải nén thư mục .zip và bạn sẽ nhận được thư mục ESPAsyncWebServer-master
15/26


3. Đổi tên thư mục của bạn từ ESPAsyncWebServer-master thành
ESPAsyncWebServer
4. Di chuyển thư mục ESPAsyncWebServer vào thư mục thư viện cài đặt Arduino IDE

của bạn
Cài đặt Thư viện TCP ESPAsync
Thư viện ESPAsyncWebServer yêu cầu thư viện ESPAsyncTCP hoạt động. Làm theo
các bước tiếp theo để cài đặt thư viện đó:
1. Bấm vào đây để tải xuống thư viện ESPAsyncTCP. Bạn sẽ có một thư mục .zip
trong thư mục Tải xuống của mình
2. Giải nén thư mục .zip và bạn sẽ nhận được thư mục ESPAsyncTCP-master
3. Đổi tên thư mục của bạn từ ESPAsyncTCP-master thành ESPAsyncTCP
4. Di chuyển thư mục ESPAsyncTCP vào thư mục thư viện cài đặt Arduino IDE của
bạn
5. Cuối cùng, mở lại Arduino IDE của bạn

Mã (DS18B20 Máy chủ Web không đồng bộ)
Mở Arduino IDE của bạn và sao chép mã sau.

16/26


/*********

Rui Santos

Complete project details at
*********/





// Import required libraries


#ifdef ESP32

#include <WiFi.h>

#include <ESPAsyncWebServer.h>

#else

#include <Arduino.h>

#include <ESP8266WiFi.h>

#include <Hash.h>

#include <ESPAsyncTCP.h>

#include <ESPAsyncWebServer.h>

#endif

#include <OneWire.h>

#include <DallasTemperature.h>

// Data wire is connected to GPIO 4

#define ONE_WIRE_BUS 4

// Setup a oneWire instance to communicate with any OneWire devices


OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature sensor

DallasTemperature sensors(&oneWire);

// Variables to store temperature values

String temperatureF = "";

String temperatureC = "";

// Timer variables

unsigned long lastTime = 0;

unsigned long timerDelay = 30000;

// Replace with your network credentials

const char* ssid = "REPLACE_WITH_YOUR_SSID";

const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Create AsyncWebServer object on port 80

AsyncWebServer server(80);

String readDSTemperatureC() {


// Call sensors.requestTemperatures() to issue a global temperature and Requests
to all devices on the bus

sensors.requestTemperatures();

float tempC = sensors.getTempCByIndex(0);

if(tempC == -127.00) {

Serial.println("Failed to read from DS18B20 sensor");

return "--";

} else {

Serial.print("Temperature Celsius: ");

Serial.println(tempC);

}

17/26


return String(tempC);

}

String readDSTemperatureF() {


// Call sensors.requestTemperatures() to issue a global temperature and Requests
to all devices on the bus

sensors.requestTemperatures();

float tempF = sensors.getTempFByIndex(0);

if(int(tempF) == -196){

Serial.println("Failed to read from DS18B20 sensor");

return "--";

} else {

Serial.print("Temperature Fahrenheit: ");

Serial.println(tempF);

}

return String(tempF);

}

const char index_html[] PROGMEM = R"rawliteral(

<!DOCTYPE HTML><html>


<head>

<meta name="viewport" content="width=device-width, initial-scale=1">

href=" integrity="sha384fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr"
crossorigin="anonymous">

<style>

html {

font-family: Arial;

display: inline-block;

margin: 0px auto;

text-align: center;

}

h2 { font-size: 3.0rem; }

p { font-size: 3.0rem; }

.units { font-size: 1.2rem; }

.ds-labels{


font-size: 1.5rem;

vertical-align:middle;

padding-bottom: 15px;

}

</style>

</head>

<body>

ESP DS18B20 Server





<i class="fas fa-thermometer-half" style="color:#059e8a;"></i>

<span class="ds-labels">Temperature Celsius</span>

<span id="temperaturec">%TEMPERATUREC%</span>

<sup class="units">°C</sup>






<i class="fas fa-thermometer-half" style="color:#059e8a;"></i>

<span class="ds-labels">Temperature Fahrenheit</span>

<span id="temperaturef">%TEMPERATUREF%</span>

18/26


<sup class="units">°F</sup>



</body>

<script>

setInterval(function ( ) {

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {

if (this.readyState == 4 && this.status == 200) {

document.getElementById("temperaturec").innerHTML = this.responseText;

}

};


xhttp.open("GET", "/temperaturec", true);

xhttp.send();

}, 10000) ;

setInterval(function ( ) {

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {

if (this.readyState == 4 && this.status == 200) {

document.getElementById("temperaturef").innerHTML = this.responseText;

}

};

xhttp.open("GET", "/temperaturef", true);

xhttp.send();

}, 10000) ;

</script>

</html>)rawliteral";


// Replaces placeholder with DS18B20 values

String processor(const String& var){

//Serial.println(var);

if(var == "TEMPERATUREC"){

return temperatureC;

}

else if(var == "TEMPERATUREF"){

return temperatureF;

}

return String();

}

void setup(){

// Serial port for debugging purposes

Serial.begin(115200);

Serial.println();


// Start up the DS18B20 library

sensors.begin();

temperatureC = readDSTemperatureC();

temperatureF = readDSTemperatureF();

// Connect to Wi-Fi

WiFi.begin(ssid, password);

Serial.println("Connecting to WiFi");

while (WiFi.status() != WL_CONNECTED) {

delay(500);

Serial.print(".");

19/26


}

Serial.println();

// Print ESP Local IP Address


Serial.println(WiFi.localIP());

// Route for root / web page

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){

request->send_P(200, "text/html", index_html, processor);

});

server.on("/temperaturec", HTTP_GET, [](AsyncWebServerRequest *request){

request->send_P(200, "text/plain", temperatureC.c_str());

});

server.on("/temperaturef", HTTP_GET, [](AsyncWebServerRequest *request){

request->send_P(200, "text/plain", temperatureF.c_str());

});

// Start server

server.begin();

}




void loop(){

if ((millis() - lastTime) > timerDelay) {

temperatureC = readDSTemperatureC();

temperatureF = readDSTemperatureF();

lastTime = millis();

}

}


Xem mã thô
Chèn thông tin đăng nhập mạng của bạn vào các biến sau và mã sẽ hoạt động ngay lập
tức.
const char* ssid = "REPLACE_WITH_YOUR_SSID";

const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Mã hoạt động như thế nào
Trong các đoạn sau, chúng tơi sẽ giải thích cách mã hoạt động. Hãy tiếp tục đọc nếu bạn
muốn tìm hiểu thêm hoặc chuyển đến phần "Trình diễn" để xem kết quả cuối cùng.
Nhập thư viện
Đầu tiên, nhập các thư viện cần thiết.
#include
#include
#include

#include
#include
#include
#include

<Arduino.h>

<ESP8266WiFi.h>

<Hash.h>

<ESPAsyncTCP.h>

<ESPAsyncWebServer.h>

<OneWire.h>

<DallasTemperature.h>

Cảm biến khởi tạo DS18B20

20/26



×