ESP8266可以直接作为一个网页客户端来使用,封装的库中提供函数以快速配置ESP8266为一个网页客户端,能够直接获取网页服务端的代码。例如打开百度首页,通过串口返回所有html代码。这里暂未设置DNS服务因此需要通过IP直接访问。
程序流程:
1、连接NodeMCU板子,打开Arduino IDE,选择好开发板型号和串口号。
2、新建ino文件,添加头文件。
- #include <Arduino.h>
- #include <ESP8266WiFi.h>
- #include <ESP8266WiFiMulti.h>
- #include <ESP8266HTTPClient.h>
- #define HTTPIP "14.215.177.37" //baidu的ip
- #define HTTPPORT 80
- #define WIFINAME "你的wifi名称"
- #define WIFIPW "wifi密码"</span>
4、配置串口并尝试连接Wifi。
- Serial.begin(115200);
- Serial.println();
- Serial.println("Connecting");
- WiFiMulti.addAP(WIFINAME,WIFIPW);
- while(WiFiMulti.run()!=WL_CONNECTED)
- {
- delay(500);
- Serial.print(".");
- }
- Serial.println("Connected!");
- http.begin(HTTPIP,HTTPPORT,"/");
- int Code = http.GET();
- if(Code)
- {
- Serial.printf("HTTP Code:%d\n",Code);
- if(Code == 200)
- {
- String payload = http.getString();
- Serial.println(payload);
- }
- else
- {
- Serial.println("Couldn't link to server");
- }
- #include <Arduino.h>
- #include <ESP8266WiFi.h>
- #include <ESP8266WiFiMulti.h>
- #include <ESP8266HTTPClient.h>
- ESP8266WiFiMulti WiFiMulti;
- #define HTTPIP "14.215.177.37"//baidu
- #define HTTPPORT 80
- #define WIFINAME "*******"
- #define WIFIPW "*****"
- void setup() {
- // put your setup code here, to run once:
- Serial.begin(115200);
- Serial.println();
- Serial.println("Connecting");
- WiFiMulti.addAP(WIFINAME,WIFIPW);
- while(WiFiMulti.run()!=WL_CONNECTED)
- {
- delay(500);
- Serial.print(".");
- }
- Serial.println("Connected!");
- }
- void loop() {
- // put your main code here, to run repeatedly:
- HTTPClient http;
- Serial.println("Try link to http.");
- http.begin(HTTPIP,HTTPPORT,"/");
- int Code = http.GET();
- if(Code)
- {
- Serial.printf("HTTP Code:%d\n",Code);
- if(Code == 200)
- {
- String payload = http.getString();
- Serial.println(payload);
- }
- else
- {
- Serial.println("Couldn't link to server");
- }
- }
- delay(5000);
- }