IoT Lab Manual
IoT Lab Manual
For
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.
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.
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.
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
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
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.
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
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
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.
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.
The circuit:
* LEDs from pins 2 through 7 to ground
created 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
http://www.arduino.cc/en/Tutorial/ForLoop
*/
int timer = 100; // The higher the number, the slower the
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);
}
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
Step 1: Connect the Arduino board to your computer using the USB cable.
created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe
domain.
http://www.arduino.cc/en/Tutorial/Button
*/
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);
19 | P a g e
}
}
Step 4: Select the board and serial port as outlined in earlier section.
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.
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.
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
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
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>
#include <Servo.h>
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
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
Parts required
27 | P a g e
Here’s the required parts for this project
Schematics
28 | P a g e
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
*/
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
}
}
}
>> 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);
}
}
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.
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 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;
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
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
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
Software requirements
1. Arduino software
2. Android Studio
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.
TX --------------------------------> RX (Pin 0)
RX --------------------------------> TX (Pin 1)
42 | P a g e
VCC --------------------------------> 5v
GND --------------------------------> 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.
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
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:
control+x, y, enter
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
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
$ ls
pi@raspberrypi:~ $ ls
Desktop Documents Downloads example Music Pictures Public python_games
$ cd example
pi@raspberrypi:~/example $ cd ..
63 | P a g e
pi@raspberrypi:~ $
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
$ 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.
64 | P a g e
$ mkdir downloads
$ cd downloads
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.
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.
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!
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
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.
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.
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()
73 | P a g e
Experiment No: 09
Raspberry pi program to implement temperature sensor
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?
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.
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.
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
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.
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:
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)
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)
sig_time = end-start
#CM:
distance = sig_time / 0.000058
#inches:
#distance = sig_time / 0.000148
print('Distance: {} centimeters'.format(distance))
GPIO.cleanup()
82 | P a g e
Experiment No: 11
Raspberry pi program to implement Garage spot light.
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
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)
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)
89 | P a g e
90 | P a g e
red_light()
Output
91 | P a g e
92 | P a g e