本程序适用于局域网,采用最简单的HTTP协议。
成品在网盘工程/HTTP中。
每个地址都不一样,使用前用netstat -an看本地地址,填入host中。
ssid WIFI 密码
password wifi密码
http地址:
String postRequest = (String)(“GET “)+“userupdate?device_id=3&wendu=35&shidu=50”+” HTTP/1.1\r\n”+
“Content-Type: text/html;charset=utf-8\r\n”+
"Host: "+host + “\r\n”+
“User-Agent: BuildFailureDetectorESP8266\r\n”+
“Connection: Keep-Alive\r\n\r\n”;
//https://www.arduino.cn/thread-92176-1-1.html
程序开始:
//https://www.arduino.cn/thread-92176-1-1.html
#include <ESP8266WiFi.h>
const char* ssid="…";
const char* password = “…”;
const char* host=“192.168.2.218”;
const int port=5000;
const char* url=“http://se.360.cn/cc/fwl_11.dat”;
char buffer[1024];
#define BASE_URL “GET %s HTTP/1.1\r\nHost:%s\r\nAccept-Language:zh-cn\r\nConnection:keep-alive\r\n\r\n”
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
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”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
sprintf(buffer,BASE_URL,”/v3/weather/now.json?key=smtq3n0ixdggurox&location=beijing&language=zh-Hans&unit=c”,“api.seniverse.com”);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print("connecting to ");
Serial.println(host);
WiFiClient client;
if(!client.connect(host,5000)){
Serial.println(“connection failed”);
return;
}
delay(10);
String postRequest = (String)("GET ")+"userupdate?device_id=3&wendu=35&shidu=50"+" HTTP/1.1\r\n"+
//"Content-Type: text/html;charset=utf-8\r\n"+
"Host: "+host + "\r\n"+
//"User-Agent: BuildFailureDetectorESP8266\r\n"+
//"Connection: Keep-Alive\r\n\r\n";
Serial.println(buffer);
//client.print(newurl);
//读取天气
client.print(postRequest);
String line = client.readStringUntil('\n');
while(line.length()!=0){
Serial.println(line);
line=client.readStringUntil('\n');
}
Serial.println(line);
client.stop();
delay(3000);
}
安装库
如前所述,我们假设使用Arduino IDE对ESP8266进行编程。如果您尚未将其配置为支持ESP8266板,请查看前面的博文。如所料,Arduino有一些库可以简化我们与DHT11交互的任务。一个非常简单易用且与ESP8266配合使用的是Simple DHT传感器库。可以通过Arduino IDE Library Manager轻松安装该库,如图3所示。
图3 - 通过库管理器安装简单的DHT传感器库。
代码
要导入新安装的库,请在代码顶部添加以下include:
1
#include <SimpleDHT.h>
同时使用GPIO引脚的编号声明一个全局变量,以便于更改。在这种情况下,我们将使用GPIO2:
1
int DHTpin = 2;
要允许将数据发送到计算机,请在设置功能中启动串行连接:
1
Serial.begin(115200);
在你的主循环中声明两个字节变量,一个用于温度,另一个用于湿度:
1
2
byte temperature;
byte humidity;
我们使用字节变量,因为DHT11在温度和湿度方面只有8位分辨率。
最后,同样在主循环函数中,读取值并通过串口发送它们:
1
2
3
4
五
6
7
8
9
10
11
12
if (simple_dht11_read(DHTpin, &temperature, &humidity, NULL)) {
Serial.print(“Failed.”);
}else {
Serial.print("temperature: "); Serial.print(temperature); Serial.println(“ºC”);
Serial.print(“Humidity: “); Serial.print(humidity); Serial.println(”%”);
}
delay(2000);