设计并制作一套基于ESP32的温湿度采集系统,要求通过ESP32连接DHT11传感器采集温湿度数据,通过MQTT协议上传到ONENET服务器。
时间: 2023-12-25 07:03:12 浏览: 140
好的,这是一个基于ESP32的温湿度采集系统,我会为您提供一些指导和建议。
1. 硬件准备
您需要准备以下硬件:
- ESP32开发板
- DHT11温湿度传感器
- 面包板
- 杜邦线
2. 硬件连接
将DHT11传感器的VCC引脚接到ESP32的3.3V引脚,将DHT11传感器的GND引脚接到ESP32的GND引脚,将DHT11传感器的DATA引脚接到ESP32的GPIO引脚。
3. 软件准备
您需要安装Arduino IDE,并在Arduino IDE中安装ESP32开发板库和PubSubClient库。
4. 编写代码
请参考以下代码:
```
#include <WiFi.h>
#include <PubSubClient.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#define WIFI_SSID "your_wifi_ssid"
#define WIFI_PASSWORD "your_wifi_password"
#define MQTT_SERVER "your_mqtt_server"
#define MQTT_PORT 1883
#define MQTT_USERNAME "your_mqtt_username"
#define MQTT_PASSWORD "your_mqtt_password"
#define MQTT_TOPIC "your_mqtt_topic"
#define DHTPIN 18
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
void setup() {
Serial.begin(115200);
delay(1000);
dht.begin();
connectWiFi();
connectMQTT();
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read data from DHT sensor");
return;
}
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
char payload[50];
sprintf(payload, "{\"temperature\":%.2f,\"humidity\":%.2f}", temperature, humidity);
mqttClient.publish(MQTT_TOPIC, payload);
delay(5000);
}
void connectWiFi() {
Serial.print("Connecting to WiFi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to WiFi");
}
void connectMQTT() {
mqttClient.setServer(MQTT_SERVER, MQTT_PORT);
while (!mqttClient.connected()) {
Serial.print("Connecting to MQTT server...");
if (mqttClient.connect("ESP32Client", MQTT_USERNAME, MQTT_PASSWORD)) {
Serial.println("Connected to MQTT server");
} else {
Serial.print("Failed to connect to MQTT server, rc=");
Serial.print(mqttClient.state());
Serial.println(" retrying in 5 seconds");
delay(5000);
}
}
}
```
5. 上传代码
将代码上传到ESP32开发板。
6. 测试
打开串口监视器,将波特率设置为115200,可以看到ESP32连接WiFi和MQTT服务器,并且定期上传温湿度数据。
以上是基于ESP32的温湿度采集系统的设计和制作过程。如果您有任何疑问,请随时向我提问。
阅读全文