Arduino Tutorials – Lesson 28 – Node MCU

Creating an LED control from web browser program

Required Components

  1. Node MCU Board -1 no
  2. Bread Board -1 no
  3. Data Cable -1 no
  4. LED -1 no

Circuit

Steps

  1. Make sure the components are working properly.
  2. Connect Node MCU Board to the Bread Board.
  3. Connect the LED Anode(+) pin to Node MCU D7(13) and cathode(-)pin to Gnd.
  4. Check the Arduino program.
  5. Check the Circuit Connections.
  6. Run the Arduino program.

Arduino Program

#include <ESP8266WiFi.h>
const char* ssid = "******";
const char* password = "********";
int ledPin = 13; // GPIO13
WiFiServer server(80);

void setup() 
{
  Serial.begin(115200);
  delay(10);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  server.begin();
  Serial.println("Server started");
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}

void loop() 
{
  WiFiClient client = server.available();
  if (!client) 
  {
    return;
  }
  Serial.println("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(ledPin, HIGH);
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1)  {
    digitalWrite(ledPin, LOW);
    value = LOW;
  }
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.print("Led pin is now: ");
  
  if(value == HIGH) {
    client.print("On");
  } 
  else {
    client.print("Off");
  }
  client.println("<br><br>");
  client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a><br/>");
  client.println("</html>");
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
}

Usage

  1. Prototyping of  IoT devices
  2. Low power battery operated applications
  3. Network

Leave a Reply

Your email address will not be published. Required fields are marked *