Hướng dẫn này chỉ ra cách xây dựng trạm thời tiết máy chủ web với ESP8266 NodeMCU để hiển thị các chỉ số cảm biến từ cảm biến môi trường BME680: khí (chất lượng không khí), nhiệt độ, độ ẩm và áp suất. Các bài đọc được cập nhật tự động trên máy chủ web bằng cách sử dụng Sự kiện do Máy chủ Gửi (SSE).Bo mạch ESP8266 sẽ được lập trình bằng Arduino IDE.
Trang 1ESP8266 Máy chủ web NodeMCU với BME680 - Trạm
thời tiết (Arduino IDE)
Hướng dẫn này chỉ ra cách xây dựng trạm thời tiết máy chủ web với ESP8266 NodeMCU
để hiển thị các chỉ số cảm biến từ cảm biến môi trường BME680: khí (chất lượng không khí), nhiệt độ, độ ẩm và áp suất Các bài đọc được cập nhật tự động trên máy chủ web
bằng cách sử dụng Sự kiện do Máy chủ Gửi (SSE) Bo mạch ESP8266 sẽ được lập trình bằng Arduino IDE.
Để xây dựng máy chủ web, chúng ta sẽ sử dụng thư viện Máy chủ Web ESP Async cung cấp một cách dễ dàng để xây dựng một máy chủ web không đồng bộ.
Cảm biến môi trường BME680
BME680 là một cảm biến môi trường kết hợp cảm biến khí, nhiệt độ, độ ẩm và áp suất.
Cảm biến khí có thể phát hiện một loạt các loại khí như các hợp chất hữu cơ dễ bay hơi (VOC) Vì lý do này, BME680 có thể được sử dụng trong kiểm soát chất lượng không khí trong nhà.
Trang 2BME680 chứa cảm biến MOX (Metal-oxide) phát hiện VOC trong không khí Cảm biến
này cung cấp cho bạn một ý tưởng định tính về tổng VOC / chất gây ô nhiễm trong
không khí xung quanh Là một tín hiệu thô, BME680 xuất ra các giá trị điện trở Các giá trị này thay đổi do sự thay đổi nồng độ VOC:
Nồng độ VOC cao hơn » Điện trở thấp hơn
Nồng độ VOC thấp hơn » Điện trở cao hơn
Trang 3Để biết thêm thông tin về BME680, hãy đọc hướng dẫn bắt đầu của chúng tôi: ESP8266 NodeMCU: Cảm biến môi trường BME680 sử dụng Arduino IDE (Khí, Áp suất, Độ ẩm,
Nhiệt độ).
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 phần sau:
Mô-đun cảm biến BME680
ESP8266 (đọc bảng phát triển ESP8266 tốt nhất)
Breadboard
Dây nhảy
Sơ đồ - ESP8266 với BME680
BME680 có thể giao tiếp bằng các giao thức truyền thông I2C hoặc SPI Trong hướng
dẫn này, chúng ta sẽ sử dụng giao thức truyền thông I2C.
Thực hiện theo sơ đồ tiếp theo để nối BME680 với ESP8266 bằng các chân I2C mặc
định.
Trang 4Đề xuất đọc: Tham khảo sơ đồ chân ESP8266: Bạn nên sử dụng chân GPIO nào?
Chuẩn bị Arduino IDE
Chúng tôi sẽ lập trình bo mạch ESP8266 bằng Arduino IDE Vì vậy, hãy đảm bảo rằng
bạn đã cài đặt tiện ích bổ sung ESP8266 Thực hiện theo hướng dẫn tiếp theo:
Cài đặt bảng ESP8266 trong Arduino IDE
Bạn cũng cần cài đặt các thư viện sau.
Làm theo hướng dẫn tiếp theo để cài đặt chúng.
Cài đặt Thư viện BME680
Để có được các bài đọc từ mô-đun cảm biến BME680, chúng tôi sẽ sử dụng thư viện
Adafruit_BME680 Làm theo các bước tiếp theo để cài đặt thư viện trong Arduino IDE
của bạn:
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ở.
Tìm kiếm "adafruit bme680" trên hộp Tìm kiếm và cài đặt thư viện.
Trang 5Cài đặt Thư viện Adafruit_Sensor
Để sử dụng thư viện BME680, bạn cũng cần cài đặt thư viện Adafruit_Sensor Làm theo các bước tiếp theo để cài đặt thư viện trong Arduino IDE của bạn:
Truy cập Sketch > Include Library > Manage Libraries và nhập "Adafruit Unified
Sensor" vào hộp tìm kiếm Cuộn xuống để tìm thư viện và cài đặt nó.
Cài đặt thư viện ESPAsyncWebServer
Trang 6Thư 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
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
Ngoài ra, trong Arduino IDE, bạn có thể vào Sketch > Include Library > Add zip Library
và chọn thư viện bạn vừa tải xuống.
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
Ngoài ra, trong Arduino IDE, bạn có thể vào Sketch > Include Library > Add zip Library
và chọn thư viện bạn vừa tải xuống.
Mã máy chủ Web ESP8266 BME680
Mở Arduino IDE của bạn và sao chép mã sau Để làm cho nó hoạt động, bạn cần chèn
thông tin đăng nhập mạng của mình: SSID và mật khẩu.
Trang 7/*********
Rui Santos
Complete project details at
https://RandomNerdTutorials.com/esp8266-nodemcu-bme680-sensor-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software
*********/
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
#include <ESP8266WiFi.h>
#include "ESPAsyncWebServer.h"
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
//Uncomment if using SPI
/*#define BME_SCK 14
#define BME_MISO 12
#define BME_MOSI 13
#define BME_CS 15*/
Adafruit_BME680 bme; // I2C
//Adafruit_BME680 bme(BME_CS); // hardware SPI
//Adafruit_BME680 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK);
float temperature;
float humidity;
float pressure;
float gasResistance;
AsyncWebServer server(80);
AsyncEventSource events("/events");
unsigned long lastTime = 0;
unsigned long timerDelay = 30000; // send readings timer
void getBME680Readings(){
// Tell BME680 to begin measurement
unsigned long endTime = bme.beginReading();
if (endTime == 0) {
Serial.println(F("Failed to begin reading :("));
return;
}
if (!bme.endReading()) {
Serial.println(F("Failed to complete reading :("));
return;
}
temperature = bme.temperature;
Trang 8pressure = bme.pressure / 100.0;
humidity = bme.humidity;
gasResistance = bme.gas_resistance / 1000.0;
}
String processor(const String& var){
getBME680Readings();
//Serial.println(var);
if(var == "TEMPERATURE"){
return String(temperature);
}
else if(var == "HUMIDITY"){
return String(humidity);
}
else if(var == "PRESSURE"){
return String(pressure);
}
else if(var == "GAS"){
return String(gasResistance);
}
return String();
}
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<title>BME680 Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr"
crossorigin="anonymous">
<link rel="icon" href="data:,">
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
p { font-size: 1.2rem;}
body { margin: 0;}
.topnav { overflow: hidden; background-color: #4B1D3F; color: white;
font-size: 1.7rem; }
.content { padding: 20px; }
.card { background-color: white; box-shadow: 2px 2px 12px 1px
rgba(140,140,140,.5); }
.cards { max-width: 700px; margin: 0 auto; display: grid; grid-gap: 2rem;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); }
.reading { font-size: 2.8rem; }
.card.temperature { color: #0e7c7b; }
.card.humidity { color: #17bebb; }
.card.pressure { color: #3fca6b; }
.card.gas { color: #d62246; }
</style>
</head>
<body>
<div class="topnav">
<h3>BME680 WEB SERVER</h3>
</div>
<div class="content">
Trang 9<div class="cards">
<div class="card temperature">
<h4><i class="fas fa-thermometer-half"></i> TEMPERATURE</h4><p><span
class="reading"><span id="temp">%TEMPERATURE%</span> °C</span></p>
</div>
<div class="card humidity">
<h4><i class="fas fa-tint"></i> HUMIDITY</h4><p><span class="reading">
<span id="hum">%HUMIDITY%</span> %</span></p>
</div>
<div class="card pressure">
<h4><i class="fas fa-angle-double-down"></i> PRESSURE</h4><p><span
class="reading"><span id="pres">%PRESSURE%</span> hPa</span></p>
</div>
<div class="card gas">
<h4><i class="fas fa-wind"></i> GAS</h4><p><span class="reading"><span
id="gas">%GAS%</span> KΩ</span></p>
</div>
</div>
</div>
<script>
if (!!window.EventSource) {
var source = new EventSource('/events');
source.addEventListener('open', function(e) {
console.log("Events Connected");
}, false);
source.addEventListener('error', function(e) {
if (e.target.readyState != EventSource.OPEN) {
console.log("Events Disconnected");
}
}, false);
source.addEventListener('message', function(e) {
console.log("message", e.data);
}, false);
source.addEventListener('temperature', function(e) {
console.log("temperature", e.data);
document.getElementById("temp").innerHTML = e.data;
}, false);
source.addEventListener('humidity', function(e) {
console.log("humidity", e.data);
document.getElementById("hum").innerHTML = e.data;
}, false);
source.addEventListener('pressure', function(e) {
console.log("pressure", e.data);
document.getElementById("pres").innerHTML = e.data;
}, false);
source.addEventListener('gas', function(e) {
console.log("gas", e.data);
document.getElementById("gas").innerHTML = e.data;
}, false);
}
Trang 10</script>
</body>
</html>)rawliteral";
void setup() {
Serial.begin(115200);
// Set the device as a Station and Soft Access Point simultaneously
WiFi.mode(WIFI_AP_STA);
// Set device as a Wi-Fi Station
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Setting as a Wi-Fi Station ");
}
Serial.print("Station IP Address: ");
Serial.println(WiFi.localIP());
Serial.println();
// Init BME680 sensor
if (!bme.begin()) {
Serial.println(F("Could not find a valid BME680 sensor, check wiring!"));
while (1);
}
// Set up oversampling and filter initialization
bme.setTemperatureOversampling(BME680_OS_8X);
bme.setHumidityOversampling(BME680_OS_2X);
bme.setPressureOversampling(BME680_OS_4X);
bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
bme.setGasHeater(320, 150); // 320*C for 150 ms
// Handle Web Server
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
// Handle Web Server Events
events.onConnect([](AsyncEventSourceClient *client){
if(client->lastId()){
Serial.printf("Client reconnected! Last message ID that it got is: %u\n",
client->lastId());
}
// send event with message "hello!", id current millis
// and set reconnect delay to 1 second
client->send("hello!", NULL, millis(), 10000);
});
server.addHandler(&events);
server.begin();
}
void loop() {
if ((millis() - lastTime) > timerDelay) {
getBME680Readings();
Serial.printf("Temperature = %.2f ºC \n", temperature);
Serial.printf("Humidity = %.2f % \n", humidity);
Trang 11Serial.printf("Pressure = %.2f hPa \n", pressure);
Serial.printf("Gas Resistance = %.2f KOhm \n", gasResistance);
Serial.println();
// Send Events to the Web Server with the Sensor Readings
events.send("ping",NULL,millis());
events.send(String(temperature).c_str(),"temperature",millis());
events.send(String(humidity).c_str(),"humidity",millis());
events.send(String(pressure).c_str(),"pressure",millis());
events.send(String(gasResistance).c_str(),"gas",millis());
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
Đọc phần này để tìm hiểu cách mã hoạt động hoặc chuyển sang phần tiếp theo.
Bao gồm cả thư viện
Bắt đầu bằng cách bao gồm các thư viện cần thiết Thư viện Wire là cần thiết cho giao
thức truyền thông I2C Chúng tôi cũng bao gồm thư viện SPI nếu bạn muốn sử dụng giao tiếp SPI thay thế.
#include <Wire.h>
#include <SPI.h>
Các thư viện Adafruit_Sensor và Adafruit_BME680 là cần thiết để giao tiếp với cảm biến BME680.
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
Các thư viện WiFi và ESPAsyncWebServer được sử dụng để tạo máy chủ web.
#include <ESP8266WiFi.h>
#include "ESPAsyncWebServer.h"
Thông tin đăng nhập mạng
Chèn thông tin đăng nhập mạng của bạn vào các biến sau, để ESP8266 có thể kết nối
với mạng cục bộ của bạn bằng Wi-Fi.
Trang 12const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
Giao tiếp I2C
Tạo một đối tượng Adafruit_BME680 gọi là bme trên các chân I8266C ESP2 mặc định.
Adafruit_BME680 bme; // I2C
Nếu bạn muốn sử dụng giao tiếp SPI thay thế, bạn cần xác định các chân SPI ESP8266 trên các dòng sau (để bỏ ghi chú, hãy xóa /* và */):
/*#define BME_SCK 14
#define BME_MISO 12
#define BME_MOSI 13
#define BME_CS 15*/
Và sau đó, tạo một đối tượng Adafruit_BME680 bằng cách sử dụng các chân đó (để bỏ ghi chú xóa //).
//Adafruit_BME680 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK);
Khai báo biến
Các biến phao nhiệt độ, độ ẩm, áp suất và điện trở khí sẽ được sử dụng để giữ số đọc
cảm biến BME680.
float temperature;
float humidity;
float pressure;
float gasResistance;
Các biến lastTime và timerDelay sẽ được sử dụng để cập nhật số đọc cảm biến sau mỗi
X số giây Ví dụ: chúng tôi sẽ nhận được số đọc cảm biến mới cứ sau 30 giây (30000 mili giây) Bạn có thể thay đổi thời gian trễ đó trong biến timerDelay.
unsigned long lastTime = 0;
unsigned long timerDelay = 30000;
Tạo một máy chủ Web không đồng bộ trên cổng 80.
AsyncWebServer server(80);
Tạo nguồn sự kiện
Để tự động hiển thị thông tin trên máy chủ web khi có kết quả đọc mới, chúng tôi sẽ sử
dụng Sự kiện do máy chủ gửi (SSE).
Dòng sau tạo nguồn sự kiện mới trên /events.
AsyncEventSource events("/events");