Setting up a webserver

HTML
The previous tutorial showed how to create a wifi access point but the ESP8266 didn't do anything once a station was connected. In this tutorial, we build upon the previous access point to serve a simple HTML web page in response to a request from a connected station.

The ESP8266 Webserver library implements a basic web server that allows the ESP to respond to incoming HTTP requests without needing to worry about the low level details of the response. Include the library at the top of the sketch with the line

#include <ESP8266WebServer.h>
Next we need to declare a new Web Server object using the HTTP port number, 80. This is the default port that a browser will use.

ESP8266WebServer webServer(80);
The ESP web server needs to be continually polled to see if anything is trying to connect to the device. This is done with a single call, placed inside the main loop code for the device

void loop() {
// put your main code here, to run repeatedly:
webServer.handleClient();
}
view raw webServerLoop.c hosted with ❤ by GitHub
Now we have set up a web server to respond to HTTP requests we need to tell it what to respond with. These last few lines create a function that replies to a root ("/") request with a simple text response "Hello World!". It is possible to add other URI responses to the webserver, to serve different pages depending on what is requested.

webServer.on("/", [](){
webServer.send(200, "text/plain", "Hello World");
});
webServer.begin();
Putting it all together gives us this sample code.

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer webServer(80);
void setup() {
//Put your setup code here, to run once:
Serial.begin(115200);
//Add the chip ID onto the end to get a unique (ish) name
String ssid = "ESP8266 " + String(ESP.getChipId(), HEX);
String pass = "password";
//Send the SSID and Password to the serial port
Serial.printf("WiFiSSID: '%s'\n", ssid.c_str());
Serial.printf("Password: '%s'\n", pass.c_str());
// Create an access point using the given user name and password
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid.c_str(), pass.c_str());
webServer.on("/", [](){
webServer.send(200, "text/plain", "Hello World");
});
webServer.begin();
}
void loop() {
// put your main code here, to run repeatedly:
webServer.handleClient();
}
view raw WifiWebServer.c hosted with ❤ by GitHub
Compile the sample code and upload it to the device, you should be able to connect to the wifi network created by the ESP chip. The default IP address for the device is 192.168.4.1 so open a browser and navigate to "http://192.168.4.1/", a page should load showing this response

Popular posts from this blog

Wiring the Ruida Controller

Rainbow Puzzle Box

Leetro to Ruida Settings