9
9
10
10
#include < ESP8266WiFi.h>
11
11
12
- const char * ssid = " your-ssid" ;
13
- const char * password = " your-password" ;
12
+ #ifndef SSID
13
+ #define SSID " your-ssid"
14
+ #define PSK " your-password"
15
+ #endif
16
+
17
+ const char * ssid = SSID;
18
+ const char * password = PSK;
14
19
15
20
// Create an instance of the server
16
21
// specify the port to listen on as an argument
@@ -19,9 +24,9 @@ WiFiServer server(80);
19
24
void setup () {
20
25
Serial.begin (115200 );
21
26
22
- // prepare GPIO2
23
- pinMode (2 , OUTPUT);
24
- digitalWrite (2 , 0 );
27
+ // prepare LED
28
+ pinMode (BUILTIN_LED , OUTPUT);
29
+ digitalWrite (BUILTIN_LED , 0 );
25
30
26
31
// Connect to WiFi network
27
32
Serial.println ();
@@ -53,17 +58,14 @@ void loop() {
53
58
if (!client) {
54
59
return ;
55
60
}
56
-
57
- // Wait until the client sends some data
58
61
Serial.println (" new client" );
59
- while (!client.available ()) {
60
- delay (1 );
61
- }
62
+
63
+ client.setTimeout (5000 ); // default is 1000
62
64
63
65
// Read the first line of the request
64
66
String req = client.readStringUntil (' \r ' );
67
+ Serial.println (" request: " );
65
68
Serial.println (req);
66
- client.flush ();
67
69
68
70
// Match the request
69
71
int val;
@@ -77,22 +79,25 @@ void loop() {
77
79
return ;
78
80
}
79
81
80
- // Set GPIO2 according to the request
81
- digitalWrite (2 , val);
82
+ // Set LED according to the request
83
+ digitalWrite (BUILTIN_LED , val);
82
84
83
- client.flush ();
84
-
85
- // Prepare the response
86
- String s = " HTTP/1.1 200 OK\r\n Content-Type: text/html\r\n\r\n <!DOCTYPE HTML>\r\n <html>\r\n GPIO is now " ;
87
- s += (val) ? " high" : " low" ;
88
- s += " </html>\n " ;
85
+ // read/ignore the rest of the request
86
+ // do not client.flush(): it is for output only, see below
87
+ while (client.available ())
88
+ // byte by byte is not very efficient
89
+ client.read ();
89
90
90
91
// Send the response to the client
91
- client.print (s);
92
- delay (1 );
93
- Serial.println (" Client disonnected" );
94
-
95
- // The client will actually be disconnected
96
- // when the function returns and 'client' object is detroyed
92
+ // it is OK for multiple small client.print/write,
93
+ // because nagle algorithm will group them into one single packet
94
+ // ::print*_P(F("string")) is always usable and saves RAM
95
+ client.print_P (F (" HTTP/1.1 200 OK\r\n Content-Type: text/html\r\n\r\n <!DOCTYPE HTML>\r\n <html>\r\n GPIO is now " ));
96
+ client.print_P ((val) ? F (" high" ): F (" low" ));
97
+ client.print_P (F (" </html>\n " ));
98
+
99
+ // The client will actually be *flushed* then disconnected
100
+ // when the function returns and 'client' object is destroyed (out-of-scope)
101
+ // flush = ensure written data are received by the other side
102
+ Serial.println (" Disconnecting from client" );
97
103
}
98
-
0 commit comments