You are on page 1of 24

IOT LAB Page|1

Name: Vinodgowda G Usn: 1EW22MC059


Program No:01 Date:
Program Statement: Run Some python program on pi like:
a) Read your name and print Hello Message with name.
b) Read two numbers and print their sum, difference, product and division.
c) Calculate the number of Words and Character String.
d) Read two input numbers and calculate the area of given (Rectangle, Triangle
and Circle) reading shape and appropriate values from standard output.
e) A program to print a name ‘n’, times where name & value has to be input from
standard input.
f) A program to handle Divide by Zero Exception.
g) A program to print current time with an interval of 10 seconds import time.
h) Read file line by line & print the word count of each line.

1a. Read your name and print Hello Message with name.

Source code:
name=input ("enter your name")

print("Hello",name)

output:
enter your name

Vinodgowda G

Hello Vinodgowda G

1b. A Program to read two number and display sum, difference, product and division.

Source code:
a=int(input("enter the value of a:"))
b=int(input("enter the value of b:"))
print("sum is:",a+b)
print("sub is:",a-b)
print("mult is:",a*b)
print("div is:",a/b)

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB Page|2

Output:
enter the value of a:5
enter the value of b:5
sum is: 10
sub is: 0
mult is: 25
div is: 1

1c. A Program to calculate number of words and characters of a given string.

Source code:
print("enter a sentence")
sen=input()
words=sen.split()
word_count=0
char_count=0
for word in words:
word_count+=1
char_count+=len(words)
print("total no of words in a sentence :",word_count)
print("total no of character in a sentence :",char_count)
print("total no of character in the sentence including space are:",char_count+word_count-1)

output:
enter a sentence
haii this is iot lab
total no of words in a sentence: 5
total no of character in a sentence: 25
total no of character in the sentence including space are: 29

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB Page|3

1d. A Program to get Area of a selected shapes(rectangle,triangle,circle)

Source code:
while True:
print("******************************")
print("select type shape")
print("""
1. rectangle
2.triangle
3.circle
4.exit""")
ch=input()
if(ch=='1'):
print("enter width of rectangle")
w=int(input())
print("enter length of rectangle")
h=int(input())
area=h*w
print("the area of rectangle is=",area)
continue
elif(ch=='2'):
print("enter base of triangle")
b=int(input())
print("enter height of triangle")
h=int(input())
areat=0.5*b*h
print("the area of triangle is=",areat)
continue
elif(ch=='3'):
print("enter radius")
r=int(input())
areac=3.142*r*r
print("the area of circle is=",areac)
continue

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB Page|4

elif(ch=='4'):
break
else:
exit(0)
print("invalid choice")
continue
print("thank you")

output:
******************************
select type shape

1.rectangle
2.triangle
3.circle
4.exit
1
enter width of rectangle
2
enter length of rectangle
2
the area of rectangle is= 4
******************************
select type shape
1.rectangle
2.triangle
3.circle
4.exit
2
enter base of triangle
3
enter height of triangle
2

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB Page|5

the area of triangle is= 3.0


******************************
select type shape

1. rectangle
2.triangle
3.circle
4.exit
3
enter radius
2
the area of circle is= 12.568

1e. A Program to print a name n times where name and n values has to be input from
standard input, using for and while loop.

Source code:
while True:
print("enter your choice from menu:")
print("1.while loop \n 2.for loop\n 3.exit")
choice=input()
if (choice=='1'):
name=str(input("enter a name:"))
n=int(input("enter the number"))
i=0
while i<n:
print(name)
i=i+1
elif(choice=='2'):
name=str(input("enter a name:"))
n=int(input("enter the number"))
for i in range(n):

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB Page|6

print(name)
else:
break

output:
enter your choice from menu:
1.while loop
2. for loop
3.exit
1
enter a name: mca
enter the number 3
mca
mca
mca
enter your choice from menu:
1.while loop
2. for loop
3.exit
2
enter a name:
Vinodgowda G

enter the number 2


Vinodgowda G
Vinodgowda G

1f. A Program to Handle Divide by Zero Exception.

Source code:
print("enter the numerator value :")
num1=int(input())
print("enter the denominator value:")
num2=int(input())
try:
result=num1/num2

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB Page|7

print("the division of given number is :",result)


except ZeroDivisionError:
print("divide by zero error. the denominator should not be zero")

Output:
enter the numerator value:
4
enter the denominator value:
2
the division of given number is: 2.0

enter the numerator value:


5
enter the denominator value:
0
divide by zero error. The denominator should not be zero

1g. A Program to print current time with an interval of 10 seconds.

Source code:
import time
for i in range(10):
second=time.time()
local_time=time.ctime(second)
print("local_time",local_time)
time.sleep(10)

Output:
local_time Sun Jan 21 19:34:34 2024
local_time Sun Jan 21 19:34:44 2024
local_time Sun Jan 21 19:34:54 2024
local_time Sun Jan 21 19:35:04 2024
local_time Sun Jan 21 19:35:14 2024

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB Page|8

local_time Sun Jan 21 19:35:24 2024


local_time Sun Jan 21 19:35:34 2024
local_time Sun Jan 21 19:35:44 2024
local_time Sun Jan 21 19:35:54 2024
local_time Sun Jan 21 19:36:04 2024

1h. A Program to Read a file and print number of words in each Line.

Source code:
f1=open('txt.txt','r')
lines=f1.readlines()
i=0
for line in lines:
i+=1
count=len(line.split())
print("line",i,"no of words",count)

output:
line 1 no of words 1
line 2 no of words 2
line 3 no of words 3
line 4 no of words 2

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB Page|9

Name: Vinodgowda G Usn: 1EW22MC059


Program No:02 Date:
Program Statement: Get input from two switches and switch on corresponding LEDs.

Source Code:
import time
import RPi.GPIO as gpio
gpio.setmode(gpio.BOARD)
gpio.setwarning(False)
led1=15
led2=13
switch1=37
switch2=35
gpio.setup(led1,gpio.OUT,initial=1)
gpio.setup(led2,gpio.OUT,initial=1)
gpio.setup(switch1,gpio.IN)
gpio.setup(switch2,gpio.IN)

def glow_led(event):
if event==switch1:
gpio.output(led1,0)
time.sleep(3)
gpio.output(led1,1)
elif event==switch2:
gpio.output(led2,0)
time.sleep(3)
gpio.output(led2,1)
gpio.add_event_detect(switch1,gpio.RISING,callback=glow_led,bouncetime=1)
gpio.add_event_detect(switch2,gpio.RISING,callback=glow_led,bouncetime=1)
try:
while(True):
time.sleep(1)
except KeyboarsInterrupt:
gpio.cleanup()

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 10

Output
Press the switch1 or switch2 on the Raspberry Pi3 board, the corresponding LED will be ON
for 3sec and will turned OFF only one switch will be taken as the input. Switch1 =led2,
switch2=led3. This program will be in loop, Press Ctrl+C to quit.

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 11

Name: Vinodgowda G Usn: 1EW22MC059


Program No.:03 Date:
Program Statement: Flash an LED at a given on time and off time cycle, where the two
times are taken from a file.

Source Code:
import time
import RPi.GPIO as gpio
gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
led1=15
gpio.setup(led1,gpio.OUT,initi
al=0)
file1=open('ledintervals.txt','r')
Lines=file1.readlines()
ON_TIME=int(Lines[0].split("="
)[1])
OFF_TIME=int(Lines[1].split("=
")[1])
try:
while(True):

gpio.output(led1,True)
time.sleep(ON_TIME)
gpio.output(led1,False)
time.sleep(OFF_TIME)
except KeyboardInterrupt:

gpio.cleanup()

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 12

Output:
Led1 will be turned ON and OFF for certain time according to the condition declared in the
text file. Content of text file File name is: ledinterval.txt ON_TIME=5 OFF_TIME=10

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 13

Name: Vinodgowda G Usn: 1EW22MC059


Program No:04 Date:
Program Statement: Switch on a relay at a given time using cron, where the relay’s
contact terminals are connected to a load.

Source code:
import time
import RPi.GPIO as gpio
gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
relay1=38
gpio.setup(relay1,gpio.OUT,initial=0)
try:
gpio.output(relay1,True)
print("Realy is switched On.Please press CTRL+c to exit")
time.sleep(15)
print("Relay is switched OFF")
gpio.output(relay1,False)
except KeyboardInterrupt:
gpio.cleanup()
print("Program exited")

output:
Relay is switched on.
Please press control +C to Exit.
Relay is switched off.

PROGRAM EXITED
pi@raspberrypi:~ $ sudo select-editor Select an editor.
To change later, run 'select-editor'.
1. /bin/ed

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 14

2. /bin/nano < ---- easiest

3. /usr/bin/vim.tiny Choose 1-3 [2]: 2 pi@raspberrypi:~ $ sudo crontab -e

Enter-> min->hr-> * * * sudo python3 /home/pi/Desktop/Group9/


4.py-> Ctrl+X ->y->enter->Light will glow

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 15

Name: Vinodgowda G Usn: 1EW22MC059


Program No:05 Date:
Program Statement: Access an image through a pi web cam.

Source code:
from picamera import PiCamera
from time import sleep
import datetime
camera=PiCamera()
camera.vflip=True
camera.resolution=(800,580)
camera.start_preview()
current_date=datetime.datetime.now().strftime('%d-%m-%y%h:%m:%s')
sleep(5)
camera.capture('/home/pi/Desktop/'+current_date+'.jpg')
camera.stop_preview()
print("image captured")

output:

Image captured.

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 16

Name: Vinodgowda G Usn: 1EW22MC059


Program No:06 Date:
Program Statement: Control a light source using web page.

Source code:

import RPi.GPIO as GPIO


import time
import datetime
led=13
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(led,GPIO.OUT,initial=0)

from flask import Flask,render_template


app=Flask(_name_)
@ app.route('/')
def hello_world():
return render_template('web.html')
@app.route('/redledon')
def redledon():
GPIO.output(13,GPIO.HIGH)
now=datetime.datetime.now()
timestring=now.strftime("%y-%m-%d%H:%M")
templateData={
'status':'ON',
'time':timestring }
return render_template('web.html',**templateData)
@app .route('/redledoff')
def redledoff():
GPIO.output(13,GPIO.LOW)
now=datetime.datetime.now()
timestring=now.strftime('%y-%m-%d%h:%m')
templateData={'status':'OFF','time':timestring
}
return render_template('web.html',**templateData)
if _name_ == '_main_':
app.run(debug=True,port=4001,host="127.0.1.1")

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 17

Web.html

<html>
<body>
<title>rasparry pi remute control</title>
<h1>rasperry pi remote control</h1>
<h2>light status:{{status}},last modified:{{time}}</h2>
<form action="http://127.0.1.1:4001/redledoff">
<input type="submit" value="redledon">
</form>
<form action="http://127.0.1.1:4001/redledon">
<input type="submit" value="redledoff">
</form>
</body>
</html>

Output:

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 18

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 19

Name: Vinodgowda G Usn: 1EW22MC059


Program No:07 Date:
Program Statement: Implement an intruder system that sends an alert to the given
email.

Source code:

import RPi.GPIO as gpio


import picamera
import time
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from email.mime.image import MIMEImage
fromaddr="vinodgowdag351@gmail.com"
toaddr="vinodgowdag350@gmail.com"
mail=MIMEMultipart()
mail["From"]=fromaddr
mail["To"]=toaddr
mail["subject"]="Alert! Someone found at your location."
body="please find the attachment"
led=15
pir=12
HIGH=1
LOW=0
gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
gpio.setup(led,gpio.OUT)
gpio.setup(pir,gpio.IN)
date=""
def sendMail(data):
mail.attach(MIMEText(body,'plain'))
dat='%s.jpg'%data
attachment=open(dat,'rb')
image=MIMEImage(attachment.read())
attachment.close()
mail.attach(image)
server=smtplib.SMTP('smtp.gmail.com',587)

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 20

server.strttls()
server.login(fromaddr,"iotgroup05")
text=mail.as_string()
server.sendmail(fromaddr,toaddr,text)
server.quit()
def capture_image():
data=time.strftime("image was captured on %H%M:%S|%d_%b_%y")
camera.start_preview()
time.sleep(2)
print(data)
camera.capture("%s.jpg"%data)
camera.stop_preview()
time.sleep(20)
sendMail(data)
gpio.output(led,0)
camera=picamera.PiCamera()
camera.rotation=360
camera.vflip=True
camera.awb_mode='auto'
camera.brightness=55
while 1:
if gpio.input(pir)==1:
gpio.output(led,HIGH)
capture_image()
while(gpio.input(pir)==1):
time.sleep(1)
else:
gpio.output(led,LOW)
time.sleep(0.01)

Output:

pi@raspberrypi :~ $ sudo apt-get install smtp


pi@raspberrypi :~ $ sudo apt-get install mailutils
pi@raspberrypi :~ $ cd/Desktop/1EW22MC495059/
pi@raspberrypi :~ $ /Desktop/1EW22MC495059
$ sudo python3 7a,py
Image was captured on 14:53:51|11_mar_2024
Image was captured on 14:54:26|11_mar_2024

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 21

Alert! Someone found at your location.


vinodgowdag350@gmail.com
Please find the attachment
1 attachment

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 22

Name: Vinodgowda G Usn: 1EW22MC059


Program No:08 Date:
Program Statement: Get the status of a bulb at a remote place( on the LAN) through the
web.

Source code:
import time
import RPi.GPIO as gpio
from flask import Flask, render_template
import datetime
import os
app = Flask(__name__)
gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
led1 = 13
switch1 = 35
gpio.setup(led1, gpio.OUT, initial=1)
gpio.setup(switch1, gpio.IN)
light_status = "OFF"
LEDS = os.path.join('static', 'LEDS')
app.config['UPLOAD_FOLDER'] = LEDS
def glow_led(event):
print("control entered here")
global light_status
if event == switch1 and light_status == "OFF":
gpio.output(led1, False)
light_status = "ON"
elif event == switch1 and light_status == "ON":
gpio.output(led1, True)
light_status = "OFF"
@app.route('/ledstatus')
def ledstatus():
now = datetime.datetime.now()
timeString = now.strftime("%H:%M %d-%m-%Y")
global led_image

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 23

if light_status == 'ON':
led_image = os.path.join(app.config['UPLOAD_FOLDER'], 'led_on.png')
elif light_status == 'OFF':
led_image = os.path.join(app.config['UPLOAD_FOLDER'], 'led_off.png')
templateData = {
'status': light_status,
'time': timeString
}
return render_template('lightstatus.html', **templateData, led_image=led_image)
gpio.add_event_detect(switch1, gpio.RISING, callback=glow_led, bouncetime=100)
if __name__ == "__main__":
time.sleep(2)
app.run(debug=True, port=4000, host='192.168.198.174')

lightstatus.html:

<!DOCTYPE html>
<html>
<head>
<title>Raspberry Pi Remote Light Status</title>
</head>
<body>
<h1>Raspberry Pi Remote Control</h1>
<img src="{{led_image}}" alt="LED Status">
<h2>Light Status: {{status}}, Last Seen: {{time}}</h2>
<form action="http://192.168.198.174:4000/ledstatus" method="get">
<input type="submit" value="Get Light Status">
</form>
</body>
</html>

EWIT DEPARTMENT OF MCA 2023-24


IOT LAB P a g e | 24

Output:

Raspberry Pi Remote Control

Light status:ON, Last modified:2024-03-11 15:35:09

Raspberry Pi Remote Control

Light status:OFF, Last modified:2024-03-11 15:37:15

EWIT DEPARTMENT OF MCA 2023-24

You might also like