Maker Pro
NodeMCU

NodeMCU with Web-server

November 22, 2020 by Parmar Nilesh
Share
banner

Gain an understanding of how to use NodeMCU as a server.

Hardware

In this project, we will make NodeMCU as a server and browser of mobile or laptop as a web client. So in our project, we will build communication between Server and client using HTTP(Hypertext Transfer Protocol) Protocol. In this protocol, a client initiates communication by requesting a particular web page using HTTP and the server acknowledges the content of that web page or an error message if unable to do so.

In our project when you send a request to NodeMCU to turn on/off led from a web browser (client) then NodeMCU will receive that data and turn on/off led.

WhatsApp Image 2020-11-22 at 1.48.32 PM (1).jpeg
#include <ESP8266WiFi.h>

WiFiClient client;
WiFiServer server(80);

#define led1 D0
#define led2 D2
#define led3 D4

void setup()
{
  Serial.begin(9600); // serial communication boad rate - send data from hardware to computer
  WiFi.begin("Wifi name", "Password"); // User ID and pasword for connet esp8266 to our internet oe make ESP as wifi
  while (WiFi.status() != WL_CONNECTED) // check nodemcu is connected or not
  {
    delay(200);
    Serial.print("..");
  }
  Serial.println();
  Serial.println("NodeMCU is connected!"); // 
  Serial.println(WiFi.localIP()); // it will print ID address on serial moniter
  server.begin();// for run nodemcu as a server
  pinMode(led1, OUTPUT);
  pinMode (led2, OUTPUT);
  pinMode (led3, OUTPUT);
  
}

void loop()
{
  // put your main code here, to run repeatedly:
  client = server.available();  //Gets a client that is connected to the server and has data available for reading.
  if (client == 1) //( if requested data is = 1)
  {
    String request =  client.readStringUntil('\n'); // store request data in string request variable
    Serial.println(request); // Read request data
    request.trim(); // clear garbege value
    
    if (request == "GET /led1on HTTP/1.1")
    {
      digitalWrite(led1, HIGH);
    }
    if (request == "GET /led1off HTTP/1.1")
    {
      digitalWrite(led1, LOW);
    }

    if (request == "GET /led21on HTTP/1.1")
    {
      digitalWrite(led2, HIGH);
    }
    if (request == "GET /led12off HTTP/1.1")
    {
      digitalWrite(led2, LOW);
    }

   if (request == "GET /led31on HTTP/1.1")
    {
      digitalWrite(led3, HIGH);
    }
    if (request == "GET /led31off HTTP/1.1")
    {
      digitalWrite(led3, LOW);
    }
  }
}
// Your code here

Author

Avatar
Parmar Nilesh

N.tech is a technical platform for those people or students who desire to learn about electronics, IoT, and electrical engineering.

Related Content

Categories

Comments


You May Also Like