0% found this document useful (0 votes)
116 views

IOT Lab Manual

The document provides the syllabus for the Internet of Things lab course as prescribed by Bikaner Technical University. It lists 8 experiments to be performed using a Raspberry Pi including basic Linux commands, Python programs to perform calculations and handle exceptions, reading input from switches and writing output to LEDs and relays, using cron jobs to schedule tasks. The instructions emphasize performing the assigned experiments, maintaining discipline, and being responsible for any damage to lab equipment.

Uploaded by

Neha Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views

IOT Lab Manual

The document provides the syllabus for the Internet of Things lab course as prescribed by Bikaner Technical University. It lists 8 experiments to be performed using a Raspberry Pi including basic Linux commands, Python programs to perform calculations and handle exceptions, reading input from switches and writing output to LEDs and relays, using cron jobs to schedule tasks. The instructions emphasize performing the assigned experiments, maintaining discipline, and being responsible for any damage to lab equipment.

Uploaded by

Neha Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

DEPARTMENT OF COMPUTER SCIENCE

AND ENGINEERING

LAB MANUAL
B.Tech. VII Semester

INTERNET OF THINGS
7CS4-21

Modern Institute of Technology & Research Centre,


Alwar, Rajasthan
Affiliated to Bikaner Technical University, Bikaner
Vision and Mission of the Institute
Vision
To produce well trained professionals and leaders for serving society
and world at large through excellence in academics, research,
development and innovations.

Mission

C
M1: To provide state of the art facility for academic excellence that
caters to regional, national and global challenges.
R
M2: To identify emerging areas of technology that can provide
innovative and sustainable solutions to global challenges.
M3: To provide an environment of industry oriented research and
IT
development
M4: To inculcate core values of professional ethics, team-work, inter
personal skills and life-Long learning for sustainable development
of the society.
M
Vision and Mission of the Department
Vision
To create competent software professionals and leaders for
serving society and world at large through excellence in academics,
research, development and innovations.

Mission

C
Mission is to

M1: Provide strong theoretical and practical computer based skills to


R
meet the global technological changes.

M2: Provide a learning environment to enhance complex problem


IT
solving skills, research based projects/activities and innovation.

M3: Establish Industry Institute Interaction Program to enhance the


entrepreneurship skills, leadership qualities, team-spirit and ethical
responsibilities.
M

M4: Prepare students for lifelong learning through sustainable


development.
Program Outcomes (POs)

1. Engineering Knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals and an engineering specialization to the solution of complex
engineering problem.
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 science.

C
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.
R
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.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
IT
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
M

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.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
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.
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.
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.

C
R
IT
M
Course Outcomes (Cos)

Course Outcomes: Upon successful completion of the course/Lab the students will be
able to

CO1: Identify the devices used to make IoT system

CO2: Explain the working of Microprocessor and Microcontroller

CO3: Implement the interfacing of different sensors to computing devices.

C
CO4: Operate various IoT devices using various communication protocol.

CO5: Construct various logic to implement working of end device.

CO6: Draw conclusion from the data gathered by sensors.


R
IT
M
7CS4-21: Internet of Things Lab

TABLE OF CONTENT
S.No Content Page No
Vision and Mission of the Institute i
Vision and Mission of the Department ii
Program Outcomes (POs) iii
Course Outcomes (Cos) v
Lab Instruction vi
BTU Syllabus vii
Lab Introduction viii
Start Raspberry Pi and try various Linix commands in com-
mand terminal window: ls, cd, touch, mv, rm, man, mkdir,
1 1-3
rmdir, tar, gzip, cat, more, less, ps, sudo, cron, chown,
chgrp, ping etc.
Run some python programs on Pi like: (a)Read your name
2 and print Hello message with name (b)Read two numbers 4-6
and print their sum, difference, product and division.
(a)Word and character count of a given string. (b)Area of
3 a given shape (rectangle, triangle and circle) reading shape 7-9
and appropriate values from standard input.
(a) Print a name ’n’ times, where name and n are read from
4 standard input, using for and while loops. (b) Handle Di- 10-12
vided by Zero Exception.
(a) Print current time for 10 times with an interval of 10
5 seconds. (b) Read a file line by line and print the word 13-15
count of each line.
(a) Light an LED through Python program (b) Get input
6 16-17
from two switches and switch on corresponding LEDs
Flash an LED at a given on time and off time cycle, where
7 18-22
the two times are taken from a file.
(a) Flash an LED based on cron output (acts as an alarm)
8 (b) Switch on a relay at a given time using cron, where the 23-27
relay’s contact terminals are connected to a load.

Department of Computer Science & Engineering, MITRC, Alwar i


7CS4-21: Internet of Things Lab

LAB INSTRUCTIONS

1. Keep silence and sit properly in the lab.

2. Keep your bag properly inside the lab.

3. Always follow the instruction given by concerned faulty to perform the assigned
experiment.

4. Do not turn on the PCs without permission.

5. Do not switch off the power supply of the PCs directly, first shut down the PCs then
switch off power supply.

6. Every student is responsible for any damage to the PCs or its accessories which is
assigned for lab work.

7. Installation or un-installation of any software is strictly prohibited.

8. Always bring your lab file and the task assigned to you must be completed.

9. Experiment performed by you should be positively checked in next turn after that
faculty may not check your work.

10. Please mention your roll number, name, node number and signature in lab register.

11. Do not go to assist any student.

Department of Computer Science & Engineering, MITRC, Alwar ii


7CS4-21: Internet of Things Lab

BTU SYLLABUS

S.No Content
Start Raspberry Pi and try various Linix commands in command ter-
1 minal window: ls, cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip, cat,
more, less, ps, sudo, cron, chown, chgrp, ping etc.
Run some python programs on Pi like:
(a) Read your name and print Hello message with name
(b) Read two numbers and print their sum, difference, product and divi-
2 sion.
(c) Word and character count of a given string.
(d) Area of a given shape (rectangle, triangle and circle) reading shape
and appropriate values from standard input.
Run some python programs on Pi like:
(a) Print a name ’n’ times, where name and n are read from standard
input, using for and while loops.
3
(b) Handle Divided by Zero Exception.
(c) Print current time for 10 times with an interval of 10 seconds.
(d) Read a file line by line and print the word count of each line.
(a) Light an LED through Python program
(b) Get input from two switches and switch on corresponding LEDs
4
(c) Flash an LED at a given on time and off time cycle, where the two
times are taken from a file.
(a) Flash an LED based on cron output (acts as an alarm)
(b) Switch on a relay at a given time using cron, where the relay’s con-
5
tact terminals are connected to a load.
(c) Get the status of a bulb at a remote place (on the LAN) through web.

Department of Computer Science & Engineering, MITRC, Alwar iii


7CS4-21: Internet of Things Lab

LAB INTRODUCTION

This lab is intended for the fourth year students of engineering branches in the subject
of Internet of Things. This manual typically contains practical/Lab Sessions related IoT
covering various aspects related to the subject to enhance understanding. The experiments
are conducted on Raspberry Pi - a single board computer. Student will learn how to setup
the board and run various python program on it. They will also learn interfacing the board
with different sensors and actuators. This lab will provide basic understanding of IoT
device and architecture.

Department of Computer Science & Engineering, MITRC, Alwar iv


7CS4-21: Internet of Things Lab

Program No. 1

Objective: Start Raspberry Pi and try various Linix commands in command terminal
window:
ls, cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip, cat, more, less, ps, sudo, cron, chown,
chgrp, ping etc

Apparatus Required

Following device will be required to run the program:

1. Computer

2. Raspberry Pi Board

3. USB Connector

4. Ethernet Connector

Linux Commands

ls : The ls command in Linux is used to display a directory’s files and folders.

$ls [Options].. [Files]..

• ls -l

The -l tag is used to display a detailed version of every file and directory available
inside the current working directory.

• ls -a, --all

do not ignore entries starting with . (hidden files)

cd : Change the shell working directory.

cd [-L|[-P [-e]] [-@]] [dir]

Department of Computer Science & Engineering, MITRC, Alwar 1


7CS4-21: Internet of Things Lab

touch : Update the access and modification times of each FILE to the current time. A
FILE argument that does not exist is created empty, unless -c or -h is supplied.

touch [OPTION]... FILE...

mv : Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.

mv [OPTION]... [-T] SOURCE DEST


mv [OPTION]... SOURCE... DIRECTORY
mv [OPTION]... -t DIRECTORY SOURCE...

rm : remove (unlink) the FILE(s).

rm [OPTION]... [FILE]...

• -d, --dir

remove empty directories

• -r, -R, --recursive

remove directories and their contents recursively

man : - an interface to the system reference manuals

man [man options] [[section] page ...] ...

mkdir : Create the DIRECTORY(ies), if they do not already exist.

mkdir [OPTION]... DIRECTORY...

rmdir : Remove the DIRECTORY(ies), if they are empty.

rmdir [OPTION]... DIRECTORY...

tar : an archiving program designed to store multiple files in a single file (an archive),
and to manipulate such archives.

tar -cf archive.tar foo bar # Create archive.tar from files foo a
tar -tvf archive.tar # List all files in archive.tar verbo
tar -xf archive.tar # Extract all files from archive.tar.

Department of Computer Science & Engineering, MITRC, Alwar 2


7CS4-21: Internet of Things Lab

Viva Voce
1. What is raspberry pi?

2. How you can change the permission of file in linux ?

3. What is the name of OS used in raspberry pi?

4. What is linux process? what is the command to kill the process?

5. What is the use of the ping command?

Reference
1. King, Andy. Programming the Internet of Things. “O’Reilly Media, Inc.", 2021.

2. Lea, Perry. IoT and Edge Computing for Architects: Implementing edge and IoT
systems from sensors to clouds with communication systems, analytics, and security.
Packt Publishing Ltd, 2020.

Department of Computer Science & Engineering, MITRC, Alwar 3


7CS4-21: Internet of Things Lab

Program No. 2

Objective: Run some python programs on Pi like:

1. Read your name and print Hello message with name

2. Read two numbers and print their sum, difference, product and division.

Apparatus Required

Following device will be required to run the program:

1. Computer

2. Raspberry Pi Board

3. USB Connector

4. Ethernet Connector

Python Program: Read your name and print Hello message with name
1 ############### PRACTICAL 1 ##########################
2 # Read your name and print Hello message with name
3

4 name = input("Enter the your name:\n")


5 print(f"Hello {name}")

Listing 1: print input

Python Program: Read two numbers and print their sum, difference, product and divi-
sion.
1 # Read the two numbers and print their sum, difference, product and
division
2

3 import sys
4

Department of Computer Science & Engineering, MITRC, Alwar 4


7CS4-21: Internet of Things Lab

5 if len(sys.argv) != 3:
6 print("Give two number as an argument")
7 sys.exit()
8

9 try:
10 a = float(sys.argv[1])
11 b = float(sys.argv[2])
12 except ValueError:
13 print("Enter only number as argument")
14

15 summ = a + b
16 print(f"Sum of two number is: {summ}")
17 diff = a - b
18 print(f"Difference of two number is: {diff}")
19 prod = a*b
20 print(f"Product of given two number is: {prod}")
21

22 try:
23 div = a/b
24 print(f"Divison of given two number is: {div}")
25 except ZeroDivisionError:
26 print("Second argument must be non zero for division")

Listing 2: basic operation with reading numbers

Viva Voce
1. How you get command argument in python?

2. What is the use argparse module in python?

3. what is difference between list and tuple?

Reference
1. King, Andy. Programming the Internet of Things. “O’Reilly Media, Inc.", 2021.

Department of Computer Science & Engineering, MITRC, Alwar 5


7CS4-21: Internet of Things Lab

2. Lea, Perry. IoT and Edge Computing for Architects: Implementing edge and IoT
systems from sensors to clouds with communication systems, analytics, and security.
Packt Publishing Ltd, 2020.

Department of Computer Science & Engineering, MITRC, Alwar 6


7CS4-21: Internet of Things Lab

Program No. 3

Objective: Run some python programs on Pi like:

1. Word and character count of a given string.

2. Area of a given shape (rectangle, triangle and circle) reading shape and appropriate
values from standard input.

Apparatus Required

Following devices are required to run the program:

1. Computer

2. Raspberry Pi Board

3. USB Connector

4. Ethernet Connector

Python Program: Word and character count of a given string.


1 ################## PRACTICAL ##################
2 # Read a string and print its number of words and character count
3

4 string=input("Enter string:")
5 char=0
6 word=1
7 for i in string:
8 char=char+1
9 if(i==’ ’):
10 word=word+1
11 print("Number of words in the string:")
12 print(word)
13 print("Number of characters in the string:")
14 print(char)

Listing 3: counting words

Department of Computer Science & Engineering, MITRC, Alwar 7


7CS4-21: Internet of Things Lab

Python Program: Area of a given shape (rectangle, triangle and circle) reading shape
and appropriate values from standard input.
1 ############# EXPERIMENT 2.D ###################
2 # Area of a given shape(rectangle, triangle, and circle) reading shape
and
3 # appropriate values from standard input.
4

5 import math
6 import argparse
7 import sys
8

9 def rectangle(x,y):
10 """
11 calculate area and perimeter
12 input: length, width
13 output: dict - area, perimeter
14 """
15 perimeter = 2*(x+y)
16 area = x*y
17 return {"area": area, "perimeter": perimeter}
18

19 def triangle(a, b, c):


20 p = a + b + c
21 s = p/2
22 area = math.sqrt(s*(s-a)*(s-b)*(s-c))
23 return {"area": area, "perimeter": p}
24

25 def circle(r):
26 perimeter = 2*math.pi*r
27 area = math.pi*r*r
28 return {"area": area, "perimeter": perimeter}
29

30 if __name__ == "__main__":
31 choices = ["tri", "circ", "rect"]
32 parser = argparse.ArgumentParser(
33 description="Calculate Area of Basic geometry")

Department of Computer Science & Engineering, MITRC, Alwar 8


7CS4-21: Internet of Things Lab

34 parser.add_argument("geom", choices=choices, help="Geometry type")


35 parser.add_argument(’para’, type=float, nargs=’*’,
36 help="parameters for geometry")
37 args = parser.parse_args()
38 if args.geom=="tri":
39 ret = triangle(args.para[0], args.para[1], args.para[2])
40 print(f"Perimeter: {ret[’perimeter’]}")
41 print(f"Area: {ret[’area’]}")
42 elif args.geom=="rect":
43 ret = rectangle(args.para[0], args.para[1])
44 print(f"Perimeter: {ret[’perimeter’]}")
45 print(f"Area: {ret[’area’]}")
46 else:
47 ret = circle(args.para[0])
48 print(f"Perimeter: {ret[’perimeter’]}")
49 print(f"Area: {ret[’area’]}")

Listing 4: calculating areas

Viva Voce
1. How you will get variable length argument in python function?

2. How you can split the string in python?

Reference
1. King, Andy. Programming the Internet of Things. “O’Reilly Media, Inc.", 2021.

2. Lea, Perry. IoT and Edge Computing for Architects: Implementing edge and IoT
systems from sensors to clouds with communication systems, analytics, and security.
Packt Publishing Ltd, 2020.

Department of Computer Science & Engineering, MITRC, Alwar 9


7CS4-21: Internet of Things Lab

Program No. 4

Objective: Run some python programs on Pi like:

1. Print a name ’n’ times, where name and n are read from standard input, using for
and while loops.

2. Handle Divided by Zero Exception.

Apparatus Required

Following devices are required to run the program:

1. Computer

2. Raspberry Pi Board

3. USB Connector

4. Ethernet Connector

python program: Print a name ’n’ times, where name and n are read from standard
input, using for and while loops.
1 # Print a name ’n’ times, where name and n are read from standard input
,
2 # using for and while loops.
3 import argparse
4

5 def name_in_while_loop(name, num):


6 i = 0
7 while i < num:
8 print(f"{name}")
9 i += 1
10

11 def name_in_for_loop(name, num):


12 for i in range(num):

Department of Computer Science & Engineering, MITRC, Alwar 10


7CS4-21: Internet of Things Lab

13 print(f"{name}")
14

15

16 if __name__ == "__main__":
17 parser = argparse.ArgumentParser("Demontrating for and while loop
of python")
18 parser.add_argument(’name’)
19 parser.add_argument(’number’)
20 args = parser.parse_args()
21 print("\nPrinting using While loop:")
22 name_in_while_loop(args.name, int(args.number))
23 print("\nPrinting using for loop:")
24 name_in_for_loop(args.name, int(args.number))

Listing 5: printing n times from standard input

python program: Handle Divided by Zero Exception.


1 # Lab 5(ii)
2 # Handle Divided by Zero Exception.
3

4 def divider(dividend, divisor):


5 return dividend / divisor
6

8 if __name__ == "__main__":
9 a = int(input("Enter Dividend: "))
10 b = int(input("Enter Divisor: "))
11 try:
12 quotient = divider(a, b)
13 print(f"Quotient is: {quotient}")
14 except ZeroDivisionError:
15 print("Zero is big mystery, Enter other divisor")
16 finally:
17 print("END")

Listing 6: handling division by zero exception

Department of Computer Science & Engineering, MITRC, Alwar 11


7CS4-21: Internet of Things Lab

Viva Voce
1. How you handle the exception in python?

2. What is use of context manager in opening file in python?

3. What are the various file opening mode in python?

Reference
1. King, Andy. Programming the Internet of Things. “O’Reilly Media, Inc.", 2021.

2. Lea, Perry. IoT and Edge Computing for Architects: Implementing edge and IoT
systems from sensors to clouds with communication systems, analytics, and security.
Packt Publishing Ltd, 2020.

Department of Computer Science & Engineering, MITRC, Alwar 12


7CS4-21: Internet of Things Lab

Program No. 5

Objective: Run some python programs on Pi like:

1. Print current time for 10 times with an interval of 10 seconds.

2. Read a file line by line and print the word count of each line.

Apparatus Required

Following devices are required to run the program:

1. Computer

2. Raspberry Pi Board

3. USB Connector

4. Ethernet Connector

python program: Print current time for 10 times with an interval of 10 seconds.

1 ############### Practical : ######################


2 # Print current time for 10 times with an interval of 10 seconds.
3 #----------------------------------------------------------------
4

5 import time
6

7 def current_time():
8 for i in range(10):
9 ct = time.ctime()
10 print(f"current time is: {ct}")
11 time.sleep(10)
12

13

14

15 if __name__=="__main__":

Department of Computer Science & Engineering, MITRC, Alwar 13


7CS4-21: Internet of Things Lab

16 current_time()

Listing 7: printing time

python program: Read a file line by line and print the word count of each line.
1 # Program:
2 # Read a file line by line and print the word count of each line.
3 #--------------------------------------------------------------
4 import sys
5

6 def count_word(line):
7 word = 1
8 for i in line:
9 if i==’ ’:
10 word += 1
11 return word
12

13 f = sys.argv[1]
14

15

16 if __name__=="__main__":
17 l = 1
18 with open(f) as fobj:
19 for line in fobj:
20 print(f"Line {l} => No of Words: {count_word(line)}")
21 l += 1

Listing 8: counting lines in file

Viva Voce
1. What is the module for working with CSV files. ?

2. What is the use of regular expresssion?

Department of Computer Science & Engineering, MITRC, Alwar 14


7CS4-21: Internet of Things Lab

Reference
1. King, Andy. Programming the Internet of Things. “O’Reilly Media, Inc.", 2021.

2. Lea, Perry. IoT and Edge Computing for Architects: Implementing edge and IoT
systems from sensors to clouds with communication systems, analytics, and security.
Packt Publishing Ltd, 2020.

Department of Computer Science & Engineering, MITRC, Alwar 15


7CS4-21: Internet of Things Lab

Program No. 6

Objective: Run some python programs on Pi like:

1. Light an LED through Python program

2. Get input from two switches and switch on corresponding LEDs

Apparatus Required

Following devices are required to run the program:

1. Computer

2. Raspberry Pi Board

3. USB Connector

4. Ethernet Connector

5. LED, Resistor, Button

Python Program : Light an LED through Python program


1 # Program:
2 # Light an LED through Python program
3 #
4 import RPi.GPIO as GPIO
5 from time import sleep
6

7 LED = 10
8

9 def led_setup():
10 GPIO.setwarnings(False)
11 GPIO.setmode(GPIO.BOARD)
12 GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW)
13

14 def main():

Department of Computer Science & Engineering, MITRC, Alwar 16


7CS4-21: Internet of Things Lab

15 led_setup()
16 while True:
17 GPIO.output(LED, GPIO.HIGH)
18 sleep(1)
19 GPIO.output(LED, GPIO.LOW)
20 sleep(1)
21

22 if __name__=="__main__":
23 try:
24 main()
25 finally:
26 GPIO.cleanup()
27 print("Closed Everything. END")

Listing 9: blinking LED

Python Program : Get input from two switches and switch on corresponding LEDs
1 # Program:
2 # Get input from two switches and switch on corresponding LEDs
3 #
4 import RPi.GPIO as GPIO
5 import time
6

7 LED1 = 8
8 LED2 = 12
9 BTN1 = 32
10 BTN2 = 36
11

12 def gpio_setup():
13 GPIO.setmode(GPIO.BOARD)
14 GPIO.setup(BTN1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
15 GPIO.setup(LED1, GPIO.OUT, initial=GPIO.LOW)
16

17 def led_on(LED):
18 GPIO.output(LED, GPIO.HIGH)
19

20 def led_off(LED):

Department of Computer Science & Engineering, MITRC, Alwar 17


7CS4-21: Internet of Things Lab

21 GPIO.output(LED, GPIO.LOW)
22

23 def led_toggle(LED):
24 if GPIO.input(LED):
25 led_off(LED)
26 else:
27 led_on(LED)
28

29 def press_2_on(LED, BTN):


30 btn = GPIO.input(BTN)
31 if btn:
32 led_off(LED)
33 else:
34 led_on(LED)
35

36 def press_2_toggle(LED, BTN):


37 btn = GPIO.input(BTN)
38 if not btn:
39 led_toggle(LED)
40

41 def main():
42 gpio_setup()
43 while True:
44 press_2_on(LED1, BTN1)
45 press_2_toggle(LED2, BTN2)
46

47

48 try:
49 main()
50 finally:
51 GPIO.cleanup()
52 print("closed Event")

Listing 10: on/off LED using switch

Department of Computer Science & Engineering, MITRC, Alwar 18


7CS4-21: Internet of Things Lab

Viva Voce
1. What is push and pull resister?

2. Explain working of LED.

3. How GPIO pin mode is set ?

Reference
1. King, Andy. Programming the Internet of Things. “O’Reilly Media, Inc.", 2021.

2. Lea, Perry. IoT and Edge Computing for Architects: Implementing edge and IoT
systems from sensors to clouds with communication systems, analytics, and security.
Packt Publishing Ltd, 2020.

Department of Computer Science & Engineering, MITRC, Alwar 19


7CS4-21: Internet of Things Lab

Program No. 7

Objective: Run some python programs on Pi like:

1. Flash an LED at a given on time and off time cycle, where the two times are taken
from a file.

Apparatus Required

Following devices are required to run the program:

1. Computer

2. Raspberry Pi Board

3. USB Connector

4. Ethernet Connector

5. LED, Resistor, Button

Python Program : Flash an LED at a given on time and off time cycle, where the two
times are taken from a file.
1 # Program:
2 # Flash an LED at a given on time and off time cycle,
3 # where the two times are taken from a file.
4 #
5 import time
6 import csv
7 import sys
8 import RPi.GPIO as GPIO
9 from time import sleep
10

11

12 def setup():
13 GPIO.setwarnings(False)

Department of Computer Science & Engineering, MITRC, Alwar 20


7CS4-21: Internet of Things Lab

14 GPIO.setmode(GPIO.BOARD)
15 GPIO.setup(10, GPIO.OUT, initial=GPIO.LOW)
16

17 def read_time():
18 timing = []
19 with open(sys.argv[1], ’rt’) as f:
20 reader = csv.reader(f)
21 for row in reader:
22 timing.append((row[0], row[1]))
23 return timing[1:]
24

25 def main():
26 setup()
27 time_seq = read_time()
28 for on, off in time_seq:
29 GPIO.output(10, GPIO.HIGH)
30 print("LED ON")
31 time.sleep(float(on))
32 GPIO.output(10, GPIO.LOW)
33 print("LED OFF")
34 time.sleep(float(off))
35

36 try:
37 main()
38 finally:
39 GPIO.cleanup()
40 print("END")

Listing 11: flashing LED with cycle reading from file

Viva Voce
1. How you write output on GPIO pin ?

2. Why you sleep duration in writing GPIO program ?

Department of Computer Science & Engineering, MITRC, Alwar 21


7CS4-21: Internet of Things Lab

Reference
1. King, Andy. Programming the Internet of Things. “O’Reilly Media, Inc.", 2021.

2. Lea, Perry. IoT and Edge Computing for Architects: Implementing edge and IoT
systems from sensors to clouds with communication systems, analytics, and security.
Packt Publishing Ltd, 2020.

Department of Computer Science & Engineering, MITRC, Alwar 22


7CS4-21: Internet of Things Lab

Program No. 8

Objective: Run some python programs on Pi like:

1. Flash an LED based on cron output (acts as an alarm)

2. Switch on a relay at a given time using cron, where the relay’s contact terminals are
connected to a load.

Apparatus Required

Following devices are required to run the program:

1. Computer

2. Raspberry Pi Board

3. USB Connector

4. Ethernet Connector

5. LED, Resistor, Button

Python Program : Flash an LED based on cron output (acts as an alarm)

1 # Flash an LED based on cron output (acts as an alarm)


2

4 # alarm.py
5 # act as alarm for cron
6 import RPi.GPIO as GPIO
7 from time import sleep
8

9 ALARM = 10
10

11 def led_setup():
12 GPIO.setwarnings(False)

Department of Computer Science & Engineering, MITRC, Alwar 23


7CS4-21: Internet of Things Lab

13 GPIO.setmode(GPIO.BOARD)
14 GPIO.setup(ALARM, GPIO.OUT, initial=GPIO.LOW)
15

16 def main():
17 led_setup()
18 GPIO.output(ALARM, GPIO.HIGH)
19 sleep(60)
20

21 if __name__=="__main__":
22 try:
23 main()
24 finally:
25 GPIO.cleanup()
26 print("Closed Everything. END")
27

28

29

30 # flashing LED as response to alarm


31 # flash_led.py
32

33 import RPi.GPIO as GPIO


34 from time import sleep
35

36 LED = 10
37

38 def led_setup():
39 GPIO.setwarnings(False)
40 GPIO.setmode(GPIO.BOARD)
41 GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW)
42

43 def main():
44 led_setup()
45 alarm = GPIO.input(10)
46 while alarm:
47 GPIO.output(LED, GPIO.HIGH)
48 sleep(1)
49 GPIO.output(LED, GPIO.LOW)

Department of Computer Science & Engineering, MITRC, Alwar 24


7CS4-21: Internet of Things Lab

50 sleep(1)
51

52 if __name__=="__main__":
53 try:
54 main()
55 finally:
56 GPIO.cleanup()
57 print("Closed Everything. END")
58

59 ############ CONSOLE ##################


60 # $ crontab -e
61 # 15 03 * * * python /home/pi/Lab10/alarm.py
62 # $ python flash_led.py

Listing 12: flash LED using cron job

Python Program : Switch on a relay at a given time using cron, where the relay’s contact
terminals are connected to a load.
1 # Flash an LED based on cron output (acts as an alarm)
2

4 # alarm.py
5 # act as alarm for cron
6 import RPi.GPIO as GPIO
7 from time import sleep
8

9 ALARM = 10
10

11 def led_setup():
12 GPIO.setwarnings(False)
13 GPIO.setmode(GPIO.BOARD)
14 GPIO.setup(ALARM, GPIO.OUT, initial=GPIO.LOW)
15

16 def main():
17 led_setup()
18 GPIO.output(ALARM, GPIO.HIGH)

Department of Computer Science & Engineering, MITRC, Alwar 25


7CS4-21: Internet of Things Lab

19 sleep(60)
20

21 if __name__=="__main__":
22 try:
23 main()
24 finally:
25 GPIO.cleanup()
26 print("Closed Everything. END")
27

28

29

30 # flashing LED as response to alarm


31 # flash_led.py
32

33 import RPi.GPIO as GPIO


34 from time import sleep
35

36 LED = 10
37

38 def led_setup():
39 GPIO.setwarnings(False)
40 GPIO.setmode(GPIO.BOARD)
41 GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW)
42

43 def main():
44 led_setup()
45 alarm = GPIO.input(10)
46 while alarm:
47 GPIO.output(LED, GPIO.HIGH)
48 sleep(1)
49 GPIO.output(LED, GPIO.LOW)
50 sleep(1)
51

52 if __name__=="__main__":
53 try:
54 main()
55 finally:

Department of Computer Science & Engineering, MITRC, Alwar 26


7CS4-21: Internet of Things Lab

56 GPIO.cleanup()
57 print("Closed Everything. END")
58

59 ############ CONSOLE ##################


60 # $ crontab -e
61 # 15 03 * * * python /home/pi/Lab10/alarm.py
62 # $ python flash_led.py

Listing 13: switching relay using cron job

Viva Voce
1. What is the use of Relay?

2. What is the use of http protocol?

3. What is the use of websocket protocol?

4. Name application protocol specially designed for IoT.

5. what is the use of cron command ?

Reference
1. King, Andy. Programming the Internet of Things. “O’Reilly Media, Inc.", 2021.

2. Lea, Perry. IoT and Edge Computing for Architects: Implementing edge and IoT
systems from sensors to clouds with communication systems, analytics, and security.
Packt Publishing Ltd, 2020.

Department of Computer Science & Engineering, MITRC, Alwar 27

You might also like