基于esp8266 2.5.2 給出的范例WiFiManualWebServer,稍做修改現(xiàn)實中文,并符合自己的控制邏輯.
全文代碼如下:
/* 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#ifndef STASSID#define STASSID "your-ssid" //修改為你自己的無線網(wǎng)絡ssid#define STAPSK "your-password" //修改為你自己的無線密碼#endif#define LED_BUILTIN 0const char* ssid = STASSID;const char* password = STAPSK;// Create an instance of the server// specify the port to listen on as an argumentWiFiServer server(80);void setup() { Serial.begin(115200); // prepare LED pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, 0); // Connect to WiFi network Serial.println(); Serial.println(); Serial.print(F("Connecting to ")); Serial.println(ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(F(".")); } Serial.println(); Serial.println(F("WiFi connected")); // Start the server server.begin(); Serial.println(F("Server started")); // Print the IP address Serial.println(WiFi.localIP());}void loop() { // Check if a client has connected WiFiClient client = server.available(); if (!client) { return; } Serial.println(F("new client")); client.setTimeout(5000); // default is 1000 // Read the first line of the request String req = client.readStringUntil('\r\n'); Serial.println(F("request: ")); Serial.println(req); // Match the request int val; if (req.indexOf(F("/gpio/0")) != -1) { val = 0; } else if (req.indexOf(F("/gpio/1")) != -1) { val = 1; } else { Serial.println(F("invalid request")); val = digitalRead(LED_BUILTIN); } // Set LED according to the request digitalWrite(LED_BUILTIN, val); // read/ignore the rest of the request // do not client.flush(): it is for output only, see below while (client.available()) { // byte by byte is not very efficient client.read(); //Serial.println(client.read()); } // Send the response to the client // it is OK for multiple small client.print/write, // because nagle algorithm will group them into one single packet client.print(F("HTTP/1.1 200 OK\r\nContent-Type: text/html;charset=utf-8\r\n\r\n\r\n\r\n 模塊狀態(tài)是: "));Serial.print(F("HTTP/1.1 200 OK\r\nContent-Type: text/html;charset=utf-8\r\n\r\n\r\n\r\n 模塊狀態(tài)是: ")); client.print((val) ? F("關") : F("開"));Serial.print((val) ? F("關") : F("開")); client.print(F("
點擊打開點擊打開點擊關閉點擊關閉返回")); Serial.print (F("'>返回"));? //client.print(F("/gpio/0'>點擊關閉"));? // The client will actually be *flushed* then disconnected? // when the function returns and 'client' object is destroyed (out-of-scope)? // flush = ensure written data are received by the other side? Serial.println(F("Disconnecting from client"));}
學習本部分代碼注意使用rom來減少ram消耗,值得學習.
關鍵詞:client.read();??string .indexOf(f(""));? client.print(F(""))