0% found this document useful (0 votes)
76 views88 pages

IoT Lab Manual

Uploaded by

vardhansinghh711
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)
76 views88 pages

IoT Lab Manual

Uploaded by

vardhansinghh711
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
You are on page 1/ 88

Laboratory Manual

Internet of Things (IoT)

For

Final year Students (CSE)

Itgalpur Rajanakunte, Yelahanka, Bengaluru, Karnataka 560064

1|Page
FOREWORD

It is my great pleasure to present this laboratory manual for Final year engineering students for the
subject Internet of Things (IoT).

As a student, many of you may be wondering with some of the questions in your mind regarding the
subject and exactly what has been tried is to answer through this manual.

As you may be aware that Presidency University has already been awarded with Best Emerging
University in south India by ASSOCHAM, INDIA and it’s our endure to technically equip our
students take the advantage of the procedural aspects of this certification.

Faculty members are also advised that covering these aspects in initial stage itself, will greatly
relieve them in future as much of the load will be taken care by the enthusiasm energies of the
students once they are conceptually clear.

Afroz Pasha
Assistant Professor,
Department of CSE,
Presidency University

2|Page
LABORATORY MANUAL CONTENTS

This manual is intended for the final year students of Computer Science and Engineering in the subject
of Internet of Things(IoT). This manual typically contains practical/lab sessions related Raspberry pi and
Android implemented in Python programming covering various aspects related the subject to enhanced
understanding.

Students are advised to thoroughly go through this manual rather than only topics mentioned in the
syllabus as practical aspects are the key to understanding and conceptual visualization of theoretical
aspects covered in the books.

Good Luck for your Enjoyable Laboratory Sessions

3|Page
PROGRAME OBJECTIVES

B.Tech. Computer Science Engineering graduates of Presidency University, will be able to:

1. Direct and coordinate activities concerned with software/hardware design, development, and testing.

2. Design and develop products and systems for various applications.

3. Monitor and analyze computing system performance for network traffic, security, and capacity.

4. Order and maintain inventory of computing equipment for customer premises equipment, facilities,
access networks and backbone network

5. Operate and trouble shoot computer-assisted engineering, design software and equipment to perform
various engineering tasks.

8|Page
PROGRAMME OUTCOMES
On successful completion of B.Tech. Computer Science Engineering programme from Presidency
University a student will be able to
1. Apply mathematics, science and engineering fundamentals to computer science engineering.
2. Solve basic computer science engineering problems using first principles of mathematics and
engineering sciences.
3. Design computing systems for domestic, commercial and industrial applications.
4. Investigate computer engineering problems including design of experiments, analysis and
interpretation of data and synthesis of information to provide valid conclusions.
5. Select appropriate techniques, resources, and modern computer science engineering tools,
including prediction and modelling, to complex engineering activities, with an understanding of
the limitations.
6. Identify societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to computer science engineering practice.
7. Appraise professional ethics and responsibilities and norms of computer science engineering
practice.
8. Relate the impact of computer science engineering solutions in a societal context and
demonstrating knowledge of and need for sustainable development.
9. Assess management and business practices, such as risk and change management, and
understanding their limitations in the context of computer science engineering.
10. Demonstrate the ability to work as an individual, and as a member or leader in diverse teams
and in multi-disciplinary settings.
11. Write effective reports and design documentation, making effective presentations, and giving
and receiving clear instructions.
12. Justify the need for engaging in independent and life-long learning.

9|Page
DOs and DON’Ts in Laboratory:
1. Make entry in the Log Book as soon as you enter the Laboratory.
2. All the students should sit according to their roll numbers starting from their left to right.
3. All the students are supposed to enter the terminal number in the log book.
4. Do not change the terminal on which you are working.
5. All the students are expected to get at least the algorithm of the program/concept to be implement.
6. Strictly follow the instructions given by the teacher/Lab Instructor.

10 | P a g e
LAB INDEX
Design, Develop and implement following using Arduino, Raspberry Pi compiler and
Python language in Linux/Windows environment.

P1 Arduino program to implement blinking of led using IDE


L1: Ilustrate Arduino program to implement blinking led using IDE.
L2: Demonstrate Arduino program to implement blinking led for 10 times using IDE.

P2 Arduino program to implement blinking of alternate leds and arduino program to implement
to fade led
L1:Illustrate Arduino program to implement blinking of alternate leds.
L2:Demonstrate arduino program to implement to fade led

P3 Arduino program to implement blinking of odd and even LEDs scrolling of LEDs
L1:Illustrate Arduino program to implement blinking of odd and even LEDs
L2:Demonstrate scrolling of LEDs

P4 To Control an LED using push button


L1:Illustrate Arduino program to control an LED using push button.
L2: Demonstrate Multiple switches to control multiple LEDs

P5 Arduino program to implement Interactive Traffic System using Push Button


L1: Illustrate Arduino program to implement Interactive Traffic System using Push Button
L2: Demonstrate traffic system without Push button

P6 Arduino program to implement i)To control Servo motor using potentiometer and
ii) To control Servo motor without using potentiometer.
L1: Demonstrate Arduino program To control Servo motor using potentiometer.
L2:Illustrate Arduino program To control Servo motor without using potentiometer

P7 Installation of Raspberry pi operating system and working with basic commands


L1: Demonstrate Installation of Raspberry pi operating system.
L2: : Illustration of working with basic commands using Raspberry Pi

P8 To demonstrate remote logging in raspberry pi


L1: demonstrate remote logging in raspberry pi using SSH
L2: demonstrate remote logging in raspberry pi using Remote desktop

P9 Raspberry pi program to Blink an LED using python.


L1: Illustrate Raspberry pi program to Blink an LED using python.
L2: Demonstrate Raspberry pi program to Blink an LED for 10 times using python

P10 Arduino program to implement IR sensor and PIR sensor for motion detection.
L1: Illustrate Arduino program to implement IR sensor to detect obstacle.
L2: Demonstrate Arduino program to implement PIR sensor for motion detection.

P11 Arduino Program to Control an LED using Bluetooth.


11 | P a g e
L1: Illustrate how to configure Bluetooth device
L2: Demonstrate Arduino Program to Control an LED using Bluetooth
P12 Raspberry pi program to Blink an odd and even LED using python.
L1: Illustrate python program to blink odd and even Leds for one time.
L2: Demonstrate python program to blink odd and even Leds for 5 times with a delay of 5 seconds.

P13 Raspberry pi program to implement Camera module


L1: Demonstrate Raspberry pi program to implement Camera module to capture two images and
video.
L2: Illustrate Raspberry pi program to implement Camera module to capture two images and flip
the images.

P14 Raspberry pi program to read temperature and humidity using DHT22 sensor.
L1: Illustrate Raspberry pi program to read temperature and humidity using DHT22 sensor
L2: Demonstrate Raspberry pi program to read temperature and humidity using DHT22 sensor
infinite times

P15 Arduino program to demonstrate security access using RFID


L1: Illustrate Arduino program to demonstrate security access using RFID
L2: Illustrate Arduino program to demonstrate security access using RFID for different RFID tags

P16 Raspberry pi program to Measure the distance using Ultra Sonic sensor
L1: Illustrate Raspberry pi program to Measure the distance using Ultra Sonic sensor in cm
L2: Demonstrate Raspberry pi program to Measure the distance using Ultra Sonic sensor in inches

P17 Garage Spot Light


L1: Illustrate Raspberry pi program for garage spot light
L2: Demonstrate garage spot light using Raspberry pi

12 | P a g e
Experiment No: 1
Arduino program to implement scrolling LED
This project will blink 6 LEDs, one at a time, in a back and forth formation. This type of circuit was
made famous by the show Knight Rider which featured a car with looping LEDs.

Sl no. Equipment’s Needed


1 Arduino board(1)
2 Power cable(1)
3 Breadboard(1)
4 LED(6)
5 220 Ω Resistor(6)
6 Jumper Wires(7)

Step 1: Connect the Arduino board to your computer using the USB cable.

Step 2: Select the board and serial port as outlined in earlier section.

Step 3: Make the Connection as follows:

Step 4: Open project code to type following program


/*
For Loop Iteration

Demonstrates the use of a for() loop.


13 | P a g e
Lights multiple LEDs in sequence, then in reverse.

The circuit:
* LEDs from pins 2 through 7 to ground

created 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/ForLoop
*/

int timer = 100; // The higher the number, the slower the

timing. void setup() {


// use a for loop to initialize each pin as an output:
for (int thisPin = 2; thisPin < 8; thisPin++)
{ pinMode(thisPin, OUTPUT);
}
}

void loop() {
// loop from the lowest pin to the highest:
for (int thisPin = 2; thisPin < 8; thisPin++)
{
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}

// loop from the highest pin to the lowest:


for (int thisPin = 7; thisPin >= 2; thisPin--)
{
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
}import RPi.GPIO as GPIO
import time

i=0
14 | P a g e
while(i<4):
if(i%2==0):

15 | P a g e
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.OUT)
GPIO.output(18,GPIO.HIGH)
time.sleep(3)
GPIO.output(18,GPIO.LOW)
GPIO.setmode(GPIO.BCM)
GPIO.setup(23,GPIO.OUT)
GPIO.output(23,GPIO.HIGH)
time.sleep(3)
GPIO.output(23,GPIO.LOW)
else: GPIO.cleanup()

GPIO.setmode(GPIO.BCM)
GPIO.setup(22,GPIO.OUT)
GPIO.output(22,GPIO.HIGH)
time.sleep(3)
GPIO.output(22,GPIO.LOW)
GPIO.setmode(GPIO.BCM)
GPIO.setup(25,GPIO.OUT)
GPIO.output(25,GPIO.HIGH)
time.sleep(3)
i+=1 GPIO.output(25,GPIO.LOW)
GPIO.cleanup()

16 | P a g e
Experiment No: 2
Arduino program to demonstrate usage of push button to control the LED

Sl no. Equipment’s Needed


1 Arduino board
2 Power cable
3 Push button Switch
4 Breadboard
5 LED
6 220 Ω Resistor
7 Jumper Wires

Step 1: Connect the Arduino board to your computer using the USB cable.

Step 2: Make the Connection as follows:

Step 3: Open project code – and write the below program


/*
Button

Turns on and off a light emitting diode(LED) connected to digital


pin 13, when pressing a pushbutton attached to pin 2.
17 | P a g e
The circuit:
* LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground

* Note: on most Arduinos there is already an LED on the


board attached to pin 13.

created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe

This example code is in the public

domain.

http://www.arduino.cc/en/Tutorial/Button
*/

// constants won't change. They're used here to


// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton
pin const int ledPin = 13; // the number of the LED pin

// variables will change:


int buttonState = 0; // variable for reading the pushbutton status

void setup() {
// 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:
18 | P a g e
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);

19 | P a g e
}
}
Step 4: Select the board and serial port as outlined in earlier section.

Step 5: Click upload button to send sketch to the Arduino

20 | P a g e
Experiment No: 3
Arduino program to implement traffic control system
In this experiment we are going to make a traffic light with pedestrian light along with button, to
request to cross the road. The Arduino will execute when the button is pressed by changing the state of
light to make the cars stop and allow the pedestrian to cross safely.

Sl no. Equipment’s Needed


1 Arduino board(1)
2 Power cable(1)
3 Breadboard(1)
4 LED(6)
2x Red LED’s
1x Yellow LED
2x Green
LED’s
5 220 Ω Resistor(6)
6 Jumper Wires(7)
7 Tactile Switch

Step 1: Connect the Arduino board to your computer using the USB cable.

Step 2: Select the board and serial port as outlined in earlier section.

Step 3: Make the Connection as follows:

Step 4: Open project code to type following program


21 | P a g e
// Interactive Traffic Lights

int carRed = 12; // To assign the car lights


int carYellow = 11;
int carGreen = 10;
int pedRed = 9; // To assign the pedestrian lights
int pedGreen = 8;
int button = 2; // Tactile button pin
int crossTime = 5000; // time allowed to cross

unsigned long changeTime; // time since button


pressed void setup()
{
pinMode(carRed, OUTPUT);
pinMode(carYellow, OUTPUT);
pinMode(carGreen, OUTPUT);
pinMode(pedRed, OUTPUT);
pinMode(pedGreen, OUTPUT);
pinMode(button, INPUT); // button on pin 2
// turn on the green light
digitalWrite(carGreen, HIGH);
digitalWrite(pedRed, HIGH);
}

void loop()
{
int state = digitalRead(button);
/* check if button is pressed and it is
over 5 seconds since last button press */
if (state == HIGH && (millis() - changeTime) > 5000)
{

22 | P a g e
// Call the function to change the lights
changeLights();
}
}
void changeLights() {
digitalWrite(carGreen, LOW); // green off
digitalWrite(carYellow, HIGH); // yellow on
delay(2000); // wait 2 seconds
digitalWrite(carYellow, LOW); // yellow off
digitalWrite(carRed, HIGH); // red on
delay(1000); // wait 1 second till its safe
digitalWrite(pedRed, LOW); // ped red off
digitalWrite(pedGreen, HIGH); // ped green on
delay(crossTime); // wait for preset time period
// flash the ped green
for (int x=0; x<10; x++) {
digitalWrite(pedGreen, HIGH);
delay(250);
digitalWrite(pedGreen, LOW);
delay(250);
}
// turn ped red on
digitalWrite(pedRed, HIGH);
delay(500);
digitalWrite(carYellow, HIGH); // Yellow will switch on
digitalWrite(carRed, LOW); // red will switch off
delay(1000);
digitalWrite(carGreen, HIGH);
digitalWrite(carYellow, LOW); // Yellow will switch off

// record the time since last change of


lights changeTime = millis();

23 | P a g e
// Retun / Loop
}

24 | P a g e
Experiment No: 4
Arduino program to demonstrate control of servo motor using potentio meter

Sl no. Equipment’s Needed


1 Arduino board
2 Power cable
3 Servo Motor
4 Potentio meter

Step 1: Connect the Arduino board to your computer using the USB cable.

Step 2: Select the board and serial port as outlined in earlier section.

Step 3: Lots of IoT applications with respevt to robotics use servo motor.
Servo motor comes with 3 different arms with 2 variants full arm and half arm and runs
1800. Black pin->Gnd pin of arduino
Red Pin-> +5V of arduino
Orange ->Used to send pulse width modulation, and is connected to pin no 09 from arduino

Potentio meter- is a three-terminal resistor with a sliding or rotating contact that forms an
adjustable voltage divider. If only two terminals are used, one end and the wiper, it acts as a
variable resistor or rheostat.
1st Nob->Gnd pin of arduino
2nd Nob->A0 pin of arduino
3rd Nob->+5v pin of
arduino
Step 4: Make the Connection as follows:

25 | P a g e
Step 5: Open project code to type following program
/*
Controlling a servo position using a potentiometer (variable resistor)
by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

modified on 8 Nov 2013


by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/Knob
*/

#include <Servo.h>

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

int potpin = 0; // analog pin used to connect the potentiometer


int val; // variable to read the value from the analog pin

void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop()
{
val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and
1023)
val = map(val, 0, 1023, 0, 180);// scale it to use it with the servo (value between 0 and
180) myservo.write(val); // sets the servo position according to the scaled value
delay(15);
} // waits for the servo to get there

Introducing the PIR Motion Sensor

The PIR motion sensor is ideal to detect movement. PIR stand for “Passive Infrared”. Basically, the PIR
motion sensor measures infrared light from objects in its field of view.

So, it can detect motion based on changes in infrared light in the environment. It is ideal to detect if a
human has moved in or out of the sensor range.

26 | P a g e
The sensor in the figure above has two built-in potentiometers to adjust the delay time (the potentiometer at
the left) and the sensitivity (the potentiometer at the right).

Pinout

Wiring the PIR motion sensor to an Arduino is pretty straightforward – the sensor has only 3 pins.

Sponsored by deriv.com
Weekend trading opportunity!
Can't find time to trade on weekdays? With Deriv, you can trade Monday to Sunday, even on holidays. Try
it today with a free demo account.
Learn More

 GND – connect to ground


 OUT – connect to an Arduino digital pin
 5V – connect to 5V

Parts required

27 | P a g e
Here’s the required parts for this project

 1x PIR Motion Sensor (HC-SR501)


 Arduino UNO – read Best Arduino Starter Kits
 1x LED
 Jumper Cables
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your
projects at the best price!

Schematics

Assemble all the parts by following the schematics below.

28 | P a g e
Code

Upload the following code.

/*
Arduino with PIR motion sensor
For complete project details, visit: http://RandomNerdTutorials.com/pirsensor
Modified by Rui Santos based on PIR sensor by Limor Fried
*/

int led = 13; // the pin that the LED is atteched to


int sensor = 2; // the pin that the sensor is atteched to
int state = LOW; // by default, no motion detected
int val = 0; // variable to store the sensor status (value)

void setup() {
pinMode(led, OUTPUT); // initalize LED as an output
pinMode(sensor, INPUT); // initialize sensor as an input
Serial.begin(9600); // initialize serial
}

void loop(){
val = digitalRead(sensor); // read sensor value
29 | P a g e
if (val == HIGH) { // check if the sensor is HIGH
digitalWrite(led, HIGH); // turn LED ON
delay(100); // delay 100 milliseconds

if (state == LOW) {
Serial.println("Motion detected!");
state = HIGH; // update variable state to HIGH
}
}
else {
digitalWrite(led, LOW); // turn LED OFF
delay(200); // delay 200 milliseconds

if (state == HIGH){
Serial.println("Motion stopped!");
state = LOW; // update variable state to LOW
}
}
}

Security access using RFID Reader


What is an RFID reader?
RFID tagging is an ID system that uses small radio frequency identification devices for identification and
tracking purposes. An RFID tagging system includes the tag itself, a read/write device, and a host system
application for data collection, processing, and transmission.
In simple words an RFID uses electromagnetic fields to transfer data over short distances. RFID is useful to
identify people, to make transactions, etc…We can use an RFID system to open a door. For example, only
the person with the right information on his card is allowed to enter. An RFID system uses:
>> tags attached to the object to be identified, in this example we have a keychain and an electromagnetic
card. Each tag has his own identification (UID).

>> two-way radio transmitter-receiver, the reader, that sends a signal to the tag and read its response

30 | P a g e
Basic Specifications:
Input voltage: 3.3V
Frequency: 13.56MHz
Now, before typing out the necessary code, you need to download the necessary library for this sensor from
this repository.
Extract the contents from the zip folder "rfid-master" and add this library folder under the existing libraries
of Arduino.
After doing so, restart your ArduinoIDE.
Now, our Arduino is ready to take commands and execute accordingly.
The Arduino Code has been uploaded at the end of this tutorial. Compile the code and eliminate "typo"
errors (if any).
Now, its time to connect our Arduino with the RFID reader. Refer to the PIN wiring below,as well as the
Connection schematic diagram for easy reference.
PinWiring to Arduino Uno
SDA------------------------Digital 10
SCK------------------------Digital 13
MOSI----------------------Digital 11
MISO----------------------Digital 12
IRQ------------------------unconnected
GND-----------------------GND
RST------------------------Digital 9
3.3V------------------------3.3V (DO NOT CONNECT TO 5V)
Reading data from an RFID tag
After having the circuit ready, go to File > Examples > MFRC522 > DumpInfo and upload the code. This
code will be available in Arduino IDE (after installing the RFID library).
Then, open the serial monitor. You should see something like the figure below:

31 | P a g e
Approximate the RFID card or the keychain to the reader. Let the reader and the tag closer until all the
information is displayed.

This is the information that you can read from the card, including the card UID that is highlighted in
yellow. The information is stored in the memory that is divided into segments and blocks as you can see in
the previous picture.
You have 1024 bytes of data storage divided into 16 sectors and each sector is protected by two different
keys, A and B.
32 | P a g e
Write down your UID card because you’ll need it later. Upload the Arduino code that has been suffixed
here.
Demonstration
Approximate the card you’ve chosen to give access and you’ll see:

If you approximate another tag with another UID, the denial message will show up

/*
*
* All the resources for this project: https://www.hackster.io/Aritro
* Modified by Aritro Mukherjee
*
*
*/

#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.

void setup()
{
Serial.begin(115200); // Initiate a serial communication
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
Serial.println("Approximate your card to the reader...");
Serial.println();
33 | P a g e
}
void loop()
{
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
//Show UID on serial monitor
Serial.print("UID tag :");
String content= "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println();
Serial.print("Message : ");
content.toUpperCase();
if (content.substring(1) == "BD 31 15 2B") //change here the UID of the card/cards that you
want to give access
{
Serial.println("Authorized access");
Serial.println();
delay(3000);
}

else {
Serial.println(" Access denied");
delay(3000);
}
}

Website Link: https://create.arduino.cc/projecthub/Aritro/security-access-using-rfid-reader-f7c746

34 | P a g e
RC522 RFID Reader Module

RC522 is a Multi-communication RFID Module for Arduino and Microcontrollers. The RC522 is known as
MFRC-522 due to its NFX semiconductor microcontroller. The module allows the developers to interface
it with any other SPI, I2C, and UART based microcontrollers. The RC522 module works on 13.56 MHz
frequency and it can act as a reader and write for UID/RFID cards. The RFID cards communicate with the
module at a short distance with radio frequency due to the mutual induction technique. In most of the
security and commercial products, the module is effective because the errors and issues with RFID Tags are
detectable by it.

In this module, there are only two kinds of pins. So, the first one is power and the second one is the
communication pins. Therefore, the device may have its microcontroller chip on itself but it only makes it
to works as an RFID. The onboard microcontroller won’t make the module a stand-alone device.
RC522 Pinout Diagram
All the pins of MFRC/RC522 RFID card Reader are:

35 | P a g e
PINS DETAILS

The power pins are VCC. In some versions of RC522, this pin is denoted
Pin 1 VCC
by 3V3 on the module instead of VCC.

It’s a reset pin for the module. Therefore, it uses to reset the device in
Pin 2 RST
case of an error on when a device isn’t giving any response.

Ground helps to make the common ground with every external device,
Pin 3 Ground
e.g. power Supply, Microcontroller or Arduino.
Power/Reset Pins
SPI and UART Communication Pins
PINS DETAILS

The device can go into sleep mode to save power. So, the IRQ helps to
Pin 4 IRQ
wake it.

This pin connects with the Arduino/Microcontrollers for SPI


communication. However, it transfers the data from module to Arduino.
SCL
Pin 5 MISO The MISO pin is also useable for other functions instead of SPI.
TX
It can also interface with I2C for clock pulse and UART Serial for Data
transfer from the module.

Pin 6 MOSI MOSI is the data input pin for RFID module in SPI communication

Pin 7 SCK The SCK pins help to send the clock pulse in SPI communications.

The SS pin is a chip enable pin in SPI communication. Therefore, it


receives the signal when Master (Arduino) must perform SPI
communication.
SDA
Pin 8 SS The SS pin in RFID is useable as a second pin (SDA) for I2C
RX
communication.

It also receives data during UART communication.

The RFID Cards are useable from both sides of the module at max 5cm.
The only 3.3V is required to activate the device.
Its auto-sleep mode makes it less power consumption module.
The module has three kinds of communications (UART, SPI, I2C). Therefore, it is useable with almost
every microcontroller or device in the market.
36 | P a g e
The RFID cards and reader (RC522) can transfer data up to 10Mb/s.
Alternative Option
PN532
SM130
RFID RDM630 Module
RC522 RFID Module Applications
RFID has most of the usage as a security device.
In some companies, the devices use with shopping items.
Some airports also start using RFID to identify and keep track of bags and other items.
The attendance or Parking system also uses RFID to keep the system secure.
How to Use RC522 RFID Reader
The RC 522 usage is simple and complex at the same time. Even its library has too much complexity to
understand. First, understand that library examples and documentation are all for SPI but the same library is
useable for other UART and I2C Serial communication.
Arduino Interfacing Example
To use the RC522 with Arduino, which is the most popular board with this module, the following circuit
needs to follow. So, here’s the circuit diagram:

37 | P a g e
38 | P a g e
Almost every board has specific pins for SPI communication. In SPI pins only SS pin is changeable others
need to be according to the device. Therefore, in the above circuit diagram, the RFID connects with
Arduino UNO through its specific SPI pins.
Programming RC522 RFID Reader
After designing the circuit, the following two libraries are required:
#include <SPI.h>

#include <MFRC522.h>

The MFRC522 library helps to decode and encode the incoming data from the RFID module and SPI helps
to establish the SPI communication. These two libraries are dependent on each other. After initializing the
libraries, the most important thing is to describe the reset and slave select (SS) pin through the following
command:
MFRC522 mfrc522(SS_PIN, RST_PIN);

In the above command change the SS_PIN with Slave select and RST_PIN with reset pin of the RFID. So,
after the above commands, the initialization of the circuit will complete. Now the developers must describe
the SPI initialization and Module initialization which needs to be done by the following two objects.
SPI.begin();

mfrc522.PCD_Init();

Till these two objects, the communication and initialization of modules will complete but the above part is a
little complex for some developers. The RC522 library offers multiple commands but to use those
commands/objects every developer must understand some features.
Card Detect Code part
In the RC522 the RFID cards are readable but whenever a new card is present near the module, it is
readable unless it isn’t present in the RC522. Here’s the question arise How a card can store in the module?
Whenever a card is read by the module it stores itself unless a default data which is “FFFFFFFFFFFFh”.
The following command will make the default key to the module.
MFRC522::MIFARE_Key key;

for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

MIFARE_Key will automatically able to access the module keys and the loop will help to store the default
ones.
Reading Card Value
The detection of the card is simple and easy whenever the default value is according to its factory setting.
Once the values are set to default the following commands will able to detect the new card
mfrc522.PICC_IsNewCardPresent()

mfrc522.PICC_ReadCardSerial()

39 | P a g e
The first command is for card detection and the next command is to read the data. Sometimes the card can
be present on the module but it has no data. Therefore, the second command ReadCardSerial will help to
detect that. After that use to the following command to see the dumb the data so it can decrypt:
mfrc522.PICC_DumpDetailsToSerial(&(mfrc522.uid));

mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

Use the first one for decimal and the second one for HEX. It helps store and read the data code. Always
remember the device can read and dump/decrypt the data of a single card at a time. Therefore, During
Dumping the device won’t be able to read the new card.
Reading Status of RFID Card
In RC522 the RFID cards status is readable. If somehow the authentication of the card gets failed or
unreadable then the program can tell the microcontroller so it doesn’t get stuck. Therefore, the status may
not look reliable but in some cases, it gives the developers to run specific instructions to remove the error.
So, the following command will help to initialize the status:
MFRC522::StatusCode status //To read the status

mfrc522.PCD_Authenticate //To get the authentication

mfrc522.MIFARE_Read //To read the card

The above commands are just the main symbols but the rest of the commands will depend on the data.
Stop RFID Card Reading
In RC522 once the card read commands has sent to the card, it will never stop until a stop command is sent.
Even to stop the encryption the commands need to send from the microcontroller. Therefore, the stops
commands for both functions will be:
mfrc522.PICC_HaltA(); // Stop reading

mfrc522.PCD_StopCrypto1(); // Stop encryption on PCD

The above commands are just simple reading commands with RC522 but now there are a bunch of other
operations that can be done by RC522. Therefore, the following manual can help:

#include<SPI.h>
#include<RFID.h>
#define SS_PIN 10
#define RST_PIN 9

RFID rfid(SS_PIN,RST_PIN);

String rfidCard;

Void setup(){
40 | P a g e
Serial.begin(9600);
Serial.println(“Starting the RFID reader”);
SPI.begin();
rfid.init();
}

void loop(){
if(rfid.isCard()){
if(rfid.readCardSerial()){
rfidCard= String(rfid.serNum[0])+” “+String(rfid.serNum[1])+” ” String(rfid.serNum[2])+”
“+String(rfid.serNum[3]);

Serial.println(rfidCard);
}

rfid.halt();
}
if(rfidCard==”119 38 185 95”){
Serial.println(“Access Allowed”);
}
else{
Serial.println(“Access Denied”);
}

41 | P a g e
Arduino and Bluetooth Module to control LED through Android
App
Let's build an IoT project using Arduino (Arduino UNO) and Bluetooth Module HC-05 to control a LED
light. In this project, we will use an Android smartphone to send Bluetooth signal to the Bluetooth module.

Hardware Requirements

1. Arduino UNO board


2. USB cable for connecter Arduino UNO
3. Bluetooth Module HC-05
4. Jumper wires male to female
5. LED
6. AC 220v/120v home appliances or 9v Hi-Walt Battery

Software requirements

1. Arduino software
2. Android Studio

The Working principle of Arduino-Bluetooth Module

In this project, there are three main components used; an Android Smartphone, Bluetooth transceiver, and
an Arduino.

The Android app is built to send serial data to the Bluetooth Module HC-05 by pressing ON button. As
Bluetooth Module HC-05 works on serial communication. It receives the data from the app and sends it
through TX pin of Bluetooth module to RX pin of Arduino. The uploaded code inside Arduino checks the
data received. If the receive data is 1, the LED turns ON, and if the received data is 0 the LED turns OFF.

Digital circuit diagram

Bluetooth Module HC-05 Arduino UNO

TX --------------------------------> RX (Pin 0)
RX --------------------------------> TX (Pin 1)
42 | P a g e
VCC --------------------------------> 5v
GND --------------------------------> GND

LED Pin UNO


Anode-------------------------------->D13 GND
Cathode --------------------------------> GND

Write a program for Arduino UNO board, if received data is equal to 1, LED turns on and if data is equal to
0, LED turns OFF.

1. char data = 0; //Variable for storing received data


2. void setup()
3. {
4. Serial.begin(9600); //Sets the baud for serial data transmission
5. pinMode(13, OUTPUT); //Sets digital pin 13 as output pin for LED
6. }
7. void loop()
8. {
9. if(Serial.available() > 0) // Send data only when you receive data:
10. {
43 | P a g e
11. data = Serial.read(); //Read the incoming data and store it into variable data
12. Serial.print(data); //Print Value inside data in Serial monitor
13. if(data == '1') // Checks whether value of data is equal to 1
14. digitalWrite(13, HIGH); //If value is 1 then LED turns ON
15. else if(data == '0') // Checks whether value of data is equal to 0
16. digitalWrite(13, LOW); //If value is 0 then LED turns OFF
17. }
18. }

Save your program and compile it.

44 | P a g e
Connect your Arduino device to your Laptop (or Monitor) via Arduino UNO USB cable. Remove all the
other connections with Arduino UNO device such as Bluetooth Module and LED while uploading the
program in Arduino UNO.

After compiling the code, upload it in Arduino UNO device. Before uploading the code in Arduino, UNO
device makes sure that your Arduino serial port is selected otherwise, it generates an error message " Serial
port not selected".

To select your serial port, open Device Manager > Ports >Arduino Uno, and then upload your code.

45 | P a g e
Download the Android app's .apk file and install it on your Android smartphone. Click Here to Download

Step to connect with Android app with Bluetooth Module

1. Open Bluetooth connecter app and allow turning on Bluetooth of the device.

46 | P a g e
2. Search for Bluetooth device for making the pair.

47 | P a g e
3. To pair with Bluetooth HC-05 module, enter a pin 0000 or 1234.

48 | P a g e
4. Select pair device HC-05 to connect with Android app.

49 | P a g e
5. Control LED device.

50 | P a g e
While clicking "ON" button it sends data 1 to Bluetooth module and this data is transmitted from the
Bluetooth module to Arduino device and it turns ON the LED. When clicking "OFF", Android app sends
data 0 to Bluetooth module, and this data is transmitted from the Bluetooth module to Arduino and it turns
OFF the LED.

51 | P a g e
52 | P a g e
Experiment No: 5
Installation of Raspberry pi software
Sl Equipment’s Needed
no.
1 Raspberry Pi
2 VGA cable
3 Power Cable

Introduction: The Raspberry Pi is a fully-fledged mini computer, capable of doing whatever you
might do with a computer. It comes with 4x USB, HDMI, LAN, built-in Bluetooth/WiFi support,
1GB RAM, 1.2GHz quad-core ARM CPU, 40 GPIO (General Purpose Input Output) pins, audio
and
composite video output, and more.

One can use Raspberry Pis as home security cameras, server monitoring devices, cheap headless
machines (basically running low-weight scripts 24/7 with a low cost-to-me)... others have used them
for media centers and even for voice-enabled IoT devices. The possibilities are endless, but first we
need to get acquainted!

Make sure that, if you do get a case, it has openings for the GPIO pins to be connected, you will also
need a 1000mA+ mini usb power supply and at least an 8GB micro SD card, but I would suggest a
16 GB micro SD card or greater.

You will also want to have a spare monitor (HDMI), keyboard, and mouse handy to make things
easier when first setting up. You wont will eventually be able to control your Pi remotely, so you

53 | P a g e
wont always need a separate keyboard, mouse, and monitor. If you don't have a monitor with HDMI
input, you can buy something like an HDMI to DVI converter.

If you're using an older version board, please see what you might need to change, for example, the
older Rasbperry Pis take a full-sized SD card, but the latest model requires a micro SD card. Also,
the Raspberry Pi 3 Model B has built-in wifi, where the older models will require a wifi dongle.

A typical Raspberry Pi shopping list, assuming you have a mouse, keyboard, and HDMI monitor
that you can use temporarily while setting up is:

1. Raspberry Pi -
2. 1000mA+ mini usb power supply -
3. 16 GB micro SD card –

Additionally, if you plan to join us on the initial GPIO (General Purpose Input Output pins)
tutorials, you will also want to pick up:

1. 10 x Male-to-Female jumper wires (you should consider just buying a bunch of these so you
have plenty in the future).
2. 1 x Breadboard (You may also want multiples of these)
3. 3 x LED light (...more wouldn't hurt)
4. ~6 x Resistors (between 300 and 1K Ohm). You will need at least 1K and 2K ohms for the
distance sensor, then ~300-1K resistance per LED bulb. You probably should just buy a kit,
they're super cheap.
5. 1 x HC-SR04 Ultrasonic Distance Sensor (...you know what I'm going to say...think about
maybe a few.)
6. 1 x Raspberry Pi camera module. You only need one of these!

For the jumpers, breadboard, and leds, you could also just buy a kit, something like: this GPIO
starter kit.

There are also a few ways to install and use an operating system on the Raspberry Pi. The most
user- friendly method is to use the NOOBS (New Out of Box Software) installer. If you're
comfortable enough, you can just simply download the operating system ISO, format the SD card,
mount the ISO, and boot the Pi. If that sounds like gibberish to you, then follow along with the
NOOBS installation option.

While we're working with the SD card, let's go ahead and Download NOOBS, which is just over 1GB.

First, we must format the SD card. If you are on Windows, you can use SD Formatter. Mac users
can also use SD Formatter, but they have a built in formatter, and Linux users can use GParted.
Whatever

54 | P a g e
the case, you need to format the SD card, do not do a "quick format" and do make sure you have the
"resize" option on. Using SDFormatter on Windows, and chosing options:

This should go without saying, but do make sure you're formatting the right drive. This will format
any flash drive, in alphabetical order. If you had something plugged in already, like your favorite
USB drive, and forgot about it, that'd likely be the default choice to format, and then you'd spend all
afternoon trying to recover your data rather than enjoying playing with your Raspberry Pi.

Once you're done, great. Now, assuming you've downloaded the NOOBS package, let's go ahead
and extract that. Now, we want to copy all these NOOBS contents to our SD Card. Do not drag the
directory, but rather the contents:

55 | P a g e
While that's transferring, let's talk about a few things on the actual Raspberry Pi board:

The GPIO (General Purpose Input/Output) pins are underlined in blue. We can use these to control
peripheral devices like motors, servos, and more. Circled in red is the micro usb power input for the
board. In orange, the HDMI output port. The yellow is where you can plug in the Raspberry Pi
camera module. The grey circle has the USB ports. This is obviously not everything, but these are
the main things to note.

56 | P a g e
Once everything is transferred to the micro SD card, you can put it in the Raspberry Pi. The slot is on
the bottom side of the board, circled in yellow here:

Once you've got the SD card plugged in, go ahead and plug in your keyboard, mouse, and HDMI
cable to your monitor. Finally, plug in the power, and this will start up the Raspberry Pi. Once fully
loaded, you should land on the following screen:

Now you can choose the operating system. In my case, the only option is Raspbian, so I will check
that box, then click "install."

57 | P a g e
Let the process go, this will take a while, something like 20-30 minutes or so.

58 | P a g e
Once that's done, hit okay and the device should reboot to desktop. While on the desktop, wait for a
moment for wifi to start up and find available connections. Connect to your wifi network if possible.
You can also plug directly in with an ethernet cable if you don't have wifi. You can also just
continue interacting directly with the Raspberry Pi with the mouse and keyboard connected to it if
you like,
but I prefer to access it remotely.

Once we've connected to our network, we'd like to actually interface with the Pi. First, we want to
update. Open a terminal by either right clicking on the desktop and opening terminal that way, or by
doing control+alt+t. Now, in the terminal, do:
59 | P a g e
60 | P a g e
$sudo apt-get update
and then
$ sudo apt-get upgrade
You do not type the $ sign, it's there to denote when you're typing something in the command line.
The upgrade might take a minute. While we wait, your Raspberry Pi's default credentials
are: username: pi password: raspberry. For some reason, the apt-get upgrade for me was taking
absurdly long. You need to be connected to your network, and have internet access, so make sure
you have those things first before doing this, but I still was having trouble. I was able to solve this
by doing:

$ sudo nano /etc/apt/sources.list

Then replace everything here with:

deb http://archive.raspbian.org/raspbian jessie main contrib non-free


deb-src http://archive.raspbian.org/raspbian jessie main contrib non-free

control+x, y, enter

$ sudo apt-get dist-upgrade

$ sudo apt-get update

$ sudo apt-get upgrade

To save some space you can also do: $ sudo apt-get purge wolfram-engine and then $ sudo apt-get
autoremove. This alone freed up almost 700mb of space for me.

This is going to conclude the first part of this tutorial series. In the next tutorial, we're going to cover
how we can remotely access our Raspberry Pi.

61 | P a g e
Experiment No: 6
Working basic commands on Raspberry pi

Sl no. Equipment’s Needed


1 Raspberry Pi
2 VGA cable

Introduction:

In this Experiment, we're going to have a quick crash course for using the terminal. Most of our
interactions with the Raspberry Pi will be via shell, since this is the simplest and most
lightweight to keep your Pi accessible.

To begin, let's assume you've just logged in. The location that you will usually log in to will be
the root directory for your user. In this case, our user is "pi," so we log in to /home/pi. We can
confirm this by using the command: pwd (print working directory)

pi@raspberrypi:~ $ pwd
/home/pi

Often times, to denote the terminal, you will see people use the $ sign. Since, most of the time,
people wont be using the same usernames and hostnames, this is the standard to denote that
we're operating in the terminal, so, instead, if you googled how you get your current directory in
linux, you'd probably see: $ pwd. This doesn't mean that you should actually type the $ sign, it's
just meant to denote that you're in the terminal.

Next, many times you might see a "permission denied" error when trying to do something. For
many tasks, you need to act as the super user, like the administrator account. The command to
act as the super user is sudo, which is short for "super user do." An example of this was when we
wanted to update and upgrade, we used sudo. Be careful when using sudo to create files...etc.
The creator is the owner, so if you use sudo to create the file, it can only be further edited by the
super user. Many files will require sudo to edit, however.

62 | P a g e
To move around the system, you can use cd, which stands for "change directory." At any time,
we can use ~ to reference the current user's home. In our case ~ is short for /home/pi. We can
change directories into there with $ cd ~.

We were already there, but, just in case you weren't, you are now!

Next, to discover the contents of the directory you are in, you can use ls to list directory contents:

$ ls

pi@raspberrypi:~ $ ls
Desktop Documents Downloads Music Pictures Public python_games Templa

It wont always be the case, but often you will see different colors for different types of files. In
our case, we just have directories, so they are all the same color.

Let's assume we want to make our own directory, to do this, we can use the mkdir command,
short for make dir.

$ mkdir example

We can list the contents again:

$ ls

Seeing our new directory:

pi@raspberrypi:~ $ ls
Desktop Documents Downloads example Music Pictures Public python_games

Then we can change directories into our new directory:

$ cd example

Maybe we don't want to be here. We can move backwards with: $ cd ..

pi@raspberrypi:~/example $ cd ..

63 | P a g e
pi@raspberrypi:~ $

We can also move back a few directories at a time: $cd ../../

pi@raspberrypi:~ $ cd ../../
pi@raspberrypi:/ $ ls
bin boot debian-binary dev etc home lib lost+found man media mnt opt proc root run
sbin srv sys tmp usr var

Let's go into our example dir now:

$ cd example

Next, we can create a simple file with any of the built in editors. There are many to choose from,
I think nano is the easiest, so I will use that:

$ nano test.py

Nano can be used to both create or edit files. If the file doesn't yet exist, it will be created. If it
does exist, it will allow you to save a new one.

Let's just add: print("hi") to this file. When done, we can exit with control+x, then press yto save,
and then enter to keep the name.

To run this file, we can do: $ python test.py

pi@raspberrypi:~/example $ python test.py


hi

Next, let's make another directory:

64 | P a g e
$ mkdir downloads

$ cd downloads

To demonstrate remote logging in raspberry pi

Sl Equipment’s Needed
no.
1 Raspberry Pi
2 VGA cable

Introduction :

In this Experiment, we're going to cover how we can remotely access our Raspberry Pi, both
with SSH and with a remote desktop client. We want to eventually be able to remotely access
our Raspberry Pi because much of the "value" of the Raspberry Pi is its size, and that it can
be put in a variety of places that we might not want to have a keyboard, mouse, and monitor
attached to it at all times and we probably don't want to have to carry over all of this stuff
when we do want to access it.

First, let's connect via shell (SSH). Open the terminal on the Raspberry Pi (control+alt+t), and
type ifconfig. If you're connected via wifi, then go under the wlan section, and look for your
inet address. This will be your local ip, something like 192.168.XX.XXX. We can use this to
connect via SSH (user: pi, pass: raspberry), BUT we first have to enable the SSH server. To
do this, type sudo raspi-config. Here, we can do quite a few things, but let's head into
option #5 interfacing options, next choose the 2nd option forSSH and enable the server. Once
this is done, you can shell into the Raspberry Pi.

On Windows, you will need to use an SSH client. But the recommended is PuTTY . Once
downloaded, you can open PuTTy, fill in "host name" field with your Pi's local ip, hit enter,
and then you will be asked for a username and password.

When successful, you should have something like:

65 | P a g e
This is identical to the terminal you accessed earlier from the Pi's desktop.

Now, sometimes, you might really want to get access to the desktop instead of just the
terminal. To do this, you need the "host" to have remote desktop capabilities, as well as
whatever remote PC you attempt to use to access it. First, let's deal with the Raspberry Pi.
We're going to install xrdp.

sudo apt-get remove xrdp vnc4server tightvncserver

seudo apt-get update

sudo apt-get install xrdp

sudo apt-get install tightvncserver

Now let's deal with the computer from which you plan to connect your Raspberry Pi.

For Mac and Windows, you can use the Microsoft application called Remote Desktop. On
linux, you can use grdesktop (sudo apt-get install grdesktop). All three of these examples are
going to act the same way. Run them, fill in the IP address of the Raspberry pi, the username,
the password, and connect!

When done, you should have something like:

66 | P a g e
With the SSH server turned on, you will likely be seeing warnings every time you log in that
your password is still the default password. The SSH server is turned off by default because,
as the Pi has gained popularity, people who might not realize the security risk are using it in
places like their homes and businesses. All it takes is someone to connect to your wifi, scan
for other local ips, and try them all with default usernames and passwords for various devices,
like the Raspberry Pi, and boom they're in. If you want to change your password, you can do
sudo raspi- config, and it's the first option.

67 | P a g e
Experiment No: 7
Raspberry pi program to implement blinking LED

Sl no. Equipment’s Needed


1 Raspberry Pi
2 VGA cable
3 Power Cable
4 Jumper Cables

Step 1: Understanding of Raspberry pi Pin out diagram and Bread board connections

68 | P a g e
Step 2: Make the connections as follows

69 | P a g e
Step 3: Write the python program to implement blinking LED
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.HIGH)

time.sleep(3) GPIO.output(18,

GPIO.LOW)
GPIO.cleanup()

70 | P a g e
Experiment No: 8
Raspberry pi-camera module
Sl Equipment’s Needed
no.
1 Raspberry Pi
2 Raspberry Pi Camera Module
3 VGA cable
4 Power Cable

Step 1: Open the notch “Connect camera” module to raspberry pi Blue should be facing
towards Ethernet port.

Step 2: pi@raspberrypi:~ $cd Desktop/

Step 3: Enable Camera


pi@raspberrypi:~ /Desktop$ sudo raspi-config
Interfacing option Enable camera

71 | P a g e
Yes to enable, and then go ahead and reboot:

72 | P a g e
Step4: Let's open the terminal next (control+alt+t) and do a $ sudo apt-get install python3-
picamera. You will likely find that you already have it, but we want to be sure.

Now, in our cameraexample.py file:


Step 5: Write the Phython program
pi@raspberrypi:~ /Desktop$ nano cameraexample.py

import picamera
import time

camera = picamera.PiCamera()
camera.capture('example.jpg')

camera.vflip = True

camera.capture('example2.jpg')

camera.start_recording('examplevid.h264')
time.sleep(5)
camera.stop_recording()

Step 6: Command to view recorded video


$ omxplayer examplevid.h264.

73 | P a g e
Experiment No: 09
Raspberry pi program to implement temperature sensor

Sl no. Equipment’s Needed


1 Raspberry Pi Model 3
2 Raspberry Pi Camera Module
3 Digital humidity and temperature sensor-(DHT 22)
4 VGA cable
5 Power Cable

Step Raspberry Pi DHT11 Humidity and Temperature Sensor Interface


No.

1 Raspberry Pi DHT11 Humidity and Temperature Sensor Interface

In this project, we will learn about DHT11 Humidity and Temperature Sensor and how the
Raspberry Pi DHT11 Humidity Sensor interface works. By Interfacing DHT11 Temperature
and Humidity Sensor with Raspberry Pi, you can implement a basic IoT Project like a simple
Weather Station.

Overview

DHT11 is a Digital Sensor consisting of two different sensors in a single package. The sensor
contains an NTC (Negative Temperature Coefficient) Temperature Sensor, a Resistive-type
Humidity Sensor and an 8-bit Microcontroller to convert the analog signals from these
sensors and produce a Digital Output.

74 | P a g e
I have already worked with the DHT11 Sensor in my DHT11 Humidity Sensor on
ArduinoProject. In that project, I have mentioned the Pin Configuration of the DHT11
Sensor, how to interface it with a Microcontroller and how the digital Output from the
DHT11 Sensor can be decoded.

So, I suggest you to refer to that project once for more information on DHT11 Humidity and
Temperature Sensor. I’ll explain a few thing which I have missed in the Arduino Project.

We know that the output from the DHT11 Sensor is Digital. But how exactly we can read this
digital data?

Reading Digital Output from DHT11

DHT11 uses a Single bus data format for communication. Only a single data line between an
MCU like Arduino or Raspberry Pi and the DHT11 Sensor is sufficient for exchange of
information.

In this setup, the Microcontroller acts as a Master and the DHT11 Sensor acts as a Slave. The
Data OUT of the DHT11 Sensor is in open-drain configuration and hence it must always be
pulled HIGH with the help of a 5.1KΩ Resistor.

This pull-up will ensure that the status of the Data is HIGH when the Master doesn’t request
the data (DHT11 will not send the data unless requested by the Master).

Now, we will the how the data is transmitted and the data format of the DHT11 Sensor.
Whenever the Microcontroller wants to acquire information from DHT11 Sensor, the pin of
the

75 | P a g e
Microcontroller is configured as OUTPUT and it will make the Data Line low for a minimum
time of 18ms and releases the line. After this, the Microcontroller pin is made as INPUT.

The data pin of the DHT11 Sensor, which is an INPUT pin, reads the LOW made by the
Microcontroller and acts as an OUTPUT pin and sends a response of LOW signal on the data
line for about 80µs and then pulls-up the line for another 80µs.

After this, the DHT11 Sensor sends a 40 bit data with Logic ‘0’ being a combination of 50µs
of LOW and 26 to 28µs of HIGH and Logic ‘1’ being 50µs of LOW and 70 to 80µs of HIGH.

After transmitting 40 bits of data, the DHT11 Data Pin stays LOW for another 50µs and
finally changes its state to input to accept the request from the Microcontroller.

NOTE: We have implemented this logic while programming the Arduino. But for Raspberry
Pi, we used a library that takes care of all these things.

Raspberry Pi DTH11 Humidity and Temperature Sensor Interface

By interfacing the DHT11 Sensor with Raspberry Pi, you can build your own IoT Weather
Station. All you need to implement such IoT Weather is a Raspberry Pi, a DHT11 Humidity
and Temperature Sensor and a Computer with Internet Connectivity.

2 Circuit Diagram

The following is the circuit diagram of the DHT11 and Raspberry Pi Interface.

76 | P a g e
3 Components Required

 Raspberry Pi 3 Model B
 DHT11 Temperature and Humidity Sensor
 Connecting Wires
 Power Supply
 Computer

4 Circuit Design

If you observe the circuit diagram, there is not a lot of stuff going on with respect to the
connections. All you need to do is to connect the VCC and GND pins of the DHT11 Sensor to
+5V and GND of Raspberry Pi and then connect the Data OUT of the Sensor to the GPIO4 i.e.
Physical Pin 7 of the Raspberry Pi.

5 Installing DTH11 Library

Since we are using a library called Adafruit_DHT provided by Adafruit for this project, we
need to first install this library into Raspberry Pi.

77 | P a g e
First step is to download the library from GitHub. But before this, I have created a folder
called ‘library’ on the desktop of the Raspberry Pi to place the downloaded files. You don’t
have to do that.

Now, enter the following command to download the files related to the Adafruit_DHT

library. git clone https://github.com/adafruit/Adafruit_Python_DHT.git

All the contents will be downloaded to a folder called ‘Adafruit_Python_DHT’. Open this
directory using cd Adafruit_Python_DHT. To see the contents of this folder, use ‘ls’
command.

In that folder, there is file called ‘setup.py’. We need to install this file using the following
command.

sudo python setup.py install

Code

As we are using the library Adafruit_DHT for this project, there is nothing much to do in the
Python Programming part. All you need to do is to invoke the library with the Sensor and
GPIO Pin and print the values of Temperature and Humidity.

import sys
import Adafruit_DHT
import time

78 | P a g e
79 | P a g e
while True:

humidity, temperature = Adafruit_DHT.read_retry(22, 4)

print 'Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature, humidity)


time.sleep(1)

view rawRaspberry_Pi_DHT_11.py hosted with by GitHub


Working

Make the connections as per the circuit diagram and install the library. Use the above python
program to see the results.

80 | P a g e
Experiment No: 10
Demonstration of Raspberry Pi with distance sensor (ultrasonic sensor HC-SR04)

Sl no. Equipment’s Needed


1 Raspberry Pi Model 3
2 Raspberry Pi ultrasonic sensor HC-SR04
3 VGA cable
4 Power Cable

Step 1: Make the connections as follows

Step 2: Open the terminal CTRL+ALT+T


and type $ Sudo nano Filename.py to open empty notepad
Step 3: Write the python program to implement use of raspberry pi with temperature sensor

import RPi.GPIO as GPIO


81 | P a g e
import time

GPIO.setmode(GPIO.BCM)

TRIG = 4
ECHO = 18

GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)

while GPIO.input(ECHO) == False:


start = time.time()

while GPIO.input(ECHO) == True:


end = time.time()

sig_time = end-start

#CM:
distance = sig_time / 0.000058

#inches:
#distance = sig_time / 0.000148

print('Distance: {} centimeters'.format(distance))

GPIO.cleanup()

Step 3: Compile the program using command $ Python Filename.py


And verify the output

82 | P a g e
Experiment No: 11
Raspberry pi program to implement Garage spot light.

Sl no. Equipment’s Needed


1 Raspberry Pi Model 3
2 Raspberry Pi ultrasonic sensor HC-SR04
3 VGA cable
4 Power Cable
5 Jumper cables- Male to Female
6 3 different colored LEDs-RGB

Step 1: The idea of a garage stop-light is to show green when you have plenty of room to pull
your car forward in your garage, and then turn yellow as you approach the fully forward
position, and then red when you should stop. We're going to build this system with our
Raspberry Pi, and use some distances that we can easily test.

Step 2: To start, we'll just leave the distance sensor hooked up as is, but now we're going to add
the light circuits, only this time we have three. Here's how I set mine up:

83 | P a g e
Step 3: Same as in the previous tutorials, the filled in boxes are the jumper wires by color, and
the boxes themselves are the pins on the pi or the openings on the breadboard. The filled
in blue blobs are the resistors, the leds are labeled. Black boxes are ground.

Once you have everything hooked up and you're confident you've not messed anything
up, you can power on your Raspberry Pi. You may want to re-reference the Adafruit
image shared earlier:

84 | P a g e
Step 4: Garage spot light script

import RPi.GPIO as GPIO


import time

GPIO.setwarnings(False)
# doing this first, since we're using a while True.
GPIO.cleanup()

GPIO.setmode(GPIO.BCM)
TRIG = 4
ECHO = 18

85 | P a g e
86 | P a g e
GREEN = 17
YELLOW = 27
RED = 22

GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

GPIO.setup(GREEN,GPIO.OUT)
GPIO.setup(YELLOW,GPIO.OUT)
GPIO.setup(RED,GPIO.OUT)

def green_light():
GPIO.output(GREEN, GPIO.HIGH)
GPIO.output(YELLOW, GPIO.LOW)
GPIO.output(RED, GPIO.LOW)

def yellow_light():
GPIO.output(GREEN, GPIO.LOW)
GPIO.output(YELLOW, GPIO.HIGH)
GPIO.output(RED, GPIO.LOW)

def red_light():
GPIO.output(GREEN, GPIO.LOW)
GPIO.output(YELLOW, GPIO.LOW)
GPIO.output(RED, GPIO.HIGH)

def get_distance():

87 | P a g e
88 | P a g e
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)

while GPIO.input(ECHO) == False:


start = time.time()

while GPIO.input(ECHO) == True:


end = time.time()

sig_time = end-start

#CM:
distance = sig_time / 0.000058

#inches:
#distance = sig_time / 0.000148
#print('Distance: {} centimeters'.format(distance))

return distance

while True:
distance = get_distance()
time.sleep(0.05)
print(distance)

if distance >= 30:


green_light()
elif 30 > distance > 10:
yellow_light()
elif distance <= 10:

89 | P a g e
90 | P a g e
red_light()

Output

Hand getting close:

91 | P a g e
92 | P a g e

You might also like