CONTROL LED USING NODEMCU / ESP8266

In this tutorial you will learn how to control LED using IoT dashboard or web server. To control led using NodeMCU / ESP8266, you need to write a couple of lines more as you write before in setup WiFi connection.

CIRCUIT DIAGRAM

control LED using IoT

QUICK START

  1. As you installed ESP8266 Board package from Board Manager you don’t need to include basic library for NodeMCU
  2. Select board you are using under Tools → Boards, here I am using NodeMCU 0.9 (ESP-12 Module).
  3. Same as for Arduino, select communication port (COM) under Tools → Port, on which NodeMCU connected.

PROGRAM CODE

Note: If your ESP8266 and ESP8266HTTPClient library colour doesn’t change it means didn’t selected correct board

#include<ESP8266WiFi.h>
#include<ESP8266HTTPClient.h>

HTTPClient http;

const char* WIFINAME = "YOUR_SSID_NAME";
const char* PASS = "YOUR_SSID_PASSWORD";
//int led = D0;
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println("");
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.print("Connecting To ");
  Serial.println(WIFINAME);

  WiFi.begin(WIFINAME, PASS);

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

void loop() {
  // Enter in this if block only if nodemcu is connected to wifi network
  if (WiFi.status() == WL_CONNECTED) {

    HTTPClient http;

    //////////////// http client to read data for LED /////////////////////////////
    http.begin("http://iot-dashboard.shoolinlabs.com/1/bulb.txt");
    int httpCode = http.GET();
// List of HTTP codes: https://pijaeducation.com/list-of-http-status-codes/
    if (httpCode > 0) {

      String payload = http.getString();
      Serial.println(payload);
      if (payload == "1") {
        digitalWrite(LED_BUILTIN, LOW);
        Serial.println("LED ON");
      }
      else if (payload == "0") {
        digitalWrite(LED_BUILTIN, HIGH);
        Serial.println("LED OFF");
      }
    }

    http.end();
  }
  delay(100);
}

CODE EXPLANATION

WiFiServer server(80)

This function creates a server that listens to the specified port for the incoming connections.

WiFiServer server(80);

The default HTTP port is 80, here Web server is on port 80, you can also use other ports, you need to enter port number after IP address to open the web page, with different port number. E.g. You must type 192.168.2.2.2:81 in your browser for port number 81.

ESP8266WiFi LIBRARY

ESP8266 is all about Wi-Fi. If you are eager to connect your new ESP8266 module to Wi-Fi network to start sending and receiving data, this is a good place to start.

In the first line of sketch

#include<ESP8266WiFi.h>

We are including ESP8266WiFi library. This library provides ESP8266 specific Wi-Fi routines we are calling to connect to network.

ESP8266HTTPClient LIBRARY

Then, we need the ESP8266HTTPClient library, which provides methods to send HTTP requests.

WiFi.begin()

Actual connection to Wi-Fi is initialized by calling

  WiFi.begin(WIFINAME, PASS);

In the line WiFi.begin(“network-name”, “pass-to-network”)
replace network-name and pass-to-network with name and password to the Wi-Fi network you like to connect. Then upload this sketch to ESP module and open serial monitor.
You should see something like:

Wifi begin

WiFi CONNECTION PROCESS

Connection process can take couple of seconds and we are checking for this to complete in the following loop:

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

WiFi.status()

Some functions provide more than just a binary status information. A good example is WiFi.status(), can return following codes to describe what is going on with Wi-Fi connection

    • 0 : WL_IDLE STATUS, when Wi-Fi is in process of changing between statuses
    • 1 : WL_NO_SSID_AVAIL, in case configured SSID cannot be reached
    • 3 : WL_CONNECTED, after successful connection is established
    • 4 : WL_CONNECT_FAILED, If password is incorrect
    • 6 : WL_DISCONNECTED, if module is not configured in station mode

WiFi.localIP()

The last line in setup will print out IP address assigned to ESP module

  Serial.println(WiFi.localIP());

HTTPClient http

Create variable object http for the Class (generalized term Library) HTTPClient to access all the methods (generalized term function) of this class, like obj.begin(), obj.getString() etc.

    HTTPClient http;

http.begin()

Using http object we are accessing class HTTPClient method begin(). This begin method initialize the request to the specific URL location we want. We need to call another method below in order to actually send the request.

http.begin("http://iot-dashboard.shoolinlabs.com/1/bulb.txt")

http.GET()

Now we will send the actual request using GET method. This method will return the HTTP response code returned by the server, if the request sent successfully.

For example:  404 Not Found  – The server can not find the requested page etc.

If an internal error occurred in the ESP8266, then it will return a value lesser than 0 may be -1. HTTP status codes list is here

    int httpCode = http.GET();

http.getString()

To get the content of the response means content of the target file like we have bulb.txt, you can see in the http.begin url, we simply need to call the getString method of the HTTPClient using http object. This method needs no arguments, & returns a string as output/response. Which gets stored in String payload.

      String payload = http.getString();

http.end()

To free the resources we need to call end method

    http.end();

 

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x