DMC6312 INTERNET OF THINGS LABORATORY
OBJECTIVES
● To learn tools relevant to embedded system and IoT development.
● To write simple assembly programs that uses various features of the processor.
● To design and develop IoT application Arduino/Raspberry pi for real world scenario.
SYLLABUS
1. Implement assembly and Interfacing Programs Using Embedded C.
2. Embedded Application Development (i) Using Arduino and Raspberry Pi (ii) Using
Bluemix platform
3. IoT Application Development (i) Using sensors and actuators (temperature sensor,
light sensor, infrared sensor) (ii) Interfacing sensors with Arduino/Raspberry Pi/other
equivalent boards (iii) Reading data from sensors
4. Explore different communication methods with IoT devices.
5. Collecting and processing data from IoT systems in the cloud using XivelyPaaS.
6. Develop IoT applications using Django Framework and Firebase/ Bluemix
platform.
S.No Experiment Page Number
Part A Assembly and Interfacing Programs Using Embedded C.
1. 3
Embedded C programming- Overview
Introduction to -Keil IDE
2. 5
Write an embedded C program for the blinking of Led
using an 8051 microcontroller.
3. Write a program to generate a 10KHz square wave using 7
8051
4. 8
Write a program to show the use of INT0 & INT1 of
8051
5. 10
Write a C program to interface stepper motor.
6. 11
To interface LCD and keypad using embedded C
7. 14
To write a C program to interface Temperature Sensor
Part B Application Development using Arduino/ Node MCU
Study and Installation of Arduino, Node
MCU(ESP8266), and Raspberry Pi Boards.
1. Blinking a LED with delay using Arduino/Node MCU 18
2. Monitoring Temperature using sensor 19
3. Interfacing IR sensor for Motion Detection 21
4. Interfacing Light Dependent Resistor (LDR) to measure 23
the intensity of light.
5. Interfacing ultrasonic sensor for obstacle detection 24
6. Interfacing a servo motor to rotate an object with high 27
precision
7. Interfacing Potentiometer and Servo 28
8. Connecting NodeMCU (ESP8266) to Wifi AP 29
9. Node MCU as a Server 31
10. Interfacing a GPS to Aurdino/ Node MCU 33
11. Connecting Blutooth with Aurdino 38
12. Interfacing GSM with Aurdino 40
Part C IoT cloud Applications
1. Collecting and processing data from IoT systems in the 41
cloud using ThingSpeak.
2. Develop IoT applications using Django Framework and 43
Firebase/ Bluemix platform.
Part A
1.Embedded C programming- Overview
Introduction to 8051 Microcontroller
In the 1980s, Intel Invented the 8051 Microcontroller based on
Harvard architecture principally developed for Embedded system
applications. Keil Microcontroller development kit (MDK) can be used for
implementing embedded C programming in vast devices.
8051 Microcontroller PIN diagram
Figure 1. 8051 Pin Configuration
Installation of Keil:
STEP 1
Go to https://www.keil.com/download/product/ –>Download –> Product Downloads –>Hit
on C51 Setup. Enter your contact information with valid address, phone number and email.
Fill in all fields of form. Download is free for evaluation version.
STEP 2
Then click on C51V9XXA.EXE and Download it on your computer.
STEP 3
The next step is to run the setup file C51VXXA.EXE and then we’ll get pop-up box, hit on
Next, and Proceed with Installation.
STEP 4
Read the license agreement, check I agree to all the terms…., and click Next.
STEP 5
Select the Destination folder where you want to install Keil or the default destination is
already there. And hit on Next.
STEP 6
Fill the required fields with all relevant information and click on Next.
STEP 7
Wait for installation complete and hit on Next.
STEP 8
Tick on show release notes, deselect remaining (as per your choice) and click on Finish.
2. Write an embedded C program for the blinking of Led using 8051 microcontrollers.
Aim:
To write an embedded C program for the blinking of Led using 8051 microcontroller.
Hardware requirements:
• LED
• Keil IDE
• 8051 microcontroller
Source code:
#include <reg51.h>
//delay function declaration
void delay(void);
void main(void)
{
//an infinite loop
while(1)
// Turn ON all LED's connected to Port1
P1 = 0xFF;
delay();
// Turn OFF all LED's connected to Port1
P1 = 0x00;
delay();
//delay function definition
void delay(void)
int i,j;
for(i=0;i<0xff;i++)
for(j=0;j<0xff;j++);
Circuit Diagram:
Output:
LED blinks
Result:
Blinking of LED has been done successfully using 8051 Microcontroller
3.Write a program to generate a 10KHz square wave using 8051.
Aim:
To write a program to generate a 10KHz square wave using 8051.
Hardware requirements:
• Keil IDE
• 8051 micro controller
Code:
#include<reg51.h>
void main() {
unsigned int x;
for(;;){
P1=0X80;
for(x=0;x<40000;x++){
P1=0X00;
Output:
Result:
Square wave of 10Khz has been successfully generated
4.Write a program to show the use of INT0 & INT1 of 8051
Aim:
To write a program to show the use of INT0 & INT1 of 8051
Hardware requirements:
• LED
• Keil IDE
• 8051 micro controller
Code:
//interrupt INT0 & INT1
#include <reg51.h>
sbit LED1 =P1^0;
sbit LED2 =P1^1;
//Function Declaration
port_init();
InitINT0();
InitINT1();
//Main Function
main()
{
port_init();
InitINT0();
InitINT1();
while(1)
port_Init()
P0=0X00;
P1=0X00;
P2=0X00;
P3=0X0C;
InitINT0() //int0 ISR
IT0=1;
EX0=1;
EA=1;
InitINT1()//INT1 ISR
IT1=1;
EX1=1;
EA=1;
external0_isr()//interrupt 0
{
LED1 = ~LED1;
external1_isr()//interrupt 2
LED2 = ~LED2;
Output:
The interrupts given at PORT 3 (P2.2 & P2.3) using PULL-UP KEYS (K5 & K6) will do the
following:-
● When K5 pressed - LED on.
● When K5 pressed again - LED off.
Similarly,
● When K6 pressed - LED on.
● When K6 pressed again - LED off
Result:
The usage of INT0 and INT1 has been showed successfully in 8051
5.Write a C program to interface stepper motor.
Aim:
To write a C program to interface stepper motor.
Hardware requirements:
• Stepper motor
• Keil IDE
• 8051 micro controller
Code:
#include <REG51xD2.H>
void delay (unsigned int x) /* Delay Routine */
for(;x>0;x--);
return;
main ( )
unsigned char Val, i;
P0=0x00;
while(1)
Val = 0x11;
for (i=0;i<4;i++)
P0 = Val;
Val = Val<<1; /* Val= Val>>1; for clockwise direction*/
delay (500);
Output:
Motor Rotates
Result:
Stepper has been successfully interfaced using 8051
6.LCD and keypad interfacing
Aim:
To interface LCD and keypad using embedded C
Hardware requirements:
• LCD
• Keypad
• Keil IDE
• 8051 micro controller
Code:
#include <REG51xD2.H>
#include "lcd.h"
unsigned char getkey();
void delay(unsigned int);
main()
unsigned char key,tmp;
InitLcd(); //Initialise LCD
WriteString("Key Pressed="); // Display msg on LCD
while(1)
GotoXY(12,0); //Set Cursor Position
key = getkey(); //Call Getkey method
unsigned char getkey()
unsigned char i,j,k,indx,t;
P2 = 0x00; //P2 as Output port
indx = 0x00;//Index for storing the 1st value of scanline
for(i=1;i<=4;i<<=1) //for 3 scanlines
{
P2 = 0x0f & ~i; //write data to scanline
t = P0; //Read readlines connected to P0
t = ~t;
if(t>0) //If key press is true
delay(6000); //Delay for bouncing
for(j=0;j<=7;j++) //Check for 8 lines
t >>=1;
if(t==0) //if get pressed key
k = indx+j; //Display that by converting to Ascii
t = k>>4;
t +=0x30;
WriteChar(t); //Write upper nibble
t = k & 0x0f;
if(t > 9)
t+=0x37;
else
t+=0x30;
WriteChar(t); //write lower nibble
return(indx+j); //Return index of the key pressed
}
indx += 8; //If no key pressed increment index
void delay(unsigned int x) //Delay routine
{ for(;x>0;x--); }
Block Diagram:
Result:
LCD and keyboard have been successfully interfaced using 8051
7. C program to interface Temperature Sensor program
Aim:
To write a C program to interface Temperature Sensor
Hardware requirements:
• LCD
• LM 35 temperature sensor
• Keil IDE
• 8051 micro controller
Code:
# include <at89c51xd2.h>
#include<intrins.h>
#include "lcd.h"
unsigned int Adc;
unsigned char Low_adc,High_adc,relay;
read_adc(){
unsigned char status;
P2_3 = 1 ; // Start conversion of ADC
status = P1; //Read status of ADC
while((status & 0x01) != 0x01){
status = P1;
P2_2 = 0; // Enable outputs
P2_0 = 0; // Activate B1 to B8 outputs
Low_adc = P0; // Read lower byte of ADC and place in R0
P2_0 = 1; // Deactivate B1 to B8 outputs
P2_1 = 0; // Activate B9 to B12 and POL, over range outputs
High_adc = P0; // Read higher byte of ADC
High_adc = High_adc & 0x0F;
P2_1 = 1; // deactivate B9 to B12 and
POL, over range outputs
P2_2 = 1; // Disable outputs
P2_3 = 0; // Stop conversion of ADC
main()
{ float Temp,Vol,Res;
unsigned char Temp1;
unsigned char Temp2,Temp3;
P0 = 0xFF ; // Make port 0 as input
P2 = 0xFF ; // Make port 2 as high now the relay is on.
P1_1 = 0 ; // switch OFF relay
P2_3 = 0 ; // STOP conversion of ADC
relay = 10;
while(1){
read_adc(); //Read ADC
Adc = High_adc;
Adc <<= 8;
Adc = Adc | Low_adc;
if( (Adc > 0x656) && (relay != 0)) //IF greater than 0x0656 Switch OFF
relay
ClrLcd();
WriteString("RELAY OFF");
P1_1 = 0 ;
relay = 0;
else if ( (Adc < 0x5b9) && (relay!= 1)) //IF less than 0x05B9 Switch ON
relay
{ClrLcd();
WriteString("RELAY ON");
P1_1 = 1 ;
relay = 1;}
Vol =-((Adc/10)*0.000488); //voltage before amplifier
Res =((100*(1.8-Vol)-100*Vol)*100) /(100*Vol + 100*(1.8+Vol));//
Resistance Value
Res = Res - 100;
Temp = Res/ 0.384;
Temp1 = Temp;
Temp2 = 0x30 + (Temp1 / 0x0A);
Temp3 = 0x30 + (Temp1 % 0x0A);
GotoXY(0,1);
WriteString("Temperature ");
WriteChar(Temp2);
WriteChar(Temp3);
WriteString("'C");
Circuit Diagram:
Output:
Temperature is displayed on the LCD using LM 34/35 sensor
Result:
Temperature has been successfully measured using 8051 and temperature sensor.
Part B
Ex-1 : Blinking a LED
Aim:
To blink a LED using Node MCU
Hardware Requirements:
● NodeMCU x 1
● LED x 1
● BreadBoard
● 200 ohm – 1K ohm resistor x 1
● Micro USB cable x 1
● PC x 1
● Software Arduino IDE(version 1.6.4+)
● Jumper Wires (Male – Female & Male – Male)
Circuit:
Code:
int LED = 5; // Assign LED pin i.e: D1 on NodeMCU
void setup() {
// initialize GPIO 5 as an output
pinMode(LED, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED, HIGH); // turn the LED on
delay(1000); // wait for a second
digitalWrite(LED, LOW); // turn the LED off
delay(1000); // wait for a second
}
Output:
Result:
Blinking of LED has been done successfully using Node MCU and the results are
verified.
Ex: 2 Measuring Temperature using temperature sensor
Aim:
To measure the temperature of the room / surrounding using temperature sensor &
Node MCU
Hardware Requirements:
● NodeMCU
● LM35 Temperature Sensor
● Bread Board
● Jumper Wires
● Micro USB Cable
● Arduino IDE
● 200 ohm – 1K ohm resistor x 1
● PC
Circuit Diagram:
Code:
// initializes or defines the output pin of the LM35 temperature sensor
int outputpin= A0;
//this sets the ground pin to LOW and the input voltage pin to high
void setup() {
Serial.begin(9600);
}
void loop() //main loop
{
int analogValue = analogRead(outputpin);
float millivolts = (analogValue/1024.0) * 3300; //3300 is the voltage provided by NodeMCU
float celsius = millivolts/10;
Serial.print("in DegreeC= ");
Serial.println(celsius);
//----------Calculation for Fahrenheit ----------//
float fahrenheit = ((celsius * 9)/5 + 32);
Serial.print(" in Farenheit= ");
Serial.println(fahrenheit);
delay(1000);
}
Output:
Result:
Temperature has been measured successfully using Temperature sensor and the
results are verified.
Ex: 3 InfraRed Sensor using Node MCU
Aim:
To detect any motion in the room / surrounding using temperature sensor & Node
MCU
Hardware Requirements:
● NodeMCU
● IR Sensor
● Bread Board
● Jumper Wires
● Micro USB Cable
● Arduino IDE
● 200 ohm – 1K ohm resistor x 1
● PC
● LED
Circuit Diagram:
Code:
int ledPin = 12; // choose pin for the LED
int inputPin = 13; // choose input pin (for Infrared sensor)
int val = 0; // variable for reading the pin status
void setup()
{
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare Infrared sensor as input
}
void loop()
{
val = digitalRead(inputPin); // read input value
if (val == HIGH)
{ // check if the input is HIGH
digitalWrite(ledPin, LOW); // turn LED OFF
}
else
{
digitalWrite(ledPin, HIGH); // turn LED ON
}
}
Output:
IR sensor identifies object nearby and turns LED ON
If no object is present in front then LED is OFF.
Result:
IR sensor has been used successfully using Node MCU and the results are verified.
Ex: 4 Light Sensor
Aim:
To use Light Sensor using Node MCU
Hardware Requirements:
● NodeMCU
● LDR/PhotoResistor
● Bread Board
● Jumper Wires
● Micro USB Cable
● Arduino IDE (with ESP8266 Library installed)
● 200 ohm – 1K ohm resistor x 1
● PC
Circuit Diagram:
Code:
void setup() {
Serial.begin(9600); // initialize serial communication at 9600 BPS
}
void loop() {
int sensorValue = analogRead(A0); // read the input on analog pin 0
float voltage = sensorValue * (5.0 / 1023.0); // Convert the analog reading (which
goes from 0 - 1023) to a voltage (0 - 5V)
Serial.println(voltage); // print out the value you read
}
Output:
with light
without light
Result:
Light Sensor has been used successfully using Node MCU and the results are verified.
Ex: 5 Proximity Detection
Aim:
To detect the location using ultrasonic sensor
Hardware Required:
● NodeMCU
● HC-SR04 (Ultra-sonic Sensor)
● Bread Board
● Jumper Wires
● Micro USB Cable
Circuit Diagram:
Code: (1)
void setup() {
// ultrosonic HCSR -04 - proximity detection
pinMode(D6,OUTPUT); //trigger pin
pinMode(D7,INPUT);//Echopin //rcr
void loop() {
// put your main code here, to run repeatedly:
//trigger sonic waves
digitalWrite(D6,LOW);
delayMicroseconds(2);
digitalWrite(D6,HIGH);
delayMicroseconds(10);
// receive ECHO and find DISTANCE
long duration= pulseIn(D7,HIGH);
float dist= duration * 0.034/2;
Serial.println("Distance is...");
Serial.println(dist);
delay(2000);
}
Code:(2)
// defines pins numbers
const int trigPin = 2; //D4
const int echoPin = 0; //D3
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
delay(2000);
}
Output:
Result:
Proximity Detection using Ultra Sonic Sensor has been used successfully using Node
MCU and the results are verified.
Ex : 6 Servo Motor
Aim:
To push or rotate an object with great precision at specific angles or distance using
servo motor
Code:
#include <Servo.h>
Servo newservo1;//define a name for servo
void setup() {
// put your setup code here, to run once:
newservo1.attach(D6);
}
void loop() {
// put your main code here, to run repeatedly:
newservo1.write(180);
delay(1000);
newservo1.write(0);
delay(1000);
}
Output:
Servo Motor rotates 180 degree and comes back with 1 second delay
Result:
Servo motor has been used successfully rotated using Node MCU and the results are
verified
Ex : 7 Potentiometer with servo motor
Aim:
To use a potentiometer with servo motor
Code:
# include<Servo.h>
Servo mew 1;
Setup ()
New1.attach(D6);
Serial.begin(9600);
pinMode(A0, INPUT);
loop()
float x=analogRead(A0);
x=map(x,0,1023,0,180);
new1.write (x);
delay(15);}
Output:
Servo Motor rotates 180 degree once counter is above 4 and comes back to same position
when counter is less than 4
Result:
Servo motor with potentiometer has been used successfully rotated using Node MCU
and the results are verified
Ex : 8 IoT with cloud
Aim:
To connect with Internet through WIfi Acces point using Node MCU
Code:
#include<ESP8266WIFI>
Char* SSid =”rajesh”;
Char* Password =”Koushan”
Void setup()
WiFi.begin(SSid, Password);
Serial.begin(115200);
Serial.print(“Connecting: ”);
While (WiFi.status()!= WL_CONNECTED)
Serial.print(“Waiting to connect”)
While(WiFi.Status()!=WL_CONNECTED)
Serial. Print(“Waiting to connect”);
delay(1000);
Serial.println(‘\n’);
Serial.println (“Connection established”);
Serial.println (“IP Address\t”);
Serial.println(WiFi.LocalIP());
Output:
___
_____________________
Result:
Connecting with internet has been done successfully using Node MCU and the results
are verified
Ex : 9 Making a node as Server
Aim:
To make a node as a server using Node MCU
Code:
#include<ESP8266WiFi>
#include<ESP8266Webserver.h>
ESP8266Webserver server(80)
Char* ssid, Char pass;
Void setup()
WiFi.begin(SSid, Password);
Serial.begin(115200);
Serial.print(“Connecting: ”);
While (WiFi.status()!= WL_CONNECTED)
Serial.print(“Waiting to connect”)
While(WiFi.Status()!=WL_CONNECTED)
Serial. Print(“Waiting to connect”);
delay(1000);
Serial.println(‘\n’);
Serial.println (“Connection established”);
Serial.println (“IP Address\t”);
Serial.println(WiFi.LocalIP());
}
Server.on(%[]() { Server.send()
}
Output:
Result:
Making a node has been done successfully using Node MCU and the results are
verified
Ex : 10 Interfacing a GPS
Aim:
To find the present location using GPS module
Hardware Required:
● NodeMCU ESP8266
● GPS module
● Bread Board
● Jumper wires
Circuit Diagram:
Code:
#include <TinyGPS++.h> // library for GPS module
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
TinyGPSPlus gps; // The TinyGPS++ object
SoftwareSerial ss(4, 5); // The serial connection to the GPS device
const char* ssid = "Onlilo_SP"; //ssid of your wifi
const char* password = "ArduinoUno"; //password of your wifi
float latitude , longitude;
int year , month , date, hour , minute , second;
String date_str , time_str , lat_str , lng_str;
int pm;
WiFiServer server(80);
void setup()
{
Serial.begin(115200);
ss.begin(9600);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password); //connecting to wifi
while (WiFi.status() != WL_CONNECTED)// while wifi not connected
{
delay(500);
Serial.print("."); //print "...."
}
Serial.println("");
Serial.println("WiFi connected");
server.begin();
Serial.println("Server started");
Serial.println(WiFi.localIP()); // Print the IP address
}
void loop()
{
while (ss.available() > 0) //while data is available
if (gps.encode(ss.read())) //read gps data
{
if (gps.location.isValid()) //check whether gps location is valid
{
latitude = gps.location.lat();
lat_str = String(latitude , 6); // latitude location is stored in a string
longitude = gps.location.lng();
lng_str = String(longitude , 6); //longitude location is stored in a string
}
if (gps.date.isValid()) //check whether gps date is valid
{
date_str = "";
date = gps.date.day();
month = gps.date.month();
year = gps.date.year();
if (date < 10)
date_str = '0';
date_str += String(date);// values of date,month and year are stored in a string
date_str += " / ";
if (month < 10)
date_str += '0';
date_str += String(month); // values of date,month and year are stored in a string
date_str += " / ";
if (year < 10)
date_str += '0';
date_str += String(year); // values of date,month and year are stored in a string
}
if (gps.time.isValid()) //check whether gps time is valid
{
time_str = "";
hour = gps.time.hour();
minute = gps.time.minute();
second = gps.time.second();
minute = (minute + 30); // converting to IST
if (minute > 59)
{
minute = minute - 60;
hour = hour + 1;
}
hour = (hour + 5) ;
if (hour > 23)
hour = hour - 24; // converting to IST
if (hour >= 12) // checking whether AM or PM
pm = 1;
else
pm = 0;
hour = hour % 12;
if (hour < 10)
time_str = '0';
time_str += String(hour); //values of hour,minute and time are stored in a string
time_str += " : ";
if (minute < 10)
time_str += '0';
time_str += String(minute); //values of hour,minute and time are stored in a string
time_str += " : ";
if (second < 10)
time_str += '0';
time_str += String(second); //values of hour,minute and time are stored in a string
if (pm == 1)
time_str += " PM ";
else
time_str += " AM ";
}
}
WiFiClient client = server.available(); // Check if a client has connected
if (!client)
{
return;
}
// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n <!DOCTYPE html>
<html> <head> <title>GPS DATA</title> <style>";
s += "a:link {background-color: YELLOW;text-decoration: none;}";
s += "table, th, td </style> </head> <body> <h1 style=";
s += "font-size:300%;";
s += " ALIGN=CENTER> GPS DATA</h1>";
s += "<p ALIGN=CENTER style=""font-size:150%;""";
s += "> <b>Location Details</b></p> <table ALIGN=CENTER style=";
s += "width:50%";
s += "> <tr> <th>Latitude</th>";
s += "<td ALIGN=CENTER >";
s += lat_str;
s += "</td> </tr> <tr> <th>Longitude</th> <td ALIGN=CENTER >";
s += lng_str;
s += "</td> </tr> <tr> <th>Date</th> <td ALIGN=CENTER >";
s += date_str;
s += "</td></tr> <tr> <th>Time</th> <td ALIGN=CENTER >";
s += time_str;
s += "</td> </tr> </table> ";
s += "</body> </html>"
client.print(s); // all the values are send to the webpage
delay(100);
}
Output:
Webpage displays date, time , longitude and latitude of the location.
Result:
Location has been successfully identified using GPS and Node MCU and the results
are verified.
Ex : 11 Interfacing Bluetooth
Aim:
To interface Bluetooth module using Node MCU
Hardware Required:
● ESP8266 Node MCU
● Bluetooth Module
● LED
● 1K-ohm resistor
● Connecting Wires
● Breadboard
Circuit Diagram:
Code:
int led_pin = 2;
void setup() {
pinMode(led_pin, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available())
{
char data_received;
data_received = Serial.read();
if (data_received == 'O')
{
digitalWrite(led_pin, HIGH);
Serial.write("LED is now ON!\n");
}
else if (data_received == 'X')
{
digitalWrite(led_pin, LOW);
Serial.write("LED is now OFF!\n");
}
else
{
Serial.write("Specify correct option\n");
}
}
}
Output:
LED is ON when O is sent
LED is OFF when X is sent
Result:
Bluetooth module has been successfully interfaced with Node MCU and the results
are verified.
Ex : 12 Interfacing GSM
Aim:
To interface with GSM and send message using Node MCU
Hardware Required:
● GSM SIM900A
● Node MCU
● Jumper Wire
● Power adapter 5V
● SIM card
● Breadboard
Circuit Diagram :
Code:
void setup()
{
//Begin nodemcu serial-0 channel
Serial.begin(9600);
}
void loop()
{
Serial.print("AT"); //Start Configuring GSM Module
delay(1000); //One second delay
Serial.println();
Serial.println("AT+CMGF=1"); // Set GSM in text mode
delay(1000); // One second delay
Serial.println();
Serial.print("AT+CMGS="); // Enter the receiver number
Serial.print("\"+91XXXXXXXXXX\"");
Serial.println();
delay(1000);
Serial.print("IOT LAB"); // SMS body - Sms Text
delay(1000);
Serial.println();
Serial.write(26); //CTRL+Z Command to send text and end session
while(1); //Just send the text ones and halt
}
Output:
SMS is received at the given mobile number
Result:
Interface with GSM and sending a SMS using Node MCU has been done successfully
and the results are verified.
Part C IoT Cloud Applications
1)Aim:
To collecting and processing data from IoT systems in the cloud using Thing Speak.
Code:
#include <ESP8266WiFi.h>
#include "ThingSpeak.h"
char msg[50];
const char* ssid = "boolean"; // your network SSID (name)
const char* password = "meowmeow"; // your network password
WiFiClient client;
unsigned long myChannelNumber = 0000000; // Your channel number
const char * myWriteAPIKey = "UGGJHGJHJHJ"; // Your WriteAPI Key
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 30000;
// Variable to hold temperature readings
float temperatureC;
int outputpin = A0;
void setup() {
Serial.begin(115200); //Initialize serial
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect");
while (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, password);
delay(5000);
}
Serial.println("\nConnected.");
}
}
void loop() {
if ((millis() - lastTime) > timerDelay || 1) {
int analogValue = analogRead(outputpin);
float millivolts = (analogValue / 1024.0) * 3300;
temperatureC = millivolts / 80 + random(10);
Serial.print("Temperature (ºC): ");
Serial.println(temperatureC);
int x = ThingSpeak.writeField(myChannelNumber, 1, temperatureC, myWriteAPIKey);
if (x == 200) {
Serial.println("Channel update successful.");
}
else {
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
lastTime = millis();
}
}
Output:
Result:
Data has been successfully connected and processed using ThingSpeak.
2.Aim:
To develop IoT applications using Django Framework and Firebase/ Bluemix
platform.
Code:
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
// Watson IoT connection details
#define MQTT_HOST "vzrica.messaging.internetofthings.ibmcloud.com"
//change su1efs
#define MQTT_PORT 1883
#define MQTT_DEVICEID "d:vzrica:ESP8266:dev01"
//change su1efs
#define MQTT_USER "use-token-auth"
#define MQTT_TOKEN "Manoj_Selvam" // change your auth_id :
#define MQTT_TOPIC "iot-2/evt/status/fmt/json"
#define MQTT_TOPIC_DISPLAY "iot-2/cmd/display/fmt/json"
// Add WiFi connection information
char ssid[] = "galaxy123"; // your network SSID (name)
char pass[] = "tebv7047"; // your network password
// MQTT objects
void callback(char* topic, byte* payload, unsigned int length);
WiFiClient wifiClient;
PubSubClient mqtt(MQTT_HOST, MQTT_PORT, callback, wifiClient);
// variables to hold data
StaticJsonDocument<100> jsonDoc;
JsonObject payload = jsonDoc.to<JsonObject>();
JsonObject status = payload.createNestedObject("d");
static char msg[50];
float t = 0.0;
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] : ");
payload[length] = 0; // ensure valid content is zero terminated so can treat as c-string
Serial.println((char *)payload);
}
void setup() {
// Start serial console
Serial.begin(115200);
Serial.setTimeout(2000);
while (!Serial) { }
Serial.println();
Serial.println("ESP8266 Sensor Application");
// Start WiFi connection
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi Connected");
// Connect to MQTT - IBM Watson IoT Platform
if (mqtt.connect(MQTT_DEVICEID, MQTT_USER, MQTT_TOKEN)) {
Serial.println("MQTT Connected");
mqtt.subscribe(MQTT_TOPIC_DISPLAY);
} else {
Serial.println("MQTT Failed to connect!");
ESP.reset();
}
}
void loop() {
mqtt.loop();
while (!mqtt.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqtt.connect(MQTT_DEVICEID, MQTT_USER, MQTT_TOKEN)) {
Serial.println("MQTT Connected");
mqtt.subscribe(MQTT_TOPIC_DISPLAY);
mqtt.loop();
} else {
Serial.println("MQTT Failed to connect!");
delay(5000);
}
}
// get t from temp sensor
int analogValue = analogRead(A0);
float millivolts = (analogValue/1024.0) * 3300;
t = millivolts/40;
// Check if any reads failed and exit early (to try again).
if ( isnan(t) ) Serial.println("Failed to read from DHT sensor!");
else {
// Send data to Watson IoT Platform
status["temp"] = t+random(10);
serializeJson(jsonDoc, msg, 50);
Serial.println(msg);
if (!mqtt.publish(MQTT_TOPIC, msg)) {
Serial.println("MQTT Publish failed");
}
}
// Pause - but keep polling MQTT for incoming messages
for (int i = 0; i < 10; i++) {
mqtt.loop();
delay(1000);}
}
}
Output:
Result:
IoT applications using Bluemix platform has been successfully developed and the
results are verified.