0% found this document useful (0 votes)
56 views92 pages

Iot Lab Workbook 2023-24

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views92 pages

Iot Lab Workbook 2023-24

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Geethanjali College of Engineering and Technology

(UGC AUTONOMOUS)
Cheeryal (V), Keesara (M), Medchal District – 501 301 (T.S)

Internet of Things
LABORATORY WORK BOOK
B.Tech III Year II Semester (CSE)

DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
(2023-2024)
Geethanjali College of Engineering and Technology
UGC AUTONOMOUS
Cheeryal (V), Keesara (M), Medchal District – 501 301 (T S)

Internet of Things
Laboratory Work Book

Name:

RollNo:

Class: Branch:

Academic Year: 20 -20


Geethanjali College of Engineering and Technology
UGC AUTONOMOUS
Cheeryal (V), Keesara (M), Medchal District – 501 301 (T S)

CERTIFICATE
This is to certify that Mr./Miss
has satisfactorily completed number of experiments in the Internet of
Things Laboratory.

RollNo: Branch:
Year: Academic Year:

Course Faculty
Coordinator In charge

Internal Examiner External Examiner


Geethanjali College of Engineering and Technology
(UGC AUTONOMOUS)
Cheeryal (V), Keesara (M), Medchal District – 501 301 (T S)

20CS32L01-Internet of Things Lab


III Year II Semester (CSE)
L T P/D C
- - 2 1
Internet of Things Lab Syllabus

Course Objectives

Develop ability to
1. Assess the vision and introduction of IoT and understanding how M2M is connected to
internet of things
2. Identify the appropriate Hardware and software components of IoT for communication
3. Gain knowledge on Cloud Storage models, web servers and how to integrate device, data
and cloud management framework for IoT.
4. Learn the concepts of various data analytics and operational technology security with IoT.
5. Understand advanced and emerging concepts fog computing and Edge computing-IoT

Course Outcomes

After end of the course, student would be able to


CO1: Interpret the vision of IoT from a global context, compare and contrast M2M and
IoT Technology
CO2: Relate the appropriate Hardware and software components of IoT for providing the
communication among the devices
CO3: Implement device, data and cloud management services for IoT applications.
CO4: Explore various data analytical techniques and operational security for IoT applications.
CO5: Comprehend the need of Fog Computing and Edge Computing-IoT
.
List of Experiments:

1. Getting Started with IoT (Arduino).


2. Write an Arduino sketch to blink an LED Light for a particular interval of time.
3. Write an Arduino sketch to measure the distance(in cms) of a certain object.
4. Write an Arduino sketch to
i. Blink an LED and a buzzer if the distance measured is less than a threshold value
ii. Illustrate the working of PIR Sensor with an example.
iii. Illustrate the IR and DHT Sensor
5. Write an Program to send the humidity and temperature data to Cloud (ThingSpeak)
6. Write a program to alert the user through SMS and Email notification if humidity is greater
than a threshold value using IFTTT and Thingspeak cloud.
7. Write a Python program that blinks an LED at a rate of 3 second ON, 1 second OFF
8. Connect a PIR sensor to the GPIO pins of the Raspberry Pi. Perform measurements to
determine the range of the sensor, i.e., start with a small distance (e.g., a few inches) and see if
the motion sensor responds. Repeat these for increasing distances until the sensor stops
responding. Report the measured distance.

1
9. Select at least 1 input sensor (not PIR) and 1 output device and make the RPi control the
chosen output device in response to activity by the input device (e.g., a temperature sensor as
input and two or more LEDs indicating the current temperature in binary code).
10. Write a python program for client-server based intruder detection system using mqtt
application layer protocol
11. Write an Arduino sketch to blink an LED Light for a particular interval of time using
wireless communication protocol (LoRa)

Case study:

1. Assume that you are in a college, design and implement a IoT prototype to measure the
amount of usage of water at a given location (take the location from user) on a day to day basis
and send the information to Cloud.

2. Receive the above information from the sensors/ cloud and apply necessary algorithms to
predict the amount of water being wasted at a particular location and also send a notification to
the user

2
S.No Index Page No
1 Vision, Mission, Program Educational Objectives (PEO) 5
2 Program Outcomes, Mapping of Lab course with PEO’s and PO’s 6
3 Performance Indicator 11
LIST OF EXPERIMENTS
4 Week -1:
Getting Started with IoT (Arduino). 13

5 Week-2:
Write an Arduino sketch to blink an LED Light for a particular
interval of time. 30

6 Week-3: 32
Write an Arduino sketch to measure the distance(in cms) of a certain
object.

7 Week-4: 37
Write an Arduino sketch to
i. Blink an LED and a buzzer if the distance measured is less
than a threshold value
ii. Illustrate the working of PIR Sensor with an example.
iii. Illustrate the IR and DHT Sensor

8 Week-5: 48
Write an Program to send the humidity and temperature data to
Cloud (ThingSpeak)

9 Week-6: 56
Write a program to alert the user through SMS and Email
notification if humidity is greater than a threshold value
using IFTTT and Thingspeak cloud.

10 Week-7: 67
Write a Python program that blinks an LED at a rate of 3
second ON, 1 second OFF

3
11 Week- 8: 69
Connect a PIR sensor to the GPIO pins of the Raspberry Pi.
Perform measurements todetermine the range of the sensor, i.e.,
start with a small distance (e.g., a few inches) and see if the motion
sensor responds. Repeat these for increasing distances until the
sensor stopsresponding. Report the measured distance.

12 Week-9: 71
Select at least 1 input sensor (not PIR) and 1 output device and make the
RPi control the chosen output device in response to activity by the
input device (e.g., a temperature sensor as input and two or more LEDs
indicating the current temperature in binary code).

13 Week-10: 74
Write a python program for client-server based intruder
detection system using mqtt application layer protocol.

14 Week-11: 76
Write an Arduino sketch to blink an LED Light for a particular
interval of time using wireless communication protocol (LoRa)

15 Case Study/ Mini Project 80


16 Annexure 1 ( Basics of Arduino) 85
17 Annexure 2 ( Basics of Raspberry Pi) 86
18 Annexure 3 (Python commands) 88
19 Notes 91

4
VISION OF THE DEPARTMENT – CSE

To produce globally competent and socially responsible computer science engineers


contributing to the advancement of engineering and technology which involves creativity and
innovation by providing excellent learning environment with world class facilities.

MISSION OF THE DEPARTMENT – CSE

1. To be a centre of excellence in instruction, innovation in research and scholarship, and


service to the stake holders, the profession, and the public.
2. To prepare graduates to enter a rapidly changing field as a competent computer science
engineer.
3. To prepare graduate capable in all phases of software development, possess a firm
understanding of hardware technologies, have the strong mathematical background
necessary for scientific computing, and be sufficiently well versed in general theory to
allow growth within the discipline as it advances.
4. To prepare graduates to assume leadership roles by possessing good communication
skills, the ability to work effectively as team members, and an appreciation for their
social and ethical responsibility in a global setting.

5
PEO’s, PO’s & PSO’s

PROGRAM EDUCATIONAL OBJECTIVES (PEO’s) - CSE

1. To provide graduates with a good foundation in mathematics, sciences and engineering


fundamentals required to solve engineering problems that will facilitate them to find employment
in industry and / or to pursue postgraduate studies with an appreciation for lifelong learning.
2. To provide graduates with analytical and problem-solving skills to design algorithms, other
hardware / software systems, and inculcate professional ethics, inter-personal skills to work in a
multi-cultural team.
3. To facilitate graduates to get familiarized with the art software / hardware tools, imbibing
creativity and innovation that would enable them to develop cutting-edge technologies of multi-
disciplinary nature for societal development.

PROGRAM OUTCOMES (Common to all branches)


Engineering Graduates would be able to:

PO 1:Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.

PO 2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

PO 3: Design/development of solutions: Design solutions for complex engineering problems and


design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO 4: Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

PO 5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.

PO 6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess

6
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

PO 7: Environment and sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

PO 8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO 9: Individual and teamwork: Function effectively as an individual, and as a member or leader


in diverse teams, and in multidisciplinary settings.

PO 10: Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

PO 11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO 12: Life-long learning: Recognize the need for and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change..

PROGRAM SPECIFIC OUTCOMES (PSO’s) - (CSE)


PSO 1: Demonstrate competency in Programming and problem-solving skills and apply these
skills in solving real world problems
PSO 2: Select appropriate programming languages, Data structures and algorithms in
combination with modern technologies and tools, apply them in developing creative and
innovative solutions
PSO 3: Demonstrate adequate knowledge in emerging technologies

7
Mapping of Lab Course with Programme Educational Objectives

S.No Course Code Course Year/Semester PEO 1 PEO 2 PEO 3


component
Computer INTERNET OF
1 20CS32L01 III Year II Sem √ √
Science THINGS LAB

Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes- CSE:

1:LOW 2:MEDIUM 3:HIGH


Pos 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
INTERNET OF THINGS LAB
CO1. Interpret the vision of IoT 2 1 1 1 2 1 1 1 - - - 2 1 1 3
from a global context, compare
and contrast M2M and IoT
Technology
CO2 Relate the appropriate 2 3 3 1 3 1 1 1 - - 1 2 2 1 3
Hardware and software components
of IoT for providing the
communication among the devices
CO3. : Implement device, data and 2 3 3 2 3 1 1 1 - - 1 2 2 2 3
cloud management services for IoT
applications.
CO4. Explore various data analytical 2 3 3 3 1 1 1 1 - - 1 2 2 2 3
techniques and operational security
for IoT applications.

CO5. Comprehend the need of Fog 2 2 1 1 2 1 1 1 - - - 2 2 2 2


Computing and Edge Computing-
IoT

Prerequisites:
20CS11L01- Programming for Problem Solving Lab
20CS31L02 - Computer Networks Lab

8
INSTRUCTIONS TO THE STUDENTS:

1. Students are required to attend all labs.


2. Students should be dressed in formals when attending the laboratory sessions.
3. Students will work individually in computer laboratories.
4. While coming to the lab bring the observation book and Work book etc.
5. Before coming to the lab, prepare the pre-lab questions. Read through
the lab experiment to familiarize you.
6. Utilize 3hours time properly to perform the experiment and noting
down the outputs.
7. If the experiment is not completed in the prescribed time, the pending work
hasto be done in the leisure hour or extended hours.
8. You will be expected to submit the completed work book
according to the deadlines set up by your instructor.

INSTRUCTIONS TO LABORATORY TEACHERS:

1. Observation book and lab records submitted for the lab work are to be
checked andsigned before the next lab session.
2. Students should be instructed to switch ON the power supply
after theconnections are checked by the lab assistant / teacher.
3. The promptness of submission should be strictly insisted by awarding the
marks accordingly.
4. Ask viva questions at the end of the experiment.
5. Do not allow students who come late to the lab class.
6. Encourage the students to do the experiments innovatively.
7. Fill continuous Evaluation sheet, on regular basis.
8. Ensure that the students are dressed in formals.

9
Scheme of Lab Exam Evaluation:

Evaluation of Internal Marks:

a) 15 Marks are awarded for day to day work

1) Record and Observation book ---------- 5Marks


2) Attendance and behavior of student ---------- 5 Marks
3) Viva and performance ---------------- 5 Marks

b) 15 Marks are awarded for conducting laboratory test as follows:

1) Write up and program ------- 5Marks


2) Execution of Program --------- 5Marks
3) Viva and performance ---------------- 5Marks

Evaluation of External Marks:

70 Marks are awarded for conducting laboratory test as follows:


1) Algorithm------------------------25 Marks.
2) Write up and program --------- 15Marks
3) Execution of Program-----------15Marks
4) Viva--------------------------------15 Marks

10
PERFORMANCE INDICATOR

Page Date of Date of Marks Faculty Remarks


S No. Name of the Experiment
No. Experiment Submission awarded Sign.
1

10

11

13

14

15

16

17

18

19

11
20

21

22

23

24

25

26

27

28

29

30

ADDITIONAL EXPERIMENTS

12
WEEK1
Arduino Installation Date:

Aim: Getting Started with IoT (Arduino) and perform necessary software installation

Arduino:
 Arduino is a platform that makes it easy for you to build projects using electronics.
 IoT is a way of using electronics - to make electronic modules talk to each other remotely and
wirelessly (often using a Cloud) to solve problems.
 Now, Arduino can also help you easily build IoT projects in two ways: Using traditional Arduino
boards and attaching communication breakout modules (like nRF, Bluetooth,WiFi,LoRA,GSM, etc)
to them.

 Arduino is a micro controller that can be connected to one or more sensors and help you capture the
data or information and then pass it on to processor. If you know the full stack of IoT then you should
also look at Raspberry.

 RaspPi is a microprocessor so the basic difference between Arduino and RasPi is that RaspPi is
controller plus processor and Arduino is just a micro controller.

 They suit the need for different use cases. You can easily read online about this both.

Download and install the Arduino software (Arduino IDE 1.8.15)


 Go to the Arduino website and click the download link to go to the download page.
 After downloading, locate the downloaded file on the computer and extract the folder from the
download zipped file. Copy the folder to a suitable place such as your desktop.

13
INSTALLING THE ARDUINO IDE ONWindows PCs

1. Visit http://www.arduino.cc/en/main/software to download the latest Arduino IDE version for your
computer’s operating system. There are versions for Windows, Mac, and Linux systems. At the download
page, click on the “Windows Installer” option for the easiest installation.
2. Save the .exe file to your hard drive.
3. Open the .exe file.
4. Click the button to agree to the licensing agreement:

5. Decide which components to install, and then click “Next”:

14
6. Select which folder to install the program to, then click “Install”:

7. Wait for the program to finish installing, and then click “Close”:

8. Now find the Arduino shortcut on your Desktop and click on it. The IDE will open up and you’ll seethe
code editor:

15
CONFIGURING THE ARDUINO IDE
The next thing to do is to make sure the software is set up for your particular Arduino board. Go to the
“Tools” drop-down menu, and find “Board”. Another menu will appear where you can select from a list of
Arduino models. I have the Arduino Uno R3, so I chose “Arduino Uno”.
Selecting arduino board

16
Selecting arduino port

EXPLORING THE ARDUINO IDE


If you want, take a minute to browse through the different menus in the IDE. There is a good variety of
example programs that come with the IDE in the “Examples” menu. These will help you get started with
your Arduino right away without having to do lots of research:

17
Running the Arduino IDE Software

This is a display of the Arduino IDE Software. The application is ready to be used to create amazing projects.

Install the Arduino Software (IDE) on Linux


The Linux build of the Arduino Software (IDE) comes in different packages depending on your system
architecture. There are no specific instructions needed for the different distributions of Linux (e.g. Ubuntu).

Download the Arduino Software (IDE)

Get the latest version from the download page. You can choose between the 32, 64 and ARM versions. It is
very important that you choose the right version for your Linux distro. Clicking on the chosen version brings
you to the donation page and then you can either open or save the file. Please save it on your computer.

18
Extract the package

The file is compressed and you have to extract it in a suitable folder, remembering that it will be executed
from there.

Run the install script

Open the arduino-1.6.x folder just created by the extraction process and spot the install.sh file. Right click
on it and choose Run in Terminal from the contextual menu. The installation process will quickly end and
you should find a new icon on your desktop.

If you don't find the option to run the script from the contextual menu, you have to open a Terminal window
and move into the arduino-1.6.x folder. Type the command ./install.sh and wait for the process to finish.
You should find a new icon on your desktop.

19
Proceed with board-specific instructions

When the Arduino Software (IDE) is properly installed you can go back to the Getting Started Home and
choose your board from the list on the right of the page.

Please Read...

It might happen that when you upload a sketch - after you have selected your board and the serial port -, you
get an error Error opening serial port ... If you get this error, you need to set serial port permission.

Open Terminal and type:

ls -l /dev/ttyACM*

you will get something like:

crw-rw --- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we
need is "dialout" (is the group owner of the file).

Now we just need to add our user to the group:

sudousermod -a -G dialout<username>

20
where <username> is your Linux user name. You will need to log out and log in again for this change to
take effect.

This is the procedure to access the serial port from the Arduino Software (IDE) if you get an error

After this procedure, you should be able to proceed normally and upload the sketch to your board or use the
Serial Monitor.

Steps to connect Arduino board:

Step 1 − First you must have your Arduino board (you can choose your favorite board) and a USB cable. In
case you use Arduino UNO, Arduino Duemilanove, Nano, Arduino Mega 2560, or Diecimila, you will need
a standard USB cable (A plug to B plug), the kind you would connect to a USB printer as shown in the
following image.

In case you use Arduino Nano, you will need an A to Mini-B cable instead as shown in the following image.

Step 2 − Download Arduino IDE Software.

21
You can get different versions of Arduino IDE from the Download page on the Arduino Official website.
You must select your software, which is compatible with your operating system (Windows, IOS, or Linux).
After your file download is complete, unzip the file.

Step 3 − Power up your board.


The Arduino Uno, Mega, Duemilanove and Arduino Nano automatically draw power from either, the USB
connection to the computer or an external power supply. If you are using an Arduino Diecimila, you have to
make sure that the board is configured to draw power from the USB connection. The power source is
selected with a jumper, a small piece of plastic that fits onto two of the three pins between the USB and
power jacks. Check that it is on the two pins closest to the USB port.
Connect the Arduino board to your computer using the USB cable. The green power LED (labeled PWR)
should glow.
Step 4 − Launch Arduino IDE.
After your Arduino IDE software is downloaded, you need to unzip the folder. Inside the folder, you can
find the application icon with an infinity label (application.exe). Double-click the icon to start the IDE.

22
Step 5 − Open your first project.
Once the software starts, you have two options −

 Create a new project.


 Open an existing project example.
To create a new project, select File → New.

23
To open an existing project example, select File → Example → Basics → Blink.

Here, we are selecting just one of the examples with the name Blink. It turns the LED on and off with some
time delay. You can select any other example from the list.
Step 6 − Select your Arduino board.
To avoid any error while uploading your program to the board, you must select the correct Arduino board
name, which matches with the board connected to your computer.
Go to Tools → Board and select your board.

24
Here, we have selected Arduino Uno board according to our tutorial, but you must select the name matching
the board that you are using.
Step 7 − Select your serial port.
Select the serial device of the Arduino board. Go to Tools → Serial Port menu. This is likely to be COM3 or
higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect
your Arduino board and re-open the menu, the entry that disappears should be of the Arduino board.
Reconnect the board and select that serial port.

25
Step 8 − Upload the program to your board.
Before explaining how we can upload our program to the board, we must demonstrate the function of each
symbol appearing in the Arduino IDE toolbar.

A − Used to check if there is any compilation error.


B − Used to upload a program to the Arduino board.
C − Shortcut used to create a new sketch.
D − Used to directly open one of the example sketch.
E − Used to save your sketch.
F − Serial monitor used to receive serial data from the board and send the serial data to the board.
Now, simply click the "Upload" button in the environment. Wait a few seconds; you will see the RX and TX
LEDs on the board, flashing. If the upload is successful, the message "Done uploading" will appear in the
status bar.
Arduino uno Board

26
1.Power USB
Arduino board can be powered by using the USB cable from your computer. All you need to do is connect
the USB cable to the USB connection (1).

2. Power (Barrel Jack)


Arduino boards can be powered directly from the AC mains power supply by connecting it to the Barrel Jack
(2).

3. Voltage Regulator
The function of the voltage regulator is to control the voltage given to the Arduino board and stabilize the DC
voltages used by the processor and other elements.

4. Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. How does Arduino calculate time? The
answer is, by using the crystal oscillator. The number printed on top of the Arduino crystal is 16.000H9H. It
tells us that the frequency is 16,000,000 Hertz or 16 MHz.

5, 17- Arduino Reset


You can reset your Arduino board, i.e., start your program from the beginning. You can reset the UNO board
in two ways. First, by using the reset button (17) on the board. Second, you can connect an external reset
button to the Arduino pin labelled RESET (5).

6,7,8,9: Pins (3.3, 5, GND, Vin)


• 3.3V (6) − Supply 3.3 output volt
5V (7) − Supply 5 output volt
• Most of the components used with Arduino board works fine with 3.3 volt and 5 volt.
• GND (8)(Ground) − There are several GND pins on the Arduino, any of which can be used to
groundyour circuit.
• Vin (9) − This pin also can be used to power the Arduino board from an external power source, like
AC mains power supply.

10. Analog pins


The Arduino UNO board has six analog input pins A0 through A5. These pins can read the signal from an
analog sensor like the humidity sensor or temperature sensor and convert it into a digital value that can be
read by the microprocessor.

11.Main microcontroller
Each Arduino board has its own microcontroller (11). You can assume it as the brain of your board. The
main IC (integrated circuit) on the Arduino is slightly different from board to board. The microcontrollersare
usually of the ATMEL Company. You must know what IC your board has before loading up a new program
from the Arduino IDE. This information is available on the top of the IC. For more details about the IC
construction and functions, you can refer to the data sheet.
12. ICSP pin
Mostly, ICSP (12) is an AVR, a tiny programming header for the Arduino consisting of MOSI, MISO, SCK,
RESET, VCC, and GND. It is often referred to as an SPI (Serial Peripheral Interface), which could be
considered as an "expansion" of the output. Actually, you are slaving the output device to the master of the
SPI bus.

27
13. Power LED indicator
This LED should light up when you plug your Arduino into a power source to indicate that your board is
powered up correctly. If this light does not turn on, then there is something wrong with the connection.

14. TX and RX LEDs


On your board, you will find two labels: TX (transmit) and RX (receive). They appear in two places on the
Arduino UNO board. First, at the digital pins 0 and 1, to indicate the pinsresponsible for serial
communication. Second, the TX and RX led (13). The TX led flashes with different speed while sending the
serial data. The speed of flashing depends on the baud rate used by the board. RX flashes during the
receiving process.

15. Digital I/O


The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM (Pulse Width Modulation)
output. These pins can be configured to work as input digital pins to read logic values (0 or 1) or as digital
output pins to drive different modules like LEDs, relays, etc. The pins labeled “~” can be used to generate
PWM.

16. AREF
AREF stands for Analog Reference. It is sometimes, used to set an external reference voltage (between 0
and 5 Volts) as the upper limit for the analog input pins.

Sketch − The first new terminology is the Arduino program called “sketch”.

Structure
Arduino programs can be divided in three main parts: Structure, Values (variables and constants),
and Functions. In this tutorial, we will learn about the Arduino software program, step by step, and how we
can write the program without any syntax or compilation error.
Let us start with the Structure. Software structure consists of two main functions −

 Setup( ) function
 Loop( ) function

Void setup ( ) {

}
 PURPOSE − The setup() function is called when a sketch starts. Use it to initialize the variables, pin
modes, start using libraries, etc. The setup function will only run once, after each power up or reset
of the Arduino board.
 INPUT − -
 OUTPUT − -
 RETURN − -
Void Loop ( ) {
}

28
 PURPOSE − After creating a setup() function, which initializes and sets the initial values,
the loop() function does precisely what its name suggests, and loops consecutively, allowing your
program to change and respond. Use it to actively control the Arduino board.
 INPUT − -
 OUTPUT − -
 RETURN − -

Viva Questions:
1. What is the name of program written with the Arduino IDE?

2. What does p refers to in ATmega328p?

3. What are the two functions in Arduino Sketch?

4. How many digital pins are there in the Arduino Uno board?

5. What is the Stable version of Arduino software?

29
WEEK-2 Date:

AIM: To interface LED/Buzzer with Arduino/Raspberry Pi and write a program to turn ON LED for 1 sec
after every 2 seconds.

Hardware Requirements:

1. 1x Breadboard
2. 1x Arduino Uno R3
3. 1x RGB LED
x Jumper Wires

Procedure:

1. Connect the Arduino board to your computer using the USB cable.
2. Set the pin-mode as LED output
3. Set the pin-mode as Buzzer output.
4. Set the delay time for output
5. Set the digital pin-mode on.
6. Set the digital pin-mode off.

Source Code:

int led=13;
int buzzer=11;
void setup() {
pinMode(13, OUTPUT);
pinMode(11, OUTPUT);

}
void loop() {
digitalWrite(13, HIGH);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(13, LOW);
digitalWrite(11, LOW);
delay(2000);
}

30
OUTPUT:

Viva Questions

1. What is the use of pinMode() in Arduino IDE?

2. In which language Arduino software was written?

3. What are the functions of time in Arduino?

4. How many times does the setup() function run on every startup of the Arduino System?

5. How many times does the loop() function run on every startup of the Arduino System?

31
WEEK-3: Date:

AIM: Write an Arduino sketch to measure the distance (in cm’s) of a certainobject.

Ultrasonic Sensor:
The HC-SR04 ultrasonic sensor uses SONAR to determine the distance of an object just like the bats do. It
offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use
package from 2 cm to 400 cm or 1” to 13 feet.
The operation is not affected by sunlight or black material, although acoustically, soft materials like cloth
can be difficult to detect. It comes complete with ultrasonic transmitter and receiver module.

Ultrasonic Sensor

Hardware Requirements:

1. 4 x jumping wires(male to female)


2. 1 x Arduino Uno R3
3. 1 x ULTRASONIC Sensor (HC-SR04)

32
Procedure:

Follow the circuit diagram and make the connections as shown in the image given below.

The Ultrasonic sensor has four terminals - +5V, Trigger, Echo, and GND connected as follows −

1. Connect the +5V pinto +5v on your Arduino board.


2. Connect Trigger to digital pin 7 on your Arduino board.
3. Connect Echo to digital pin 6 on your Arduino board.
4. Connect GND with GND on Arduino.

33
Source code:

const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor

const int echoPin = 6; // Echo Pin of Ultrasonic Sensor

void setup() {

Serial.begin(9600); // Starting Serial Terminal

void loop() {

long duration, inches, cm;

pinMode(pingPin, OUTPUT);

digitalWrite(pingPin, LOW);

delayMicroseconds(2);

digitalWrite(pingPin, HIGH);

delayMicroseconds(10);

digitalWrite(pingPin, LOW);

pinMode(echoPin, INPUT);

duration = pulseIn(echoPin, HIGH);

inches =microsecondsToInches(duration);

cm = microsecondsToCentimeters(duration);

Serial.print(inches);

Serial.print("in, ");

Serial.print(cm);

Serial.print("cm");

Serial.println();

delay(100); }

34
long microsecondsToInches(long microseconds) {

return microseconds / 74 / 2;

long microsecondsToCentimeters(long microseconds) {

return microseconds / 29 / 2;

Procedure to see output:

1. Upload code.
2. Open serial monitor under tools menu.
3. Output will be shown.

OUTPUT:

To see output:

Go to tools -> Serial Monitor

35
Viva Questions:

1. What is the unit of delay() in Arduino?

2. What is the Use of Ultrasonic Sensor?

3. How many pins are present in the Ultrasonic Sensor?

4. What mode should we put the Arduino pin to , in order for object detection to work withthe
Ultrasonic Sensor?

5. What kind of waves does the Ultrasonic Sensor works on?

36
WEEK-4: Date:

i. AIM :Write an Arduino sketch to blink an LED and a buzzer if the distance measured is less than
a threshold value.

Hardware Requirements:

1. 1x Breadboard
2. 1x Arduino Uno R3
3. 1x Buzzer
4. 6x Jumper Wires
5. 1 x ULTRASONIC Sensor (HC-SR04)

Pin diagram:

Procedure:

1. Arduino GND to Ultrasonic sensor GND.


2. Vcc of Ultrasonic to +5V of Arduino.
3. Echo of Ultrasonic to pin 7 of Arduino.
4. Trig of Ultrasonic to pin 6 of Arduino.
5. Cathode of Buzzer to pin 3 of Arduino.
6. Anode of Buzzer to GND of Arduino.

37
Source Code:

const int TRIG_PIN = 6; // Arduino pin connected to Ultrasonic Sensor's TRIG pin
const int ECHO_PIN = 7; // Arduino pin connected to Ultrasonic Sensor's ECHO pin
const int BUZZER_PIN = 3; // Arduino pin connected to Piezo Buzzer's pin
const int DISTANCE_THRESHOLD = 50; // centimeters
const int LED_PIN = 13;

// variables will change:


float duration_us, distance_cm;

void setup() {
Serial.begin (9600); // initialize serial port
pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode
pinMode(ECHO_PIN, INPUT); // set arduino pin to input mode
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
// set arduino pin to output mode
}

void loop() {
// generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// measure duration of pulse from ECHO pin


duration_us = pulseIn(ECHO_PIN, HIGH);
// calculate the distance
distance_cm = 0.017 * duration_us;

if(distance_cm< DISTANCE_THRESHOLD){
digitalWrite(BUZZER_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
// turn on Piezo Buzzer
}
else{
digitalWrite(BUZZER_PIN, LOW); // turn off Piezo Buzzer
digitalWrite(LED_PIN, LOW);
}
// print the value to Serial Monitor
Serial.print("distance: ");
Serial.print(distance_cm);
Serial.println(" cm");

delay(500);
}

38
OUTPUT:

To see output:

Go to tools -> Serial Monitor

ii. AIM :Write an Arduino sketch to Illustrate the working of PIR Sensor with an example.

Hardware Requirements:
1. 1x Arduino Uno R3
2. 3x Jumper Wires
3. 1 x PIR Sensor

PIR Sensor:

39
Pin Diagram:

Procedure:

1. Arduino GND to PIR sensor GND.


2. Vcc of PIR to +5V of Arduino.
3. Out of PIR to pin 2 of Arduino.

Source Code:
#definepirPin 2
int calibrationTime = 30;
long unsigned int lowIn;
long unsigned int pause = 5000;
booleanlockLow = true;
booleantakeLowTime;
int PIRValue = 0;

void setup() {
Serial.begin(9600);
pinMode(pirPin, INPUT);
}

void loop() {
PIRSensor();
}

40
void PIRSensor() {
if(digitalRead(pirPin) == HIGH) {
if(lockLow) {
PIRValue = 1;
lockLow = false;
Serial.println("Motion detected.");
delay(1);
}
takeLowTime = true;
}
if(digitalRead(pirPin) == LOW) {
if(takeLowTime){
lowIn = millis();takeLowTime = false;
}
if(!lockLow&&millis() - lowIn> pause) {
PIRValue = 0;
lockLow = true;
Serial.println("Motion ended.");
delay(1);
}
}
}

OUTPUT:

To see output:

Go to tools -> Serial Monitor

41
iii. AIM : Write an Arduino sketch to Illustrate the IR and DHT Sensor

IR Sensor:

Hardware Requirements:
1. 1x Arduino Uno R3
2. 3x Jumper Wires
3. 1 x IR Sensor
4. 1 x LED
Procedure:

1. Arduino GND to IR sensor GND.


2. Vcc of IR to +5V of Arduino.
3. Out of IR to pin 7 of Arduino.
4. LED to Pin 13 of Arduino.

Pin diagram

42
Source Code:
void setup() {
pinMode(7,INPUT);
Serial.begin(9600);
pinMode(13,OUTPUT);
}

void loop() {
Serial.print("IRSensorip ");
Serial.println(digitalRead(7));
if(digitalRead(7)==0)
{
digitalWrite(13,HIGH);
}
else{
digitalWrite(13,LOW);
}

OUTPUT:

If there is any obstacle ahead the LED will glow.

DHT Sensor

Hardware Requirements:
1. 1x Arduino Uno R3
2. 3x Jumper Wires
3. 1 x DHT Sensor

43
Procedure:
1. Arduino GND to DHT sensor GND.
2. Vcc of IR to +5V of Arduino.
3. DATA of IR to pin 2 of Arduino.
Installing Libraries:
1. Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries.
2. The Library Manager should open.
3. Search for “DHT” on the Search box and install the DHT library from Adafruit

4. After installing the DHT library from Adafruit, type “Adafruit Unified Sensor” in the search box.
Scroll all the way down to find the library and install it.

44
Pin Diagram:

Procedure:

1. Vcc of DHT11 to +5V of Arduino.


2. GND of DHT11 to GND.
3. DATA of DHT11 to Pin 2 of Arduino.

45
Source Code:
#include "DHT.h"
#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}
void loop() {
// Wait a few seconds betweenmeasurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();
// Read temperature as Fahrenheit
float f = dht.readTemperature(true);

// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index
// Must send in temp in Fahrenheit!
float hi = dht.computeHeatIndex(f, h);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hi);
Serial.println(" *F");
}

46
OUTPUT:

To see output:

Go to tools -> Serial Monitor

Viva Questions:

1. What is the Use of IR Sensor?

2. How many pins are present in the IR Sensor?

3. What is the full form of PIR Sensor?

4. Which type of DHT11 sensor is?

5. How many pins have does temperature sensor have?

47
WEEK-5 Date:

AIM: Write an Program to send the humidity and temperature data to Cloud (ThingSpeak).

Hardware Requirements:

1. 3 x jumping wires(female to female)


2. 1 xNodeMCU
3. 1 x DHT11 Sensor

NodeMCU Pin diagram

Procedure:

1. Create account on ThingSpeak cloud using official college mail I’d.

2. Setting up Arduino IDE to read NodeMCU.


3. Upload data to cloud using NodeMCU and DHT11.

Creating account on ThingSpeak cloud:

Step1: Go to https://thingspeak.com/ and create account using official college mail I’d.

48
Step2: Create a new channel and add two fields namely “Temperature” and “Humidity”.

Step3: Scroll down and click “save”.

49
Step4: Make a note of Channel number and API Key.

Setting Arduino IDE to read NodeMCU:

Step1: Open Arduino IDE.

Step2:Open file->Preferences.

Step3:In the Additional Board Managers URL field enter the below link

http://arduino.esp8266.com/stable/package_esp8266com_index.json

50
Click Ok .

Step4:
Search the word ESP8266 in Boards>boards manager from Tools menu. Then install ESP8266 boards.
After complete installation, you will see the INSTALLED label on ESP8266 boards.

51
Step5: Go to tools and Select the board and we can see ESP8266 and select NodeMCU 0.9 from the list.

Uploading data to cloud:

Write the code in Arduino IDE and Verify and upload the code.

The Code gets uploaded to cloud this takes some time.

The output graphs can be seen in the channel created on ThingSpeak Cloud.

Pin Diagram:

52
Source Code:

#include <DHT.h> // Including library for dht


#include <ESP8266WiFi.h>

String apiKey = "AZLPGOM7VG3H0BFE"; // Enter your Write API key from ThingSpeak
const char *ssid= "wifi network name "; // replace with your wifissid and wpa2 key
const char *pass = "password of wifi network";
const char* server = "api.thingspeak.com";

#define DHTPIN 0 //pin where the dht11 is connected

DHT dht(DHTPIN, DHT11);

WiFiClient client;

void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();

Serial.println("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, pass);

while (WiFi.status() != WL_CONNECTED)


{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

void loop()
{
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}

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

String postStr = apiKey;


postStr +="&field1=";
postStr += String(t);
postStr +="&field2=";
postStr += String(h);
postStr += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");


client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);

Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop();

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

// thingspeak needs minimum 15 sec delay between updates, i've set it to 30 seconds
delay(10000);
}

54
OUTPUT:

Viva Questions:

1. What is use of ESP8266 ?

2. How many pins are present in the ESP8266 wifi module?

3. What is the use of TX pin in ESP8266?

4. What is the use of ThingSpeak Cloud?

5. How to submit data to the ThingSpeak Cloud?

55
Week-6: Date:

Aim: Write a program to alert the user through SMS and Email notification if humidity is
greater than a threshold value using IFTTT and Thingspeak cloud.

Hardware Requirements:
1. 3 x jumping wires(female to female)
2. 1 xNodeMCU
3. 1 x DHT11 Sensor
Steps:
1. Cresting account on IFTTT and setting up applet
Step1: Open ifttt.com
Step2: Click on create

Step3: Click on if This -> add

Step4: Search for webhooks and select webhooks

56
Step 5: Choose Receive Web Request

Step 6: Choose Connect

Step 7: Enter event name and click on Create Trigger

57
Step 8: Choose add of “Then That”

Step 9: Search for email and choose Email and select send me Email

Step 10: Click Create Action

58

58
Step 11: Click Continue

Step 12: Click Finish

Step 13: Click on in the next page shown below

Step 14: Choose Documentation

59
Step 15: Replace event with the name of event given for the applet

2. Thingspeak

Step 1: Open Thingspeak and create a channel for temperature and humidity readings

Step 2: From Apps select ThingHTTP

60
Step 3: Select New ThingHTTP

Step 4: Fill the fields as mentioned below

61
Step 5: Click on Save ThingHTTP

Step 6: From Apps select React

Step 7: Click on New React

62
Step 8: Fill the details mentioned below

Step 9: Save React


3. Run and upload the code to send data to thingspeak cloud
4. A Email is received when the temperature is above threshold

63
Pin Diagram:

Code:
#include <DHT.h> // Including library for
dht #include <ESP8266WiFi.h>
String apiKey = "GEHPJR80CJV2HXJ1"; // Enter your Write API key from
ThingSpeak const char *ssid = " ";// replace with your wifi ssid and wpa2 key
const char *pass = " ";
const char* server = "api.thingspeak.com";
#define DHTPIN 0 //pin where the dht11 is connected
DHT dht(DHTPIN, DHT11);

WiFiClient client;

void setup()
{
Serial.begin(9600);
delay(10);
dht.begin();

Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);

while (WiFi.status() != WL_CONNECTED)


{
delay(500);
Serial.print(".")
}
Serial.println("");
Serial.println("WiFi connected");

64
void loop()
{

float h = dht.readHumidity();
float t = dht.readTemperature();

if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com
{
String postStr = apiKey;
postStr +="&field1=";
postStr += String(t);
postStr +="&field2=";
postStr += String(h);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop(); Serial.println("Waiting...");

// thingspeak needs minimum 15 sec delay between updates, i've set it to 30 seconds
delay(10000);
}

65
Output:
An Email is triggered when the humidity exceeds threshold value

Viva Questions:

1. Abbrevate IFTTT?

2. What is the purpose of IFTTT ?

3. What is the unique identity used to upload data to ThingSpeak Cloud?

4. How the data in cloud is read by the webhook?

5. Which method is used to update the data to the React App?

66
Week-7 Date:

Aim: Write a Python program that blinks an LED at a rate of 3 second ON, 1 second OFF
Hardware Requirements:

1. 2 x jumping wires(female to female)


2. 1 x RaspberryPi
3. 1 x LED
Pin diagram:

1. Cathode ofLED to PIN8 of RaspberryPi


2. Anode of LED to PIN6 of RaspberryPi
Code:
import RPi.GPIO as GPIO
from time import sleep

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BOARD)
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW)
while True:
GPIO.output(8,GPIO.HIGH)
sleep(3)
GPIO.output(8,GPIO.LOW)
sleep(1)

67
Output:
The Led will blink at the rate of 3 seconds ON and 1 second OFF.
Viva Questions:

1. What is raspberry pi?

2. How many pins are there in RaspberryPi?

3. What are GPIO Pins in RaspberryPi?

4. Which language is preferred for coding using RaspberryPi?

5. What is setmode function?

68
Week 8: Date:

Aim: Connect a PIR sensor to the GPIO pins of the Raspberry Pi. Perform measurements to determine
the range of the sensor, i.e., start with a small distance (e.g., a few inches) and see if the motion sensor
responds. Repeat these for increasing distances until the sensor stops responding. Report the measured
distance.
Hardware Requirements:

1. 3 x jumping wires(female to female)


2. 1 x RaspberryPi
3. 1 x PIR Sensor
Pin Diagram:

1. Power of PIR to PIN 2 of RaspberryPi


2. OUTPUT of PIR to PIN 11 of RaspberryPi
3. GND of PIR to PIN 6 of RaspberryPi
4. Cathode of LED to PIN 3 of RaspberryPi
5. Anode of LED to PIN 9 of RaspberryP

69
Code:
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOAR
D) GPIO.setup(11,GPIO.IN)
GPIO.setup(3,GPIO.OUT)
GPIO.output(3,GPIO.LOW)

while True:
if(GPIO.input(11)):
GPIO.output(3,GPIO.HIGH)
print("Intruder Detected!!")

else:
GPIO.output(3,GPIO.LOW)
print("NO Intruder")

Output:
The Led will blink when an intruder is detected

Viva Questions:

1. What is the range of detection for PIR Sensor?

2. Which type of lens is generally used in the PIR sensors?

3. Which type of emitted light is detected by PIR sensor from obstacles?

4. List the applications of PIR Sensor

5. Which pin is used to take input from PIR Sensor?

70
Week 9: Date:

Aim: Select at least 1 input sensor (not PIR) and 1 output device and make the RPi control thechosen
output device in response to activity by the input device (e.g., a temperature sensor asinput and two or
more LEDs indicating the current temperature in binary code)
Hardware Requirements:

1. 6 x jumping wires(female to female)


2. 1 x RaspberryPi
3. 1 x DHT11
4. 3x LED

Installing Adafruit library:


1. To start with update your package lists and install a few Python libraries :
sudo apt-get update
sudo apt-get install build-essential python-dev
2. Then clone the Adafruit library from their repository :
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
3. Then install the library for Python 3 :
sudo python3 setup.py install

Pin Diagram:

71
Code:
import sys
import Adafruit_DHT
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.OUT)
GPIO.setup(10,GPIO.OUT)
GPIO.setup(12,GPIO.OUT)
GPIO.output(8,GPIO.LOW)
GPIO.output(10,GPIO.LOW)
GPIO.output(12,GPIO.LOW)
while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
#4 means pin number 7 in raspberry pi
print('Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature, humidity))
temp_int = int(temperature)
if temp_int<20:
GPIO.output(8,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
GPIO.output(12,GPIO.LOW)

elif temp_int>20 and temp_int < 30:


GPIO.output(10,GPIO.HIGH)
GPIO.output(8,GPIO.LOW)
GPIO.output(12,GPIO.LOW)

elif temp_int >= 30:


GPIO.output(12,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
GPIO.output(8,GPIO.LOW)

Output:

Green led will blink if the temperature is less than 20oC

Yellow led will blink if the temperature range is between 20 oC to 30oC

Red led will blink if the temperature is more than 30oC

72
Viva Questions:

1. How does DHT sensor work?

2. What is the range of DHT11 sensor?

3. Which library is used to integrate DHT11 with RaspberryPi?

4.Which module is imported to read temperature and humidity data?

5. what is the use of Adafruit_DHT.read_retry?

73
Week-10 Date:

Aim: Write a python program for client-server based intruder detection system using mqtt
application layer protocol.

Hardware Requirements:

1. 5 x jumping wires(female to female)


2. 2 x RaspberryPi
3. 1 x PIR Sensor
4. 1x LED
Client Pin diagram:

Client.py
# Import socket module
import socket
import RPi.GPIO as GPIO
from time import sleep
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.OUT)
GPIO.output(8,GPIO.LOW)

# Create a socket object


s = socket.socket()
# Define the port on which you want to connect
port = 8787
# connect to the server on local computer
s.connect(('192.168.21.232', port))
# receive data from the server and decoding to get the string.
print (s.recv(1024).decode())
while True:
if s.recv(1024).decode()=='1':
print('intruder detected')

74
GPIO.output(8,GPIO.HIGH)
sleep(10)
else:
GPIO.output(8,GPIO.LOW)
print('intruder not detected')
# close the connection
s.close()

Server pin diagram

Server.py
import socket
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.IN)
# next create a socket object
s = socket.socket()
print ("Socket successfully created")
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 8787
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
s.bind(('', port))
print ("socket binded to %s" %(port))
# put the socket into listening mode
s.listen(5)
print ("socket is listening")
# a forever loop until we interrupt it or
# an error occurs

74
while True:
# Establish connection with client.
c, addr = s.accept()
print ('Got connection from', addr )

# send a thank you message to the client. encoding to send byte type.
c.send('Thank you for connecting'.encode())
while True:
if GPIO.input(7):
c.send("1".encode())
print("INtruder DEtected")
else:
c.send("0".encode())
print("No INtruder")

Output:
If the intruder is detected on server side then led will blink on the client side.

Viva Questions:
1. What is the abbreviation of MQTT Protocol?

2. How does MQTT Work?

3. What is an MQTT topic?

4. What is the difference between HTTP and MQTT?

5. Does MQTT use TCP or UDP?

75
Week-11 Date:

Aim: Write an Arduino sketch to blink an LED Light for a particular interval of time using wireless
communication protocol (LoRa)

Hardware Requirements:
1. 2 x Arduino Uno boards
2. 2 x LoRa Modules
3. Connecting wires
4. 1 x push button
5. 1 x LED

Pin Diagram:

Transmitter:

Receiver:

76
Transmitter Code:

#include <SPI.h>
#include <LoRa.h>
int pot = A0;

void setup() {
Serial.begin(9600);
pinMode(pot,INPUT);

while (!Serial);
Serial.println("LoRa Sender");
if (!LoRa.begin(433E6)) { // or 915E6, the MHz speed of yout module
Serial.println("Starting LoRa failed!");
while (1);
}
}

void loop() {
int val = map(analogRead(pot),0,1024,0,255);
LoRa.beginPacket();
LoRa.print(val);
LoRa.endPacket();
delay(50);

77
Receiver Code:
#include <SPI.h>
#include <LoRa.h>
int LED = 3;
String inString = ""; // string to hold input
int val = 0;

void setup() {
Serial.begin(9600);
pinMode(LED,OUTPUT);

while (!Serial);
Serial.println("LoRa Receiver");
if (!LoRa.begin(433E6)) { // or 915E6
Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {
// try to parse packet
int packetSize = LoRa.parsePacket();
if (packetSize) {
// read packet
while (LoRa.available())
{
int inChar = LoRa.read();
inString += (char)inChar;
val = inString.toInt();
}
inString = "";
LoRa.packetRssi();
}

Serial.println(val);
analogWrite(LED, val);
}

Output:

If the button is pressed on the transmitter side then led will blink on the receiver side.

78
Viva Questions:

1. What is LoRa?

2. How Does LoRa work?

3. What is the frequency band of loRa in India?

4. How far can LoRa transmit?

5. How many pins does LoRa have?

79
Case Study/ Mini Project:
Basics of Arduino:
Basics of Raspberry Pi
Python commands:
Notes:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy