基于Arduino IDE的ESP8266模块读取DHT11温湿度并上传至阿里云代码
时间: 2024-05-01 07:20:47 浏览: 185
物联网项目实战开发之基于STM32+ESP8266上传DHT12温湿度到阿里云物联网平台代码程序
5星 · 资源好评率100%
以下是基于Arduino IDE的ESP8266模块读取DHT11温湿度并上传至阿里云的示例代码,其中包含了一些必要的库和变量设置,请根据自己的实际需求进行修改:
```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// WiFi参数
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// MQTT服务器参数
const char* mqtt_server = "your_MQTT_SERVER";
const int mqtt_port = 1883;
const char* mqtt_user = "your_MQTT_USERNAME";
const char* mqtt_password = "your_MQTT_PASSWORD";
// 阿里云产品参数
const char* productKey = "your_PRODUCT_KEY";
const char* deviceName = "your_DEVICE_NAME";
const char* deviceSecret = "your_DEVICE_SECRET";
// DHT11引脚
#define DHTPIN D1
// DHT11类型
#define DHTTYPE DHT11
// DHT11对象
DHT dht(DHTPIN, DHTTYPE);
// WiFi客户端对象和MQTT客户端对象
WiFiClient espClient;
PubSubClient client(espClient);
// MQTT订阅和发布的主题
const char* subTopic = "/sys/" + String(productKey) + "/" + String(deviceName) + "/thing/event/property/post";
const char* pubTopic = "/sys/" + String(productKey) + "/" + String(deviceName) + "/thing/event/property/post";
// 上一次更新时间
unsigned long lastUpdate = 0;
// 温湿度数据
float temperature = 0;
float humidity = 0;
void setup() {
// 初始化串口和DHT11
Serial.begin(9600);
dht.begin();
// 连接WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected!");
// 连接MQTT服务器
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
if (client.connect(deviceName, mqtt_user, mqtt_password)) {
Serial.println("MQTT connected!");
client.subscribe(subTopic);
} else {
Serial.println("MQTT connection failed!");
delay(1000);
}
}
}
void loop() {
// 每隔10秒读取一次温湿度数据,并上传至阿里云
if (millis() - lastUpdate > 10000) {
lastUpdate = millis();
// 读取温湿度
temperature = dht.readTemperature();
humidity = dht.readHumidity();
// 将温湿度数据转换为JSON格式
String payload = "{\"id\":\"1\",\"params\":{\"Temperature\":{\"value\":\"" + String(temperature) + "\",\"unit\":\"C\"},\"Humidity\":{\"value\":\"" + String(humidity) + "\",\"unit\":\"%\"}},\"method\":\"thing.event.property.post\"}";
// 发布温湿度数据
client.publish(pubTopic, payload.c_str());
}
// 处理MQTT消息
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
// 处理MQTT消息
// ...
}
```
注意:在使用此代码前,请确保已经创建了阿里云物联网平台产品、设备和Topic,并将设备的三元组(ProductKey、DeviceName和DeviceSecret)、WiFi参数、MQTT服务器参数和Topic参数正确填写到代码中。同时,为了保证代码正常运行,请确保已经安装了ESP8266WiFi、PubSubClient和DHT库。
阅读全文