esp8266基本使用 - WebServer

准备

手边有一块WeMos D1,上面是esp8266的wifi模块
arduino官方库提供了esp8266的Broad库,便于快速开发

安装步骤:
文件 -> 首选项 -> 附加开发板管理器网址:http://arduino.esp8266.com/stable/package_esp8266com_index.json
工具 -> 开发板 -> 开发板管理器 -> 选择安装:esp8266 by ESP8266 Community

选择对应开发板:WeMos D1


代码

该示例仅是简单使用esp8266建一个小网页,用网页控制led灯
只是为了用最简单的例子入门

1.作为终端

中文注释为比较重要的操作,关键步骤列有序号
将wemos d1作为终端,连入wifi,用其它设备接入同一wifi下进行控制

/*
    This sketch demonstrates how to set up a simple HTTP-like server.
    The server will set a GPIO pin depending on the request
      http://server_ip/gpio/0 will set the GPIO2 low,
      http://server_ip/gpio/1 will set the GPIO2 high
    server_ip is the IP address of the ESP8266 module, will be
    printed to Serial when the module is connected.
*/

#include 

const char* ssid = "##这里是自己的路由器WIFI名称##";
const char* password = "##WIFI密码##";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
  // 初始化串口,只是显示一些打印的状态消息
  Serial.begin(115200);
  delay(10);

  // prepare GPIO2
  // 控制片上led灯的引脚
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  // 1.设置wifi模式为终端
  WiFi.mode(WIFI_STA);
  // 2.连接wifi
  WiFi.begin(ssid, password);
//  WiFi.softAP(ssid, password);  // 开AP热点

  // 显示连接状态
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  // 3.启动服务
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  // 4.循环获取连接到此服务的客户端(就是其它设备的连接对象)
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while (!client.available()) {
    delay(1);
  }

  // Read the first line of the request
  // 5.读取请求的地址数据
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();		// 清空客户端数据

  // Match the request
  // 6.在此对不同的请求地址做不同的处理(不同页面地址请求,做出不同的处理)
  int val;
  if (req.indexOf("/gpio/0") != -1) { // 硬件控制
    val = 0;
  } else if (req.indexOf("/gpio/1") != -1) {  // 硬件控制
    val = 1;
  }
  // 7.控制页面,在此显示一个UI界面页面,点击不同的按键,用一个