帮我写一个用ESP32-S3开发板连接DHT11测量温湿度的程序
时间: 2024-06-10 08:06:45 浏览: 227
好的,我可以为您提供一个基本的示例程序:
```
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>
#include <HTTPClient.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#define DHTPIN 4 // 定义DHT11连接的引脚
#define DHTTYPE DHT11 // 定义传感器类型为DHT11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "your_SSID"; // 修改为您的WiFi信息
const char* password = "your_PASSWORD";
const char* serverName = "http://your_server.com/data_receiver.php"; // 修改为您的服务器地址和文件名
void setup() {
Serial.begin(115200);
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to WiFi.");
}
void loop() {
float temperature = dht.readTemperature(); // 读取温度数据
float humidity = dht.readHumidity(); // 读取湿度数据
if (isnan(temperature) || isnan(humidity)) { // 如果读数失败
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\n");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
if (WiFi.status() == WL_CONNECTED) { // 如果WiFi连接成功
HTTPClient http;
String data = "temperature=" + String(temperature) + "&humidity=" + String(humidity); // 组装POST数据
Serial.print("Posting data: ");
Serial.println(data);
http.begin(serverName);
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置POST数据类型
int httpResponseCode = http.POST(data); // 发送POST请求
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error sending data to server. HTTP Response code: ");
Serial.println(httpResponseCode);
}
http.end(); // 关闭HTTP连接
} else {
Serial.println("WiFi not connected!");
}
delay(1000); // 等待1秒后重新读取数据
}
```
您需要根据实际情况修改程序中的WiFi连接信息和服务器地址。如果您没有自己的服务器,可以在本地搭建一个简单的服务器,收集来自ESP32-S3的数据。
阅读全文