基于arduino uno的编写一个获取温湿度数据并通过esp8266WIFIo=模块采取http协议上传数据的代码
时间: 2023-06-01 07:02:08 浏览: 175
onenet上传温湿度数据_onenet_stm32onenet_stm32+OneNet_onenethttp协议_onene
5星 · 资源好评率100%
下面是一份基于Arduino Uno的获取温湿度数据并通过ESP8266 WIFI模块采用HTTP协议上传数据的代码:
```
#include <DHT.h>
#include <SoftwareSerial.h>
// 初始化DHT传感器
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// 初始化ESP8266
SoftwareSerial esp(3, 4); // RX, TX
String ssid = "your_wifi_ssid";
String password = "your_wifi_password";
String server = "your_server_address";
String url = "/your_upload_url";
void setup() {
Serial.begin(9600);
esp.begin(9600);
dht.begin();
connectWifi();
}
void loop() {
// 读取温湿度数据
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// 发送HTTP请求上传数据
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
} else {
String data = "temperature=" + String(temperature) + "&humidity=" + String(humidity);
String request = "POST " + url + " HTTP/1.1\r\n" +
"Host: " + server + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + String(data.length()) + "\r\n" +
"Connection: close\r\n\r\n" +
data + "\r\n";
sendHttpRequest(request);
}
delay(10000); // 每10秒上传一次数据
}
// 连接WiFi网络
void connectWifi() {
String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
sendCommand(cmd, 5000);
}
// 发送HTTP请求
void sendHttpRequest(String request) {
String response = "";
esp.print(request);
delay(1000);
while (esp.available()) {
char c = esp.read();
response += c;
}
Serial.println(response);
}
// 发送AT指令
void sendCommand(String command, int timeout) {
String response = "";
esp.println(command);
delay(timeout);
while (esp.available()) {
char c = esp.read();
response += c;
}
Serial.println(response);
}
```
注意事项:
1. 需要先安装DHT库和SoftwareSerial库。
2. 需要将ESP8266模块与Arduino Uno连接,RX接到Arduino的TX,TX接到Arduino的RX,VCC接到Arduino的5V,GND接到Arduino的GND。
3. 需要将ssid、password、server和url替换成实际的值。
阅读全文