ESP8266 Arduino als Webserver - Beispielprojekt

1:  #include <ESP8266WiFi.h>  
2:  //http://www.arduinesp.com/wifiwebserver  
3:  const char* ssid = "OPPO A51f";  
4:  const char* password = "12345678";  
5:  int ledPin = 13; // GPIO2  
6:  WiFiServer server(80);  
7:  void setup() {  
8:  Serial.begin(115200);  
9:  delay(10);  
10:  pinMode(ledPin, OUTPUT);  
11:  digitalWrite(ledPin, LOW);  
12:  // Connect to WiFi network  
13:  Serial.println();  
14:  Serial.println();  
15:  Serial.print("Connecting to ");  
16:  Serial.println(ssid);  
17:  WiFi.begin(ssid, password);  
18:  while (WiFi.status() != WL_CONNECTED) {  
19:  delay(500);  
20:  Serial.print(".");  
21:  }  
22:  Serial.println("");  
23:  Serial.println("WiFi connected");  
24:  // Start the server  
25:  server.begin();  
26:  Serial.println("Server started");  
27:  // Print the IP address  
28:  Serial.print("Use this URL to connect: ");  
29:  Serial.print("http://");  
30:  Serial.print(WiFi.localIP());  
31:  Serial.println("/");  
32:  }  
33:  void loop() {  
34:  // Check if a client has connected  
35:  WiFiClient client = server.available();  
36:  if (!client) {  
37:  return;  
38:  }  
39:  // Wait until the client sends some data  
40:  Serial.println("new client");  
41:  while(!client.available()){  
42:  delay(1);  
43:  }  
44:  // Read the first line of the request  
45:  String request = client.readStringUntil('\r');  
46:  Serial.println(request);  
47:  client.flush();  
48:  // Match the request  
49:  int value = LOW;  
50:  if (request.indexOf("/LED=ON") != -1) {  
51:  digitalWrite(ledPin, HIGH);  
52:  value = HIGH;  
53:  }  
54:  if (request.indexOf("/LED=OFF") != -1) {  
55:  digitalWrite(ledPin, LOW);  
56:  value = LOW;  
57:  }  
58:  // Set ledPin according to the request  
59:  //digitalWrite(ledPin, value);  
60:  // Return the response  
61:  client.println("HTTP/1.1 200 OK");  
62:  client.println("Content-Type: text/html");  
63:  client.println(""); // do not forget this one  
64:  client.println("<!DOCTYPE HTML>");  
65:  client.println("<html>");  
66:  client.print("Led pin is now: ");  
67:  if(value == HIGH) {  
68:  client.print("On");  
69:  } else {  
70:  client.print("Off");  
71:  }  
72:  client.println("<br><br>");  
73:  client.println("Click <a href=\"/LED=ON\">here</a> turn the LED on pin 13 ON<br>");  
74:  client.println("Click <a href=\"/LED=OFF\">here</a> turn the LED on pin 13 OFF<br>");  
75:  client.println("</html>");  
76:  delay(1);  
77:  Serial.println("Client disonnected");  
78:  Serial.println("");  
79:  }  

Kommentare