stm32 esp8266发送数据温湿度具体代码
时间: 2024-11-28 18:25:13 浏览: 18
在STM32和ESP8266平台联合应用中,通常会通过WiFi模块ESP8266将温度和湿度传感器(如DHT11或DHT22)采集的数据发送到服务器或其他设备。这里是一个简化版的代码示例,假设使用了DHT11传感器并通过WiFi连接:
```c
#include "dht.h"
#include "Arduino Esp8266WiFi.h"
// 定义DHT11传感器的引脚
#define DHT11_PIN 4
// WiFi配置
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const int serverPort = 80; // 服务器端口
DHT dht(DHT11_PIN);
void setup() {
Serial.begin(9600);
if (dht.begin()) {
Serial.println("DHT11 sensor connected");
} else {
Serial.println("Failed to connect DHT11 sensor");
return;
}
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop() {
float humidity, temperature;
if (dht.read(&humidity, &temperature)) { // 读取湿度和温度
String data = "Temp: " + String(temperature) + " C, Humidity: " + String(humidity) + "%";
// 发送HTTP POST请求到服务器
WiFiClient client;
if (!client.connect("your_server_ip", serverPort)) {
Serial.println("Connection failed");
return;
}
client.print("POST /api/data HTTP/1.1\r\n");
client.print("Host: your_server_ip\r\n");
client.print("Content-Type: application/json\r\n");
client.print("Content-Length: ");
client.print(data.length());
client.print("\r\n\r\n");
client.print(data.c_str());
size_t written = client.write(data.c_str(), data.length());
if (written < data.length()) {
Serial.println("Write error");
}
client.stop();
Serial.println("Data sent successfully");
} else {
Serial.println("Failed to read from DHT11");
}
delay(5 * 60 * 1000); // 每隔5分钟读一次
}
```
注意:这个代码只是一个基础示例,实际项目中可能需要处理错误、添加超时机制以及更复杂的网络通信逻辑。请确保替换相应的SSID、密码、IP地址等信息,并根据你的WiFi库(如ESP8266WiFi)进行适当的调整。
阅读全文