/*This sketch demonstrates how to set up a simple HTTP-like server.The server will set a GPIO pin depending on the requesthttp://server_ip/gpio/0 will set the GPIO2 low,http://server_ip/gpio/1 will set the GPIO2 highserver_ip is the IP address of the ESP8266 module, will beprinted to Serial when the module is connected. */#include const char* ssid = "************"; // wifi 2.4 名称 const char* password = "***********"; // wifi 2.4 密码// 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 networkSerial.println();Serial.println();Serial.print("Connecting to ");Serial.println(ssid);// 1.设置wifi模式为终端WiFi.mode(WIFI_STA);// 2.连接wifiWiFi.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 addressSerial.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 dataSerial.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界面页面,点击不同的按键,用一个执行一个页面跳转激活上面的相应地址,实现页面请求,控制硬件 else if(req.indexOf("/") != -1){ // 控制页面String IPAdress = WiFi.localIP().toString();String html = " ";html += "";html += "";html += "";html += "";html += ">";// 8.返回html页面给客户端显示client.print(html);}else {Serial.println("invalid request");client.stop(); // 请求完后,可以停止return;}// Set GPIO2 according to the request// 根据val值(上面不同页面请求设置),控制小灯digitalWrite(2, val);// 清空客户端数据client.flush();// Prepare the response// 通过页面显示灯的状态 // String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n\r\n\r\nGPIO is now "; // s += (val) ? "high" : "low"; // s += "\n";// Send the response to the client // client.print(s);delay(1);Serial.println("Client disonnected");// The client will actually be disconnected// when the function returns and 'client' object is detroyed }