ESP32 接收温湿度信息通过串口通信传输给ESP8266mqtt上次阿里云的代码
时间: 2023-07-15 16:14:56 浏览: 177
以下是 ESP32 接收温湿度信息并通过串口通信传输给 ESP8266,最终发送到阿里云的示例代码:
```
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <WiFi.h>
#include <PubSubClient.h>
// DHT11传感器引脚定义
#define DHTPIN 18
// DHT11传感器类型
#define DHTTYPE DHT11
// WiFi 接入点名称和密码
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// MQTT Broker 地址和端口
const char* broker = "your_BROKER_ADDRESS";
const int port = your_BROKER_PORT;
// MQTT 订阅主题和发布主题
const char* subscribeTopic = "your_topic/sub";
const char* publishTopic = "your_topic/pub";
// 创建 WiFi 客户端
WiFiClient wifiClient;
// 创建 MQTT 客户端
PubSubClient mqttClient(wifiClient);
// 创建 DHT11 对象
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// 初始化串口
Serial.begin(115200);
// 初始化 DHT11 传感器
dht.begin();
// 连接 WiFi 网络
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected.");
// 连接 MQTT Broker
mqttClient.setServer(broker, port);
while (!mqttClient.connected()) {
Serial.println("Connecting to MQTT Broker...");
if (mqttClient.connect("ESP32Client")) {
Serial.println("MQTT Broker connected.");
mqttClient.subscribe(subscribeTopic);
} else {
Serial.print("Failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
// 读取温湿度数据
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// 如果读取失败,则重试
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
delay(2000);
return;
}
// 将温湿度数据输出到串口
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("%\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println("°C");
// 将温湿度数据转换为 JSON 格式
String payload = "{\"humidity\":" + String(humidity) + ",\"temperature\":" + String(temperature) + "}";
// 将温湿度数据发布到 MQTT Broker
mqttClient.publish(publishTopic, payload.c_str());
// 等待 5 秒
delay(5000);
}
```
请替换代码中的 WiFi 接入点名称和密码、MQTT Broker 地址和端口、订阅主题和发布主题,然后将代码分别上传到 ESP32 和 ESP8266 上即可。
阅读全文