编写使用ESP8266+DHT11进行湿度监测的代码
时间: 2024-01-16 07:03:00 浏览: 72
下面是使用ESP8266和DHT11模块进行湿度监测的代码:
```c++
#include <ESP8266WiFi.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// DHT11 Sensor
#define DHTPIN 2 // DHT11 data pin
#define DHTTYPE DHT11 // DHT11 sensor type
DHT dht(DHTPIN, DHTTYPE);
// Create WiFi client object
WiFiClient client;
void setup() {
Serial.begin(115200);
delay(10);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Initialize DHT11 sensor
dht.begin();
}
void loop() {
// Wait a few seconds before reading sensor
delay(2000);
// Read temperature and humidity from DHT11 sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reads failed
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT11 sensor!");
return;
}
// Print sensor data
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("%\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println("°C");
// Connect to server and send data
if (client.connect("server_IP", 80)) {
Serial.println("Connected to server!");
String data = "humidity=" + String(humidity) + "&temperature=" + String(temperature);
client.println("POST /sensorData HTTP/1.1");
client.println("Host: server_IP");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(data.length());
client.println();
client.print(data);
client.println();
client.stop();
} else {
Serial.println("Failed to connect to server");
}
}
```
请注意,您需要将以下信息替换为与您的网络和服务器相对应的值:
- `ssid`:您的WiFi网络名称
- `password`:您的WiFi网络密码
- `server_IP`:您的服务器的IP地址
然后您需要在服务器端编写一个API来接收POST请求并处理数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)