0% found this document useful (0 votes)
5 views53 pages

IoT LabManual

The document outlines a course on the Internet of Things (IoT) with various experiential learning exercises involving Arduino and Raspberry Pi. It includes detailed instructions for designing and simulating projects such as LED displays, servo motors, ultrasonic sensors, flame sensors, and gas sensors, along with their respective circuit diagrams and code examples. The aim is to provide hands-on experience in IoT applications and data transmission to cloud platforms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views53 pages

IoT LabManual

The document outlines a course on the Internet of Things (IoT) with various experiential learning exercises involving Arduino and Raspberry Pi. It includes detailed instructions for designing and simulating projects such as LED displays, servo motors, ultrasonic sensors, flame sensors, and gas sensors, along with their respective circuit diagrams and code examples. The aim is to provide hands-on experience in IoT applications and data transmission to cloud platforms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Course Code : 22CB102006

Course Title : Internet of Things

EXPERIENTIAL LEARNING

LIST OF EXERCISES:

1. Design and Simulate LED 7-Segment Display interfacing with Arduino.


2. Design and Simulate Servo motor interfacing with Arduino.

3. Design and Simulate ultrasonic sensor and LCD interfacing with Arduino.

4. Design and Simulate Flame Sensor interfacing with Arduino.

5. Design and Implement to capture Gas Sensor and send sensor data to cloud from your
NodeMCU device using Arduino IDE.
6. Design and Implementation of Humidity and Temperature Monitoring Using Arduino and
upload data to cloud using MQTT.
7. Design and Implementation of an IoT ECG (Electrocardiogram) System to record heart's
electrical activity.
8. Design and Simulate controlling an LED 7-Segment Display with Raspberry Pi.

9. Design and implementation of Raspberry Pi Home Security System with Camera and PIR
Sensor with Email Notifications.
10. Design and Implement to upload Light sensor (TSL) data to cloud through Raspberry Pi.
11. Design and Implementation of Motion Detector with NodeMCU and BLYNK.
12. Design and Implementation of Fire notification IoT system with BLYNK.
EXPERIMENT – 1-a

1. (a) DESIGN AND SIMULATE LED 7-SEGMENT DISPLAY INTERFACING WITH ARDUINO

AIM:

Using 7-Segment Module circuit using Arduino and display the values.

PROCEDURE

A) Procedure for Connecting 7 Segment :

In Common Anode all LED pins of 7 segment connected to arduino GPIO, and Vcc pin connected in Common,
In Common Cathode all LED pins of 7 segment connected to arduino GPIO, and Ground pin connected in
Common
1. Make the connection as per the circuit diagram
2. Open the Arduino IDE in computer and write the program.
3. Compile the program for any errors and upload it to the Arduino.
4. Use the 220 Ohm resistor’s to connect the 7 Segment display at anode to power 3.3V.
5. Observe the 7 Segment display is updated .

Components :

S. No Name of the equipment Quantity

1 Arduino Uno having Microcontroller(ATMEGA328P) 1

2 7 Segment 1

220 Ohm , resistor


3 (resistance is represented by Red, Red, Black code.) 1

4 Bread Board 1

5 USB B Data Cable 1

6 Computer with Arduino IDE software 1

7 Male to Male Jumper Cables As required


CIRCUIT DIAGRAM:

7- Segment

For Common Anode – use LOW to GLOW LED


For Common Cathode – use HIGH to GLOW LED

Figure.1.1 “ 7 Segment to display numbers from 0 to 9 “

Figure: 1.2 Circuit Diagram for 7 Segment Common Cathode to connect to Arduino
Figure: 1.2 Circuit Diagram for 7 Segment Common Cathode to connect to Arduino
Program Code:

A) Code for 7
Segment:
void setup()

{
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);

}
void loop() {

//EIGHT : 6
digitalWrite(12,HIGH); // A
digitalWrite(11,LOW); // B
digitalWrite(10,HIGH); // C
digitalWrite(9,HIGH); //D
digitalWrite(8,HIGH); //E
digitalWrite(7,HIGH); // F
digitalWrite(6,HIGH); //G

delay(500);

//EIGHT : 7

digitalWrite(12,HIGH); // A
digitalWrite(11,HIGH); // B
digitalWrite(10,HIGH); // C
digitalWrite(9,LOW); //D
digitalWrite(8,LOW); //E
digitalWrite(7,HIGH); // F
5
digitalWrite(6,HIGH); //G

delay(500);

//EIGHT : 8

digitalWrite(12,HIGH); // A
digitalWrite(11,HIGH); // B
digitalWrite(10,HIGH); // C
digitalWrite(9,HIGH); //D
digitalWrite(8,HIGH); //E
digitalWrite(7,HIGH); // F
digitalWrite(6,HIGH); //G

delay(500);
}

EXPERIMENT – 1-b

1. (b) Design and Simulate Servo motor interfacing with Arduino.

Aim : To design and simulate servo motor interfacing with Arduino to perform 180
degree movement.

PROCEDURE:
6
1. Orange Wire: PWM output from pin9 to Motor Control Input
2. Red Wire: +6V supply for Motor
3. Black Wire: 0V (Ground)
4. Connect the Supply to the board (5-12V DC). Connect USB with PC and upload the
sketch to the board.
5. On connecting the board first time, it’ll ask for the drivers (which can be
downloaded from arduino website).
6. Open Arduino IDE and Create a new Sketch (In Arduino world code/program is
called a ‘sketch’).
7. Write the code and ‘verify’ (option on toolbar) it. After verifying it will notify if
there are any errors otherwise ‘Done Compiling’ will be shown.
8. Now Upload the sketch to the Hardware. When sketch is Uploaded, Press Reset on
the board. Now connect Servo control Pin at respective Pin and provide supply to
it. The Pin9 of PWM port of the board provides motor control.

Components :

1.Arduino Uno with USB Cable

2. Male to Male Jumper Cable – 3Nos

3. Servo Motor

Circuit Diagram :

7
Program Code :

#include <Servo.h>

Servo servo1; // create servo object to control a servo

int posn = 0; // variable to store the servo position

void setup()

servo1.attach (9); // attaches the servo on pin 9 to the servo object

void loop()

for (posn = 0; posn < 180; posn += 1) // goes from 0 degrees to 180 degrees

{ // in steps of 1 degree

servo1.write (posn); // tell servo to go to position in variable 'pos'

delay (10); // waits 10ms for the servo to reach the position

for (posn = 180; posn>=1; posn-=1) // goes from 180 degrees to 0 degrees

// in steps of 1 degree

servo1.write (posn); // tell servo to go to position in variable 'pos'

delay (10); // waits 10ms for the servo to reach the position

8
EXPERIMENT – 2-a

2. (a) Design and Simulate ultrasonic sensor and LCD interfacing with Arduino.

Aim :To find the distance between , using SR04 Ultrasonic distance sensor coding in
Arduino

Procedure :

I2C (Inter-Integrated Circuit)

Distance measuring instrument design and development using Arduino UNO and
Ultrasonic Sensor SR04.

INSTALL LIBRARY LIQUIDCRYSTAL I2C :

9
10
Components:

The components required:

1. Arduino UNO
2. Ultrasonic sensor SR04
3. 16×2 LCD (HDD44780 driver based)
4. 6v battery or 5v USB power source (Mobile adapter/laptop)
5. I2C Board
6. Jumper wires
7. Breadboard

Circuit Diagram :

SRO4 : PIN : 12 = ECHO, 13= TRIG , VCC 3V, GND

I2C : SCL : A5 =SCL , A4 = SDA , VCC 5V, GND

11
Program Code:

#include <Wire.h>

#include <LiquidCrystal_I2C.h>

#include <HCSR04.h>

//UltraSonicDistanceSensor sensor(triggerPin, echoPin);

// Initialize sensor that uses digital pins 13 and 12.

UltraSonicDistanceSensor distanceSensor(13, 12);

// set the LCD address to 0x27 for a 16 chars and 2 line display & 20 X 4 for 20 chars and
4 line display

LiquidCrystal_I2C lcd(0x27,16,2);

void setup()

// We initialize serial connection so that we could print values from sensor.

Serial.begin(9600);

lcd.init(); // initialize the lcd

lcd.init();

//Print a message to the LCD.

lcd.backlight();

lcd.setCursor(3,0); //column,row

lcd.print("SVEC");

lcd.setCursor(2,1);

lcd.print("DEPT IT");

delay(2000);

lcd.setCursor(1,2);

lcd.print("Distance");

void loop()

float dist;

dist=distanceSensor.measureDistanceCm();

Serial.println(round(dist));

delay(1000);

lcd.clear();
12
lcd.setCursor(0,0);

lcd.print("Distance : ");

lcd.setCursor(10,0);

lcd.print(round(dist));

lcd.setCursor(13,0);

lcd.print(" cm");

13
EXPERIMENT – 2-b

2 (b) Design and Simulate Flame Sensor interfacing with Arduino.

Aim : To perform an alarm when a fire is detected , using FlameSensor with photo diode and
coding in Arduino.

Procedure :

The flame sensor detects the presence of fire or flame based on the Infrared (IR)
wavelength emitted by the flame. It gives logic 1 as output if a flame is detected,
otherwise, it gives logic 0 as output. Arduino Uno checks the logic level on the output pin
of the sensor and performs further tasks such as activating the buzzer and LED, sending
an alert message.

The Flame Sensor and connectivity

A flame detector is a sensor designed to detect and respond to the presence of a flame
or fire. Responses to a detected flame depend on the installation but can include
sounding an alarm, deactivating a fuel line (such as a propane or a natural gas line), and
activating a fire suppression system. The IR Flame sensor used in this project is shown
below, these sensors are also called Fire sensor module or flame detector
sensor sometimes.

we are using an IR based flame sensor.


The Pin Description of the Flame sensor Module:

Pin Description

Vcc 3.3 – 5V power supply

GND Ground

Dou
Digital output
t

Applications
Flame Sensors are very important devices in detecting fire and they can be used in a
variety of applications/areas like:
 Hydrogen stations
 Combustion monitors for burners
 Oil and gas pipelines
 Automotive manufacturing facilities
 Nuclear facilities
 Aircraft hangars
 Turbine enclosures
 Car or Automobile
 Fire Fighting Robots
 Garage Safety Equipment
 Warehouses

14
Components Required

 Arduino Uno (any Arduino board can be used)


 Flame sensor module
 LED
 Buzzer
 Resistor
 Jumper wires

Circuit Diagram

The below image is the Arduino fire sensor circuit diagram, it shows how to interface
the fire sensor module with Arduino.

15
16
Code explanation

The complete Arduino code for this project is given at the end of this article. The code
is split into small meaningful chunks and explained below.

In this part of the code, we are going to define pins for Flame sensor, LED and
buzzer which are connected to Arduino. The flame sensor is connected to digital pin 4 of
Arduino. The buzzer is connected to digital pin 8 of Arduino. LED is connected to digital
pin 7 of Arduino.

Variable “flame_detected” is used for storing the digital value read out from the flame
sensor. Based on this value we will detect the presence of flame.

int buzzer = 8 ;

int LED = 7 ;

int flame_sensor = 4 ;

int flame_detected ;

In this part of the code, we are going to set the status of digital pins of Arduino and
configure

Baud rate for Serial communication with PC for displaying the status of the flame
detection circuit.

void setup()

Serial.begin(9600) ;

pinMode(buzzer, OUTPUT) ;

pinMode(LED, OUTPUT) ;

pinMode(flame_sensor, INPUT) ;

This line of code reads the digital output from flame sensor and stores it in the variable
“flame_detected”.

flame_detected = digitalRead(flame_sensor) ;

Based on the value stored in “flame_detected”, we have to turn on the buzzer and LED.
In this part of the code, we compare the value stored in “flame_detected” with 0
or 1.

If its equal to 1, it indicates that flame has been detected. We have to turn on buzzer
and LED and then display an alert message in Serial monitor of Arduino IDE.

If its equal to 0, then it indicates that no flame has been detected so we have to turn
off LED and buzzer. This process is repeated every second to identify the presence of fire
or flame.

if (flame_detected == 1)

17
Serial.println("Flame detected...! take action immediately.");

digitalWrite(buzzer, HIGH);

digitalWrite(LED, HIGH);

delay(200);

digitalWrite(LED, LOW);

delay(200);

else

Serial.println("No flame detected. stay cool");

digitalWrite(buzzer, LOW);

digitalWrite(LED, LOW);

delay(1000);

We have built a fire fighting robot based on this concept, which automatically detects the
fire and pump out the water to put down the fire. Now you know how to do fire detection
using Arduino and flame sensor, hope you enjoyed learning it, if you have any questions
leave them in the comment section below.

Code

int buzzer = 8;
int LED = 7;
int flame_sensor = 4;
int flame_detected;

void setup()
{
Serial.begin(9600);
pinMode(buzzer, OUTPUT);
pinMode(LED, OUTPUT);
pinMode(flame_sensor, INPUT);
}

void loop()
{
flame_detected = digitalRead(flame_sensor);
if (flame_detected == 1)
{
Serial.println("Flame detected...! take action immediately.");
digitalWrite(buzzer, HIGH);
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED, LOW);
delay(200);
}
else
{
Serial.println("No flame detected. stay cool");
digitalWrite(buzzer, LOW);
18
digitalWrite(LED, LOW);
}
delay(1000);
}

EXPERIMENT – 3

3. Design and Implement to capture Gas Sensor and send sensor data to cloud
from your NodeMCU device using Arduino IDE.

Aim : To find the quality of air using Gas Sensor MQ135 with Nodemcu and send data to
Thingspeak cloud

Procedure :

Connect the Gas Sensor to Nodemcu

1. Nodemcu D0 Pin to MQ135 Gas Sensor D0 Pin,


2. Nodemcu 3.3v Vcc to 3.3V MQ135
3. Nodemcu GND to MQ135 GND

a. Create account in thingspeak cloud to upload data at https://thingspeak.com/

[IoT Analytics - ThingSpeak Internet of Things

19
Components
1. NodeMCU
2. GAS Sensor MQ135
3. Breadboard
4. Male to Male Jumper Cables – 3Nos

20
Circuit Diagram :

Code :

#include <ESP8266WiFi.h>

String apiKey = "EVSGQZMUPF1CH82A"; // Enter your Write API key from ThingSpeak

const char *ssid = "IOTLAB 403"; // replace with your wifissid and wpa2 key

const char *pass = "123456789";

const char* server = "api.thingspeak.com";

WiFiClient client;

void setup()

Serial.begin(115200);//SERIAL MONITORING SETUP

delay(10);

Serial.println("Connecting to ");

Serial.println(ssid);

WiFi.begin(ssid, pass);

while (WiFi.status() != WL_CONNECTED)

delay(500);

Serial.print(".");

Serial.println("");
21
Serial.println("WiFi connected");

void loop()

float h = analogRead(A0);

if (isnan(h))

Serial.println("Failed to read from sensor!");

return;

if (client.connect(server, 80)) // "184.106.153.149" or api.thingspeak.com

String postStr = apiKey;

postStr += "&field1=";

postStr += String(h/1023*100);

postStr += "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");

client.print(postStr);

Serial.print("Gas Level: ");

Serial.println(h/1023*100);

Serial.println("Data Send to Thingspeak"); }

delay(500);

client.stop();

Serial.println("Waiting...");

// thingspeak needs minimum 15 sec delay between updates.

delay(1500);

22
EXPERIMENT – 4

4. Design and Implementation of Humidity and Temperature Monitoring Using

NodeMCU and upload data to cloud using MQTT.

Aim : To get temperature and humidity data from DHT11 Module using
Nodemcu microcontroller , and then uploading the same data to adafruit mqtt
cloud.

Procecudre :

Introduction

This example will demonstrate how to report the temperature and humidity data
collected by the DHT11 sensor to the MQTT service in the cloud through the MQTT
protocol and the NodeMCU based on ESP8266 , and show how the application subscribes
to and processes the data. The reason why mqtt protocol is used in this article is that it is
lightweight and energy-saving, which is very suitable for the use scenarios of the Internet
of things. At present, all major public cloud providers have basically opened IOT hub
services based on MQTT protocol. For example, the IOT Core of AWS and the IOT Hub of
Azure can easily access these data to these public cloud services through MQTT protocol.

The overall architecture is as follows:

Hardware Configuration

NodeMCU board x 1: NodeMCU is an open source IoT platform. It includes firmware


which runs on the ESP8266 Wi-Fi SoC, 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.

DHT11 temperature / humidity sensor x 1: DHT11 digital temperature and humidity


sensor is a composite sensor with calibrated digital signal output

Breadboard x 1

Several jumper wires

23
Arduino IDE Configuration

1.Download and install CH340G USB driver

2. Install ESP8266 module : Set the preferences

URL: https://arduino.esp8266.com/stable/package_esp8266com_index.json

3. Install AdaFruitMQTT library (by Adafruit)

Sketch -> Include Library -> Manage Libraries… -> Type AdaFruitMQTT in Search field ->
Install , AdaFruit MQTT with Client Service

After the data is successfully collected through NodeMCU, it needs to be sent to the
MQTT cloud service in the cloud. This article uses the MQTT cloud service provided by
Adafruit. We choose other MQTT cloud services according to their own circumstances,
such as Azure IoT Hub or AWS IoT Core.

Each cloud service needs to provide different authentication methods when accessing.
Therefore, when connecting to the MQTT service in the cloud via NodeMCU, it is required
to set the connection method according to the security requirements of the target cloud
service. For the sake of simplicity, this article uses a non-secure connection method. In a
formal production environment, a connection with a secure authentication method must
be set.

Click Adafruit MQTT Cloud registration address to register

https://www.adafruit.com/

After registration, then signin , click on IO  MyKey and collect API Authentication Key
and User Name,

Then choose, Feeds  View All -> Create New Feed , Give a Name to the Feed ,
then press OK ,to Create Feed .

Repeat the process of creating Feed , then update the Feed Names in code given for the
Adafruit MQTT client program to be uploaded into NodeMCU Device.

Components :

1. Nodemcu – 1No
2. DHT11 - 1 No
3. BreadBoard -1 No
4. JumperCables-3 No
5. USB Cable – 1No

24
Circuit Diagram :

25
Coding :

#include <ESP8266WiFi.h>

#include "Adafruit_MQTT.h"

#include "Adafruit_MQTT_Client.h"

#include <SimpleDHT.h>

/************************* WiFi Access Point *********************************/

#define WLAN_SSID "IOTLAB 403"

#define WLAN_PASS "123456789"

// Adafruit IO

#define AIO_SERVER "io.adafruit.com"//Broker domain Name

#define AIO_SERVERPORT 1883 //The port at which broker is listening

#define AIO_USERNAME "iotlabdEVICE" //update with your username

#define AIO_KEY "aio_aVPB13a7XSLTg1M0USAgciZJEt12" // update ur key ty

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.

WiFiClient client;

// or... use WiFiClientSecure 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 'photocell' for publishing.

// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>

Adafruit_MQTT_Publish Temperature1 = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME


"/feeds/Temperature1");

Adafruit_MQTT_Publish Humidity1 = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME


"/feeds/Humidity1");
26
// Setup a feed called 'onoff' for subscribing to changes.

int pinDHT11 = D3;

SimpleDHT11 dht11(pinDHT11);

byte hum = 0; //Stores humidity value

byte temp = 0; //Stores temperature value

void setup() {

Serial.begin(115200); //Start the serial communication for debugging

Serial.println(F("Adafruit IO Example"));

// Connect to WiFi access point.

Serial.println(); Serial.println();

delay(10);

Serial.print(F("Connecting to "));

Serial.println(WLAN_SSID);

WiFi.begin(WLAN_SSID, WLAN_PASS);

while (WiFi.status() != WL_CONNECTED) {

delay(500);

Serial.print(F("."));

Serial.println();

Serial.println(F("WiFi connected"));

Serial.println(F("IP address: "));

Serial.println(WiFi.localIP());

// connect to adafruitio

connect();

// connect to adafruitio via MQTT

void connect() {

Serial.print(F("Connecting to Adafruit IO... "));

27
int8_t ret;

while ((ret = mqtt.connect()) != 0) {

switch (ret) {

case 1: Serial.println(F("Wrong protocol")); break;

case 2: Serial.println(F("ID rejected")); break;

case 3: Serial.println(F("Server unavail")); break;

case 4: Serial.println(F("Bad user/pass")); break;

case 5: Serial.println(F("Not authed")); break;

case 6: Serial.println(F("Failed to subscribe")); break;

default: Serial.println(F("Connection failed")); break;

if(ret >= 0)

mqtt.disconnect();

Serial.println(F("Retrying connection..."));

delay(10000);

Serial.println(F("Adafruit IO Connected!"));

void loop() {

// ping adafruitio a few times to make sure we remain connected

if(! mqtt.ping(3)) {

// reconnect to adafruitio

if(! mqtt.connected())

connect();

dht11.read(&temp, &hum, NULL);

Serial.print((int)temp); Serial.print(" *C, ");

Serial.print((int)hum); Serial.println(" H");

delay(5000);

if (! Temperature1.publish(temp)) { //Publish to Adafruit

Serial.println(F("Failed"));

28
if (! Humidity1.publish(hum)) { //Publish to Adafruit

Serial.println(F("Failed"));

else {

Serial.println(F("Sent!"));

29
EXPERIMENT – 5

5. Design and Implementation of an IoT ECG (Electrocardiogram) System to


record heart's electrical activity.

Aim :

Procedure :

The EKG or ECG (Electrocardiogram) is a non-invasive diagnostic test that assesses heart rhythm and
function through a recording of the electrical activity of the heart that occurs with each heartbeat.
This electrical activity is recorded from the patient’s body surface and is drawn on a paper using a
graphical representation or tracing, where different waves are observed that represent the electrical
stimuli of the atria and ventricles. The device with which the electrocardiogram is obtained is called
an electrocardiograph.

The normal rhythm of an ECG is formed by a P wave, a QRS complex and a T wave. To interpret an
electrocardiogram, the presence of these waves, their shape and duration, as well as the ST segment
(time that elapses between the end of depolarization and the beginning of repolarization of the
ventricles, measures less than 1 mm, if it is greater than 1 mm it indicates infarction or ischemia).

The P waves allow us to know the time between the heartbeats, it is represented as a straight line
between the lowest and the highest point. The T wave represents the small perceptible beat after
the first and marks the end of the heartbeat. The time elapsed between one and the other must be
fairly regular throughout the entire test, if on the contrary, during the test we see that the elapsed
time is variable, this indicates an irregularity in the heartbeat.

Connect the A0 to OUTPUT in the module , LO- to 11 pin in arduino , LO+ to 10 pin in arduino.
Upload code and check the graph in Serial Plotter.

Understanding graphical diagram of ECG Value at Serial Plotter Connection Locations at Limbs

30
Components :

1. Arduino Uno
2. ECG module (AD8232)
3. ECG electrode - 3 pieces
4. ECG electrode connector - 3.5 mm
5. DATA Cable
6. Jumper Wires

Circuit Diagram

Code :

void setup()
{
// initialize the serial communication:
Serial.begin(9600);
pinMode(10, INPUT); // Setup for leads off detection LO +
pinMode(11, INPUT); // Setup for leads off detection LO -
}

void loop()
{
if((digitalRead(10) == 1)||(digitalRead(11) == 1))
{
Serial.println('!');
}
else
{
// send the value of analog input 0:
Serial.println(analogRead(A0));
}
//Wait for a bit to keep serial data from saturating
delay(1);
}

Output at serial plotter :

Choose : Tools -> Serial Plotter


31
32
EXPERIMENT – 6

6. Design and Simulate controlling an LED 7-Segment Display with Raspberry


Pi.

Aim : To implement display of numbers in 7 segment using Raspberry Pi

Procedure:

A seven segment display is a simple displaying device that uses 8 LEDs to display decimal numerals. It
is generally used in digital clocks, calculators, electronic meters, and other devices that displays
numerical information.

A seven segment display has 8 LEDs in it. Each LED is controlled through specific pin. It is made of
seven different illuminating segments which are arranged in such a way that it can form the numbers
from 0-9 by displaying different combinations of segments. It is also able to form some alphabets like
A, B, C, H, F, E, G, DP.

These can be two type common anode and common cathode. In common cathode type the cathode
is common for all 8 LEDs and in common anode type the anode is common for all 8 LEDs. A seven
segment display has 10 pin interface, 2 pins are for Common and 8 pins are for each LED. Both
common pins are internally shorted.

The RPi.GPIO is used to import and to the OUTPUT or INPUT mode of a pin action is mentioned then
OUT / IN is used to

Open the editor thonny , type the program code to perform , write Python 3 file_name.py > Press
Enter. (.py is file extension).click on run-button.

33
Raspberry Pi pin diagram:

34
Components :

1. Raspberry PI - 1No

2. 7 Segment Common Anode - 1No


3. Male to Female Jumper Cables – 9 No
4. 220 Ohm Resistor
5. Bread Board

Circuit Diagram :

Pinouts 7segment connecting to Raspberry Pi:

35
7 Segment connections at Raspberry Pi

Code :

import RPi.GPIO as GPIO

import time

import os, sys

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BOARD)

#setup output pins

GPIO.setup(35, GPIO.OUT) //GPIO19

GPIO.setup(12, GPIO.OUT) //GPIO18

GPIO.setup(36, GPIO.OUT) //GPIO16

GPIO.setup(33, GPIO.OUT) //GPIO13

GPIO.setup(32, GPIO.OUT) //GPIO12

GPIO.setup(38, GPIO.OUT) //GPIO20

GPIO.setup(40, GPIO.OUT) //GPIO21

#define 7 segment digits

digitclr=[1,1,1,1,1,1,1]

36
digit0=[0,0,0,0,0,0,1]

digit1=[1,0,0,1,1,1,1]

digit2=[0,0,1,0,0,1,0]

digit3=[0,0,0,0,1,1,0]

digit4=[1,0,0,1,1,0,0]

digit5=[0,1,0,0,1,0,0]

digit6=[0,1,0,0,0,0,0]

digit7=[0,0,0,1,1,1,1]

digit8=[0,0,0,0,0,0,0]

digit9=[0,0,0,1,1,0,0]

gpin=[35,12,36,33,32,38,40]

#routine to clear and then write to display

def digdisp(digit):

for x in range (0,7):

GPIO.output(gpin[x], digitclr[x])

for x in range (0,7):

GPIO.output(gpin[x], digit[x])

#routine to display digit from 0 to 9

digdisp(digit0)

time.sleep(1)

digdisp(digit1)

time.sleep(1)

digdisp(digit2)

time.sleep(1)

digdisp(digit3)

time.sleep(1)

digdisp(digit4)

time.sleep(1)

digdisp(digit5)

time.sleep(1)

digdisp(digit6)

time.sleep(1)

digdisp(digit7)

37
time.sleep(1)

digdisp(digit8)

time.sleep(1)

digdisp(digit9)

time.sleep(1)

#tidy up

GPIO.cleanup()

import sys

sys.exit()

38
Output:

39
EXPERIMENT – 7

7. Design and implementation of Raspberry Pi Home Security System with


Camera and PIR Sensor with Email Notifications.

Aim:

To take the picture and save it in system when a intrusion is detected by PIR and send email
notification

Procedure :

Here we use 5MP Raspberry Pi 3 Model B Camera Module with Cable equips flexible cable for
attaching with Raspberry Pi 3 Model B. The camera connects to the BCM2835 processor on the Pi
via the CSI bus, a higher bandwidth link which carries pixel data from the camera back to the
processor. This bus travels along the ribbon cable that attaches the camera board to the Pi.

Without giving power to Raspberry Pi , Connect the raspberry pi camera facing the terminal line to
HDMI direction and blue color to USB direction, then connect PIR out at raspberry pi GPIO 4, then
GND at any GND and Vcc at 5V at top right.

Open the editor thonny , type the program code to perform , write Python 3 file_name.py > Press
Enter. (.py is file extension).click on run-button.

Components :

1. Raspberry Pi 3 with SD Card loaded with Raspberry Pi Os

2. HDMI Cable for Raspberry Pi 3, or Micro HDMI Cable for Raspberry Pi 4

3. Power up with USB Cable for Raspberry Pi 3 or power up with USB C for Raspberry Pi 4

4. PIR Module with (GND, DATA, VCC)

5. Female to Female Jumper Cables – 3 Nos

Circuit Diagram :

40
41
Code :

from gpiozero import MotionSensor

from picamera import PiCamera

import smtplib

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

pir = MotionSensor(4)

camera = PiCamera()

pir.wait_for_motion()

camera.capture('selfie3.png')

print("Motion detected!")

camera.close()

pir.wait_for_no_motion()

mail_content = 'Hello,This is a simple mail'

#The mail addresses and password

sender_address = '[email protected]'

sender_pass = 'Svec_123'

receiver_address = '[email protected]'

#Setup the MIME

message = MIMEMultipart()

message['From'] = sender_address

message['To'] = receiver_address

message['Subject'] = 'A test mail sent by Python. It has an attachment.' #The subject
line

#The body and the attachments for the mail

message.attach(MIMEText(mail_content, 'plain'))

#Create SMTP session for sending the mail

session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port

session.starttls() #enable security

session.login(sender_address, sender_pass) #login with mail_id and password

text = message.as_string()

session.sendmail(sender_address, receiver_address, text)

session.quit()

print('Mail Sent')

42
EXPERIMENT – 8

8. Design and Implement to upload Light sensor (TSL) data to cloud through
Raspberry Pi.

Aim : To simulate automatic glow of LED when intensity of Light is LOW using
LDR

Procedure :

An LDR (Light Dependent Resistor) or a photo resistor is a photo conductive sensor. It is a


variable resistor that changes it’s resistance in a proportion to the light exposed to it. Its
resistance decreases with the intensity of light.

The LDR is connected with 3.3v and the other leg of the LDR is connected with the
positive leg of the 10UF capacitor the other leg of the capacitor is connected with the
ground… now take a wire from the middle and connect it with pin number 7 of the
raspberry pi. our circuit diagram is completed. So LED is connected with pin number 11
and the RC circuit is connected with pin number 7

Components :

1. Raspberry zPi
2. LDR
3. Female to Male Jumper Wires – 2 Nos
4. BreadBoard

Circuit Diagram:

43
44
Code :

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

delayt = .1

value = 0 # this variable will be used to store the ldr value

ldr = 7 #ldr is connected with pin number 7

led = 11 #led is connected with pin number 11

GPIO.setup(led, GPIO.OUT) # as led is an output device so that’s why we set it to output.

GPIO.output(led, False) # keep led off by default

def rc_time (ldr):

count = 0

#Output on the pin for

GPIO.setup(ldr, GPIO.OUT)

GPIO.output(ldr, False)

time.sleep(delayt)

#Change the pin back to input

GPIO.setup(ldr, GPIO.IN)

#Count until the pin goes high

while (GPIO.input(ldr) == 0):

count += 1

return count

#Catch when script is interrupted, cleanup correctly

try:

# Main loop

while True:

print("Ldr Value:")

45
value = rc_time(ldr)

print(value)

if ( value <= 10000 ):

print("Lights are ON")

GPIO.output(led, True)

if (value > 10000):

print("Lights are OFF")

GPIO.output(led, False)

except KeyboardInterrupt:

pass

finally:

GPIO.cleanup()

46
EXPERIMENT – 9
9. Design and Implementation of Motion Detector with NodeMCU and
BLYNK.

Aim: To create a IoT based mobile application using Blynk for notification,
we use demonstrating Motion Detection using Nodemcu

Procedure :

Include ESP8266 Core to Arduino IDE


1) Goto 'Preferences' and enter the following URL to Additional Board Manager URLs
http://arduino.esp8266.com/stable/package_esp8266com_index.json
2) Open the Boards Manager (Tools > Board Menu)
3) Search for "esp8266" and install the latest version
4) Select your board under Tools > Board and define Baud Rate etc.
Install Blynk libraries
1) Install the latest release of the Blynk libraries on GitHub URLs
https://github.com/blynkkk/blynk-library/releases/tag/v0.6.1
2) Unpack it
3) Move the libraries to C:/User//Documents/Arduino/libraries

Install Blynk App


1) Download the App for iOS or Android
In Android or ios

Do:

1. Click 'Create New Project'


2. Choose your device and connection type (NodeMCU, WiFi)
3. Receive and note down your 'Auth Token'
4. Open the 'Widget Box' ('+')
5. Add a button
6. Name it and select switch mode
7. Define the output pin the LED is connected to (anode Dx, cathode GND)

47
In Windows 8/or/Linux do :Arduino IDE

The client-side code for remote controlling an LED is very easy.

1. Open the Arduino IDE


2. Goto Examples > Blynk > Boards_WiFi and select your dev board
3. Enter your 'Auth Token' (char auth[])
4. Enter your WiFi credentials (char ssid[], char pass[])
5. Compile and Upload
6. Open the Serial Monitor and check whether connecting was successful

ex1: blink on/off D2 pin

#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>

#include <BlynkSimpleEsp8266.h>

// You should get Auth Token in the Blynk App.

// Go to the Project Settings (nut icon).

char auth[] = "-IcaRG685davMuxEAI52bS7KHojW8uml";

48
// Your WiFi credentials.

// Set password to "" for open networks.

char ssid[] = "Sree";

char pass[] = "123456789";

void setup()

// Debug console

Serial.begin(9600);

Blynk.begin(auth, ssid, pass);

// You can also specify server:

//Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);

//Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);

void loop()

Blynk.run();

ex2:PIR

#include <ESP8266WiFi.h>

#define BLYNK_PRINT Serial

#include <BlynkSimpleEsp8266.h>

char auth[] = "rioy3a0H5Ktacxx1TKIg3TPR8KmDhMGO";

/* WiFi credentials */

char ssid[] = "Sree";

char pass[] = "123456789";

/* HC-SR501 Motion Detector */

#define pirPin 5 // Input for HC-S501

int pirValue; // Place to store read PIR Value

int pinValue; //Variable to read virtual pin

49
BLYNK_WRITE(V0)

pinValue = param.asInt();

void setup()

Serial.begin(115200);

delay(10);

Blynk.begin(auth, ssid, pass);

pinMode(pirPin, INPUT);

void loop()

if (pinValue == HIGH)

getPirValue();

Blynk.run();

void getPirValue(void) //Get PIR Data

pirValue = digitalRead(pirPin);

if (pirValue)

Serial.println("Motion detected");

Blynk.notify("Motion detected");

50
EXPERIMENT –10

10. Design and Implementation of Fire notification ΙοΤ system with BLYNK.

Aim: To demonstrate IoT based mobile application get notification when a fire
is detected by firesensor.

Procedure :

Include ESP8266 Core to Arduino IDE


1) Goto 'Preferences' and enter the following URL to Additional Board Manager URLs
http://arduino.esp8266.com/stable/package_esp8266com_index.json
2) Open the Boards Manager (Tools > Board Menu)
3) Search for "esp8266" and install the latest version
4) Select your board under Tools > Board and define Baud Rate etc.
Install Blynk libraries
1) Install the latest release of the Blynk libraries on GitHub URLs
https://github.com/blynkkk/blynk-library/releases/tag/v0.6.1
2) Unpack it
3) Move the libraries to C:/User//Documents/Arduino/libraries

Install Blynk App


1) Download the App for iOS or Android
In Android or ios

Do:

1. Click 'Create New Project'


2. Choose your device and connection type (NodeMCU, WiFi)
3. Receive and note down your 'Auth Token'
4. Open the 'Widget Box' ('+')
5. Add a Notification
6. Define the output pin the FireSensor is connected to (anode Dx, cathode GND)

Components :
51
1.Nodemcu

2. FireSensor

3. FireGenerating Component/MatchBox/High Intensity of Light

Circuit Diagram:

Code :

// BLYNK LIBRARY

// https://github.com/blynkkk/blynk-library

// ESP8266 LIBRARY

// https://github.com/ekstrand/ESP8266wifi

#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>

#include <BlynkSimpleEsp8266.h>

BlynkTimer timer;

char auth[] = "your-auth-code"; //Auth code sent via Email

char ssid[] = "your-wifi-ssid"; //Wifi name

char pass[] = "your-wifi-password"; //Wifi Password

int flag=0;

void notifyOnFire()

int isButtonPressed = digitalRead(D1);

if (isButtonPressed==1 && flag==0) {

52
Serial.println("Fire DETECTED");

Blynk.notify("Alert : Fire detected");

flag=1;

else if (isButtonPressed==0)

flag=0;

void setup()

Serial.begin(9600);

Blynk.begin(auth, ssid, pass);

pinMode(D1,INPUT_PULLUP);

timer.setInterval

53

You might also like