Create A Simple ESP8266 NodeMCU Web Server
Create A Simple ESP8266 NodeMCU Web Server
Over the past few years, the ESP8266 has been a growing star among IoT or
WiFi-related projects. It’s an extremely cost-effective WiFi module that – with a
little extra effort – can be programmed to build a standalone web server.
How cool is that!
Web server is a place which stores, processes and delivers web pages
to Web clients. Web client is nothing but a web browser on our
laptops and smartphones. The communication between client and
server takes place using a special protocol called Hypertext Transfer
Protocol (HTTP).
One of the greatest features ESP8266 provides is that it cannot only connect to
an existing WiFi network and act as a Web Server, but it can also set up a
network of its own, allowing other devices to connect directly to it and access
web pages. This is possible because ESP8266 can operate in three different
modes: Station mode, Soft Access Point mode, and both at the same time. This
provides possibility of building mesh networks.
The ESP8266 that connects to an existing WiFi network (one created by your
wireless router) is called Station (STA)
The ESP8266 that creates its own WiFi network and acts as a hub (Just like WiFi
router) for one or more stations is called Access Point (AP). Unlike WiFi router,
it does not have interface to a wired network. So, such mode of operation is
called Soft Access Point (soft-AP). Also the maximum number of stations that
can connect to it is limited to five.
In AP mode ESP8266 creates a new WiFi network and sets SSID (Name of the
network) and IP address to it. With this IP address, it can deliver web pages to
all connected devices under its own network.
Wiring – Connecting LEDs to ESP8266
NodeMCU
Now that we know the basics of how web server works, and in which modes
ESP8266 can create a web server, it’s time to connect some LEDs to ESP8266
NodeMCU that we want to control over WiFi.
When you’re done you should have something that looks similar to the
illustration shown below.
So, you might be thinking, “How am I going to control things from a web server
that merely processes and delivers web pages?” Well, then you need to
understand what’s going on behind the scene.
When you type a URL in a web browser and hit ENTER, the browser sends a
HTTP request (a.k.a. GET request) to a web server. It’s a job of web server to
handle this request by doing something. You might have figured it out by now
that we are going to control things by accessing a specific URL. For example,
suppose we entered a URL like http://192.168.1.1/ledon in a browser. The
browser then sends a HTTP request to ESP8266 to handle this request. When
ESP8266 reads this request, it knows that user wants to turn the LED ON. So, it
turns the LED ON and sends a dynamic webpage to a browser showing LED
status : ON As easy as Pie!
As the heading suggests, this example demonstrates how to turn the ESP8266
into an access point (AP), and serve up web pages to any connected client. To
start with, plug your ESP8266 NodeMCU into your computer and Try the sketch
out; and then we will dissect it in some detail.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server(80);
void setup() {
Serial.begin(115200);
pinMode(LED1pin, OUTPUT);
pinMode(LED2pin, OUTPUT);
WiFi.softAP(ssid, password);
After uploading the sketch, open the Serial Monitor at a baud rate of 115200.
And press the RESET button on ESP8266. If everything is OK, it will show HTTP
server started message.
Next, find any device that you can connect to a WiFi network – phone, laptop,
etc. And look for a network called NodeMCU. Join the network with password
123456789.
Now, let’s take a closer look at the code to see how it works, so that you are
able to modify it to fulfill your needs.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
As we are setting the ESP8266 NodeMCU in Access Point (AP) mode, it will
create a WiFi network. Hence, we need to set its SSID, Password, IP address, IP
subnet mask and IP gateway.
We configure our HTTP server before actually running it. First of all, we open a
serial connection for debugging purpose and set GPIO ports to OUTPUT.
Serial.begin(115200);
pinMode(LED1pin, OUTPUT);
pinMode(LED2pin, OUTPUT);
WiFi.softAP(ssid, password);
WiFi.softAPConfig(local_ip, gateway, subnet);
delay(100);
For example, the first line of below code snippet indicates that when a server
receives an HTTP request on the root (/) path, it will trigger the
handle_OnConnect() function. Note that the URL specified is a relative path.
server.on("/", handle_OnConnect);
server.on("/led1on", handle_led1on);
server.on("/led1off", handle_led1off);
server.on("/led2on", handle_led2on);
server.on("/led2off", handle_led2off);
We haven’t specified what the server should do if the client requests any URL
other than specified with server.on() . It should respond with an HTTP status
404 (Not Found) and a message for the user. We put this in a function as well,
and use server.onNotFound() to tell it that it should execute it when it
receives a request for a URI that wasn’t specified with server.on
server.onNotFound(handle_NotFound);
Now, to start our server, we call the begin method on the server object.
server.begin();
Serial.println("HTTP server started");
Inside Loop() Function
void loop() {
server.handleClient();
if(LED1status)
{digitalWrite(LED1pin, HIGH);}
else
{digitalWrite(LED1pin, LOW);}
if(LED2status)
{digitalWrite(LED2pin, HIGH);}
else
{digitalWrite(LED2pin, LOW);}
}
In our case, we are sending the code 200 (one of the HTTP status codes), which
corresponds to the OK response. Then, we are specifying the content type as
“text/html“, and finally we are calling SendHTML() custom function which
creates a dynamic HTML page containing status of LEDs.
void handle_OnConnect()
{
LED1status = LOW;
LED2status = LOW;
Serial.println("GPIO7 Status: OFF | GPIO6 Status: OFF");
server.send(200, "text/html", SendHTML(LED1status,LED2status));
}
Likewise, we need to create four functions to handle LED ON/OFF requests and
404 Error page.
void handle_led1on() {
LED1status = HIGH;
Serial.println("GPIO7 Status: ON");
server.send(200, "text/html", SendHTML(true,LED2status));
}
void handle_led1off() {
LED1status = LOW;
Serial.println("GPIO7 Status: OFF");
server.send(200, "text/html", SendHTML(false,LED2status));
}
void handle_led2on() {
LED2status = HIGH;
Serial.println("GPIO6 Status: ON");
server.send(200, "text/html", SendHTML(LED1status,true));
}
void handle_led2off() {
LED2status = LOW;
Serial.println("GPIO6 Status: OFF");
server.send(200, "text/html", SendHTML(LED1status,false));
}
void handle_NotFound(){
server.send(404 "text/plain" "Not found");
The first text you should always send is the <!DOCTYPE> declaration that
indicates that we’re sending HTML code.
Next, the <meta> viewport element makes the web page responsive in any
web browser. While title tag sets the title of the page.
Next, we have some CSS to style the buttons and the web page appearance.
We choose the Helvetica font, define the content to be displayed as an inline-
block and aligned at the center.
Following code then sets color, font and margin around the body, H1, H3 and p
tags.
Some styling is applied to the buttons as well with properties like color, size,
margin, etc. The ON and OFF button has different background color while
:active selector for buttons ensure button click effect
Next, heading of the web page is set; you can change this text to anything that
suits your application.
To dynamically generate the buttons and LED status, we use if statement. So,
depending upon the status of the GPIO pins, ON/OFF button is displayed.
if(led1stat)
{ptr +="<p>LED1 Status: ON</p><a class=\"button button-off\"
href=\"/led1off\">OFF</a>\n";}
else
{ptr +="<p>LED1 Status: OFF</p><a class=\"button button-on\"
href=\"/led1on\">ON</a>\n";}
if(led2stat)
{ptr +="<p>LED2 Status: ON</p><a class=\"button button-off\"
href=\"/led2off\">OFF</a>\n";}
else
{ptr +="<p>LED2 Status: OFF</p><a class=\"button button-on\"
href=\"/led2on\">ON</a>\n";}
Before you head for uploading the sketch, you need to make some changes to
make it work for you. You need to modify the following two variables with your
network credentials, so that ESP8266 can establish a connection with existing
network.
Once you are done, go ahead and try the sketch out.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server(80);
void setup() {
Serial.begin(115200);
delay(100);
pinMode(LED1pin, OUTPUT);
pinMode(LED2pin, OUTPUT);
Serial.println("Connecting to ");
After uploading the sketch, open the Serial Monitor at a baud rate of 115200.
And press the RESET button on ESP8266. If everything is OK, it will output the
dynamic IP address obtained from your router and show HTTP server started
message.
Next, load up a browser and point it to the IP address shown on the serial
monitor. The NodeMCU should serve up a web page showing current status of
LEDs and two buttons to control them. If take a look at the serial monitor at
the same time, you can see status of NodeMCU’s GPIO pins.
Now, click the button to turn LED1 ON while keeping an eye on the URL. Once
you click the button, the ESP8266 receives a request for /led1on URL. It then
turns the LED1 ON and serves a web page with status of LED updated. It also
prints the status of GPIO pin on the serial monitor.
You can test LED2 button and check that it works in a similar way.
Code Explanation
If you observe this code with the previous code, the only difference is that we
are not setting the soft Access Point, Instead we are joining existing network
using WiFi.begin() function.
While the ESP8266 tries to connect to the network, we can check the
connectivity status with WiFi.status() function
Just for your information, this function returns the following statuses:
• WL_CONNECTED: assigned when connected to a Wi-Fi network
Once the ESP8266 is connected to the network, the sketch prints the IP
address assigned to ESP8266 by displaying WiFi.localIP() value on serial
monitor.
Serial.println("");
Serial.println("WiFi connected..!");
Serial.print("Got IP: "); Serial.println(WiFi.localIP());
The only difference between AP & STA mode is one creates the network and
other joins the existing network. So, rest of the code for handling HTTP
requests and serving web page in STA mode is same as that of AP mode
explained above. This includes:
• Declaring NodeMCU’s GPIO pins to which LEDs are connected
• Creating custom functions that are executed when specific URL is hit
Share