#include<ESP8266WiFi.h>constchar*ssid="<SSID>";// 替换为自己的热点 ID
constchar*password="<PASSWORD>";// 替换为自己的热点密码
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServerserver(80);voidsetup(){Serial.begin(9600);delay(10);// prepare GPIO2
pinMode(2,OUTPUT);digitalWrite(2,0);// Connect to WiFi network
Serial.println();Serial.println();Serial.print("Connecting to ");Serial.println(ssid);WiFi.begin(ssid,password);structip_infoinfo;IP4_ADDR(&info.ip,192,168,43,119);//替换为自己的热点 IP
IP4_ADDR(&info.gw,192,168,43,1);//替换为自己的热点网关 IP
IP4_ADDR(&info.netmask,255,255,255,0);wifi_station_dhcpc_stop();wifi_set_ip_info(STATION_IF,&info);//设置 sta 模式的 IP
while(WiFi.status()!=WL_CONNECTED){delay(500);Serial.print(".");}Serial.println("");Serial.println("WiFi connected");// Start the server
server.begin();Serial.println("Server started @ ");// Print the IP address & instructions
Serial.println(WiFi.localIP());Serial.println("To control GPIO, open your web browser.");Serial.println("To set GPIO 0 high, type:");Serial.print(WiFi.localIP());Serial.println("/gpio/1");Serial.println("To set GPIO 0 low, type:");Serial.print(WiFi.localIP());Serial.println("/gpio/0");Serial.println("To toggle GPIO 0, type:");Serial.print(WiFi.localIP());Serial.println("/gpio/0");}voidloop(){// Check if a client has connected
WiFiClientclient=server.available();if(!client){delay(100);return;}// Read the first line of the request
Stringreq=client.readStringUntil('\r');Serial.println(req);client.flush();// Match the request
intval;if(req.indexOf("/gpio/0")!=-1)val=0;elseif(req.indexOf("/gpio/1")!=-1)val=1;elseif(req.indexOf("/gpio/4")!=-1)val=(!digitalRead(0));// <<<<< Edit: insert /gpio/3 lines after this line.
else{Serial.println("invalid request");client.print("HTTP/1.1 404\r\n");client.stop();return;}// Set GPIO2 according to the request
digitalWrite(2,val);client.flush();// Prepare the response
Strings="HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n<p style='color:#666; font-size:40px; text-align:center;'>状态:";s+="<head><meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" /></head>";s+=(val)?"LED 已关闭</p>":"LED 已开启</p>";s+="<p style='font-size:40px; text-align:center;'><a style='color:#666;' href='/gpio/0'>开启 LED</a></p><p style='font-size:40px; text-align:center;'><a style='color:#666;' href='/gpio/1'>关闭 LED</a></p><p style='color:#666; font-size:40px; text-align:center;'>GuanQirui 嵌入式系统与应用课程设计</p></html>\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
}