Tag Archive: NODEMCU


title_iot1

IOT is Internet Of Things where devices are connected over internet and made SMART.

These devices can be controlled from any where in the World or collect data from devices to process.

In this 1st post of IOT series I will introduce the hardware required to start with and also the IOT platforms used.

Arduino boards are much popular among hobbyists and developers.But these Arduino boards (UNO,MEGA) lack Ethernet or WIFI capability which is essential for IOT.

For wired connection there is ETHERNET Shield which can be plugged on directly to UNO or Mega.

l1

 

For internet access I’m using a Huawei make USB Dongle with a Data SIM inserted.This dongle

can be used in standalone mode , as it has got WIFI capability.But plugging this to a Router

like TP-LINK enhances its capability of WIFI Range, more Clients, Static IP setting,etc..

i3

 

i1

 

The Ethernet shield can be plugged on to Arduino and an Ethernet cable (straight type)

can be used to connect with the Router.

The Router will then allot an IP Address (local IP) to the ethernet shield which is now a client.

DHCP server of Router allots the IP on first come first basis.As this IP is DYNAMIC ,

the address may not be the same if powered off and connected again.’’

To make the IP address STATIC , the ROUTER has ADDRESS RESERVATION settings

under DHCP.

MAC address of the device is used to make the local IP STATIC.

l3

Instead of wired Ethernet connection you can go for WIFI Devices. ESP8266 WIFI modules are

cheap and popular now.

ESP8266 WIFI modules , a wide range available.ESP8266-01 module is basic model .As it is not breadboard friendly , you can make use of a base board to plug on , as shown in picture below.

ESP8266-12E module has more GPIO pins and memory.

These modules can communicate with ARDUINO using AT COMMANDS for ESP.

 

I6

 

To use ESP modules we need a controller like Arduino.

Easier option is to use NODEMCU Modules.These NODEMCU modules are built on ESP12E chip

and has USB to upload code.LUA is the official Firmware that comes with NODEMCU.

Using BOARDS MANAGER in Arduino IDE you can implement ARDUINO CORE on to NODEMCU

and start using NODEMCU individually.

You can check out my video on how to implement Arduino core on to NODEMCU.

https://www.youtube.com/watch?v=BbiLBiFvlsI

Once Arduino core implemented , you can use Arduino IDE and libraries to develop code on NODEMCU.

Latest arrival is ESP32 which is much more powerful than NODEMCU with more Analog pins

and with BLUETOOTH,BLE and inbuilt sensors.

I8

For IOT and HOME AUTOMATION projects RELAY BOARDS are helpful to connect wide

range  of Loads or devices.

5V Relay boards are available with 1 channel , 2, 4,8 Upto 16 channels .

Each relay is driven by an opto coupler and a NPN transistor.The relay contacts are

provided as Terminal connectors.

Each Relay has a  common POLE,  a NC –Normally Connected contact and a

NO – Normally Open contact.

 

I10

These 5V relay boards are LOW ENBLED, meaning , a LOW at input will energize the Relay.

A low at input will make the opto coupler conduct which drives the NPN Transistor.

This in turn will switch ON the relay.

jdvcc

Electronic solid state relay boards are also available which are called SSR.

 

SSR

12v Relay modules also are available.Here the relay is driven by a NPN transistor .12V Modules are HIGH ENABLED ,meaning, a HIGH at input drives the relay ON.

 

I11

 

Any load ,DC or AC can be connected to the RELAY contacts, irrespective of the supply voltage to relay board.

The power supply to load is connected to POLE pin and the actual load is connected to the NO pin.

As the relay is energized the pole pin changes from NC to NO ,thus activating  the Load.

While using AC load take precaution to insulate properly the wires as well as the Relay boar.Do not touch relay board with AC load.

I12

 

You can control the devices over Local Area Network or through Cloud or internet.

While using LAN , make sure that the NODEMCU and your mobile , both are connected to the same Router SSID.

For control over internet you need to PORT FORWARD the local ip device port on the router settings.But nowadays a number of IOT PLATFORMS are available as CLOUD. Though you need a paid subscription , most of them offer free service for hobbyists with some limitations.

BLYNK, CAYENNE, THINGSBOARD are some popular IOT PLATFORMS.

Sign in to any of these platforms and start controlling the devices from anywhere in the world.

iot2

VIDEO support :

 

blog_image

In this post we’ll see how to control an LED connected to NODEMCU from a WebBrowser.

The WebBrowser is a CLIENT & the NodeMCU is the SERVER .

The Nodemcu has to be installed with Boards Manager Arduino core. Refer to the previous post on how to do this.

 

Image 1

 

Connect the long pin of LED to D2 pin of NodeMCU , short pin to GND through a 470E resistor.

Connect the NodeMCU to USB port of PC & note the COM port allotted.Feed in this COM port number in IDE & select the board as NodeMcu v1.0 (ESP12E).

Upload the following code.

 

You can Download the code used in this post HERE

————————————-

 

#include <ESP8266WiFi.h>
#define LED D2
const char* ssid = “SARAVANA-ACT”;
const char* password = “str5412stk4141”;
unsigned char status_led=0;

WiFiServer server(80);

void setup() {
Serial.begin(115200);
pinMode(LED, OUTPUT);
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.println(WiFi.localIP());
}

void loop() {
WiFiClient client = server.available();
if (!client) {
return;
}

Serial.println(“new client”);
while(!client.available())
{
delay(1);
}
String req = client.readStringUntil(‘\r’);
Serial.println(req);
client.flush();
if (req.indexOf(“/ledoff”) != -1)
{
status_led=0;
digitalWrite(LED,LOW);
Serial.println(“LED OFF”);
}
else if(req.indexOf(“/ledon”) != -1)
{
status_led=1;
digitalWrite(LED,HIGH);
Serial.println(“LED ON”);
}
String web = “HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n”;
web += “<html>\r\n”;
web += “<body>\r\n”;
web += “<h1>LED Status</h1>\r\n”;
web += “<p>\r\n”;
if(status_led==1)
web += “LED On\r\n”;
else
web += “LED Off\r\n”;
web += “</p>\r\n”;
web += “</p>\r\n”;
web += “<a href=\”/ledon\”>\r\n”;
web += “<button>LED On</button >\r\n”;
web += “</a>\r\n”;
web += “</p>\r\n”;

web += “<a href=\”/ledoff\”>\r\n”;
web += “<button>LED Off</button >\r\n”;
web += “</a>\r\n”;

web += “</body>\r\n”;
web += “</html>\r\n”;

client.print(web);
}

——————————————-

First of all, we include the ESP8266WiFi library, which will make available the functionality needed for the ESP8266 to connect to a WiFi network.Then we define the D2 pin as LED where an Led is connected.

#include <ESP8266WiFi.h>
#define LED D2

The SSID name & password are stored in char variables.

A WiFiserver object called “server “ is created & we pass the port 80 where the server will be listening ( 80 is the default port of HTTP)

WiFiServer server(80);

In the setup() function serial monitor is started at baud 115200 & the LED pin is declared as Output.

The begin() function of WiFi class is used with parameters ssid & password to start connection to WiFIi

WiFi.begin(ssid, password);

We wait till the WiFi.status() becomes WL_CONNECTED which indicates that connection is established .Until then we print a dot every 500msec.

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

Once connection is established , an IP address is allotted to NodeMCU by your Router.We print the IP address using the localIP() function.

Serial.println(WiFi.localIP());

Inside the loop we create an object called client of class WiFiClient & assign the server.available() result (it returns true or false) to it.

WiFiClient client = server.available();

It waits for a client ( here a web browser is the client) to connect with.

Once a request is received  , the client.readStringUntil (‘\r”) will read the request till it encounters a  carriage return & assign it to a String variable req

String req = client.readStringUntil(‘\r’);

indexOf() function of String is used to find out ehether the request is ledoff or ledon.

if (req.indexOf(“/ledoff”) != -1)

The indexOf() function returns a –1 if no match found.

Accordingly the LED is made ON or OFF.

Now let us see how a HTML page is served to webbrowser when a client request is received

ode will be stored in strings that will be returned in the HTTP responses

we can declare it in a string and just return it when a HTTP request is performed on the desired URL.

 

String web = “HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n”;
web += “<html>\r\n”;
web += “<body>\r\n”;
web += “<h1>LED Status</h1>\r\n”;

 

First, we  return the 200 HTTP code (OK code). Then, we need to make sure that we specify the return content as text/html, so the browser will know that it should be interpreted and rendered as such

Finally, we pass the string with the HTML/CSS code

The <html> element represents the root of an HTML document. All other elements must be descendants of this element .

The <body> tag specifies where the body of the document starts .

The <h1> tag specifies the Heading of Webpage

The <p> tag specifies a paragraph and thus we use it to indicate our description message.

 

web += “<a href=\”/ledon\”>\r\n”;
web += “<button>LED On</button >\r\n”;

The <a> tag allows us to create a hyperlink by specifying the URL of a page and the message of the hyperlink. So, in the href attribute we specify the URL we want the user to be redirected to, and between the two tags we specify the message of the hyperlink.

In this case, we are specifying a path in the current address, so we don’t need to put the IP and the port. So, when a user clicks the hyperlink, the browser knows it will need to redirect the user to

http://IP Port/[href value]

As we will see later, the paths we are specifying in the href will correspond to the paths where the NodeMcu will be programmed to return the corresponding code.

the <br> tag is just a simple line break between the hyperlinks.

One thing that is very important is that we are specifying the HTML code inside a string, and thus some details need to be taken in consideration.

First, in order to leave the code structured, we should split the declaration of the string in multiple lines. To do so, we need to put the double quotes in each line so the compiler will know that it should be considered as a single string. So, the outermost quotes of the previous code are not from the HTML but from the declaration of a string in multiple lines.

Finally, every quote that is part of the HTML code (for example, the quotes around the URLs in the <a> tag) needs to be escaped with the \ character. So, the \ characters we see before the quotes are also not part of the HTML code but rather the escaping mechanism.

The <button> tag allows for the definition of a clickable button. One of its functionalities allows us to specify a function that is executed when the button is clicked

 

web += “<button>LED Off</button >\r\n”;

Now upload the code & open the serial monitor

Image 5_1

WiFi connection starts & displays IP if connection established.

Open your web browser & type in the IP you got from the serial monitor.

Once you click the Enter button , a CLIENT request is sent to NodeMCU.

Now the HTML page is served & buttons LED ON & LED OFF are displayed on the browser.

Image 6_1

If you click LED ON button , the message string “ledon” is added to URL & sent to Nodemcu.

The string is read and accordingly the LED will be ON or OFF.

Image 7_1

 

Here is another version of code where we use client.print() to serve the Webpage

 

———————————-

 

#include <ESP8266WiFi.h>
#define LED D2  // LED at GPIO4 D2

const char* ssid = “SARAVANA-ACT”;
const char* password = “str5412stk4141”;
unsigned char status_led=0;

WiFiServer server(80);

void setup() {
Serial.begin(115200);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);

// Connect to WiFi network
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”);

// Start the server
server.begin();
Serial.println(“Server started at…”);
Serial.println(WiFi.localIP());

}

void loop() {

// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Wait until the client sends some data
Serial.println(“new client”);
while (! client.available())
{
delay (1);
}

// Read the first line of the request
String req = client.readStringUntil(‘\r’);
Serial.println(req);
client.flush();

// Match the request

if (req.indexOf(“/ledoff”) != -1)  {
status_led=0;
digitalWrite(LED, LOW);
Serial.println(“LED OFF”);
}
else if(req.indexOf(“/ledon”) != -1)
{
status_led=1;
digitalWrite(LED,HIGH);
Serial.println(“LED ON”);
}

// Return the response
client.println(“HTTP/1.1 200 OK”);
client.println(“Content-Type: text/html”);
client.println(“Connection: close”);
client.println(“”);

client.println(“<!DOCTYPE HTML>”);
client.println(“<HTML>”);
client.println(“<H1> LED CONTROL </H1>”);
client.println(“<br />”);

client.println(“<a href=\”/ledon\”\”> <button style=’FONT-SIZE: 50px; HEIGHT: 200px;WIDTH: 300px; 126px; Z-INDEX: 0; TOP: 200px;’> LED ON </button> </a>”);
client.println(“<a href=\”/ledoff\”\”> <button style=’FONT-SIZE: 50px; HEIGHT: 200px; WIDTH: 300px; 126px; Z-INDEX: 0; TOP: 200px;’> LED OFF </button> </a>”);
client.println(“</html>”);

delay(1);
Serial.println(“Client disconnected”);
Serial.println(“”);

}
———————————–

Inside <button> tag we create a style to make big size buttons.

On clicking the respective buttons the LED is made ON or OFF.

 

Image 9

 

Image 10

 

Image 11

VIDEO DEMO :

cooltext753793315   cooltext753790696

NODEMCU is built on ESP8266 12E Module & is an excellent , economical IOT PLATFORM.

Generally it is shipped from factory with NODEMCU FIRMWARE which can be programmed with LUA Script.

In this post we shall install the ARDUINO CORE for ESP8266 on NODEMCU & start exploring how to use the ARDUINO IDE to code NODEMCU

nodemcu_pins1

 

To use the ARDUINO IDE , first thing is to install the ARDUINO CORE on to NODEMCU.

Open the ARDUINO IDE & under FILE –> PREFERENCES paste the link provided below :

Arduino Boards Manager file link is HERE

 

Image 1

under Tools –> BOARDS –> BOARDS MANAGER

search for ESP8266 & then click on it to install the latest version.

Image 2

 

Connect the NODEMCU to the USB of PC & open the DEVICE MANAGER to note the COM PORT allotted.If you see exclamation mark , then install the CP2102 driver for the NODEMCU.

Under Tools –>

select the board as NODEMCU V1.0 (ESP12E) , Port as the COM port alloted, Programmer as USBASP , UPLOAD SPEED as 115200.

Image 3

 

Under FILE –> EXAMPLES –> ESP8266 select the BLINK sketch

Image 4

 

Here the LED_BUILTIN is mapped to the inbuilt LED on board NODEMCU.

So , just click on the UPLOAD button.

Image 5

 

Once the sketch is compiled , the uploading starts , as seen at the bottom of the IDE.

It takes some time to upload ( i.e the reason to select upload speed 115200 , to make it fast)

as the code upload is like upgrading Firmware.

As the sketch is uploaded , the blue LED on the ESP chip (near WIFI antenna) flickers & finally the RED LED on board blinks.

In the next example let us connect an LED at pin D2 through a resistor.

D2 pin is GPIO4 of NODEMCU , but in the code we use the notation Dx to represent GPIO pin.

To control GPIO4 pin we use D2 in the code & not GPIO4 directly.

Image 7

 

In the blink code , the following line is added

#define LED_BUILTIN D2

Image 8

Upload the code to see the LED connected at DS2 blinking.

In the same way we can use ANALOG WRITE function to give a fade effect on the LED.

 

Now let us explore the NETWORKING capabilities of NODEMCU.

To start with we include the ESP8266WiFi.h header file.

The WIFI library is enhanced version of Arduino & is installed along with the Boards Manager.

This ESP8266WiFi  library has several classes, methods and properties  , which combines many powerful FUNCTIONS .

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.

After the header file  , we store the SSID name & Password as character arrays

#include <ESP8266WiFi.h>
char ssid[]=”SSID_NAME”;
char pass[]=”Password”;

Inside the setup function , Serial communication is started with 9600 baud & the name of SSID is printed.

void setup() {
Serial.begin(9600);
delay(500);
Serial.print(“Connecting to..”);
Serial.println(ssid);
delay(500);

WiFi.disconnect() function is called to disconnect any previous connections

While using the WiFi CLASS , there is no need to create WiFi Object.Simply call the function like

begin(),  SSID(), status(), disconnect(), scanNetworks(), localIP(), etc..

Actual connection to Wi-Fi is initialized by calling the begin() function.We pass on the 2 parameters to WiFi.begin() function to start the connection

  WiFi.disconnect();
WiFi.begin(ssid,pass);

We use a While loop to test the status of WiFi.status(). Here we check whether it returns WL_CONNECTED

IF not connected , a dot is printed every 500 msec.

while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.println(“.”);
}

Once connection is established , it jumps out of loop & prints the SSID name connected with.

if connection is established, and then lost for some reason, ESP will automatically reconnect to last used access point once it is again back on-line. This will be done automatically by Wi-Fi library, without any user intervention.

Serial.print(“SSID…”);
Serial.println (WiFi.SSID());
Serial.println(“Successfully connected!!!”);

 

Next the IP address allotted to the NODEMCU by the Router  (by DHCP method) is printed by calling the function WiFi.localIP()

The MAC address is printed using WiFi.macaddress()

 

Serial.print(“IP Address allotted to NodeMcu ESP..”);
Serial.println(WiFi.localIP());

Serial.print(“MAC Address of ESP…”);
Serial.println(WiFi.macAddress());

WiFi.printDiag(Serial) prints all the WiFi credentials like Channel , SSID name , Password , etc..

This specific function  prints out key Wi-Fi diagnostic information:

WiFi.printDiag(Serial);
}

void loop()
{
}

Upload the code & open the Serial monitor at baud 9600 to see the result.

 

Image 10

Next example is to scan the surrounding networks & print the name of SSIDs.

Here we use the function scanNetworks() which returns an Integer value on the number of surrounding SSIDs.

We assign this to an integer variable

int n = WiFi.scanNetworks();

& then in a For loop iterate to print out name of each surrounding SSIDs

 

for (int i=0; i<n; i++)

{

Serial.println(  WiFi.SSID (i) )

}

Image 11

 

Scan for available Wi-Fi networks in one run and return the number of networks that has been discovered.

WiFi.scanNetworks();

There is on Overload of this function that accepts two optional parameters to provide extended functionality of asynchronous scanning as well as looking for hidden networks

WiFi.scanNetworks(async,show_hidden);

Both function parameters are of boolean type. They provide the flowing functionality: * asysnc – if set to true then scanning will start in background and function will exit without waiting for result. To check for result use separate function scanComplete . * show_hidden – set it to true to include The in scan result networks with hidden SSID.

 

Image12

Download code samples HERE

Download ESP8266 Library document PDF HERE

VIDEO TUTORIALS :

 

 

cooltext753793315   cooltext753790696