Phipps Electronics

Order within the next 

FREE SHIPPING OVER $199

50,000+ ORDERS

WORLDWIDE SHIPPING

SSL SECURED

Setting up a NodeMCU server

Contents

Introduction

The NodeMCU server or ESP8266 is an MCU with Wi-Fi and Web Server functionality. It has 2 Web Server modes, namely, station mode (STA) and soft-access point mode (AP). Before going on further with the modes, let’s get into the details of a Web Server.

What is a Webserver

Typically, a web server’s main function is to let web clients access web pages stored in physical media storage. With this setup, most of the transactions are GET requests from the clients accessing a particular web address. They are done through HTTP (or Hyper Text Transfer Protocol). We’ll see this happening when we go to the code section of this article.

Operating Modes

STA Mode

STA or station mode operates together with a wireless network or router. This mode makes it possible for the ESP8266 to have several clients as many as the wireless router can handle.

Soft-AP Mode

In soft access point (soft-AP) mode, the NodeMCU establishes its own limited WiFi network. This enables web clients to connect with it directly with limitations on the number of connections (usually 5 clients only).

Mixed Mode

Finally, ESP8266 also operates in both station and soft access point mode at the same time.

Outcomes

We will be covering how to work in station (STA) mode using NodeMCU and how to connect with a wireless network. We’ll be creating a web server inside our Wi-Fi network. Our clients will be entering through this server, accessing the web pages stored in the NodeMCU. Through this access, we’ll be able to determine the client’s intention and create some action, such as controlling LEDs.

Creating The Webpages

The web page we’d like to create inside our NodeMCU is about controlling LEDs. One link turns ON an LED while another link turns it OFF.

Preparing the Arduino Environment

First, provide the URL: http://arduino.esp8266.com/stable/package_esp8266com_index.json in the Additional Boards Manager section so that the Arduino IDE can use ESP8266 boards. You can do this by going to File->Preferences in the Arduino menu.

Next, go to Tools->Boards->Boards Manager, then search and install boards for ESP8266.

Choose your board from Tools->Board. Be sure to select your correct ESP8266 dev board. Your board properties should be a bit similar to this.

Code

				
					// put your setup code here, to run once:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

/*SSID & Password*/
const char* ssid = "YOUR_SSID";  // Enter SSID here
const char* password = "YOUR_PASSWORD";  //Enter Password here

ESP8266WebServer server(80);

uint8_t LEDpin = D3;
bool LEDstatus = false;

void setup() {
  
  pinMode(LEDpin, OUTPUT);

  Serial.begin(115200);
  Serial.println(" ");
  Serial.println("Connecting: ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while(WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.println(".");
  }
  Serial.println(" ");
  Serial.print("Connected at: ");
  Serial.println(WiFi.localIP());

  server.on("/", Connect_handler);
  server.on("/ledon", LED_ON_handler);
  server.on("/ledoff", LED_OFF_handler);
  server.onNotFound(Not_found_handler);

  server.begin();
  Serial.println("Web server has began");
}

void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();

  if(LEDstatus){
    digitalWrite(LEDpin, HIGH);
  }else{
    digitalWrite(LEDpin, LOW);
  }
}

void Connect_handler()
{
  LEDstatus = false;
  Serial.println("LED has been turned OFF");
  server.send(200, "text/html", SendClient());
}

void LED_ON_handler()
{
  LEDstatus = true;
  Serial.println("LED has been turned ON");
  server.send(200, "text/html", SendClient());
}

void LED_OFF_handler()
{
  LEDstatus = false;
  Serial.println("LED has been turned OFF");
  server.send(200, "text/html", SendClient());
}

void Not_found_handler()
{
  server.send(404, "text/plain", "address not found");
}

String SendClient()
{
  
  String html ="<!doctype html>\n";
  html += "<html> <head> <title>HTML Editor - Full Version</title> </head>\n"; 
  html += "<body>\n"; 
  html += "<h1>ESP8266 Web Server</h1> <h1>STA mode</h1>\n";
  html += "<h1>Press the button to toggle LED:</h1>\n";

  html += "<h1><a title=\"ledon\" href=\"ledon\">ledon</a></h1>\n"; 
  html += "<h1><a title=\"ledoff\" href=\"ledoff\">ledoff</a></h1>\n";

  html += "<script>class RocketElementorAnimation{constructor(){this.deviceMode=document.createElement("span"),this.deviceMode.id="elementor-device-mode-wpr",this.deviceMode.setAttribute("class","elementor-screen-only"),document.body.appendChild(this.deviceMode)}_detectAnimations(){let t=getComputedStyle(this.deviceMode,":after").content.replace(/"/g,"");this.animationSettingKeys=this._listAnimationSettingsKeys(t),document.querySelectorAll(".elementor-invisible[data-settings]").forEach(t=>{const e=t.getBoundingClientRect();if(e.bottom>=0&&e.top<=window.innerHeight)try{this._animateElement(t)}catch(t){}})}_animateElement(t){const e=JSON.parse(t.dataset.settings),i=e._animation_delay||e.animation_delay||0,n=e[this.animationSettingKeys.find(t=>e[t])];if("none"===n)return void t.classList.remove("elementor-invisible");t.classList.remove(n),this.currentAnimation&&t.classList.remove(this.currentAnimation),this.currentAnimation=n;let s=setTimeout(()=>{t.classList.remove("elementor-invisible"),t.classList.add("animated",n),this._removeAnimationSettings(t,e)},i);window.addEventListener("rocket-startLoading",function(){clearTimeout(s)})}_listAnimationSettingsKeys(t="mobile"){const e=[""];switch(t){case"mobile":e.unshift("_mobile");case"tablet":e.unshift("_tablet");case"desktop":e.unshift("_desktop")}const i=[];return["animation","_animation"].forEach(t=>{e.forEach(e=>{i.push(t+e)})}),i}_removeAnimationSettings(t,e){this._listAnimationSettingsKeys().forEach(t=>delete e[t]),t.dataset.settings=JSON.stringify(e)}static run(){const t=new RocketElementorAnimation;requestAnimationFrame(t._detectAnimations.bind(t))}}document.addEventListener("DOMContentLoaded",RocketElementorAnimation.run);</script><script type="text/javascript" id="perfmatters-delayed-styles-js">!function(){const e=["keydown","mousemove","wheel","touchmove","touchstart","touchend"];function t(){document.querySelectorAll("link[data-pmdelayedstyle]").forEach(function(e){e.setAttribute("href",e.getAttribute("data-pmdelayedstyle"))}),e.forEach(function(e){window.removeEventListener(e,t,{passive:!0})})}e.forEach(function(e){window.addEventListener(e,t,{passive:!0})})}();</script></body></html>\n";
  
 return html;
}
				
			

Code Explanation

We start by importing the necessary libraries and setting the variable which holds authentication information of our wireless network. The ESP8266WiFi.h header file includes libraries for WiFi functionality, while the ESP8266WebServer.h includes server and HTTP-related libraries.

				
					#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

/*SSID & Password*/
const char* ssid = "YOUR_SSID";  // Enter SSID here
const char* password = "YOUR_PASSWORD";  //Enter Password here
				
			

Next, we create a web server object. We’ll want to use port 80 for this. We declare a global variable called LEDpin holding the pin number of the LED that we want to control and also a variable called LEDstatus to hold its status.

				
					ESP8266WebServer server(80);

uint8_t LEDpin = D3;
bool LEDstatus = false;
				
			

The first part of the setup function sets the NodeMCU pin as an output, begins the serial debug port, then begins connecting to the Wi-Fi network. We inform the user if it connected successfully and display the webserver’s IP address.

				
					void setup() {
  
  pinMode(LEDpin, OUTPUT);

  Serial.begin(115200);
  Serial.println(" ");
  Serial.println("Connecting: ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while(WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.println(".");
  }
  Serial.println(" ");
  Serial.print("Connected at: ");
  Serial.println(WiFi.localIP()
				
			

In the second part of the function, we utilize the server object. Several server.on( ) statements state that whenever we receive a specific HTTP address request we execute an action through several handler functions. We see here, for example, that the “/” is actually the root HTTP address. The “/ledon” is another HTTP equivalent address. The handler functions are Connect_handler, LED_ON_handler, LED_OFF_handler, and Not_found_handler.

				
					  server.on("/", Connect_handler);
  server.on("/ledon", LED_ON_handler);
  server.on("/ledoff", LED_OFF_handler);
  server.onNotFound(Not_found_handler);

  server.begin();
  Serial.println("Web server has began");
}
				
			

The loop part starts executing a necessary client handler function server.handleClient( ). After that, we change the status of the LEDs according to the LEDstatus variable that may have been changed in the process.

				
					void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();

  if(LEDstatus){
    digitalWrite(LEDpin, HIGH);
  }else{
    digitalWrite(LEDpin, LOW);
  }
}
				
			

Next, we have the server.on( ) handler functions declared. You’ll see that it changes the LEDstatus variable and executes the server.send( ) function. This server.send( ) function sends first a status (200 = OK), then the actual webpage through HTTP in HTML format (“text/html”). The actual webpage is a string type executed by the SendClient( ) function.

				
					void Connect_handler()
{
  LEDstatus = false;
  Serial.println("LED has been turned OFF");
  server.send(200, "text/html", SendClient());
}

void LED_ON_handler()
{
  LEDstatus = true;
  Serial.println("LED has been turned ON");
  server.send(200, "text/html", SendClient());
}

void LED_OFF_handler()
{
  LEDstatus = false;
  Serial.println("LED has been turned OFF");
  server.send(200, "text/html", SendClient());
}

void Not_found_handler()
{
  server.send(404, "text/plain", "address not found");
}
				
			

Lastly, we have the SendClient( ) function. This function simply formats the string-type HTML webpage that the client requests. You’ll be able to write your own HTML code through any HTML editor. This webpage contains the links required to turn ON or OFF the LED. Once the user presses these links, the client will perform a GET request to the web server with the specified address link. Accordingly, the NodeMCU will perform a specific action based on this address link.

				
					String SendClient()
{
  
  String html ="<!doctype html>\n";
  html += "<html> <head> <title>HTML Editor - Full Version</title> </head>\n"; 
  html += "<body>\n"; 
  html += "<h1>ESP8266 Web Server</h1> <h1>STA mode</h1>\n";
  html += "<h1>Press the button to toggle LED:</h1>\n";

  html += "<h1><a title=\"ledon\" href=\"ledon\">ledon</a></h1>\n"; 
  html += "<h1><a title=\"ledoff\" href=\"ledoff\">ledoff</a></h1>\n";

  html += "<script type="text/javascript" id="perfmatters-delayed-styles-js">!function(){const e=["keydown","mousemove","wheel","touchmove","touchstart","touchend"];function t(){document.querySelectorAll("link[data-pmdelayedstyle]").forEach(function(e){e.setAttribute("href",e.getAttribute("data-pmdelayedstyle"))}),e.forEach(function(e){window.removeEventListener(e,t,{passive:!0})})}e.forEach(function(e){window.addEventListener(e,t,{passive:!0})})}();</script></body></html>\n";
  
 return html;
}
				
			

Converting HTML Code For Arduino

Prior to uploading HTML code to the device, some modifications need to be made to the code so it can be interpreted correctly.

To do that, there is a tool that can be used that allows raw HTML code to be pasted in, and it will then output the code in the correct format to be uploaded. Click the button below to open up the tool

Accessing The Webserver

After the code has been compiled and uploaded successfully, we’ll want to access the webpage. See the IP address of the web server through the Serial Monitor.

You should see the webpage that you had made. Click on the links and see both the link address and LED change accordingly.

SUBSCRIBE FOR NEW POST ALERTS

Subscribe to be the first to know when we publish a new article!
List Subscriptions(Required)

POPULAR POSTS

Scroll to Top