Build An ESP8266 Web Serve1
Build An ESP8266 Web Serve1
Schematics (NodeMCU)
This tutorial is a step-by-step guide that shows how to build a standalone ESP8266 Web
Server that controls two outputs (two LEDs). This ESP8266 NodeMCU Web Server is
mobile responsive and it can be accessed with any device with a browser in your local
network.
his tutorial covers two different methods to build the web server:
/*********
Rui Santos
Complete project details at http://randomnerdtutorials.com
*********/
void setup() {
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(output5, OUTPUT);
pinMode(output4, OUTPUT);
// Set outputs to LOW
digitalWrite(output5, LOW);
digitalWrite(output4, LOW);
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
Connect two LEDs to your ESP8266 as shown in the following schematic diagram – with
one LED connected to GPIO 4 (D2), and another to GPIO 5 (D1).
Testing the Web Server
Now, you can upload the code, and it will work straight away. Don’t forget to check if you
have the right board and COM port selected, otherwise you’ll get an error when trying to
upload. Open the Serial Monitor at a baud rate of 115200.
Next, you create auxiliar variables to store the current state of your outputs. If you want to
add more outputs and save its state, you need to create more variables.
loop()
In the loop() we program what happens when a new client establishes a connection with
the web server.
The ESP is always listening for incoming clients with this line:
The web page is sent to the client using the client.println() function. You should
enter what you want to send to the client as an argument.
he first text you should always send is the following line, that indicates that we’re sending
HTML.
<!DOCTYPE html><html>
Then, the following line makes the web page responsive in any web browser.
if (output5State=="off") {
client.println("<p><a href=\"/5/on\"><button
class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/5/off\"><button class=\"button
button2\">OFF</button></a></p>");
}
We use the same procedure for GPIO 4.
Taking it Further
Now that you know how the code works, you can modify the code to add more outputs, or
modify your web page. To modify your web page you may need to know some HTML and
CSS.
Instead of controlling two LEDs, you can control a relay to control practically any electronics
appliances.
To build a web server to display sensor readings, you can read the following tutorials: