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
| #include <WiFi.h>
#include <PubSubClient.h>
#include <DHT11.h>
DHT11 dht11(2);
const char* ssid = "your wifi ssid";
const char* password = "your wifi password";
//Mqtt服务器
const char* mqtt_server = "test.mosquitto.org";
WiFiClient espClient;
//创建MQTT客户端对象
PubSubClient client(espClient);
//上一次发送数据的时间戳
long lastMsg = 0;
char msg[50]; //发送的消息字符串
int value = 0; //待发送数据
int temperature = 0; //温度
int humidity = 0; //湿度
void setup() {
// put your setup code here, to run once:
//初始化串口通信
Serial.begin(115200);
//配置wifi连接
setup_wifi();
//配置mqtt服务器
client.setServer(mqtt_server,1883);
}
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
//连接wifi网络
WiFi.begin(ssid,password);
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
//循环尝试mqtt连接
while(!client.connected()) {
Serial.print("Attempting MQTT connection...");
//String clientId = "ESP32Client-";
//clientId += String(random(0xffff), HEX);
//尝试连接mqtt服务器
if(client.connect("esp32c3_Telemetry")) {
Serial.println("connected");
//client.subscribe("esp32c3_Telemetry/temp"); //订阅主题
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
// put your main code here, to run repeatedly:
//如果MQTT客户端没有连接
if(!client.connected()) {
reconnect();
}
//MQTT客户端保持连接
client.loop();
//获取当前时间
long now = millis();
//存储温湿度值的数组
//float temp_hum_val[2] = {0};
//如果当前时间与上次消息发送时间间隔超过5s
if(now - lastMsg > 5000) {
//更新上次发送消息时间
lastMsg = now;
//获取温湿度值
int result = dht11.readTemperatureHumidity(temperature, humidity);
//温度值转化为字符串缓冲区
char tempString[8];
dtostrf(temperature,1,2,tempString);
Serial.print("Temerature: ");
Serial.println(tempString); //打印温度字符
//String temp= tempString +" °C";
client.publish("esp32c3_Telemetry/Temperaturedataread",tempString); //发布mqtt温度数据
//湿度值转化为字符串缓冲区
char humString[8];
dtostrf(humidity,1,2,humString);
Serial.print("Humidity: ");
Serial.println(humString); //打印温度字符
//String hum = humString +" %";
client.publish("esp32c3_Telemetry/Humiditydataread",humString); //发布mqtt温度数据
}
}
|