在ESP8266上编写代码,以连接到OneNet的MQTT服务器上传dht11模块所监测的数据
时间: 2023-05-27 22:02:13 浏览: 130
使用ESP8266进行片上 开发MQTT客户端设备(采集气象站数据上传到MQTT服务器).zip
下面是一个示例的ESP8266代码,以连接到OneNet的MQTT服务器上传dht11模块所监测的温度和湿度数据:
```c++
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// Replace with your WiFi credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Replace with your OneNet MQTT Host and Key
const char* mqtt_server = "mqtt.heclouds.com";
const char* mqtt_username = "your_MQTT_Username";
const char* mqtt_password = "your_MQTT_Password";
const char* mqtt_topic = "your_MQTT_Topic";
// Replace with your DHT11 connected pin
#define DHTPIN D1
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
dht.begin();
delay(100);
WiFi.begin(ssid, password);
Serial.println();
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected to WiFi: ");
Serial.println(WiFi.SSID());
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
Serial.println("Connecting to MQTT...");
while (!client.connected()) {
if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) {
Serial.println("MQTT connected!");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.subscribe(mqtt_topic);
}
void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
String msg = String("{\"datastreams\":[{\"id\":\"temp\",\"datapoints\":[{\"value\":\"") + t + String("\"}]}," +
"{\"id\":\"humi\",\"datapoints\":[{\"value\":\"") + h + String("\"}]}]}");
Serial.print("Sending to OneNet: ");
Serial.println(msg);
if (!client.connected()) {
reconnect();
}
client.publish(mqtt_topic, (char*)msg.c_str());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.printf("Message arrived [%s]: ", topic);
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");
if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) {
Serial.println("MQTT connected!");
client.subscribe(mqtt_topic);
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
```
请注意:在使用该代码之前,您需要进行以下更改:
1. 替换“ssid”和“password”与您的WiFi凭证。
2. 替换“mqtt_server”、“mqtt_username”和“mqtt_password”与您在OneNet上创建的MQTT套餐的相关数据。
3. 替换DHT模块连接的引脚(在示例中为D1)。
该代码将读取DHT11模块的温度和湿度数据,将其打包到指定MQTT主题的消息中,并上传到OneNet。您可以在您的OneNet帐户中查看和分析数据。
阅读全文