A Hand Book On IOT: Dr. S. Arumuga Perumal
A Hand Book On IOT: Dr. S. Arumuga Perumal
A Hand Book On IOT: Dr. S. Arumuga Perumal
IOT
Prepared by
Dr. S. Arumuga Perumal, P. Eng
Advisor, Riyasaa Labs
Ex.Chairman, IETE NAGERCOIL PAC,
Trivandrum Center.
A hand book on Internet of Things
Definition of IoT
There are many technologies that facilitate the IoT such as Addressability,
Short range wireless (BLE,ZigBee,NFC,RFID), Medium range
wireless(LTE-Advanced), Long Range wireless(LPWAN,VSAT) and
Wired (Ethernet and Power Line Communication).
Research Issues in IOT
Platform fragmentation
Privacy, autonomy, and control
Data storage
Security and Safety
Environmental sustainability impact
Intentional obsolescence of devices
1
Lack of interoperability and unclear value propositions
Business planning and models
IOT Prototype design
IOT prototype is the process of building IoT hardware and devices enhanced
with smart sensors and embedded systems using many off-the-shelf
components like sensors, circuit boards, and microcontrollers. Alot of these
off-the-shelf solutions are readily available to end consumers. Take an
NodeMCU/Arduino board, for illustration. You can order it online and have
it delivered within 24 hours. Also, a prototype is by no means a market-
ready product. It is just a trial version of your connected solution and acts as
proof that your innovative idea will work the way you visualize it.
IOT will seep into every facet of our daily lives, managing our homes, tending
our gardens, and even monitoring our mailboxes. In future IOT products will
be as omnipresent as mobile devices you use in your daily life, so now it is a
great time to get involved and practicing in this area to fit you in the present
job market. Your IOT prototype is used to understand the pinch points and
frame out the necessary parameters of your IOT product deployment. The
prototype must be end-to-end, including a thin thread connecting the sensor
through the device, network, cloud, end-user interface, and enterprise
integration. However, building an Internet of Things (IoT) prototype is
rewarding and also a frustratingly challenging engineering process.
To build your own End to End IoT Solution, Be familiar with
Master IoT Fundamentals
Design your IoT prototype
Develop your IoT prototype
Deploy your IoT prototype & Applications
Application of IOT
Smart Parking System
Smart Street Lighting
Smart Water Management
Smart Homes & Building
Smart Waste Management
Smart Transportation
Smart Citizen Safety
Smart Security
2
Smart Appliances
Smart Health Monitoring
Smart Retail
Smart Energy Management
Smart Grids
Smart Environment
Smart Manufacturing
Smart Industries
Smart Roads & Infrastructure
Smart Agriculture
Smart Public Information systems
Smart Asset Management
IOT Engineer will have expertise in any one of the IOT devices,
gateways, IOT Platforms, Cloud services and application development.
Smart Device/Gateway Communication Cloud Platform Application
Android
Arduino YUN Wi-Fi Amazon Web Services
Application
Angular js + Node
Arduino + Lora Shield GSM /GPRS Microsoft Azure
js
NodeMCU
The IoT boards can be broken down into two types, microcontroller
boards and single computer boards (SBC). A microcontroller board is
a system on a chip (SoC) that has data processing and storage Containing
processing cores, RAM and EPROM for the storage of custom
programs that are executed on the microcontroller, these boards are
3
PCBs with added circuitry that support the microcontroller. This makes
it more convenient when using the board to prototype and program. A
single board computer is a step up from microcontroller boards as it
allows for the attachment of computer peripheral devices while offering
more processing power and memory. Just like microcontroller boards,
SBC capabilities can be expanded with the addition of expansion boards
or through external modules, such as motor controllers, to mitigate device
limitations.
NodeMCU is an open source IoT platform. It includes firmware which
runs on the ESP8266 Wi-Fi transceiver module with low cost, and
hardware which is based on the ESP-12 module. The term “NodeMCU”
by default refers to the firmware rather than the development kits. The
firmware uses the Lua scripting language. NodeMCU was created shortly
after the ESP8266 came out. On December 30, 2013, Espressif
Systems began production of the ESP8266. The ESP8266 is a Wi-Fi
SoC integrated with a Tensilica Xtensa LX106 core, widely used in IoT
applications. NodeMCU started on 13 Oct 2014.
The pinout diagram of NodeMCU is shown in the following Figure 1
For simplicity, IETE NCL PAC designed an IOT KIT with plug
and play concepts to motivate the Engineers in the field of
Automation with Node MCU as the controlling unit of IETE PAC
NCL IoT KIT.
7
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
Output : LED brightness increase and decrease continuously
Exercise 1c : Bi-Color LED
Aim : To Blink Bi-Color LEDs (Alternate blinking of Red
and Green LEDs.)
Requirements: Bicolor LED, nodemcu, connecting wires
Procedure : Bicolor LED has 3 pins one is cathode and Others
are anode (Red/Green) Connect two digital pin D0
and D1 corresponding Bicolor LED
Program :
void setup() {
pinMode ( D0, OUTPUT);
pinMode (D1, OUTPUT);
}
void loop() {
digitalWrite(D0, HIGH);
digitalWrite(D1, LOW);
delay(1000);
digitalWrite(D0, LOW);
digitalWrite(D1,HIGH);
delay(1000);
}
Output:Red LED connected to port D0 is ON, Green LED connected
to port D1 will be OFF and Green LED will be ON for 1 second. This
process will be repeated till power is applied.
Exercise 1d : Tri-Color LED
Aim : TRI Color LED
Requirements: TRI Color LED, Nodemcu , connecting wires
8
Procedure : LED connect Respective pins D1,D2,D3
Program :
int Red =D3, Green = D2, Blue =D 1; //LED pins
void setup() {
pinMode(Red, OUTPUT);//declare pin-5 to be an output
pinMode(Green, OUTPUT);//declare pin-6 to be an output
pinMode(Blue, OUTPUT);//declare pin-7 to be an output
}
void loop() {
digitalWrite(Red, LOW); digitalWrite(Green, HIGH);
digitalWrite(Blue, LOW); delay(1000);
digitalWrite(Red, HIGH); digitalWrite(Green, LOW);
digitalWrite(Blue, LOW); delay(1000);
digitalWrite(Red, LOW); digitalWrite(Green, LOW);
digitalWrite(Blue, HIGH); delay(1000);
}
Output:You should see your Red LED turn on, Green LED turn off
and Blue LED turn off, your Red LED turn off, Green LED turn on and
Blue LED turn off, your Red LED turn off, Green LED turn off and Blue
LED turn on. If the required output is not seen, make sure you have
assembled the circuit correctly, and verified and uploaded the code to
your board.
Exercise 1e : Control LED using Button
Aim : An LED indicator by pressing a Switch (INPUT
and OUTPUT Concept)
Requirements : LED, Button , Nodemcu , connecting wires
Procedure : LED is connected to D0 and Switch is connected
to D1
When Switch (Push Button) is pressed, LED will be switched ON and
when Switch (Push Button) is released, LED will be switched OFF.
Program:
/* Input – Switch and Output – LED demo */
const int ledPin = D0; // the number of the LED pin
const int buttonPin = D1; // the number of the pushbutton pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
9
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
Output:When Switch is pressed, LED gets switched ON and the LED
will be switched OFF when the switch gets released.
Exercise 1f: Controlling Relay using Button
Aim : To design a Relay by pressing a Switch (INPUT and
OUTPUT Concept)
Requirements : Relay Module,Lamp Holder, AC Power supply,LED,
Button , Nodemcu , connecting wires
Procedure : Relay is connected to D0 and Switch is connected to
D1
When Switch (Push Button) is pressed, Relay will be ON trigger the
AC unit and when Switch (Push Button) is released, Relay will be
switched OFF.
Program:
/* Input – Switch and Output – Relay demo */
const int relayPin = D0; // the number of the LED pin
const int buttonPin = D1; // the number of the pushbutton pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
10
// initialize the LED pin as an output:
pinMode(relayPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(relayPin, HIGH);
} else {
// turn LED off:
digitalWrite(relayPin, LOW);
}
}
Output:When Switch is pressed, Relay gets switched ON and the Relay
will be switched OFF when the switch gets released.
II. ADC Concept
Exercise 2a : POT Sensor Interface
Aim : To Interface a POT Sensor to ADC Channel and
sending equivalent digital data to COM port
Requirements: POT, Nodemcu , connecting wires
Procedure : POT is connected to A0 and Serial port is configured
to 9600, N81.
When POT sensor is rotated, analog value applied to Analog Channel
A0 will be varied from 0V to 5V and its equivalent digital value (in
decimal form) will be displayed in the serial monitor.
Program:
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
11
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(100); // delay in between reads for stability
}
The Table shows Analog, Binary and Decimal equivalent reading
S.No Analog Input in Volts Binary Output Decimal Output
Program:
void setup() {
Serial.begin(9600);
}
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
//(default state is below 350)
if(sensorValue>350) //read Gas sensor
Serial.println(“gas Detected “);
else
Serial.println(“No gas Detected “);
delay(1000);// delay in between reads for stability
}
Result: You will see Gas Detected on Serial Monitor when the values
will exceeds 350 values corresponding to the voltage at pin A0. If those
values are below 350 then you will see No Gas Detected on Serial
Monitor Frequently of every 1000 milli seconds.
13
Exercise 2d : Temperature Sensor(LM35)
Aim : To monitor room temperature using Temperature
Sensor
Requirements: Temperature Sensor(LM35),Nodemcu,Connecting
Wires
Procedure : Temperature sensor Connected to A0 pin of Nodemcu
Program :
void setup() {
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
float sensorValue = analogRead(A0);
sensorValue=(sensorValue*5000)/10230 ;
// print out the value you read:
Serial.println(sensorValue);
delay(1000);// delay in between reads for stability
}
Output: You will see the temperature display on the serial port monitor
which is updated every second.
Exercise 2e : Light Sensor using LDR
Aim : To monitor light intensity level using LDR(Light
Dependent Resistor)
Requirements : LDR,Nodemcu,connecting wires
Procedure : LDR connected to A0 Pin of Nodemcu.Open Serial
monitor
Program:
void setup() {
//initialize serial communication
//at 9600 bits per second:
Serial.begin(9600);
}
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A5);
// print out the value you read:
14
Serial.println(sensorValue);
delay(1000);//delay in between reads for stability
}
Output:
The sensor value is much higher. The numbers you see will vary. This
depends on how much light is in the room, and how much gets through
to the sensor even when your hand is covering it.
Exercise 2f : DHT sensor
Aim : To measure temperature/Humidity using DHT
sensor
Requirements: DHT11, Nodemcu , connecting wires
Procedure : Connect pin 1 (on the left) of the sensor to +5V/3.3V
Connect pin 4 (on the right) of the sensor to GROUND
Connect pin 2 of the sensor to whatever your Digital
Pin DHTPIN
Program:
// Example testing sketch for various DHT humidity/temperature sensors
#include “DHT.h”
#define DHTPIN D2 // what digital pin we’re connected to
// Uncomment whatever type you’re using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
15
Serial.println(“DHTxx test!”);
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds ‘old’ (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(“Failed to read from DHT sensor!”);
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print(“Humidity: “);
Serial.print(h);
Serial.print(“ %\t”);
Serial.print(“Temperature: “);
Serial.print(t);
Serial.print(“ *C “);
Serial.print(f);
Serial.print(“ *F\t”);
Serial.print(“Heat index: “);
Serial.print(hic);
Serial.print(“ *C “);
Serial.print(hif);
16
Serial.println(“ *F”);
}
Output:
RS D0
EN D1
Data 4 D2
Data 5 D5
Data 6 D6
Data 7 D7
19
Program:
#include <LiquidCrystal.h>
// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = D0, en = D1, d4 = D2, d5 = D5, d6 = D6, d7 = D7;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
// set up the LCD’s number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
Serial.begin(9600);
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
int Temperature = analogRead(A0);
float TempinC = ( Temperature * 3300)/ 10230.0 ;
lcd.setCursor(0,0);
lcd.print(“Digital Thermometer!”);
lcd.setCursor(0, 1);
lcd.print(“ “);
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(TempinC);
Serial.println(TempinC);
delay(1000);
}
Output:Temperature sensor display the Digital value of the room
temperature
IV. Communication Protocol concept
Exercise 4a : UART Protocol wired
Aim : LED ON/OFF using Serial monitor input condition
Requirements : USB cable ,LED, Nodemcu, connecting wires
Procedure : LED will be connect D0 pin,
Program:
const int led1=D0;
20
char incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
pinMode(led1,OUTPUT);
Serial.println(“ .”);
Serial.println(“you have entered 1 LED ON , 0 LED OFF”);
}
void loop() {
// send data only when you receive data:
if (Serial.available()) {
// read the incoming byte:
incomingByte = Serial.read();
Serial.println(incomingByte);
if((incomingByte==’1'))
{
Serial.println(“you have entered 1 LED ON “);
digitalWrite(led1,HIGH);
}
if((incomingByte==’0'))
{
Serial.println(“you have entered 0 LED OFF “);
digitalWrite(led1,LOW);
}
}
}
Output:LED will be ON when 1 enter in serial Monitor, LED will be
OFF when 0 enter in serial Monitor
Exercise 4b : UART Protocol wireless
Aim : LED ON/OFF using Bluetooth Module input condition
Requirements : Bluetooth, Bluetooth Terminal app,USB cable, LED,
Nodemcu, connecting wires
Procedure : Blue Tooth Module HC-05 is interfaced to
NodeMCU
BlueTooth Rx -> Tx of NodeMCU
BlueTooth Tx -> Rx of NodeMCU
Bluetooth vcc ->(3.3v) of NodeMcu
Bluetooth gnd ->(gnd) of NodeMcu
21
Finally , All set up finish. Open Bluetooth terminal app .Scan and Connect
Bluetooth. Send Command in ASIC format
Program:
const int led1=D0;
char incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
pinMode(led1,OUTPUT);
Serial.println(“ .”);
Serial.println(“you have entered 1 LED ON , 0 LED OFF”);
}
void loop() {
// send data only when you receive data:
if (Serial.available()) {
// read the incoming byte:
incomingByte = Serial.read();
Serial.println(incomingByte);
if((incomingByte==’1'))
{
Serial.println(“you have entered 1 LED ON “);
digitalWrite(led1,HIGH);
}
if((incomingByte==’0'))
{
Serial.println(“you have entered 0 LED OFF “);
digitalWrite(led1,LOW);
}
}
}
Output:LED will be ON when 1 enter in Bluetooth app, LED will be
OFF when 0 enter in Bluetooth app.
Exercise 4c : Hard serial port
Aim : Display your name using Serial monitor through Hard
serial port
Requirements: NodeMCU and Connecting wires
Procedure : Run following Program. Open Serial Monitor
Program :
22
void setup()
{
Serial.begin(9600);
delay(20);
}
void loop()
{
Serial.println(“ RIYASAA LABS “);
delay(2000);
}
Output:RIYASAA LABS will be printed in Serial Monitor.
Exercise 4d : Soft serial port
Aim : Display your name using serial monitor through soft
serial port
Requirements : NodeMCU and Connecting Wires
Procedure : Connect NodeMCU Digital Pin D7 and D8 to
bluetooth as Rx and Tx
Program:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(D7, D8); // RX, TX
void setup()
{
mySerial.begin(9600);
delay(20);
}
void loop()
{
mySerial.println(“ RIYASAA LABS “);
delay(200);
}
Output:RIYASAA LABS will be printed in Serial Monitor.
Exercise 4e : Bi-directional Communication
Aim : Bidirectional data Communication using BTM
(Bluetooth Module)
23
Requirements : Bluetooth, Bluetooth Termonal app,LED, Nodemcu,
connecting wires
Procedure : Blue Tooth Module HC-05 is interfaced to
NodeMCU through Soft Serial.
BlueTooth Rx -> D7 of NodeMCU
BlueTooth Tx -> D8 of NodeMCU
POT connected to A0 and LED connected to D0
Analog Value at A0 will be sent to mobile phone through Blue Tooth.
LED connected to Digital Output DO will be controlled (ON/OFF) by
sending a Character (A to ON and a to OFF) from Mobile phone
through Blue Tooth
Program:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(D7, D8); // RX, TX
char c;
#define LED D0
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
pinMode(LED,OUTPUT);
Serial.println(“Goodnight moon!”);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
mySerial.println(“Hello, world?”);
}
void loop() { // run over and over
//Serial.println(“HI...”);
int a =analogRead(A0);
mySerial.println(a);
delay(200);
if (mySerial.available()) {
c = mySerial.read();
if(c == ‘A’) //ASCII mode in app
digitalWrite(LED,HIGH);
24
if(c == ‘a’)
digitalWrite(LED,LOW);
}
}
Output:In your Android Mobile phone, install BlueTooth terminal HC-
05 available in Google play store.
Select the paired device RiyassaBT1. (BlueTooth module HC-05 is
already renamed as RiyassaBT1 and it is paired with our mobile phone
– default pairing code is 1234)
Run the BlueTooth terminal HC-05 App and select RiyassaBT1 as the
device, you will be able to see the value of Analog POT in The terminal
of BT HC-05 App.
By sending character A, LED at port D0 of NodeMCU will be switched
ON.
By sending character a, LED at port D0 of NodeMCU will be switched
OFF.
Both Transmission and reception through Bluetooth interface of
NodeMCU can be understood through this program.
Exercise 4f : SPI Protocol
Aim : To connect ADC channel using MCP3008 Analog
IC through SPI protocol
Requirements : Any 1 Sensor, MCP3008 Analog IC, Nodemcu,
connecting wires.
Procedure : NodeMCU has one Analog channel. So ,To increase
the Analog Channel connect MCP3008 Analog IC
to NodeMCU
DownloadZipfile : https://github.com/adafruit/Adafruit_MCP3008
Add .zip fle in Arduino IDE
Connect following SPI Pins MCP3008 to NodeMCU
MCP3008 NodeMCU
16 vcc 3.3v
14 gnd gnd
13 clk D5
12 Dout D6
11 Din D7
10 CS D8
25
Program:
#include <MCP3008.h>
#include <SPI.h>
// put pins inside MCP3008 constructor
//MCP3008 adc(CLOCK_PIN, MOSI_PIN, MISO_PIN, CS_PIN);
MCP3008 adc(D5,D7,D6,D8);
void setup() {
// open serial port
Serial.begin(9600);
}
void loop() {
/*int val = adc.readADC(0); // read Chanel 0 from MCP3008 ADC
Serial.println(val);
*/
Serial.println(“value 0 :” + String(adc.readADC(0)));
Serial.println(“value 1 :” + String(adc.readADC(1)));
Serial.println(“value 2:” + String(adc.readADC(2)));
Serial.println(“value 3:” + String(adc.readADC(3)));
Serial.println(“value 4:” + String(adc.readADC(4)));
Serial.println(“value 5:” + String(adc.readADC(5)));
Serial.println(“value :” + String(adc.readADC(6)));
delay(4000);
}
Output:Using SPI Protocol read Analog data from MCP3008 IC to
NodeMCU
IV. Web and Cloud Connectivity concept
Exercise 5a : WiFi scan
Aim : To Scan the available WiFi Network through
NodeMCU
Requirements : Nodemcu, connecting wires,WiFi Network
Procedure : Run following Program.Open Serial Monitor
Program:
#include “ESP8266WiFi.h”
void setup() {
Serial.begin(115200);
26
// Set WiFi to station mode and disconnect from an AP if it was previously
connected
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println(“Setup done”);
}
void loop() {
Serial.println(“scan start”);
// WiFi.scanNetworks will return the number of networks found
int n = WiFi.scanNetworks();
Serial.println(“scan done”);
if (n == 0) { Serial.println(“no networks found”); }
else { Serial.print(n);
Serial.println(“ networks found”);
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(“: “);
Serial.print(WiFi.SSID(i));
Serial.print(“ (“);
Serial.print(WiFi.RSSI(i));
Serial.print(“)”);
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? “ “ : “*”);
delay(10); } }
Serial.println(“”);
// Wait a bit before scanning again
delay(5000); }
(Note that COM Port is configured to work at baud rate of 115200 )
Output:Open Serial Monitor,WiFiScan Network display.
27
Exercise 5b : WiFi scan and Connect
Aim : To Scan and connect the specific WiFi Network
Requirements : Nodemcu, connecting wires,WiFi Network
Procedure : Run following Program. Before that replace SSID
and PASSWORD for your Network in Program
Open Serial Monitor
Program:
#include<ESP8266WiFi.h>
/************** WiFi Access Point ************************/
#define WLAN_SSID “Riyasaa labs”
#define WLAN_PASS “riyasaa54321”
WiFiServer server( 80);
void setup()
{
Serial.begin(9600);
delay(10);
Serial.println();
Serial.println();
Serial.print(“Connecting to “);
Serial.println(WLAN_SSID);
delay(500);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
Serial.println();
server.begin();
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
}
void loop()
{
Serial.print(“IP address: “);
Serial.println(WiFi.localIP());
delay(5000);
28
}
Output:
//(Note that COM Port is configured to work at baud rate of 9600 )
30
}
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.println(“ <head>”);
client.println(“ </head>”);
//client.println(“ <body bgcolor = \”#f7e6ec\”>”);
client.println(“ <hr/><hr>”);
client.println(“ <h4><center> RIYASAA LABS </center></h4>”);
client.println(“ <hr/><hr>”);
client.println(“ <br><br>”);
client.println(“ <br><br>”);
client.println(“ <center>”);
client.println(“ Light1”);
//client.println(“<button onclick=\”funt1()\”> one</button> “);
//client.println(“<script> funtion funt1()”);
if (digitalRead(D2))// read digital pin 5
{
client.println(“ <a href =\”/ l1on\”\”><button style =\”background-
color:green\”> Turn On </button></a>”);
client.println(“ <a href =\”/ l1off\”\”><button> Turn Off </button></
a><br/>”);
}
else
{
client.println(“ <a href =\”/ l1on\”\”><button > Turn On </button></
a>”);
client.println(“ <a href =\”/ l1off\”\”><button style =\”background-
color:red\”> Turn Off </button></a><br/>”);
}
client.println(“ </center>”);
client.println(“ <br><br>”);
client.println(“ <center>”);
client.println(“ Light 2”);
if (digitalRead(D7))// read digital pin 4
31
{
client.println(“ <a href =\”/ l2on\”\”><button style=\”background-
color:green\”> Turn On </button></a>”);
client.println(“ <a href =\”/ l2off\”\”><button> Turn Off </button></
a><br/>”);
}
else
{
client.println(“ <a href =\”/ l2on\”\”><button > Turn On </button></
a>”);
client.println(“ <a href =\”/ l2off\”\”><button style=\”background-
color:red\”> Turn Off </button></a><br/>”);
}
client.println(“ </center>”);
client.println(“ <br><br>”);
client.println(“ <center>”);
client.println(“ <table border =\” 5\”>”);
client.println(“ <tr>”);
if (digitalRead(D2))// read digital pin 5
{client.print(“ <td> Light 1 is ON </td>”); }
else
{ client.print(“ <td> Light 1 is OFF </td>”); }
if (digitalRead(D7))// read digital pin 4
{ client.print(“ <td> Light 2 is ON </td>”); }
else
{ client.print(“ <td> Light 2 is OFF </td>”); }
client.println(“ </tr>”);
client.println(“ </table>”);
client.println(“ </center>”);
client.println(“ </html>”);
delay( 1);
Serial.println(“ Client disonnected”);
Serial.println(“”);
}
Output: Webpage Will be displayed in that control your LED through
ON/OFF
32
Exercise 5d : Environmental Data in Webpage
Aim : Displaying Environmental data in Webpage
Requirements : POT ,Nodemcu, connecting wires,WiFi Network
Procedure : Run following Program,. Before that replace SSID
and PASSWORD for your Network in Program.
Open Serial Monitor
Local IP address display. Open Browser Type IP
address. Webpage Will be appeared.
In that page your sensor data update periodically.
Program:
#include <ESP8266WiFi.h>
const char* ssid = “Riyasaa labs”;
const char* password = “riyasaa54321”;
WiFiServer server(80);
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.printf(“Connecting to %s “, ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(“.”);
}
Serial.println(“ connected”);
server.begin();
Serial.printf(“Web server started, open %s in a web browser\n”,
WiFi.localIP().toString().c_str());
33
}
// prepare a web page to be send to a client (web browser)
String prepareHtmlPage()
{
String htmlPage =
String(“HTTP/1.1 200 OK\r\n”) +
“Content-Type: text/html\r\n” +
“Connection: close\r\n” + // the connection will be closed after
completion of the response
“Refresh: 5\r\n” + // refresh the page automatically every 5 sec
“\r\n” +
“<!DOCTYPE HTML>” +
“<html>” +
“<h1>Welcome to Riyasaa Labs 1</h1>”+
“Analog input POT Value : “ + String(analogRead(A0)) +
“</html>” +
“\r\n”;
return htmlPage;
}
void loop()
{
WiFiClient client = server.available();
// wait for a client (web browser) to connect
if (client)
{
Serial.println(“\n[Client connected]”);
while (client.connected())
{
// read line by line what the client (web browser) is requesting
if (client.available())
{
String line = client.readStringUntil(‘\r’);
Serial.print(line);
// wait for end of client’s request, that is marked with an empty line
if (line.length() == 1 && line[0] == ‘\n’)
{
client.println(prepareHtmlPage());
34
break;
}
}
}
delay(1); // give the web browser time to receive the data
// close the connection:
client.stop();
Serial.println(“[Client disonnected]”);
}
}
Output:
Webpage Will be displayed in that control your LED through ON/OFF
35
const char *pass = “riyasaa54321”;
const char* server = “api.thingspeak.com”;
WiFiClient client;
void setup()
{
Serial.begin(115200);
delay(10);
Serial.println(“Connecting to “);
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(“.”);
}
Serial.println(“”);
Serial.println(“WiFi connected”);
}
void loop()
{
float t = analogRead(A0);
if (client.connect(server,80)) // “184.106.153.149” or api.thingspeak.com
{
String postStr = apiKey;
postStr +=”&field1=”;
postStr += String(t);
//postStr +=”&field2=”;
// postStr += String(h);
postStr += “\r\n\r\n”;
client.print(“POST /update HTTP/1.1\n”);
client.print(“Host: api.thingspeak.com\n”);
client.print(“Connection: close\n”);
client.print(“X-THINGSPEAKAPIKEY: “+apiKey+”\n”);
client.print(“Content-Type: application/x-www-form-urlencoded\n”);
client.print(“Content-Length: “);
client.print(postStr.length());
client.print(“\n\n”);
36
client.print(postStr);
Serial.print(“Temperature: “);
Serial.print(t);
//Serial.print(“ degrees Celcius, Humidity: “);
// Serial.print(h);
Serial.println(“%. Send to Thingspeak.”);
}
client.stop();
Serial.println(“Waiting...”);
delay(10000);
}
Output:POT /sensor data stored in cloud Platform
37
#include “Adafruit_MQTT_Client.h”
#define Relay1 D1
#define Relay2 D5
#define Relay3 D2
#define Relay4 D6
#define WLAN_SSID “Riyasaa labs” // Your SSID
#define WLAN_PASS “riyasaa54321” // Your password
/**************** Adafruit.io Setup **********************/
#define AIO_SERVER “io.adafruit.com”
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME “ARUNV_25” // Replace it with
your username
#define AIO_KEY “8500637f6fe4480397314e1c2acd650a” /
/ Replace with your Project Auth Key
/************ Global State (you don’t need to change this!)
******************/
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;
// Setup the MQTT client class by passing in the WiFi client and MQTT
server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER,
AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
/********************** Feeds *************************/
// Setup a feed called ‘onoff’ for subscribing to changes.
Adafruit_MQTT_Subscribe Light1 = Adafruit_MQTT_
Subscribe(&mqtt, AIO_USERNAME”/feeds/Relay1"); // FeedName
Adafruit_MQTT_Subscribe Light2 = Adafruit_MQTT_ Subscribe
(&mqtt, AIO_USERNAME “/feeds/Relay2”);
Adafruit_MQTT_Subscribe Light3 = Adafruit_MQTT_ Subscribe
(&mqtt, AIO_USERNAME “/feeds/Relay3”);
Adafruit_MQTT_Subscribe Light4 = Adafruit_MQTT_ Subscribe
(&mqtt, AIO_USERNAME “/feeds/Relay4”);
void MQTT_connect();
void setup() {
38
Serial.begin(115200);
pinMode(Relay1, OUTPUT);
pinMode(Relay2, OUTPUT);
pinMode(Relay3, OUTPUT);
pinMode(Relay4, OUTPUT);
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print(“Connecting to “);
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
Serial.println();
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
// Setup MQTT subscription for onoff feed.
mqtt.subscribe(&Light1);
mqtt.subscribe(&Light3);
mqtt.subscribe(&Light2);
mqtt.subscribe(&Light4);
}
void loop() {
MQTT_connect();
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(20000))) {
if (subscription == &Light1) {
Serial.print(F(“Got: “));
Serial.println((char *)Light1.lastread);
int Light1_State = atoi((char *)Light1.lastread);
digitalWrite(Relay1, Light1_State);
}
39
if (subscription == &Light2) {
Serial.print(F(“Got: “));
Serial.println((char *)Light2.lastread);
int Light2_State = atoi((char *)Light2.lastread);
digitalWrite(Relay2, Light2_State);
}
if (subscription == &Light3) {
Serial.print(F(“Got: “));
Serial.println((char *)Light3.lastread);
int Light3_State = atoi((char *)Light3.lastread);
digitalWrite(Relay3, Light3_State);
}
if (subscription == &Light4) {
Serial.print(F(“Got: “));
Serial.println((char *)Light4.lastread);
int Light4_State = atoi((char *)Light4.lastread);
digitalWrite(Relay4, Light4_State);
}
}
}
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print(“Connecting to MQTT... “);
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println(“Retrying MQTT connection in 5 seconds...”);
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries—;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
40
}
}
Serial.println(“MQTT Connected!”);
}
Output:
41
Appendix 1: IoT gateway and Sensors
42
43
44
45
Appendix 2: Procedure to visualize through Thingspeak
Thingspeak Procedure
How can create Thingspeak account
Go to Thingspeak Websitehttps://thingspeak.com/
Click sign in and follow the Procedure Below
46
47
Note: Copy your Channel write API Key and Read API Key
48
Now, create dashboard at Adafruit. This dashboard is a user interface
to control things remotely.
After following above steps, provide name to the dashboard and save
it. We can see our dashboard as follows,
Now, create feed (user interface) to control light On-Off. To create it,
just click on ‘+’ symbol and select toggle feed shown below,
49
After selecting toggle feed, pop-up window appears as shown below.
Enter name of our feed (shown in red box) and create it. After creation,
select the created feed (here mine is light) and then click on Next step.
In the next step configure the feed which is shown below,
Here, I used 0(OFF) and 1(ON) text for button and then click on create.
This will create toggle button on your dashboard which can be used to
control things remotely.
50
IFTTT Procedure
How can create IFTTT account?
Go to website https://ifttt.com/
Click signup
Click My applets
51
Click your New Applet
Click this
52
We can enter any phrase as per our application. As you can see, the
phrases entered in the above fields is for making Light ON. For
making Light OFF, we have to create another applet with different
phrases.
Now, we get another page on which we have to click on that option
which is used to connect Google Assistant with Adafruit.
Interfacing Diagram
https://www.youtube.com/watch?v=1goTMGq26wE
55
Appendix 4: List of Experiments
IoT BASED PROJECTS
1) IoT based Home Automation
2) IoT based Agriculture System
3) IoT based Patient Monitoring System
4) IoT based Humidity and Temperature Monitoring System
5) IoT based Weather Reporting System
6) IoT based Smart Water Management System
7) IoT based Garbage Monitoring System
8) IoT based Smart Street Light Management System
9) IoT based Industry Automation
10) To control AC units through Webpage
11) To Displaying Environment Data in Webpage
12) Uploading Environment Data to cloud & visualized through
Thingspeak
13) Bluetooth Based Home automation
14) Smart Home Automation control using Google Assistance(GA)
15) Smart Home Automation control using Alexa
16) Smart Building Project using PIR
56