ESP8266WebServer example
Posted: Sat Mar 28, 2015 12:42 am
ESP8266WebServer is an easy-to-use library to set up a web server on ESP8266. It is quite minimal, nowhere near other perfect production-ready web servers like esp-httpd or WebBase. It serves only one client at a time.
It is however very easy to set up and use.
First, include the library into your sketch and create a server object:
Next, in your setup function tell the server what URIs it needs to respond to:
or, which is equivalent:
The first argument is the URI and the second is the function that will be called to respond to this URI.
In that function you need to call
Processing arguments of GET and POST requests is also easy enough. Let's make our sketch turn a led on or off depending on the value of a request argument.
http://<ip address>/led?state=on will turn the led ON
http://<ip address>/led?state=off will turn the led OFF
The complete example which also shows how to do forms and images is available here:
https://gist.github.com/igrr/3b66292cf8708770f76b.
It is however very easy to set up and use.
First, include the library into your sketch and create a server object:
Code: Select all
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server(80);
Next, in your setup function tell the server what URIs it needs to respond to:
Code: Select all
server.on("/", [](){
server.send(200, "text/plain", "This is an index page.");
});
or, which is equivalent:
Code: Select all
void handle_index() {
server.send(200, "text/plain", "This is an index page.");
}
// later, in setup() function:
server.on("/", handle_index);
The first argument is the URI and the second is the function that will be called to respond to this URI.
In that function you need to call
Code: Select all
to actually send contents.server.send(code, content_type, content)
Processing arguments of GET and POST requests is also easy enough. Let's make our sketch turn a led on or off depending on the value of a request argument.
http://<ip address>/led?state=on will turn the led ON
http://<ip address>/led?state=off will turn the led OFF
Code: Select all
server.on("/led", []() {
String state=server.arg("state");
if (state == "on") digitalWrite(13, LOW);
else if (state == "off") digitalWrite(13, HIGH);
server.send(200, "text/plain", "Led is now " + state);
});
The complete example which also shows how to do forms and images is available here:
https://gist.github.com/igrr/3b66292cf8708770f76b.