0% found this document useful (0 votes)
34 views21 pages

IOTlab Deepak

The document describes experiments conducted in an "Internet of Things Lab". It provides instructions on using various Linux commands like ls, cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip, cat, more, less, ps, sudo, cron, chown, chgrp, ping, chmod, curl, echo, exit, find, finger, free, and grep in the command terminal of a Raspberry Pi. It also involves running Python programs on the Raspberry Pi to perform tasks like reading input, printing output, handling exceptions, reading and writing files. The experiments cover topics like controlling LEDs, using switches as input, setting timers for flashing LEDs, using cron jobs to control rel
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)
34 views21 pages

IOTlab Deepak

The document describes experiments conducted in an "Internet of Things Lab". It provides instructions on using various Linux commands like ls, cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip, cat, more, less, ps, sudo, cron, chown, chgrp, ping, chmod, curl, echo, exit, find, finger, free, and grep in the command terminal of a Raspberry Pi. It also involves running Python programs on the Raspberry Pi to perform tasks like reading input, printing output, handling exceptions, reading and writing files. The experiments cover topics like controlling LEDs, using switches as input, setting timers for flashing LEDs, using cron jobs to control rel
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/ 21

“INTERNET OF THINGS LAB”

Submitted in partial fulfilment of


the requirements for the award of the degree of

Bachelor of Technology
In
Computer Science & Engineering
(Bikaner Technical University, Bikaner)

SUBMITTED BY: SUBMITTED TO:


Name- Mr. Deepak Kumawat Dr. Maninder Singh Nehra
University Roll No.: 20EEBCS022 Assistant Professor
Branch: CSE-1(A1) Department of CSE

Year (Semester): 4th (7th)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


ENGINEERING COLLEGE, BIKANER
INDEX

Exp.no. List of Experiments Page no.

2-6
Start Raspberry Pi and try various Linix commands in
1 command terminal 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:


i)Read your name and print Hello message with name
ii)Read two numbers and print their sum, difference, product and
division.
2 7-11
iii)Word and character count of a given string.
iv)Area of a given shape (rectangle, triangle and circle) reading
shape and appropriate values from standard input.

Run some python programs on Pi like:


i)Print a name 'n' times, where name and n are read from
standard input, using for and while loops. ii)Handle Divided
by Zero Exception. 12-14
3
iii)Print current time for 10 times with an interval of 10 seconds.
iv)Read a file line by line and print the word count of each line.

4 i) Light an LED through Python program 15-16


ii) Get input from two switches and switch on corresponding
LEDs
iv)Flash an LED at a given on time and off time cycle, where the
two times are taken from a file.

5 i) Flash an LED based on cron output (acts as an alarm) 17-19


ii) Switch on a relay at a given time using cron, where the relay's
contact terminals are connected to a load.
iii)Get the status of a bulb at a remote place (on the LAN) through
web.

1
Experiment – 1
Aim: Start Raspberry Pi and try various Linux commands in command terminal window:ls,
cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip, cat, more, less, ps, sudo,cron, chown, chgrp,
ping, chmod, curl, echo, exit, find, finger, free, grep, kill etc.Use command line terminal of
linux operating system, preferably Raspberry Pi operating system.

Linux Commands:

1. ls: It lists directory contents of files and directories.

- Display All Information About Files/Directories Using $ ls -l

- Open Last Edited File Using ls -t

- Display File Size in Human Readable Format Using ls –lh

2. cd: cd command in linux known as change directory command. It is used to change


the current working directory.

Syntax:
$ cd [directory]

- cd /: this command is used to change directory to the root directory

- cd dir_1/dir_2/dir_3: This command is used to move inside a directory from a


directory
- cd .. : this command is used to move to the parent directory of current directory, or
the directory one level up from the current directory.

- cd “dir name”: This command is used to navigate to a directory with white spaces.

3. touch: Used to create, change and modify timestamps of a file. It is used to


create a file without any content.
Touch command Syntax to create a new file:
touch file_name
Touch command to create multiple files: touch

File1_name File2_name File3_name

2
4. mv: mv stands for move. mv is used to move one or more files or directories from
one place to another in file system.
It has two distinct functions:

- It rename a file or folder. - It moves group of files to different directory.

Syntax: mv [Option] source destination

5. rm : rm stands for remove here. rm command is used to remove objects such as files,
directories, symbolic links and so on from the file system Syntax: rm [OPTION]... FILE...

6. man: man command in Linux is used to display the user manual of any
command

Syntax :
$man [OPTION]... [COMMAND NAME]...

7. mkdir: mkdir command in Linux allows the user to create directories

Syntax :
$man [OPTION]... [COMMAND NAME]...

8. rmdir: rmdir command in Linux allows the user to create directories

Syntax:
rmdir [-p] [-v | –verbose] [–ignore-fail-on-non-empty] directories …

9. tar: The Linux ‘tar’ stands for tape archive, is used to create Archive and extract the
Archive files.

Syntax:
tar [options] [archive-file] [file or directory to be archived]

10. gzip: gzip command compresses files. Syntax : gzip [Options] [filenames]

3
Example:

$ gzip [mydoc.txt]

11. cat: It reads data from the file and gives their content as output. It helps us to
create, view, concatenate files.
Command:
$cat filename

12. more: more command is used to view the text files in the command prompt, displaying
one screen at a time in case the file is large (For example log files). The more command
also allows the user do scroll up and down through the page.
Syntax: more [-options] [-num] [+/pattern] [+linenum]
[file_name]

[-options] : any option that you want to use in order to change the way the file is
displayed. Choose any one from the followings: (-d, -l, -f, -p, -c, - s, -u)

[-num] : type the number of lines that you want to display per screen. ∙

[+/pattern]: replace the pattern with any string that you want to find in the text file.

[+linenum]: use the line number from where you want to start displaying the text
content.

[file_name]: name of the file containing the text that you want to display on the screen.
13. Less: less command is linux utility which can be used to read contents of text

file one page (one screen) per time. It has faster access because if file is large, it don’t
access complete file, but access it page by page.

syntax :
less filename

14. ps : ps for viewing information related with the processes on a system which
stands as abbreviation for “Process Status”
Syntax – ps [options]

15. sudo: sudo ( S uper U ser DO ) command in Linux is generally used as a prefix of some
command that only superuser are allowed to run.
16. cron: automates the scheduled task at a predetermined time. It is a daemon
process , which runs as a background process.
4
Syntax: cron [-f] [-l] [-L
loglevel]

17. chown: chown command is used to change the file Owner or group. Whenever you
want to change ownership you can use chown command.

Syntax:
chown [OPTION]… [OWNER][: [GROUP]] FILE… chown

[OPTION]… –reference=RFILE FILE…

18. chgrp : chgrp command in Linux is used to change the group ownership of a file or
directory.

Syntax:

Chgrp [OPTION]… GROUP FILE… chgrp

[OPTION]… –reference=RFILE FILE…

19. ping: PING (Packet Internet Groper) command is used to check the network
connectivity between host and server/host.
20. chmod : the chmod command is used to change the access mode of a file. The
name is an abbreviation of change mode .

Syntax :
chmod [reference][operator][mode] file...

21. curl: curl is a command line tool to transfer data to or from a server, using any of the
supported protocols

Syntax:
curl [options] [URL...]

22. echo: echo command in linux is used to display line of text/string that are
passed as an argument .

Syntax : echo [option] [string]

23. exit: exit command in linux is used to exit the shell where it is currently
running.
It takes one more parameter as [ N] and exits the shell with a return of status N .

Syntax:

exit [n]

5
24. find: It can be used to find files and directories and perform subsequent
operations on them. It supports searching by file, folder, name, creation date,
modification date, owner and permissions.

Syntax :

$ find [where to start searching from]

[ expression determines what to find] [-options] [what to find]

25. Finger: command is a user information lookup command which gives details of all the
users logged in

Syntax:

$finger[username]

26. Free: command which displays the total amount of free space available along with
the amount of memory used and swap memory in the system, and also the buffers
used by the kernel.
Syntax:

$free [OPTION]

27. Grep: The grep filter searches a file for a particular pattern of characters, and
displays all lines that contain that pattern.

Syntax:

grep [options] pattern [files]

28. Kill: command in Linux (located in /bin/kill), is a built-in command which is used to
terminate processes manually. kill command sends a signal to a process which
terminates the process.

6
Experiment – 2

Aim: Run some python programs on Pi like:

a) Read your name and print Hello message with name.

Python Program:

name = input('What is
your name?\n') print ('Hello
%s.' % name)

Output:

What is your name?

Mr. Akshat Jain Hello

Mr. Akshat Jain.

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

Python Program:

num1 = int(input("Enter First Number: ")) num2 =

int(input("Enter Second Number:"))

print("Enter which operation would you like to perform?")ch = input("Enter any of these
char for specific operation +,-,*,/: ") result =

0 if ch == '+':

result = num1 + num2 elif


ch == '-':

result = num1 - num2 elif


ch == '*':

result = num1 * num2 elif


ch == '/':

result = num1 / num2 else:

7
print("Input character is not recognized!") print(num1,

ch , num2, ":", result)

Output 1: Addition

Enter First Number:100

Enter Second Number:5

Enter which operation would you like to perform? Enter any


of these char for specific operation
+ ,-,*,/:

100+ 5:105

Output 2: Subtraction Enter First Number: 8 Enter Second Number: 7

Enter which operation would you like to perform?


Enter any of these char for specific operation +,-,*,/: -
8-7:1

Output 3: Multiplication Enter First Number: 6 Enter Second Number: 8

Enter which operation would you like to perform? Enter any of these char for
specific operation +,-,*,/: * 6 * 8 : 48

Output 4: Division Enter First Number: 20 Enter Second Number: 5

Enter which operation would you like to perform? Enter any of these char for
specific operation +,-,*,/: /20 5 : 4.0

c) Word and character count of a given string.

Python Program:

word_count = 0 char_count

=0

usr_input = input("Enter a string :")


split_string = usr_input.split()
word_count = len(split_string)

8
for word in split_string: char_count +=
len(word)

print("Total words : {}".format(word_count)) print("Total


characters :{}".format(char_count))

Output:

Enter a string : Hello, How are You?

Total words : 4 Total

characters : 16

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

Python Program:

width = float(input('Please Enter the Width of a Rectangle: ')) height =

float(input('Please Enter the Height of a Rectangle: '))

# calculate the area Area = width * height

# calculate the Perimeter Perimeter = 2 * (width + height)

print("\n Area of a Rectangle is: %.2f" %Area) print("Perimeter of

Rectangle is: %.2f"%Perimeter)

Output:

Please Enter th Widt of a Rectangle:22


e h
Please Enter th Height of a
e
Rectangle: 5

Area of a Rectangle is: 110.00

Perimeter of Rectangle is: 54.00

Python Program:

# Python Program to find the area of triangle


9
# Three sides of the triangle a, b and c are provided by the user a =

float(input('Enter first side: ')) b = float(input('Enter second side:')) c

= float(input('Enter third side: '))

# calculate the semi-perimeter s = (a + b + c) / 2

# calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The

area of the triangle is %0.2f' %area)

Output:

Enter first side: 3


Enter second side:4
Enter third side: 5

The area of the triangle is 6.00

Python Program:

# Python Program to find Diameter, Circumference, and Area of a

Circle PI = 3.14 radius = float(input(' Please Enter the radius of

acircle: '))

diameter = 2 * radius

circumference = 2 * PI * radius area = PI * radius * radius

print(" \n Diameter of a Circle = %.2f" %diameter)

print("Circumferenceof a Circle =%.2f"%circumference) print("

Area of a Circle = %.2f" %area)

Output: Please Enter the radius of a circle: 5

Diameter of a Circle = 10.00

Circumference of a Circle = 31.40

Area of a Circle = 78.50

10
Combined Python Program:

#Area print("Select one of the following:") print("1. Rectangle\n2. Triangle\n3.

Circle") s=input("Enter your choice: ")

if s=='1':

x=int(input("Enter length:"))
y=int(input("Enter breadth:"))
print("Area={}".format(x*y))
elif s=='2':

x=int(input("Enter base:"))

y=int(input("Enter height:"))

print("Area={}".format(0.5*x*y)) elif

s=='3': x=int(input("Enter radius:"))

print("Area={}".format(3.14*x*x))

else:

print("Enter a valid choice")

11
Experiment – 3

Aim: 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.

Python Program (Using For Loop):

i=1

print ("enter the name") name=raw_input()

print ("enter the no of time" ) num=raw_input()

#print (type(num)) num=int(num) for i in

range(1,num+1): print (i , name) i=i+1

Python Program (Using While Loop): print ("enter

the name") name=raw_input() print ("enter the no of

time" ) num=raw_input() print (type(num))

num=int(num) i=1 while(i<=num): print (name) i=i+1

Python Program (Without Loop): def

name(n):

if n != 0:

name(n-1)

print("Name") name(10)

b) Handle Divided by Zero Exception.

Python Program:

print ("enter two no n1 and n2")

12
n1=raw_input()

n2=raw_input()

n1=int(n1) n2=int(n2)

try:

div=n1/n2 print (div)


except ZeroDivisionError:

print ("zero division is handled") print

("out of try catch block ")

Output:

Enter n1:10 Enter n2:0

zero division is handled

#DivideByZero Exception x=int(input("First No:"))

y=int(input("Second No:"))

try:

print("x/y={}".format(x/y))
except Exception:

print("DivideByZero
Exception")

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

Python Program:

import time for i in range(1,11):

zz=time.asctime(time.localtime(time.time())) zz=zz[11:19]

print (zz)

print (time.asctime(time.localtime(time.time()))) time.sleep(10)

13
Python Program:

#Current time 10 times import datetime import time

for i in range(0,10):
print(datetime.datetime.now().time()) time.sleep(10)

d) Read a file line by line and print the word count of each line. Python

Program: file=open("eee.txt","r") line=1

for i in file:

print ("print the line no=" , line , "and line is =" , i) z=i.split()

print ("no of word in line =" , line ,"is = " , len(z))


line = line+1

Python Program:

# read line by line from file

L = ["Welcome to India", "Delhi is the capital\n", "Have fun\n"] file1 = open('myfile.txt', 'w')

file1.writelines((L)) file1.close() file1

= open('myfile.txt', 'r') count = 0 while

True:

count+=1 line =

file1.readline()

if not line: break

print("Word Count in Line{}: {}".format(count, len(line.split())) )file1.close()

14
Experiment -4

a) Light an LED through Python program:

import RPi.GPIO as GPIO import


time

LED_PIN = 18 # Assuming the LED is connected to GPIO pin 18

GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN,
GPIO.OUT)

try: while
True:
GPIO.output(LED_PIN, GPIO.HIGH) # LED ON time.sleep(2) # Wait
for 2 seconds
GPIO.output(LED_PIN, GPIO.LOW) # LED OFF time.sleep(2) # Wait
for 2 seconds

except KeyboardInterrupt:
GPIO.cleanup()

b) Get input from two switches and switch on corresponding LEDs:


import RPi.GPIO as GPIO

LED_PIN_1 = 18
LED_PIN_2 = 23
SWITCH_PIN_1 = 17
SWITCH_PIN_2 = 27

GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN_1, GPIO.OUT)
GPIO.setup(LED_PIN_2, GPIO.OUT)
GPIO.setup(SWITCH_PIN_1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(SWITCH_PIN_2, GPIO.IN, pull_up_down=GPIO.PUD_UP)

try: while
True:
input_state_1 = GPIO.input(SWITCH_PIN_1)

input_state_2 = GPIO.input(SWITCH_PIN_2) if

input_state_1 == GPIO.LOW:

GPIO.output(LED_PIN_1, GPIO.HIGH) else:


GPIO.output(LED_PIN_1, GPIO.LOW)

15
if input_state_2 == GPIO.LOW:
GPIO.output(LED_PIN_2, GPIO.HIGH) else:
GPIO.output(LED_PIN_2, GPIO.LOW)

except KeyboardInterrupt:
GPIO.cleanup()

c) Flash an LED at a given on time and off time cycle from a

file:

import RPi.GPIO as GPIO

LED_PIN = 18

GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN,
GPIO.OUT)

try: with open('flash_times.txt', 'r') as file:


on_time = float(file.readline()) off_time
= float(file.readline())

while True:
GPIO.output(LED_PIN, GPIO.HIGH)
time.sleep(on_time)
GPIO.output(LED_PIN, GPIO.LOW)
time.sleep(off_time)

except KeyboardInterrupt: GPIO.cleanup()

16
Experiment-5
Aim:(a) Flash an LED based on cron output (acts as an alarm)

Python Program:

Python code: blink.py

import RPi.GPIO as GPIO

import time

LedPin = 11 # pin11 def setup():

GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location

GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output

GPIO.output(LedPin, GPIO.HIGH) # Turn ON led

def blink():

while True:

GPIO.output(LedPin, GPIO.HIGH) # led on time.sleep(1)

GPIO.output(LedPin, GPIO.LOW) # led

off time.sleep(1)

def destroy():

GPIO.output(LedPin, GPIO.LOW) # led off

GPIO.cleanup() # Release resource

if name == ' main ': # Program start from here setup()

try:

bink()

except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.

destroy()

17
a) Switch on a relay at a given time using cron:

Hardware Setup:
● Connect the relay module to the Raspberry Pi's GPIO pins.
● Connect the load (such as a light bulb or any other electrical appliance) to
the relay's contact terminals.
Cron Job Setup:
● Create a Python script (let's name it relay_control.py ) that will turn on the
relay at a specific time using gpiozero library.

Python code:- from gpiozero import


OutputDevice from datetime import
datetime

# GPIO pin number connected to the relay relay_pin = 17 # Change


this to the actual GPIO pin you're using

# Initialize the GPIO pin relay =


OutputDevice(relay_pin)

# Turn on the relay relay.on()

# Log the action (optional) with open('relay_log.txt', 'a')


as log_file: log_file.write(f"Relay turned on at
{datetime.now()}\n")

Cron Job Setup:


● Open the crontab editor using crontab -e .
● Add an entry to run the script at the desired time:

# Run the relay_control.py script at 8:00 AM every day


0 8 * * * /usr/bin/python3 /path/to/relay_control.py

This setup will execute the Python script at the specified time, turning on the relay, which
in turn powers the connected load.

b) Get the status of a bulb at a remote place (on the LAN) through the web:

For remote access to the bulb's status over the LAN through a web interface, you can:
Set Up a Web Server on Raspberry Pi:

● Use a Python web framework like Flask or Django to create a web server on
the Raspberry Pi.

18
Implement an Endpoint for Bulb Status:
● Within your web application, create an endpoint (URL) that returns the
status of the bulb.
● The status could be retrieved by reading the GPIO pin connected to a sensor
or a relay controlling the bulb.

Python code-

from flask import Flask

app = Flask(__name__)

# Endpoint to get bulb status

@app.route('/bulb_status') def get_bulb_status():

# Code to read GPIO pin status and determine the bulb status # For

example: bulb_status = "ON" # Replace this with actual logic to determine

bulb status return f"Bulb status: {bulb_status}"

if __name__ == '__main__':

app.run(host='0.0.0.0', port=80) # Run the web server on LAN

(c) Get the status of a bulb at a remote place (on the LAN) through web.

Accessing the Status:

● Access the Raspberry Pi's IP address and the specified endpoint


( /bulb_status ) from a web browser or another device on the same LAN.
● The web page or response will show the current status of the bulb as
retrieved from the Raspberry Pi's GPIO pin or relay.

19

You might also like