Control an led using node MCU ESP8266 and web server

Aim:  Control an led using node MCU ESP8266 and web server.

Objective

This project aims to control a simple LED using a Node MCU ESP8266 development board and create a web server to interact with the LED via a web interface.

Requirements

  1. Node MCU ESP8266
  2. 5mm led
  3. 220 Ohm resistor
  4. Breadboard
  5. Jumper wires
  6. Micro USB (V8) data cable
  7. Computer with internet connection
  8. Arduino IDE

Circuit Diagram

Node mcu web server

Procedure:

Step 1: Set up the Hardware

  1. Connect the Node MCU ESP8266 to the breadboard.
  2. Connect the positive leg of the LED to the digital pin D4 (GPIO2) of the Node MCU via a current-limiting resistor (220Ω).
  3. Connect the negative leg of the LED to the ground (GND) pin of the Node MCU.

Step 2: Select the Board and Port

  1. Go to “Tools” > “Board” and select “Node MCU 1.0 (ESP-12E Module)” under the ESP8266 boards section.
  2. Go to “Tools” > “Port” and select the appropriate port to which the Node MCU is connected.

Step 3: Understanding the code

This code is an example of an Arduino sketch that creates a web server using the ESP8266WiFi library. The web server allows you to control an LED connected to GPIO2 (D4) of the ESP8266 module through a web interface. Let’s go through the code part by part:

  1. #include <ESP8266WiFi.h>

   – This line includes the ESP8266WiFi library, which provides functions to connect to a Wi-Fi network and create a web server.

  1. const char* ssid = “SSID”; // Your Wi-Fi Name

   – This line defines a constant variable `ssid` that stores the name of your Wi-Fi network. Replace “FreakEngineer” with the actual name (SSID) of your Wi-Fi network.

  1. const char* password = “Password”; // Your Wi-Fi Password

   – This line defines a constant variable `password` that stores the password for your Wi-Fi network. Replace “password” with the actual password for your Wi-Fi network.

  1. int LED = 2; // led connected to GPIO2 (D4)

   – This line defines an integer variable `LED` that represents the GPIO pin number to which the LED is connected. In this case, the LED is connected to GPIO2, which corresponds to pin D4 on the ESP8266 module.

  1. WiFiServer server(80);

   – This line creates a `WiFiServer` object named `server` that will listen for incoming client connections on port 80, which is the default port for HTTP communication.

  1. void setup()

   – This is the setup function. It is called once when the Arduino board starts up.

  1. Serial.begin(115200); // Default Baudrate

   – This line initializes the serial communication at a baud rate of 115200. It allows you to send and receive data between the Arduino board and your computer via the serial port.

  1. pinMode(LED, OUTPUT);

   – This line sets the GPIO pin connected to the LED (GPIO2/D4) as an output pin.

  1. digitalWrite(LED, LOW);

   – This line sets the initial state of the LED to LOW (off).

  1. Serial.print(“Connecting to the Network”);

    – This line prints a message to the serial monitor indicating that the Arduino is attempting to connect to the Wi-Fi network.

11.WiFi.begin(ssid, password);

    – This line initiates a connection to the Wi-Fi network using the provided SSID (Wi-Fi name) and password.

  1. while (WiFi.status() != WL_CONNECTED)

    – This loop waits until the Wi-Fi connection is established. It continuously checks the status of the Wi-Fi connection until it becomes connected.

  1. delay(500);

    – This line introduces a 500 milliseconds delay between each iteration of the loop.

  1. Serial.print(“.”);

    – This line prints a dot (.) to the serial monitor to indicate that the connection process is ongoing.

  1. Serial.println(“WiFi connected”);

    – This line prints a message to the serial monitor indicating that the Wi-Fi connection has been successfully established.

  1. server.begin();

    – This line starts the web server.

  1. Serial.println(“Server started”);

    – This line prints a message to the serial monitor indicating that the web server has started successfully.

  1. Serial.print(“IP Address of network: “);

    – This line prints a message to the serial monitor indicating that

 the IP address of the network is about to be displayed.

  1. Serial.println(WiFi.localIP());

    – This line prints the IP address of the ESP8266 module to the serial monitor. This IP address represents the address that you can use to access the web server.

  1. Serial.print(“Copy and paste the following URL: https://”);

    – This line prints a message to the serial monitor instructing you to copy and paste a URL to access the web server.

  1. Serial.print(WiFi.localIP());

    – This line prints the IP address of the ESP8266 module to the serial monitor, continuing from the previous message.

  1. Serial.println(“/”);

    – This line prints a forward slash (/) and a newline character to the serial monitor, completing the URL message.

The remaining code consists of the `loop()` function, which is executed repeatedly after the `setup()` function. The `loop()` function performs the following tasks:

  1. WiFiClient client = server.available();

    – This line checks if there is a client connected to the web server. If a client is available, it creates a `WiFiClient` object named `client` to handle the client’s request.

  1. if (!client)

    – This condition checks if a client is connected. If there is no client, the code returns to the beginning of the `loop()` function and waits for a new client.

  1. Serial.println(“Waiting for new client”);

    – This line prints a message to the serial monitor indicating that the server is waiting for a new client’s request.

  1. while(!client.available())

    – This loop waits until the client sends a request. It continuously checks if the client has sent any data.

  1. delay(1);

    – This line introduces a 1-millisecond delay between each iteration of the loop.

  1. String request = client.readStringUntil(‘r’);

    – This line reads the client’s request from the network buffer until a carriage return (‘r’) character is encountered. It stores the request in a String variable called `request`.

  1. Serial.println(request);

    – This line prints the client’s request to the serial monitor.

  1. client.flush();

    – This line discards any remaining data in the client’s buffer.

  1. The code then checks the client’s request to see if it contains “/LED=ON” or “/LED=OFF” using the `indexOf()` function.
  1. If the request contains “/LED=ON”, it sets the LED pin to HIGH, turning the LED on.
  1. If the request contains “/LED=OFF”, it sets the LED pin to LOW, turning the LED off.
  1. 34. The code then generates an HTML response to send back to the client.
  1. The HTML response includes the current state of the LED and provides buttons to control it.
  1. The response is sent to the client using the `client.println()` function.
  1. Finally, there is a short delay before the end of the loop, and then the process repeats.

That’s a breakdown of the code’s functionality. It creates a web server that responds to client requests and controls an LED based on the request received.

Step 4: Write the Code

#include <ESP8266WiFi.h>

const char* ssid = “SSID”;    //  Your Wi-Fi Name

const char* password = “Password”;   // Your Wi-Fi Password

int LED = 2;   // led connected to GPIO2 (D4)

WiFiServer server(80);

void setup()

{

  Serial.begin(115200); //Default Baudrate

  pinMode(LED, OUTPUT);

  digitalWrite(LED, LOW);

  Serial.print(“Connecting to the Newtork”);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)

  {

    delay(500);

    Serial.print(“.”);

  }

  Serial.println(“WiFi connected”);

  server.begin();  // Starts the Server

  Serial.println(“Server started”);

  Serial.print(“IP Address of network: “); // will IP address on Serial Monitor

  Serial.println(WiFi.localIP());

  Serial.print(“Copy and paste the following URL: https://”); // Will print IP address in URL format

  Serial.print(WiFi.localIP());

  Serial.println(“/”);

}

void loop()

{

  WiFiClient client = server.available();

  if (!client)

  {

    return;

  }

  Serial.println(“Waiting for new client”);

  while(!client.available())

  {

    delay(1);

  }

  String request = client.readStringUntil(‘r’);

  Serial.println(request);

  client.flush();

  int value = LOW;

  if(request.indexOf(“/LED=ON”) != -1)

  {

    digitalWrite(LED, HIGH); // Turn LED ON

    value = HIGH;

  }

  if(request.indexOf(“/LED=OFF”) != -1)

  {

    digitalWrite(LED, LOW); // Turn LED OFF

    value = LOW;

  }

//*——————HTML Page Code———————*//

  client.println(“HTTP/1.1 200 OK”); //

  client.println(“Content-Type: text/html”);

  client.println(“”);

  client.println(“<!DOCTYPE HTML>”);

  client.println(“<html>”);

  client.print(” CONTROL LED: “);

  if(value == HIGH)

  {

    client.print(“ON”);

  }

  else

  {

    client.print(“OFF”);

  }

  client.println(“<br><br>”);

  client.println(“<a href=”/LED=ON””><button>ON</button></a>”);

  client.println(“<a href=”/LED=OFF””><button>OFF</button></a><br />”);

  client.println(“</html>”);

   delay(1);

  Serial.println(“Client disonnected”);

  Serial.println(“”);

}

Step 5: Upload the Code

  1. Connect the Node MCU to your computer using the USB cable.
  2. Select the correct board and port name from the Arduino IDE, as mentioned in Step 2.
  3. Click on the “Upload” button to compile and upload the code to the Node MCU.

Step 6: Test the Functionality

  1. Once the code is successfully uploaded, open the Serial Monitor in the Arduino IDE (Ctrl+Shift+M) to monitor the IP address assigned to the Node MCU.
  2. Connect your computer or mobile device to the same Wi-Fi network as mentioned in the code (replace “YourSSID” and “YourPassword” with your network credentials).
  3. Open a web browser (in a smartphone or computer) and enter the IP address displayed in the Serial Monitor.
  4. You should see a web page with LED control options. Click on the links to turn the LED ON or OFF.

Conclusion

In this lab work, you have successfully controlled a simple LED using a Node MCU ESP8266 development board and created a web server to interact with the LED through a web interface. This concept can be extended further to control other devices or sensors using the Node MCU and web server functionality.

Precaution

  1. Make sure there is no space in your “SSID” and “Password”.
  2. Check all the connections before powering up the node MCU.

Author

Akash Sharma


Visit YouTube Channel

Share This Post

Leave a Comment