使用arduino添加的ESP8266库编写程序,ESP8266通过连接网络访问服务器用到库函数示例。
添加的ESP8266库文件名:8266_package_2.6.3(这里之前没有提到之前实现的都的用,我这没办法直接导入这个用程序自己自行下载)
材料:ESP8266,数据线
代码如下:
#include<ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>const char* ssid = "huaweip30"; //要连接的wifi的名称
const char* password = "1234567890"; //要连接的wifi的密码const char* URL = "http://www.example.com"; // 测试HTTP请求用的URL。注意网址前面必须添加"http://"void setup() {Serial.begin(115200); //启动串口,并设置波特率为115200connectWiFi(); //连接WiFihttpClientRequest(); //通过客户端发送http请求,并响应
}void loop() {
}void httpClientRequest(){HTTPClient httpClient; //1、创建http的客户端httpClient.begin(URL); //2、通过begin函数配置请求地址。此处也可以不使用端口号Serial.print("URL: "); Serial.println(URL);int httpCode = httpClient.GET(); //3、通过GET函数启动连接并发送HTTP请求if (httpCode > 0) {Serial.printf("[HTTP] GET... code: %d\n", httpCode);if (httpCode == HTTP_CODE_OK) {String payload = httpClient.getString(); //获取响应体Serial.println(payload);} else {Serial.printf("[HTTP] GET... failed, error: %s\n", httpClient.errorToString(httpCode).c_str());}} else {Serial.printf("[HTTP] Unable to connect\n");}httpClient.end();
}void connectWiFi(){Serial.println();Serial.print("Connecting to");Serial.println(ssid);WiFi.begin(ssid,password); //启动WIFIwhile(WiFi.status()!=WL_CONNECTED){ //判断WiFi的连接状态,如果没有连接成功,等待delay(500);Serial.print(".");}Serial.println("");Serial.println("WiFi connected");Serial.print("IP address:");Serial.println(WiFi.localIP()); //获取本机的IP
}
之后打开串口会显示连接等一系列信息最后会给出一个测试网页的代码如下:
<!doctype html>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
body {background-color: #f0f0f2;margin: 0;padding: 0;font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;}
div {width: 600px;margin: 5em auto;padding: 2em;background-color: #fdfdff;border-radius: 0.5em;box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
}
a:link, a:visited {color: #38488f;text-decoration: none;
}
@media (max-width: 700px) {div {margin: 0 auto;width: auto;}
}
</style>
Example Domain
This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.
More information...
将其复制粘贴在自己创建的一个文本文档中,找到其文本文档的文件夹,更改其文本文档的格式就可以看到这是一个网页信息。