108个传感器之-BME280(54)

108个传感器之-BME280(54)

介绍

BME280 是一个用于测量温度、湿度和气压的传感器。它具有 I2C 和 SPI 接口,因此可以轻松集成到各种项目中。在本教程中,我们将使用 ESP8266 和 BME280 传感器来创建一个简单的 Web 服务器,该服务器将传感器数据发送到浏览器。

代码示例

我们将使用I2C通信与BME280传感器模块。为此,将传感器连接到默认的ESP8266 SCL (GPIO 5) 和SDA (GPIO 4) 引脚,如下面的示意图所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*********
Rui Santos
Complete instructions at https://RandomNerdTutorials.com/esp8266-nodemcu-websocket-server-sensor/

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 <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "LittleFS.h"
#include <Arduino_JSON.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>

// 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);

// Create a WebSocket object
AsyncWebSocket ws("/ws");

// Json Variable to Hold Sensor Readings
JSONVar readings;

// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 30000;

// Create a sensor object
Adafruit_BME280 bme; // BME280 connect to ESP32 I2C (GPIO 21 = SDA, GPIO 22 = SCL)

// Init BME280
void initBME(){
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
}

// Get Sensor Readings and return JSON object
String getSensorReadings(){
readings["temperature"] = String(bme.readTemperature());
readings["humidity"] = String(bme.readHumidity());
readings["pressure"] = String(bme.readPressure()/100.0F);
String jsonString = JSON.stringify(readings);
return jsonString;
}

// Initialize LittleFS
void initFS() {
if (!LittleFS.begin()) {
Serial.println("An error has occurred while mounting LittleFS");
}
else{
Serial.println("LittleFS mounted successfully");
}
}

// Initialize WiFi
void initWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}

void notifyClients(String sensorReadings) {
ws.textAll(sensorReadings);
}

void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
AwsFrameInfo *info = (AwsFrameInfo*)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
//data[len] = 0;
//String message = (char*)data;
// Check if the message is "getReadings"
//if (strcmp((char*)data, "getReadings") == 0) {
//if it is, send current sensor readings
String sensorReadings = getSensorReadings();
Serial.print(sensorReadings);
notifyClients(sensorReadings);
//}
}
}

void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
switch (type) {
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(arg, data, len);
break;
case WS_EVT_PONG:
case WS_EVT_ERROR:
break;
}
}

void initWebSocket() {
ws.onEvent(onEvent);
server.addHandler(&ws);
}

void setup() {
Serial.begin(115200);
initBME();
initWiFi();
initFS();
initWebSocket();

// Web Server Root URL
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(LittleFS, "/index.html", "text/html");
});

server.serveStatic("/", LittleFS, "/");

// Start server
server.begin();
}

void loop() {
if ((millis() - lastTime) > timerDelay) {
String sensorReadings = getSensorReadings();
Serial.print(sensorReadings);
notifyClients(sensorReadings);

lastTime = millis();

}

ws.cleanupClients();
}

参考

https://randomnerdtutorials.com/esp8266-nodemcu-websocket-server-sensor

作者

dev

发布于

2025-01-27

更新于

2025-11-07

许可协议

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×