Arduino Webserver using Esp8266 NodeMCU

by Jun 20, 2020Projects

Update : I build a simple app to control Devices on this webserver. (visit Here)

Introduction:

In this post, we will see how we can build a web server using the ESP8266 NodeMcu device. This web server will be used to control the status of all the devices connected to the Nodemcu. Also, it can be accessed and controlled from any device’s web browser present in the same network.

What is a Web server and how it works?

Web server is a place that stores, processes and delivers web pages to Web clients. The web client is nothing but a web browser on our laptops and smartphones. The communication between client and server takes place using Hypertext Transfer Protocol (HTTP) thorugh a web browser.

CODE:

The entire code for this project is available at the following github repository:https://github.com/htgdokania/Arduino_Webserver

Structure/Work Flow:

  • Step1: Download and set up the Arduino IDE along with Esp8266 requirements.
  • Step2: Make the LED connections to the Nodemcu module.
  • Step3: Write the code and Upload it from the Arduino IDE.
  • Step4: Open Web browser to control the device

Step1: Download and set up the Arduino IDE along with Esp8266 requirements.

  • Then, click the “OK” button.
  • Next,Go to Tools > Board > Boards Manager.
  • search “esp8266” .Select and install  “esp8266 by ESP8266 Community”.(It will take some time)
  • Finally, Go to Tools > Board and choose your ESP8266 board.(ESP-12E)

Step2: Make the connections to the Nodemcu module.

Connect Each LED through a 1kohm resistor. to a GPIO pin of NodeMCU. Here we have connected to GPIO4 (D1) and GPIO5
(D2).

NodeMCU Pinout – IoT Bytes

Step3: Write the code and Upload it from the Arduino IDE.

We can create a web server using two methods:

Soft Access Point Mode(AP)

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

Station Mode (STA).

The ESP8266 that connects to an existing WiFi network (one created by your wireless router) is called Station (STA)

Let’s Have a look at AP mode first,where we do not need any external wifi network.

  • First, we include the ESP8266WiFi library.
// Load Wi-Fi library
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
  •  Set ssid and password of your wifi network
/* Put any  SSID & Password */
const char* ssid = "Arduino Webserver";  // Enter SSID here
const char* password = "12345678";  //Enter Password here (min 8 characters)
  • Next ,set IP address details as follows , you can even change the local IP as per your choice
/* Set  IP Address details */
IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
  • Then, you set your web server to port 80. If you want you can set any other port like “8081”
// Set webserver port number to 80
ESP8266WebServer server(80);
  • Define LED pin numbers along with their initial status variables(boolean type )
uint8_t LED1pin = D1;
bool LED1 = LOW;

uint8_t LED2pin = D2;
bool LED2 = LOW;
  • Next, write the void setup part:
    • Set LED pins as output kind
    • Define different server URLs, along with the function they will trigger.
    • Finally, start the server and print the local IP.
void setup() {
  Serial.begin(115200);
  pinMode(LED1pin, OUTPUT);
  pinMode(LED2pin, OUTPUT);

  WiFi.softAP(ssid, password);
  WiFi.softAPConfig(local_ip, gateway, subnet);
  delay(100);
  
  server.on("/",OnConnect);
  server.on("/led1on",led1on);
  server.on("/led1off",led1off);
  server.on("/led2on",led2on);
  server.on("/led2off",led2off);
  server.onNotFound(NotFound);
  
  server.begin();
  Serial.println("HTTP server started");
  Serial.println(WiFi.localIP());
}
  • Inside Void loop() function all we need to do is
    • To handle HTTP requests, we need to call the handleClient() method on the server object.
    • Update LED status as per HTTP request.
void loop() {
  server.handleClient();
  if(LED1)
    digitalWrite(LED1pin, HIGH);
  else
    digitalWrite(LED1pin, LOW);
  
  if(LED2)
    digitalWrite(LED2pin, HIGH);
  else
    digitalWrite(LED2pin, LOW);
}
  • Next, Lets us define the functions that will be triggered when the different URLs defined above will be envoked .
  •  In order to respond to the HTTP request, we use the server.send method defined in update_status function. Here we also attach a simple HTML page containing buttons to toggle the device status.
Note:sendHTML() function is defined below 
void update_status(){
  server.send(200, "text/html", SendHTML(LED1,LED2));  // we send HTML page alng with updated LED status.
}
  • Next we define onconnect function which we attach to root( /) URL.
void OnConnect() {
  LED1 = LOW;
  LED2 = LOW;
  update_status();
}
  • Next we define the functions to change LED status between ON & OFF
void led1on() {
  LED1 = HIGH;
  update_status();
}

void led1off() {
  LED1 = LOW;
  update_status();
}

void led2on() {
  LED2 = HIGH;
  update_status();
}

void led2off() {
  LED2 = LOW;
  update_status();
}

Finally we attach a function which is used for all the invalid URLs

void NotFound(){
  server.send(404, "text/plain", "Not found");
}

Up to This part, our main server code is done and can be uploaded and run to see the LEDs turn on and off when the specific URL is typed in the address bar.

Now for better controls/Visual GUI interface, we also add a HTML page with buttons and device current status info for easy toggle operations.

  • Lets define the SendHTML function:
    • The first text we send is <!DOCTYPE> declaration that indicates that we’re sending HTML code.
    • the <meta> viewport element makes the web page responsive in any web browser
    • Next, we give a Title to our web page “Device control”
    • Next, we have some CSS to style the buttons and the web page appearance. Also set color, font, margin, etc
String SendHTML(uint8_t led1stat,uint8_t led2stat){
  String ptr = "<!DOCTYPE html> <html>\n";
  ptr +="<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
  ptr +="<title>Device Control</title>\n";
  ptr +="<style>html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center;}\n";
  ptr +="body{margin-top: 50px;} h1 {color: #343444;margin: 50px auto 30px;} h3 {color: #434444;margin-bottom: 50px;}\n";

Next , we define the button Types ON and OFF .Also set its color, shape,and other features.

  ptr +=".button {display: block;width: 100px;background-color: #1abc9c;border:none;color: white;padding: 13px 30px;text-decoration: none;font-size: 25px;margin: 0px auto 35px;cursor: pointer;border-radius: 50%;}\n";
  ptr +=".button-on {background-color: #ff9900;}\n";
  ptr +=".button-on:active {background-color: #996633;}\n";
  ptr +=".button-off {background-color: #003399;}\n";
  ptr +=".button-off:active {background-color: #003366;}\n";

Next set the font size,color,margin and finally close the style and head and start the body of our HTML page

  ptr +="p {font-size: 14px;color: #888;margin-bottom: 10px;}\n";
  ptr +="</style>\n";
  ptr +="</head>\n";
  ptr +="<body>\n";

First we add the Heading to the web page inside the body.

  ptr +="<h1>ESP8266 based Arduino Web Server</h1>\n";

Next display Buttons for the two different devices based on the current state of the device using if else condition:

 if(led1stat)
      ptr +="<p>Device1 Status: ON</p><a class=\"button button-off\" href=\"/led1off\">OFF</a>\n";
  else
      ptr +="<p>Device2 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";

Finally end the body and html and return the ptr string,which is send as a response to the http request.

  ptr +="</body>\n";
  ptr +="</html>\n";
  return ptr;
}

Step4: Open Web browser to control the device

Simply connect to the wifi network created by the nodemcu device from any laptop or phone.

Next, open a webbrowser and type in the Ip address you set.You can also see the same from serial monitor . I have used “192.168.1.1

By default Both the devices will be in OFF state . Simply toggle the switch to see your LEDs turn on and off instantly.

Left: Both off Right : green On red off
Left: Both on Right : green Off red on
Note: Try changing the url manually instead  and see how your devices still changes state.

Now,Let’s Have a look at STA Mode ,where we connect to an existing wifi network.

  • First replace the ssid and password with your wifi network’s Credential in line 5,6 of the above code.
/* Put your SSID & Password */
const char* ssid = "Replace_with_your_wifi_SSID";  // Enter SSID here
const char* password = "Replace_With_Your_Wifi_Password";  //Enter Password here

In this mode, the only difference is that we are not setting the soft Access Point using WiFi.softAP(SSID, password);
Instead, we are joining the existing network using Wifi.begin()function. So We Replace line 23,24,25 which were previously.

  WiFi.softAP(ssid, password);
  WiFi.softAPConfig(local_ip, gateway, subnet);
  delay(100);
  • We Replace the above line with the following new lines.
  //Connect to your  wi-fi network
  WiFi.begin(ssid, password);
  delay(100);

  //check wi-fi is connected to wi-fi network
  while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
  }
  • Upload the code to the NodeMCU module.
  • Once uploaded,open Serial monitor and set the baud rate to 115200
  • Next, press the reset button on the NodeMCU.
  • You will get the local IP address assigned printed on the screen.

Open this IP address in any device’s web browser and rest all is just similar to what we got in the previous section (AP mode).

Make sure the client device is connected to the same wifi network.

That’s All we need to build our very own Web server using Arduino.

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

How to Simulate IoT projects using Cisco Packet Tracer

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

How to design a Wireless Blind Stick using  nRF24L01 Module?

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

How to implement Machine Learning on IoT based Data?

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....

How to build a Safety Monitoring System for COVID-19

How to build a Safety Monitoring System for COVID-19

It is expected that the world will need to battle the COVID-19 pandemic with precautious measures until an effective vaccine is developed. This project proposes a real-time safety monitoring system for COVID-19. The proposed system would employ an Internet of Things...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....