ESP8266 Máy chủ web NodeMCU với BME680 Trạm thời tiết (Arduino IDE)

20 1 0
ESP8266 Máy chủ web NodeMCU với BME680  Trạm thời tiết (Arduino IDE)

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

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.

ESP8266 Máy chủ web NodeMCU với BME680 - Trạm thời tiết (Arduino IDE) Hướng dẫn cách xây dựng trạm thời tiết máy chủ web với ESP8266 NodeMCU để hiển thị 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 áp suất Các đọc cập nhật tự động máy chủ web cách sử dụng Sự kiện Máy chủ Gửi (SSE) Bo mạch ESP8266 lập trình Arduino IDE Để xây dựng máy chủ web, sử dụng thư viện Máy chủ Web ESP Async cung cấp cách dễ dàng để xây dựng máy chủ web không đồng Cảm biến môi trường BME680 BME680 cảm biến mơi trường kết hợp cảm biến khí, nhiệt độ, độ ẩm áp suất Cảm biến khí phát loạt loại khí hợp chất hữu dễ bay (VOC) Vì lý này, BME680 sử dụng kiểm sốt chất lượng khơng khí nhà 1/20 BME680 chứa cảm biến MOX (Metal-oxide) phát VOC không khí Cảm biến cung cấp cho bạn ý tưởng định tính tổng VOC / chất gây nhiễm khơng khí xung quanh Là tín hiệu thô, BME680 xuất giá trị điện trở Các giá trị thay đổi thay đổi nồng độ VOC: Nồng độ VOC cao » Điện trở thấp Nồng độ VOC thấp » Điện trở cao 2/20 Để biết thêm thông tin BME680, đọc hướng dẫn bắt đầu 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 phận cần thiết Để hoàn thành hướng dẫn này, bạn cần 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 giao tiếp giao thức truyền thông I2C SPI Trong hướng dẫn này, sử dụng giao thức truyền thông I2C Thực theo sơ đồ để nối BME680 với ESP8266 chân I2C mặc định 3/20 Đề 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 lập trình bo mạch ESP8266 Arduino IDE Vì vậy, đảm bảo bạn cài đặt tiện ích bổ sung ESP8266 Thực theo hướng dẫn tiếp theo: Cài đặt bảng ESP8266 Arduino IDE Bạn cần cài đặt thư viện sau Làm theo hướng dẫn để cài đặt chúng Cài đặt Thư viện BME680 Để có đọc từ mô-đun cảm biến BME680, sử dụng thư viện Adafruit_BME680 Làm theo bước để cài đặt thư viện Arduino IDE bạn: Mở Arduino IDE bạn tới Sketch > Include Library > Manage Libraries Trình quản lý thư viện mở Tìm kiếm "adafruit bme680" hộp Tìm kiếm cài đặt thư viện 4/20 Cài đặt Thư viện Adafruit_Sensor Để sử dụng thư viện BME680, bạn cần cài đặt thư viện Adafruit_Sensor Làm theo bước để cài đặt thư viện Arduino IDE bạn: Truy cập Sketch > Include Library > Manage Libraries nhập "Adafruit Unified Sensor" vào hộp tìm kiếm Cuộn xuống để tìm thư viện cài đặt Cài đặt thư viện ESPAsyncWebServer 5/20 Thư viện ESPAsyncWebServer khơng có sẵn để cài đặt Trình quản lý thư viện Arduino IDE Vì vậy, bạn cần cài đặt tay Làm theo bước để cài đặt thư viện ESPAsyncWebServer: Bấm vào để tải xuống thư viện ESPAsyncWebServer Bạn có thư mục zip thư mục Tải xuống Giải nén thư mục zip bạn nhận thư mục ESPAsyncWebServer-master Đổi tên thư mục bạn từ ESPAsyncWebServer-master thành ESPAsyncWebServer Di chuyển thư mục ESPAsyncWebServer vào thư mục thư viện cài đặt Arduino IDE bạn Ngoài ra, Arduino IDE, bạn vào Sketch > Include Library > Add zip Library 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 bước để cài đặt thư viện đó: Bấm vào để tải xuống thư viện ESPAsyncTCP Bạn có thư mục zip thư mục Tải xuống Giải nén thư mục zip bạn nhận thư mục ESPAsyncTCP-master Đổi tên thư mục bạn từ ESPAsyncTCP-master thành ESPAsyncTCP Di chuyển thư mục ESPAsyncTCP vào thư mục thư viện cài đặt Arduino IDE bạn Cuối cùng, mở lại Arduino IDE bạn Ngoài ra, Arduino IDE, bạn vào Sketch > Include Library > Add zip Library chọn thư viện bạn vừa tải xuống Mã máy chủ Web ESP8266 BME680 Mở Arduino IDE bạn chép mã sau Để làm cho hoạt động, bạn cần chèn thơng tin đăng nhập mạng mình: SSID mật 6/20 /********* Rui Santos Complete project details at https://RandomNerdTutorials.com/esp8266-nodemcubme680-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 #include #include #include #include #include "Adafruit_BME680.h" "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 float float float temperature; humidity; pressure; 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; 7/20 pressure = 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( BME680 Web Server 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; fontsize: 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: 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; } BME680 WEB SERVER 8/20 TEMPERATURE

%TEMPERATURE% °C

HUMIDITY

%HUMIDITY% %

PRESSURE

%PRESSURE% hPa

GAS

%GAS%

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); } 9/20 )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 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); 10/20 Serial.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 bạn vào biến sau mã hoạt động const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD"; Mã hoạt động Đọc phần để tìm hiểu cách mã hoạt động chuyển sang phần Bao gồm thư viện Bắt đầu cách bao gồm thư viện cần thiết Thư viện Wire cần thiết cho giao thức truyền thông I2C Chúng bao gồm thư viện SPI bạn muốn sử dụng giao tiếp SPI thay #include #include Các thư viện Adafruit_Sensor Adafruit_BME680 cần thiết để giao tiếp với cảm biến BME680 #include #include "Adafruit_BME680.h" Các thư viện WiFi ESPAsyncWebServer sử dụng để tạo máy chủ web #include #include "ESPAsyncWebServer.h" Thông tin đăng nhập mạng Chèn thông tin đăng nhập mạng bạn vào biến sau, để ESP8266 kết nối với mạng cục bạn Wi-Fi 11/20 const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD"; Giao tiếp I2C Tạo đối tượng Adafruit_BME680 gọi bme 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 chân SPI ESP8266 dòng sau (để bỏ ghi chú, xóa /* */): /*#define BME_SCK 14 #define BME_MISO 12 #define BME_MOSI 13 #define BME_CS 15*/ Và sau đó, tạo đối tượng Adafruit_BME680 cách sử dụng chân (để bỏ ghi 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 điện trở khí sử dụng để giữ số đọc cảm biến BME680 float float float float temperature; humidity; pressure; gasResistance; Các biến lastTime timerDelay sử dụng để cập nhật số đọc cảm biến sau X số giây Ví dụ: chúng tơi nhận số đọc cảm biến sau 30 giây (30000 mili giây) Bạn thay đổi thời gian trễ biến timerDelay unsigned long lastTime = 0; unsigned long timerDelay = 30000; Tạo máy chủ Web không đồng cổng 80 AsyncWebServer server(80); Tạo nguồn kiện Để tự động hiển thị thông tin máy chủ web có kết đọc mới, chúng tơi sử dụng Sự kiện máy chủ gửi (SSE) Dòng sau tạo nguồn kiện /events AsyncEventSource events("/events"); 12/20 Sự kiện máy chủ gửi cho phép trang web (máy khách) nhận cập nhật từ máy chủ Chúng sử dụng điều để tự động hiển thị đọc trang máy chủ web đọc BME680 có sẵn Quan trọng: Sự kiện máy chủ gửi không hỗ trợ Internet Explorer Nhận đọc BME680 Hàm getBME680Reading () nhận số khí, nhiệt độ, độ ẩm áp suất từ cảm biến BME680 lưu chúng biến khíĐiện trở, nhiệt độ , độ ẩm áp suất 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; pressure = bme.pressure / 100.0; humidity = bme.humidity; gasResistance = bme.gas_resistance / 1000.0; } Xử lý Hàm processor() thay trình giữ chỗ văn HTML sử dụng để xây dựng trang web đọc cảm biến 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); } } Điều cho phép hiển thị đọc cảm biến trang web bạn truy cập lần Nếu khơng, bạn thấy khoảng trống có đọc (có thể chút thời gian tùy thuộc vào thời gian trễ bạn xác định 13/20 mã) Xây dựng trang Web Biến index_html chứa tất HTML, CSS JavaScript để xây dựng trang web Chúng không vào chi tiết cách HTML CSS hoạt động Chúng ta xem xét cách xử lý kiện gửi máy chủ Chúng ta xem nhanh dòng hiển thị nhiệt độ: TEMPERATURE

%TEMPERATURE% °C

Bạn thấy chỗ dành sẵn %TEMPERATURE% bao quanh thẻ Thuộc tính HTML id sử dụng để định id cho phần tử HTML Nó sử dụng để trỏ đến kiểu cụ thể JavaScript sử dụng để truy cập thao tác với phần tử với id cụ thể Đó chúng tơi làm Ví dụ: máy chủ web nhận kiện với số nhiệt độ nhất, cập nhật phần tử HTML với id "temp" với cách đọc Một trình tương tự thực để cập nhật đọc khác Xử lý kiện Tạo đối tượng EventSource định URL trang gửi cập nhật Trong trường hợp chúng tơi, /events if (!!window.EventSource) { var source = new EventSource('/events'); Khi bạn khởi tạo nguồn kiện, bạn bắt đầu nghe thư từ máy chủ addEventListener() Đây trình nghe kiện mặc định, hiển thị tài liệu AsyncWebServer 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); 14/20 Sau đó, thêm trình nghe kiện cho "nhiệt độ" source.addEventListener('temperature', function(e) { Khi có số nhiệt độ mới, ESP8266 gửi kiện ("nhiệt độ") cho khách hàng Các dịng sau xử lý xảy trình duyệt nhận kiện console.log("temperature", e.data); document.getElementById("temp").innerHTML = e.data; Về bản, in đọc bảng điều khiển trình duyệt đặt liệu nhận vào phần tử với id tương ứng ("temp") trang web Một xử lý tương tự thực cho độ ẩm, áp suất khả chống khí 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); Thiết lập() Trong setup(), khởi tạo Serial Monitor Serial.begin(115200); Kết nối ESP8266 với mạng cục bạn in địa IP ESP8266 // 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(); Khởi tạo cảm biến BME680 15/20 // 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 Xử lý yêu cầu Khi bạn truy cập địa IP ESP8266 thư mục gốc / URL, gửi văn lưu trữ biến index_html để xây dựng trang web chuyển xử lý làm đối số, để tất trình giữ chỗ thay đọc cảm biến server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/html", index_html, processor); }); Nguồn kiện máy chủ Thiết lập nguồn kiện máy chủ // 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 second client->send("hello!", NULL, millis(), 10000); }); server.addHandler(&events); Cuối cùng, khởi động máy chủ server.begin(); vòng lặp() Trong loop(), nhận số cảm biến mới: getBME680Readings(); In đọc Màn hình nối tiếp Serial.printf("Temperature = %.2f ºC \n", temperature); Serial.printf("Humidity = %.2f % \n", humidity); Serial.printf("Pressure = %.2f hPa \n", pressure); Serial.printf("Gas Resistance = %.2f KOhm \n", gasResistance); Serial.println(); 16/20 Cuối cùng, gửi kiện đến trình duyệt với đọc cảm biến để cập nhật trang web // 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()); Sơ đồ sau tóm tắt cách hoạt động Sự kiện Máy chủ Gửi để cập nhật trang web Tải mã lên Bây giờ, tải mã lên ESP8266 bạn Đảm bảo bạn chọn bo mạch cổng COM 17/20 Sau tải lên, mở Màn hình nối tiếp với tốc độ truyền 115200 Nhấn nút RST / EN bo mạch ESP8266 Địa IP phải in hình nối tiếp Cuộc biểu tình Mở trình duyệt mạng cục bạn nhập địa IP ESP8266 Bạn có quyền truy cập vào máy chủ web ESP8266 với đọc BME680 Các đọc cập nhật tự động cách sử dụng Sự kiện máy chủ gửi 18/20 Tổng kết Trong hướng dẫn này, bạn học cách xây dựng trạm thời tiết máy chủ web không đồng với ESP8266 để hiển thị số đọc cảm biến BME680 - khí (chất lượng khơng khí), nhiệt độ, độ ẩm áp suất - cách cập nhật đọc tự động trang web Sự kiện máy chủ gửi Chúng tơi có hướng dẫn máy chủ web khác mà bạn thích: ESP8266 DHT11 / DHT22 Nhiệt độ Độ ẩm Máy chủ Web với Arduino IDE Máy chủ web ESP8266 - Kiểm soát đầu với Arduino IDE 19/20 ESP8266 với BME280 sử dụng Arduino IDE (Áp suất, Nhiệt độ, Độ ẩm) Cảm biến nhiệt độ ESP8266 DS18B20 với Arduino IDE (Máy chủ Web, Đơn, Nhiều) Chúng hy vọng bạn tìm thấy dự án thú vị Tìm hiểu thêm ESP8266 với tài nguyên chúng tơi: Tự động hóa nhà ESP8266 Lập trình MicroPython với ESP32 ESP8266 Các dự án hướng dẫn ESP8266 khác Cảm ơn bạn đọc 20/20

Ngày đăng: 09/04/2023, 19:53

Tài liệu cùng người dùng

Tài liệu liên quan