ESP32 接收温湿度信息通过串口通信传输给ESP8266mqtt上次阿里云的代码
时间: 2023-07-15 15:15:00 浏览: 70
下面是一个简单的示例代码,用于ESP32通过串口读取DHT11传感器的温湿度数据,并将其传输到ESP8266连接的MQTT服务器上:
```C++
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#include <WiFi.h>
#define DHTPIN 4
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
#define RX 16
#define TX 17
SoftwareSerial Serial1(RX, TX); // RX, TX
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqttServer = "your_MQTT_server_address";
const int mqttPort = 1883;
const char* mqttUser = "your_MQTT_username";
const char* mqttPassword = "your_MQTT_password";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client", mqttUser, mqttPassword)) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void loop() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" *C");
String payload = String(temperature) + "," + String(humidity);
client.publish("your_topic", payload.c_str());
delay(5000);
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
}
Serial.println();
}
```
注意,上述代码需要使用以下库:
- Adafruit_Sensor
- DHT
- SoftwareSerial
- PubSubClient
- WiFi
在代码中,我们首先定义了DHT11传感器的引脚和类型。接下来,我们定义了ESP8266连接的MQTT服务器的信息,以及WiFi网络的SSID和密码。然后,我们初始化WiFi连接和MQTT客户端,并在主循环中读取DHT11传感器的温湿度数据,并将其转换为字符串形式,然后通过MQTT发布到指定的主题中。最后,我们还定义了一个回调函数,用于处理从MQTT服务器接收到的消息。
阅读全文