0% found this document useful (0 votes)
70 views38 pages

OCS352 Lab

The document outlines the practical work and course details for OCS352 - IoT Concepts and Applications at Mookambigai College of Engineering. It includes a bonafide certificate, the vision and mission of the college and department, program educational objectives, specific outcomes, and course outcomes. Additionally, it provides detailed practical exercises involving Arduino and Raspberry Pi, including interfacing with various sensors and modules.
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)
70 views38 pages

OCS352 Lab

The document outlines the practical work and course details for OCS352 - IoT Concepts and Applications at Mookambigai College of Engineering. It includes a bonafide certificate, the vision and mission of the college and department, program educational objectives, specific outcomes, and course outcomes. Additionally, it provides detailed practical exercises involving Arduino and Raspberry Pi, including interfacing with various sensors and modules.
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

MOOKAMBIGAI COLEGE OF ENGINEERING

Srinivasa Nagar, Kalamavur – 622502


(Affiliated to Anna University Chennai – 600 25)

OCS352 – IoT CONCEPTS AND APPLICATIONS

R-2021
IV Semester

DEPARTMENT OF ELECTRONICS AND


INSTRUMENTATION ENGINEERING
MOOKAMBIGAI COLLEGE OF ENGINEERING
Srinivasa Nagar, Kalamavur – 622502

BONAFIDE CERTIFICATE

Certified that this is the bonafide record of the practical work done by
………...………………………………..……..…SPRNO……………………of IV
Semester / II Year B.E. – Electronics and Instrumentation Engineering in OCS352
– IoT Concepts and Applications during the academic year 2023-
2024.

Register Number …………………………………………….

Head of the Department Staff in-Charge

Submitted for the University practical examination held on

INTERNAL EXAMINER EXTERNAL EXAMINER


MOOKAMBIGAI COLLEGE OF ENGINEERING VISION
 To be an institution of excellence committed to quality engineering education
and research toward producing socially responsible citizens.
MISSION
 To impart quality technical education in producing competent engineers by
providing a conducive learning environment.
 To build a high-quality human resource capacity with a focus on
professionalism and dedication.
 To inculcate ethical values by adopting holistic teaching methodologies.
 To instill innovative thinking and entrepreneurial traits by collaborating with industry
and academia.

DEPARTMENT OF ECE
VISION
 To produce competent electronics and instrumentation engineers towards new
technology along with social responsible citizen.
MISSION
M1 To provide quality learning environment with well-defined teaching learning
process.

M2 To promote research culture through projects and consultancy.

M3 To learn and practice latest technologies in instrumentation engineering


platforms prevalent in industry.

M4 To develop responsible citizenship through awareness and acceptance of ethical


values.
Programme Educational Objectives (PEO)

PEO 1 Engage in designing, manufacturing, operating and testing in the field of electronics
and instrumentation engineering and allied engineering industries.

PEO 2 Solve problems of social relevance by applying the knowledge of electronics and
instrumentation engineering and pursue higher education and research.

PEO 3 Work effectively as individuals and as team members in multidisciplinary projects.

PEO 4 Engage in lifelong learning career enhancement and adapt to changing


professional and social needs.

Programme Specific Outcomes (PSO)

PSO 1 Implement modern tools to automate the process industries.

PSO 2 Design and build modern electronic systems for engineering applications.

PSO 3 Specify, select and formulate the instruments for industrial engineering environments

PSO 4 Specify, select the electrical machines for different applications.

OCS352 – IoT CONCEPTS AND APPLICATIONS


COURSE OUTCOMES
COs Course Outcome: The students, after the completion of the course, are expected to ….
CO1 Understand the concepts of IoT
CO2 Study about the components and various sensors in IoT
CO3 Understand the various communication model and protocols of IoT
CO4 Realize the different technologies behind IoT
CO5 Design and Programming IoT projects using Arduino / Raspberry Pi
CO6 Study about the applications of IoT
RUBRICS

Parameters Max. Rubrics


Marks
Allotment

Aim, Apparatus Required, 02 Aim & Apparatus Required – 1 Mark


Algorithm / Procedure Algorithm / Procedure – 1 Mark

Program / Circuit 04 Logical Implementation / Program –


4 Marks

Execution & Result 02 Execution -1 Mark


Result – 1 Mark

Viva Voce 01 Knowledge about the concepts – 1


Mark

Observation 01 Observation – 1 Mark

Total 10

4
CONTENTS
Ex.No Date Title Page No Initials

1 Introduction to Arduino platform and


programming
2 Interfacing Arduino to Temperature
sensor and LCD Display
3 Interfacing Arduino to Zigbee module
4 Interfacing Arduino to GSM module
5 Interfacing Arduino to Bluetooth Module
6 Introduction to Raspberry PI platform
and python programming
7 Interfacing sensors to Raspberry PI
8 Communicate between Arduino and
Raspberry PI using any wireless medium
9 Setup a cloud platform to log the data
10 Log Data using Raspberry PI and upload
to the cloud platform

5
Ex.No.: 1 Introduction to Arduino platform and programming
Date:

Aim:
To study about the Arduino board and how to program it.

Theory:

Arduino is a prototype platform (open-source) based on an easy-to-use hardware and


software. It consists of a circuit board, which can be programed (referred to as a
microcontroller) and a ready-made software called Arduino IDE (Integrated Development
Environment), which is used to write and upload the computer code to the physical board.
The key features are −
 Arduino boards are able to read analog or digital input signals from different sensors
and turn it into an output such as activating a motor, turning LED on/off, connect to
the cloud and many other actions.
 You can control your board functions by sending a set of instructions to the
microcontroller on the board via Arduino IDE (referred to as uploading software).
 Unlike most previous programmable circuit boards, Arduino does not need an extra
piece of hardware (called a programmer) in order to load a new code onto the board.
You can simply use a USB cable.
 Additionally, the Arduino IDE uses a simplified version of C++, making it easier to
learn to program.
 Finally, Arduino provides a standard form factor that breaks the functions of the
micro- controller into a more accessible package.
Various kinds of Arduino boards are available depending on different microcontrollers used.
However, all Arduino boards have one thing in common: they are programed through the
Arduino IDE.
The differences are based on the number of inputs and outputs (the number of sensors, LEDs,
and buttons you can use on a single board), speed, operating voltage, form factor etc. Some
boards are designed to be embedded and have no programming interface (hardware), which
you would need to buy separately. Some can run directly from a 3.7V battery, others need at
least 5V.
Unlike most earlier programmable circuit boards, the Arduino does not require a separate part
of hardware in order to program a new code onto the board you can just use a USB cable. As
well, the Arduino IDE uses a basic version of C++, making it simpler to learn the program. At
last, the Arduino board offers a typical form factor that breaks out the functions of the
microcontroller into a more available package.

6
Arduino Board Processor Memory Digital I/O Analogue I/O
2KB SRAM, 32KB
Arduino Uno 16Mhz ATmega328 flash 14 6 input, 0 output
96KB SRAM, 12 input, 2
Arduino Due 84MHz AT91SAM3X8E 512KB flash 54 output
8KB SRAM, 16 input, 0
Arduino Mega 16MHz ATmega2560 256KB flash 54 output
2.5KB SRAM, 12 input, 0
Arduino Leonardo 16MHz ATmega32u4 32KB flash 20 output

Arduino IDE

The Arduino Integrated Development Environment - or Arduino Software (IDE) - contains a


text editor for writing code, a message area, a text console, a toolbar with buttons for
common functions and a series of menus. It connects to the Arduino hardware to upload
programs and communicate with them.

Programs written using Arduino Software (IDE) are called sketches. These sketches are
written in the text editor and are saved with the file extension .ino . The editor has
features for cutting/pasting and for searching/replacing text. The message area gives
feedback while saving and exporting and also displays errors. The console displays text
output by the Arduino Software (IDE), including complete error messages and other
information. The bottom righthand corner of the window displays the configured board and
serial port. The toolbar buttons allow you to verify and upload programs, create, open,
and save sketches, and open the serial monitor.

Before you can start doing anything in the Arduino programmer, you must set the board-
type and serial port.

7
After the sketch has been written, the next step is to upload it to the Arduino. To upload a
sketch, click the arrow button in the upper left side of the window. The IDE will then verify
your code by checking for any typos or syntax errors. If it finds an error, it will let you
know with an orange error message. If the code is correct and free of any errors, the IDE
will compile the sketch. Compiling is the process of converting human readable code like C
and C++ into machine readable code that the microcontroller can understand.
After the sketch has been compiled, the IDE transfers the code through the USB port to the
Arduino where it is saved in the ATMEGA328’s flash memory. The sketch starts running
right away and keeps running until the power is removed.

Result:

8
Ex.No.: 2 Interfacing Arduino to Temperature sensor and LCD Display
Date:

Aim:
To read the temperature and display it into the LCD Display using Arduino.

Apparatus Required

1. Arduion Uno R3 Board


2. 220Ω Resistor
3. LM35 Temperature Sensor
4. 16X2 LCD Display
5. Bread Board
6. Connecting Wires

Procedure

1. Connections are made as per the given circuit.


2. Connect the Arduino board with PC using USB cable.
3. Open the IDE to create a new sketch.
4. Write the program in IDE.
5. Click the Upload Sketch button to verify and upload the program into Arduino kit.
6. Read the values.

Circuit
Connection Details

Arduino Board

5V Pin - VCC of LCD, VS of LM35, LED anode.


GND Pin - GND of LM35, RW & RD, LED pin of LCD
through 220Ω Resister
A0 input - Vout of LM3
Digital I/O pin 12 - Register Select of LCD
Digital I/O pin 11 - Enable of LCD
Digital I/O pin 5, 4, 3&2 - DB4, DB5, DB6 & DB7 of LCD

//code//
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int celsius = 0;
int fahrenheit = 0;

void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
pinMode(A0, INPUT);
// Print a message to the LCD.
}

void loop() {
celsius = map(((analogRead(A0) - 20) * 3.04), 0, 1023, -40, 125);
fahrenheit = ((celsius * 9) / 5 + 32);
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0,0);
lcd.print(" ");
lcd.setCursor(0,0);
lcd.print("C = ");
lcd.setCursor(5,0);
lcd.print(String(celsius));
lcd.setCursor(0,1);
lcd.print(" ");
lcd.setCursor(0,1);
lcd.print("F = ");
lcd.setCursor(5,1);
lcd.print(String(fahrenheit));
delay(1000);
}
Result:
Ex.No.: 3 Interfacing Arduino to Zigbee module
Date:

Aim:
To transmit and receive the data using Arduino with interfacing of Zigbee Module

Apparatus Required:
1. Arduino Uno Bard – 2 Nos.
2. Xbee Pro Module – 2 Nos.
3. Xbee Explorer / USB Adaptor Board – 1 No.
4. Adruion IDE
5. XCTU 6.11 Software
6. USB Cable

Procedure:
1. Download and install XCTU software on PC
2. Place the Xbee Module 1 in Xbee Adaptor board and connect to PC
3. Connect the Xbee module by select the correct port setting.
4. Now configure PAN ID and the radio as “coordinator”
5.

6. Configure the second module as a end device

12
7. Make the connection as per the diagram
8. Connect the Arduino with PC
9. Write the program using IDE and download the sketch into board
Now run the transmitter and receiver programs

Circuit Diagram

13
Transmitter Program

#include <SoftwareSerial.h>
SoftwareSerial xbeeSerial(2,3); //RX, TX

void setup() {
Serial.begin(9600);
xbeeSerial.begin(9600);
}

void loop() {
if(Serial.available() > 0){
char input = Serial.read();
xbeeSerial.print(input);
}
}

Receiver Program

#include <SoftwareSerial.h>
SoftwareSerial xbeeSerial(2,3); //RX, TX

void setup() {
Serial.begin(9600);
xbeeSerial.begin(9600);
}

void loop() {
if(xbeeSerial.available() > 0){
char input = xbeeSerial.read();
Serial.print(input);
}
}

Result:

14
Ex.No.: 4 Interfacing Arduino to GSM module
Date:

Aim:
To develop a project to send or receive the message using GSM module with Arduino.

Apparatus Required
1. Arduino Uno R3
2. SIM 900 A GSM Module
3. 12v Power Adapter
4. Working SIM Card
5. Connecting Wires

Procedure
1. First, we will need to insert the SIM card onto the SIM card tray on the GSM module
and lock it
2. Connect the external antenna to the module, if not done already
3. Make the following connections between your Arduino and the GSM module

Arduino Uno GSM Module


D9 Tx
D10 Rx
GND GND

Note: We won’t be connecting VCC from the GSM module to the Arduino since the GSM
module will be directly powered by the 12V supply we plug into the barrel jack. But we will
connect GNDs to make the ground plane common between the two devices.

4. Once the connections are done, you can power on the GSM module by plugging in
your external 12V DC Jack
5. The onboard Network LED will initially blink rapidly. After a few minutes, the
blinking should slow down to a steady pace. This means the GSM module has
successfully been registered on the mobile network and is ready to be used
6. Programming Steps

Step 1: Open Arduino IDE


Step 2: Copy paste the same code into your IDE
Step 3: Change the phone number and the message you would like to send to the required
values
Step 4: Connect your Arduino to your PC
Step 5: Select the Board as “Arduino Uno” under Tools
Step 6: Select the correct COM port under Tools
Step 7: Click on upload

15
Program

#include <SoftwareSerial.h>
SoftwareSerial Sim(9, 10);

void setup()
{
Sim.begin(9600); // Setting the baud rate of Sim
Module
Serial.begin(9600); // Setting the baud rate of
Serial Monitor (Arduino)
delay(100);
}

void loop()
{
if (Serial.available()>0)
switch(Serial.read()) // Read data given in Serial
Monitor
{
case 's': // If data is 's', goto
SendMessage() function
SendMessage();
break;
case 'r': // If data is 'r', goto
ReceiveMessage() function
ReceiveMessage();
break;

16
}

if (Sim.available()>0)
Serial.write(Sim.read()); // If SIM module sends messages,
print it to Serial monitor
}

void SendMessage()
{
Sim.println("AT+CMGF=1"); // Sets the Sim Module in send
SMS mode
delay(1000); // Delay of 1 second
Sim.println("AT+CMGS=\"+91xxxxxxxxxx\"\r"); // Replace x with mobile number
delay(1000); // Delay of 1 second
Sim.println("I am SMS from Sim Module"); // Type in the SMS text you want
to send
delay(100); // Delay of 0.1 second
Sim.println((char)26); // ASCII code of CTRL+Z (to exit
out)
delay(1000); // Delay of 1 second
}

void ReceiveMessage()
{
Sim.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live
SMS
delay(1000); // Delay of 1 second
}

Result

17
Ex.No.: 5 Interfacing Arduino to Bluetooth module
Date:

Aim:
To develop a system to interface the Bluetooth module with Arduino board and receive
the message

Apparatus Required
1. Arduino Uno R3
2. HC-05 BT Module
3. Resistors 1k 2k
4. Breadboard
5. Bluetooth Terminal App on Mobile
6. Connecting Wires

Procedure
1. Connections are made as per the diagram
2. Write the program in Arduino IDE and download the sketch
3. Pair and connect the HC-05 module with Mobile phone
4. Open the BT terminal in Mobile phone
5. Send the message to Arduino
6. Check the serial monitor in IDE to display the message.

Circuit

18
Program

#include<SoftwareSerial.h>

/* Create object named bt of the class SoftwareSerial */


SoftwareSerial bt(2,3); /* (Rx,Tx) */

void setup() {
bt.begin(9600); /* Define baud rate for software serial communication */
Serial.begin(9600); /* Define baud rate for serial communication */
}

void loop() {

if (bt.available()) /* If data is available on serial port */


{
Serial.write(bt.read()); /* Print character received on to the serial monitor */
}
}

Result

19
Ex.No.: 6 Introduction to Raspberry PI platform and python
programming
Date:

Aim:
To study about the Raspberry Pi Soc and python programming

Theory

Raspberry Pi, developed by Raspberry Pi Foundation in association with Broadcom, is a


series of small single-board computers and perhaps the most inspiring computer available
today.

From the moment you see the shiny green circuit board of Raspberry Pi, it invites you to
tinker with it, play with it, start programming, and create your own software with it. Earlier,
the Raspberry Pi was used to teach basic computer science in schools but later, because of its
low cost and open design, the model became far more popular than anticipated.

It is widely used to make gaming devices, fitness gadgets, weather stations, and much more.
But apart from that, it is used by thousands of people of all ages who want to take their first
step in computer science.
Among these models, the Raspberry Pi B models are the original credit-card sized format.
On the other hand, the Raspberry Pi A models have a smaller and more compact footprint
and
hence, these models have the reduced connectivity options.
Raspberry Pi Zero models, which come with or without GPIO (general-purpose input
output)
headers installed, are the most compact of all the Raspberry Pi boards types.

Connect Raspberry Pi to Devices

The respective processes to connect your Raspberry Pi board to different devices is explained
below in detail. Let us begin by understanding how to connect a display device to your Pi
board.
Display device
Depending on the screen type, you have two ways to connect the display device to your Pi
board. In these two ways, we are assuming that you are going to use either monitor or
television. Apart from these two ways, there is an official Pi touchscreen that connects using
the display socket. Let us check how we can connect an HDMI display and television, as
explained below.
HDMI or DVI display
The HDMI connector is on the top surface of your Raspberry Pi board. But for the Raspberry
Pi Zero model, you need to use an adapter that converts Mini HDMI to an HDMI socket. For
connecting, insert one end of the HDMI cable in the board or Pi ZERO connector and the
other end into your monitor.

20
On the other hand, if you are using a DVI display, an adapter should be used.
Television
If the TV you are using is having a HDMI socket, you can use that for optimal results. But if
in case, your TV does not have an HDMI socket, you need to use the composite video socket.
On the Raspberry Pi Model-A and Model-B, the composite video socket is placed on the top
edge of the board. It is a round, yellow-and-silver sockets.
On other models, Raspberry Pi 3, Pi 2, and Model B+, the same socket as the audio output
can be used as a composite video socket. It is placed on the bottom of the board.
One thing you should note is that you will need to use a special RCA cable for this socket.
Connect one end of the RCA cable to the audio output socket and the other end to Video
in socket of the TV.
If you are using Pi Zero or Zero W boards then, you need to solder your own connector to the
board, where it is labelled TV. This should be done because, both these boards do not have
composite video socket.
Keyboard and Mouse
On Raspberry Pi Model B+, Model Pi 2, and Model Pi 3 the keyboard and mouse can be
directly connected. They should work fine. But for earlier models of Raspberry Pi, you
should use an external USB hub to connect keyboard and mouse.
Because with this, the devices will not draw too much power from the Pi board, and we can
reduce the risk of heat and other problems caused by devices.
On the other hand, for Raspberry Pi Zero, Model A, and Model A+, we must use a USB hub,
since these boards have only one USB socket.
Audio devices
Raspberry Pi’s audio socket is a small black or blue box. On Model A and Model B, it is
stuck along the top edge of the board. Whereas, on Model B+, Pi 2 and Pi 3, it is stuck along
the bottom edge of the board.
If you have connected an HDMI TV, then you do not need to connect a separate audio cable,
as the sound is routed through your HDMI cable.
On the other hand, if you have earphones or headphones with a 3.5mm jack, you can directly
plug them into the audio socket.
Raspbian
Raspbian, a version of a Linux distribution called Debian, is the distribution that is
recommended by the Raspberry Pi foundation. It has been optimized for the Raspberry Pi
board.
Most of the Raspberry Pi users start with Raspbian and it includes −

 Graphical Desktop software.


 Web browser.
 Development and programming tools like Scratch, Python etc.
21
It has two versions, one with the PIXEL desktop and other is termed as Raspbian Lite, with a
more minimal installation.
LibreELEC and OSMC
Both are the versions of Kodi media center. They are mainly used for playing music and
video.

RISC OS
It is an alternative to Linux OS, which most of the people use on the Raspberry Pi. It has a
GUI (Graphical User Interface). In 1987, it was created by Acorn Computers and now-a-
days, it is maintained and managed by RISC OS open Limited.
Data Partition
If you use the Data Partition option, it will give you an option to sort the data. The sorted data
can be accessed by various Linux distributions.
Lakka
It is a retro gaming system that includes emulators for a range of vintage home computers
such as Commodore 64 and Amiga, Amstrad CPC, ZX Spectrum and various Atari machines.

22
It also includes emulators for a range of game consoles such as Nintendo machines and Sony
PlayStation. Although the Bomberman clones and 2048 games are included but, if you want
to use Lakka, you need to get the games separately.
Plug your USB with games files and you will be ready to get games into Lakka.
Screenly OSE
As the name implies, it is a digital signage system. It enables the users to use a Raspberry Pi
with a connected HD screen as a digital sign. Here, OSE refers to Open Source Edition.
It enables the following to be displayed on the screen −

 Videos
 Images
 Web pages
Windows 10 IoT Core
As the name implies, it is the version of Windows which is designed to support the IoT
(Internet of things) devices. It is actually different from the windows desktop experience we
are familiar with.
THONNY IDE

Thonny is the perfect IDE for Pi if you want to code in Python. It's easy to use and comes
with Python 3.7 built-in. If you're new to Python and want to create a basic program with it,
Thonny offers a clean, vanilla interface. This helps to ensure that you don't get bogged down
with all the fancy features — like the ones found on most IDEs — and focus on getting your
code right. As an IDE, Thonny comes with a debugger to help you detect and correct errors
in your code. It has features like expression evaluation, scope explaining, syntax highlighting,
and code completion, which add convenience and improve your coding experience.

Similar to other IDEs, Thonny also supports plugins so that you can get more functionalities
onboard.

Thonny IDE comes pre-installed with the Raspberry Pi OS desktop version. If you're running
any other version of Pi OS, you can install it with:

sudo apt install thonny

Result:

23
Ex.No.: 7 Interfacing sensors to Raspberry PI
Date:

Aim:
To measure the distance using Raspberry Pi interface with Ultrasonic distance sensor

Apparatus Required

1. Raspberry Pi 3 Model B
2. HC-SR04 Ultrasonic Sensor
3. 680 Ω Resistor (1/4 Watt)
4. 1.5 KΩ Resistor (1/4 Watt)
5. Connecting Wires
6. Mini Breadboard

Procedure:
The Ultrasonic Transmitter in the Sensor generates a 40 KHz Ultrasound. This signal then
propagates through air and if there is any obstacle in its path, the signal hits the object and
bounces back. This bounced signal is then collected by the Ultrasonic Receiver. Based on the
signal’s time of travel, you can calculate the distance of the object as you already know the
speed of sound. The Ultrasonic Transmitter, will transmits a burst of 8-pulses of ultrasound
at 40 KHz. Immediately, the control circuit in the sensor will change the state of the ECHO
pin to HIGH. This pins stays HIGH until the ultrasound hits an object and returns to the
Ultrasonic Receiver. Based on the Time for which the Echo Pin stays HIGH, you can
calculate the distance between the sensor and the object. For example, if we calculated the
time for which ECHO is HIGH as 588µS, then you can calculate the distance with the help of
the speed of sound, which is equal to 340m/s.

Distance = Velocity of Sound / (Time/2) = 340m/s / (588µS /2) = 10cm.

1. Install the Raspbian OS with Imager software on Raspberry Pi Board


2. Connections are made as per the diagram.
3. Power on the Raspberry Pi Single Board Computer and Open Thonny IDE
4. Type the python code and run it
5. The system read the distance using sensor and print it on output screen.

24
Program

import RPi.GPIO as GPIO


import time

GPIO.setmode(GPIO.BOARD)

TRIG = 16
ECHO = 18
i=0

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

GPIO.output(TRIG, False)
print "Calibrating....."
time.sleep(2)

print "Place the object......"

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

while GPIO.input(ECHO)==0:
pulse_start = time.time()

25
while GPIO.input(ECHO)==1:
pulse_end = time.time()

pulse_duration = pulse_end - pulse_start

distance = pulse_duration * 17150

distance = round(distance+1.15, 2)

if distance<=20 and distance>=5:


print "distance:",distance,"cm"
i=1

if distance>20 and i==1:


print "place the object...."
i=0
time.sleep(2)

except KeyboardInterrupt:
GPIO.cleanup()

Result:

26
Ex.No.: 8 Communicate between Arduino and Raspberry PI using any
wireless medium
Date:

Aim:
To develop the communication between Arduino uno and Raspberry Pi via Bluetooth
module.

Apparatus Required
1. Raspberry Pi Board
2. Arduino Uno R3
3. HC-05 BT Module
4. Resistors 1K 2K
5. Breadboard
6. Connecting Wires

Circuit Diagram

Arduino with HC-05

Procedure

1. Connections are made as per the diagram


2. Write the program in Arduino IDE and download the sketch
3. On the other hand, Connect Raspberry Pi and Turn on
4. Install BT module on Raspberry pi

27
sudo apt-get install pi-bluetooth
sudo apt-get install bluetooth bluez blueman

Restart you pi (essential)


Now, you should be able to see menu -> preferences -> bluetooth manager
Open bluetooth manager
click bluetooth icon (actually you will see two icons, click blue one)
click setup new device
you will see “Welcome to bluetooth device setup assistant”
process Next
Search for HC-05
Proceed further.

Program

Arduino Code:

int ledPin = 13;


void setup() {
Serial.begin( 9600 ); // baud rate 9600 for the serial Bluetooth communication
}
void loop() {
// listen for the data from raspberry pi
if ( Serial.available() > 0 ) {
// read a numbers from serial port
int inputVal = Serial.parseInt();
if (inputVal > 0) {
Serial.print("Your input is: ");
Serial.println(String(inputVal));
// Here blink the LED
blinkLED(inputVal);
}

28
}
}
void blinkLED(int inputVal)
{ for (int i=0; i< inputVal; i++)
{ digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
}
}

Raspberry Pi Python Code:

import serial
import time
port = serial.Serial("/dev/rfcomm0", baudrate=9600)

# reading and writing data from and to arduino serially.


# rfcomm0 -> this could be different
while True:
print "DIGITAL LOGIC -- > SENDING..."
port.write(str(3))
rcv = port.readline()
if rcv:
print(rcv)
time.sleep( 3 )

Result:

29
Ex.No.: 9 Setup a cloud platform to log the data
Date:

Aim:
To setup Thinkspeak cloud for IoT Applications

Apparatus Required:
1. PC With Internet Connection
2. Matlab Login

Procedure

Create a new channel by clicking on the button as shown in below image – A


channel is the source for your data. Where you can store and retrieve data. A
channel can have maximum 8 fields. It means you can store 8 different data to a
channel.

Step 1: Signup for ThingSpeak


For creating your channel on ThingSpeak you first need to sign up on ThingSpeak. In case if you already
have account on ThingSpeak just sign in using your id and password.
For creating your account go to
www.thinspeak.com
Click on signup if you don’t have account and if you already have account click on sign in.
After clicking on signup fill your details.

After this verify your E-mail id and click on continue. Step 2: Create a Channel for Your Data
Once you Sign in after your account verification, Create a new channel by clicking “New Channel” button

30
After clicking on “New Channel”, enter the Name and Description of the data you want to upload on this
channel. For example I am sending my CPU data (temperature), so I named it as CPU data.
Now enter the name of your data (like Temperature or pressure) in Field1. If you want to use more than one
Field you can check the box next to Field option and enter the name and description of your data.
After this click on save channel button to save your details.

Step 3: Getting API Key in ThingSpeak


To send data to ThingSpeak, we need an unique API key, which we will use later in our python code to
upload our CPU data to ThingSpeak Website.
Click on “API Keys” button to get your unique API key for uploading your CPU data.
Click on “API Keys” button to get your unique API key for uploading your CPU data.
Step 4: Python Code for Raspberry Pi
Complete code is given at the end of this tutorial, just make a file with any name and .py extension and
copy- paste the code and save the file. Don’t forget to replace the API key with yours. You can run the
python file any time using below command:

python /path/filename.py

Assuming you already installed python in Raspberry pi using this command

31
Now copy your “Write API Key”. We will use this API key in our code.

sudo apt-get install python

Case 1: If you are using monitor screen then just use the given code.
Now install all libraries:

sudo apt-get install httplib


sudo apt-get install urllib

After installing libraries run your python code (python /path/filename.py)


If the code runs properly you will see some CPU temperature values as shown in below image.
If there are any errors uploading the data, you will receive “connection failed” message.

Case 2: If you are using “Putty” then you should follow these commands:
First update your pi using:

32
sudo apt-get update

After this make a file cpu.py using:

nano cpu.py

After creating this file copy your code to this file and save it using CTRL + X and then ‘y’ and Enter.
After this install all libraries using:

sudo apt-get install httplib


sudo apt-get install urllib

After installing libraries run your python code using:

python cpu.py

Step 6: Check ThingSpeak site for Data Logging


After completing these steps open your channel and you will see the CPU temperature data is updating into
ThingSpeak website.

33
Code

import httplib
import urllib
import time
key = "ABCD" # Put your API Key here
def thermometer():
while True:
#Calculate CPU temperature of Raspberry Pi in Degrees C
temp =
int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
# Get Raspberry Pi CPU temp
params = urllib.urlencode({'field1': temp, 'key':key })
headers = {"Content-typZZe": "application/x-www-form-
urlencoded","Accept": "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80")
34
try:
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print temp
print response.status, response.reason
data = response.read()
conn.close()
except:
print "connection failed"
break
if name == " main ":
while True:
thermometer()

Result:

35
Ex.No.: 10 Log Data using Raspberry PI and upload to the cloud platform
Date:

Aim:
To send the room temperature to cloud using raspberry pi

Apparatus Required:
1. Raspberry Pi
2. DHT11 sensor
3. Connecting Cables

Procedure

1. Create a channel in thinkspeak with matlab login


2. Add the field values
3. Get the Channel ID and API Keys
4. Connections are made as per the diagram
5. Connect Raspberry pi kit with internet
6. Install the required libraries
Before installing the libraries we need to update the packages installed in Raspberry
Pi. For installing the basic updates run these commands in a terminal window on your
Raspberry Pi
sudo apt - get update
sudo apt - get install build - essential python - dev python - openssl git
Now we install the library to read the DHT11 or DHT22 sensors. Below library
will work for both the sensor types.
7. Install Thinkspeak Library
sudo pip install thingspeak
8. Run the python program with our channel id and API Key values.

36
Program

import thingspeak
import time
import Adafruit_DHT

channel_id = 1391845 # put here the ID of the channel you created before
write_key = 'TNXXJJII892UHJ1C' # update the "WRITE KEY"

pin = 4
sensor = Adafruit_DHT.DHT11

def measure(channel):
try:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
print('Temperature = {0:0.1f}*C Humidity = {1:0.1f}%'.format(temperature,
humidity))
else:
print('Did not receive any reading from sensor. Please check!')
# update the value
response = channel.update({'field1': temperature, 'field2': humidity})
except:
print("connection failure")

if name == " main ":


channel = thingspeak.Channel(id=channel_id, write_key=write_key)
while True:
measure(channel)
#free account has a limitation of 15sec between the updates
time.sleep(15)

Result:

37
PROGRAM OUTCOMES

PO1- Engineering knowledge

PO2- Problem analysis

PO3- Design/development of solutions

PO4- Conduct investigations of complex problems

PO5- Modern tool usage

PO6- The engineer and society

PO7- Environment and sustainability

PO8- Ethics

PO9- Individual and team work

PO10- Communication

PO11- Project management and finance

PO12- Life-long learning

RBT LEVELS

K1 - Remembering
K2 - Understanding
K3 - Applying
K4 - Analyzing
K5 - Evaluating
K6 - Creating

38

You might also like