esp32dht11上阿里云代码
时间: 2024-05-07 11:17:56 浏览: 123
STM32+ESP8266+MQTT连接阿里云 (移植pahoMQTT库).zip
5星 · 资源好评率100%
以下是ESP32与DHT11传感器结合并上传阿里云的示例代码,需要先安装ESP32的开发环境和阿里云IoT平台的相关依赖库:
```c
#include "WiFi.h"
#include <AliyunIoTSDK.h>
#include "DHT.h"
#define DHTPIN 4 // DHT11传感器连接的GPIO引脚
#define DHTTYPE DHT11 // DHT11传感器类型
DHT dht(DHTPIN, DHTTYPE);
AliyunIoTSDK iot;
WiFiClient wifiClient;
char productKey[] = "YOUR_PRODUCT_KEY";
char deviceName[] = "YOUR_DEVICE_NAME";
char deviceSecret[] = "YOUR_DEVICE_SECRET";
void setup() {
Serial.begin(115200);
WiFi.begin("YOUR_SSID", "YOUR_PASSWORD"); // 连接WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected.");
dht.begin();
iot.begin(wifiClient, productKey, deviceName, deviceSecret);
}
void loop() {
float temperature = dht.readTemperature(); // 读取温度值
float humidity = dht.readHumidity(); // 读取湿度值
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\t");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
char payload[256];
sprintf(payload, "{\"CurrentTemperature\":%.1f,\"CurrentHumidity\":%.1f}", temperature, humidity); // 组装上传的数据
iot.publish(deviceName, "update", payload); // 上传数据到阿里云IoT平台
delay(1000);
}
```
需要替换代码中的SSID、PASSWORD、YOUR_PRODUCT_KEY、YOUR_DEVICE_NAME和YOUR_DEVICE_SECRET等参数,以便与您在阿里云IoT平台上创建的设备相匹配。此外,您还需要在阿里云IoT平台上创建一个Topic,以便该设备能够上传数据。
阅读全文