0% found this document useful (0 votes)
23 views31 pages

71 Iot

Internet of things lab

Uploaded by

David Mullangi
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)
23 views31 pages

71 Iot

Internet of things lab

Uploaded by

David Mullangi
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/ 31

MYLAVARAM – 521 230

NTR District (A.P)


AUTONOMOUS

PRACTICAL RECORD

INTERNET OF THINGS LABORATORY

NAME : Ch.Karthik

ROLL NO :19761A1271

COURSE : BTECH BRANCH: IT

YEAR :2022-2023

LAKIREDDY BALIREDDY COLLEGE OF ENGINEERING (AUTONOMOUS)


LAKIREDDY BALIREDDY COLLEGE OF ENGINEERING (AUTONOMOUS)
Approved by AICTE, New Delhi and Permanently Affiliated to JNTUK, Kakinada
Accredited by NAAC with "A" Grade and NBA (CSE, IT, ECE, EEE & ME) under Tier-1
and certified by ISO 9001:2015
L.B. REDDY NAGAR, MYLAVARAM, NTR Dist.

DEPARTMENT OF INFORMATION TECHNOLOGY

CERTIFICATE
Certificate that this is a bonafied record of Practical work done in INTERNET
OF THINGS Laboratory by Ch.Karthik with Regd.No 19761A1271 of IV B.
Tech Course (VII Semester) in Information Technology branch during the
academic year 2022-2023

No. of Experiments :09 No. of Experiments done:09

Date: TEACHER-IN-CHARGE

INTERNAL EXAMINAR EXTERNAL EXMINAR

ii
INDEX
S.no Date Experiment Page No.

1. 05-08-2022 Start Raspberry Pi and try various Linux commands 01 - 02


in command terminal windows, cd, touch, mv, rm,
man, mkdir, rmdir, tar, gzip, cat, more, less, ps,
sudo, cron, chown, chgrp, ping etc.
2. 12-08-2022 Run some python programs on Pi like: 03
A. Read your name and print Hello message with
name.
B. Read two numbers and print their sum, difference,
product, and division.
C. Word and character count of a given string.

3. 26-08-2022 A. Area of a given shape (rectangle, triangle, and 04 - 05


circle) reading shape and appropriate values from
standard input.
B. Print a name ‘n’ times, where name and n are read
from standard input, using for and while loops.
C. Handle Divided by Zero Exception.
D. Print current time for 10 times with an interval of
10 seconds.
E. Read a file line by line and print the word count
of each line.

4. 02-09-2022 A. Light an LED through Python program 06 - 08


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

5. 09-09-2022 A. Study and Configure Raspberry Pi. 09 - 11


B. Switch on a relay to Light an LED through
Python program

6. 30-09-2022 A. Access an image through a Pi web cam. 12 - 14


B. Control a light source using web page.
7. 21-10-2022 A. Motion Detecting Sensor to open the room 15 - 17
door and switch on the light.
B. Get an Alarm and Sprinkle water if Fire is detected
in the room.
8. 04-11-2022 A. Set the siren and open the door if smoke is 17-20
detected in the room.
B. Smart Room Temperature Monitoring System.
9. 11-11-2022 ADDITIONAL EXPERIMENTS 21 - 27

iii
EXPERIMENT-1
1.Start Raspberry Pi and try various Linux commands in command terminal
windows, cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip, cat, more, less, ps,
sudo, cron, chown, chgrp, ping etc.
ls command - The ls command is used to list files or directories in Linux and
other Unix-based operating systems.
Use the ls command to display a listing of the current directory. Remember that
commands are casesensitive.
IoTLAB@labvm:~$ ls
Use the ls command with the labs argument to display the contents of the labs
folder.
IoTLAB @labvm:~$ ls labs
Use the ls command with the -l option to display a "long display" of the contents
of the current directory. IoTLAB @labvm:~$ ls –l
Use the ls command with the -r option to display the contents of the current
directory in reverse alphabetical order.
IoTLAB @labvm:~$ ls –r
Multiple options can be used at the same time. Use the ls command with both the
-l and -r options to display the contents of the current directory both in long and
reverse order.
IoTLAB @labvm:~$ ls –lr
There are many more options that can be used with the ls command. Use the man
command with the argument ls to see all of the possibilities in the manual. The man
command can be used to look up any command within the system. Use the space
bar to advance to subsequent screens. Press q to quit.
IoTLAB @labvm:~$ man ls
You can also use --help argument after most commands to see a shorter summary of
all the available command options.
IoTLAB @labvm:~$ ls –help
Use the pwd command to display the current working directory.
IoTLAB @labvm:~$ pwd
Use the cd command to change the directory to /home/ IoTLAB
/Documents.
IoTLAB @labvm:~$ cd Documents
Use the cd command with the / symbol to change directories to the root
directory. Use pwd again to see that you are now in the root directory.
IoTLAB @labvm:~/Documents$ cd /
IoTLAB @labvm:/$ pwd /
Use the .. characters to move up a single directory. Use pwd again to see you
are back in the user’s home directory.
IoTLAB @labvm:~/Documents$ cd ..
Use the move files command. a. Use the command mv to move the myfile.sh file
to the desktop.
IoTLAB @labvm:~/Documents$ mv myfile.sh /home/ IoTLAB /Desktop/
Use the copy files command. a. Use the command cp to make a copy of the
myfile_renamed.sh file.
IoTLAB @labvm:~/Documents$ cp myfile_renamed.sh
myfile_renamed_and_copied.sh
Use the sudo command to issue a single command as the root user. A new terminal
will not be created. Use the sudo apt-get update command to update to refresh the list
of available packages installed on the VM. This command will not work without
using the sudo command.
Use the remove files command. Use the rm command to remove the
myfile_renamed_and_copied.sh file. IoTLAB @labvm:~/Documents$ rm
myfile_renamed_and_copied.sh
Use the cat command to view the contents of the linux3.txt file.
IoTLAB @labvm:~$ cat linux3.txt
Use the grep command to filter the contents of the passwd file to display the line
from the passwd file containing IoTLAB. Also notice that the grep command is
case-sensitive.
IoTLAB @labvm:~$ grep IoTLAB /etc/passwd

2
EXPERIMENT-2
Run some python programs on Raspberry Pi like:
A. Read your name and print Hello message with name.

name = input(“Enter Your Name”)


print(“Hello” , name)

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

num1 = int(input("Enter First number")) num2 =


int(input("Enter Second number"))
ch = input('Enter the operation to perform among these( + , -, * , /') res=0
if ch == '+':
res=num1+num2
elif ch == '-':
res=num1-num2
elif ch== '*':
res=num1*num2
elif ch=='/':
res=num1/num2
else:
print("character you have entered is not supported")

print(num1,ch,num2,": ",res)

A. Word and character count of a given string.

word_count =0
char_count =0
str = input("Enter a sentence to count charaters and words")
str_split=str.split()
word_count = len(str_split)

for word in str_split :


char_count += len(word)

print(str,"No. of Words :",word_count," No. of Characters :",char_count)

3
EXPERIMENT-3
Run some python programs on Raspberry Pi like:
A. Area of a given shape (rectangle, triangle, and circle) reading shape
and appropriate values from standard input.
shape = input("Enter the name of the shape to calculate Area") area=0
shape=shape.lower() if
shape=="rectangle":
l=int(input("Enter the length of the rectangle"))
b=int(input("Enter the breadth of the rectangle")) area=
l*b
print("Area of the Rectangle is :", area) elif
shape== "triangle":
b=int(input("Enter the breadth of the triangle"))
h=int(input("Enter the height of the triangle"))
area=0.5*b*h
print("Area of the triagle :", area) elif
shape== "circle":
r=int(input("Enter the radius of the circle"))
pi=3.14
area=pi *r*r
print("Area of the circle",area)
else:
print("Sorry! This shape is not availabel")

B. Print a name ‘n’ times, where name and n are read from standard
input, using for and while loops.
name=input("Enter your name")
n=int(input("Enter the value for n to print your name n times")) for i
in range(1,n+1):
print(name)

name=input("Enter your name")


n=int(input("Enter the value for n to print your name n times")) i=0
while(i<n):
print(name)
i=i+1

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


import time

for i in range(0,10):
print(time.ctime())
time.sleep(5)

4
D. Read a file line by line and print the word count of each line.
word_count =0
file1 = open("/content/sample_data/abc.txt",mode="r")
no_lines=0
len_words=0 for
line in file1:
line=line.strip("\n")
words=line.split() no_lines
+=1
len_words +=len(words)
print("No. of lines in a file", len_words)

5
. EXPERIMENT-4
4 A. Light an LED through Python program.
Aim: Study and Implement LED Lightening using Python program.
Objective: Student should get the knowledge on lightening an LED using
Python program.
Outcome: Student will develop a program to Light an LED using Python
program.

import time

from gpio import *

def main():

pinMode(0,IN)

pinMode(1,OUT)

print("Light ON")

while True:

if(digitalRead(0)== HIGH):

digitalWrite(1,HIGH) time.sleep(1)

digitalWrite(1,LOW) time.sleep(1)

if __name__ ==

"__main__": main()

6
4 B. Get input from two switches and switch on corresponding LEDs.
Aim: Study and Implement to get input from two switches and switch on corresponding
LEDs.
Objective: Student should get the knowledge on lightening on
corresponding LED with two switches using Python program.
Outcome: Student will develop a program to Light a LEDs taking input
from two switches using Python program.

import time

from gpio import *

def main():

pinMode(0,IN)

pinMode(1,IN)

pinMode(2,OUT)

pinMode(3,OUT)

print("Light ON")

while True:

if(digitalRead(0)== HIGH):

digitalWrite(2,HIGH) time.sleep(1)

digitalWrite(2,LOW)

elif(digitalRead(1)==HIGH):

7
digitalWrite(3,HIGH) time.sleep(1)

digitalWrite(3,LOW)

if __name__ ==

"__main__": main()

8
EXPERIMENT-5
Study and Configure Raspberry Pi.

Aim: Study and Configure Raspberry Pi.


Objective: Student should get the knowledge of Raspberry Pi.
Outcome: Student will be getting knowledge of Raspberry Pi Raspberry Pi

The Raspberry Pi is a series of small single-board computers developed in the


United Kingdom by the Raspberry Pi Foundation to promote the teaching of basic
computer science in schools and in developing countries. [4][5][6] The original model
became far more popular than anticipated, selling outside of its target market for
uses such as robotics. Peripherals (including keyboards, mice and cases) are not
included with the Raspberry Pi. Some accessories however have been included in
several official and unofficial bundles.
According to the Raspberry Pi Foundation, over 5 million Raspberry Pis have
been sold before February 2015, making it the best-selling British computer.
[8] By November 2016 they had sold 11 million units [9][10], reaching 12.5m in
March 2017, making it the third best-selling "general purpose computer" ever.
To get started with Raspberry Pi, you need an operating system. NOOBS (New
Out of Box Software) is an easy operating system install manager for the
Raspberry Pi.
How to get and install NOOBS
DOWNLOAD NOOBS OS FROM
We recommend using an SD card with a minimum capacity of 8GB.
1. GO to the https://www.raspberrypi.org/downloads/
2. Click on NOOBS, then click on the Download ZIP button under
‘NOOBS (offline and network install)’ and select a folder to save it to.
3. Extract the files from the zip.
FORMAT YOUR SD CARD
It is best to format your SD card before copying the NOOBS files onto it.
To do this:
1. Download SD Formatter 4.0 for either Windows or Mac.
2. Follow the instructions to install the software.

9
3. Insert your SD card into the computer or laptop’s SD card reader
and make a note of the drive letter allocated to it, e.g. G:/
4. In SD Formatter, select the drive letter for your SD card and format it.
DRAG AND DROP NOOBS FILES
1. Once your SD card has been formatted, drag all the files in the extracted
NOOBS folder and drop them onto the SD card drive.
2. The necessary files will then be transferred to your SD card.
3. When this process has finished, safely remove the SD card and insert it into
your Raspberry Pi.
FIRST BOOT
1. Plug in your keyboard, mouse, and monitor cables.
2. Now plug the USB power cable into your Pi.
3. Your Raspberry Pi will boot, and a window will appear with a list of different
operating systems that you can install. We recommend that you use Raspbian
– tick the box next to Raspbian and click on Install.
4. Raspbian will then run through its installation process. Note that this can
take a while.
5. When the install process has completed, the Raspberry Pi configuration menu
(raspiconfig) will load. Here you are able to set the time and date for your
region, enable a Raspberry Pi camera board, or even create users. You can exit
this menu by using Tab on your keyboard to move to Finish.

LOGGING IN AND ACCESSING THE GRAPHICAL USER INTERFACE


The default login for Raspbian is username pi with the password raspberry. Note that
you will not see any writing appear when you type the password. This is a security
feature in Linux. To load the graphical user interface, type startx and press Enter.

10
5 B. Switch on a relay to light an LED through Python program.

Aim: Study and Implement Switch on a relay to Light an LEDs.


Objective: Student should get the knowledge on lightening on
corresponding LED with Switch on a relay using Python
program.
Outcome: Student will develop a program to light a LEDs
with Switch on a relay using Python program.

import time
from
gpio
impo
rt *
def
main
():
pinMo
de(0,I
N)
pinMo
de(1,O
UT)
pinMo
de(2,O
UT)
pinMo
de(3,O
UT)
print("
Light

11
ON")
while
True:
if(digitalRead(0)== HIGH):
digitalWrite(1,HIG
H) time.sleep(1)
digitalWrite(1,LO
W)
digitalWrite(2,HIG
H) time.sleep(1)
digitalWrite(2,LO
W)
digitalWrite(3,HIG
H) time.sleep(1)
digitalWrite(3,LO
W)

if __name__
==
"__main
__":
main()

12
EXPERIMENT-6
6 A. Access an image through a Pi web cam.

Aim: Study and Implement to Access an image through a Pi web cam.


Objective: Student should get the knowledge to Access an image through a
Pi web cam using Python program.
Outcome: Student will develop a program using python to Access an image
through a Pi web cam.

Procedure to Configure Pi Webcam.


Place Motion Detector, webcam and connect it to switch. Connect
switch to a server using a straight through cable.
If any problem exists in connecting using straight through cable change the
adapter → click on webcam → select advanced → I/O config → change
network adapter to PT-IOT-NM-1CFE
Click on Server → services → on LEFT side select IOT → ON
Then Assign IP Address for Server, webcam and Motion Detector.
Server → Desktop → IP Configuration → IPV4 Address: - 192.168.1.1
Subnet Mask: 255.255.255.0
Webcam →Config → FastEthernet → IPV4 Address: - 192.168.1.2 Subnet
Mask: 255.255.255.0
Motion Detector →Config → FastEthernet → IPV4 Address: - 192.168.1.2
Subnet Mask: 255.255.255.0
Now click on server → Desktop → Browser → type 192.168.1.1 → Sign Up
Now and set Username: admin, Password: admin → Create
Verify whether the devices webcam and Motion detector are visible or not.

13
Now change the name of webcam IOT0 to WEBCAM and Motion Detector
IOT1 to MOTIONDETECTOR
Now Click on Webcam → Config → IoT Server → Remote Server → Server
Address :- 192.168.1.1 , Username: admin, Password: admin → click on
Connect, --- Wait until it changes to refresh.
Now Click on Motion Detector → Config → IoT Server → Remote Server →
Server Address :- 192.168.1.1 , Username: admin, Password: admin → click
on Connect, --- Wait until it changes to refresh.
Now click on server → Desktop → Browser → type 192.168.1.1 →
Registration Server Login: Username: admin, Password: admin → Sign in
Now you can see the devices WEBCAM and MOTIONDETETOR Listed in
Web browser.
Now click on Conditions → ADD → Name : WEBCAM ON → IF – select
MOTIONDETECTOR → ON → TRUE
THEN SET → WEBCAM → ON → TRUE → Click on OK
Now click on Conditions → ADD → Name : WEBCAM OFF → IF – select
MOTIONDETECTOR → ON → FALSE
THEN SET → WEBCAM → ON → FALSE → Click on OK
Now click on server → Desktop → Browser → type 192.168.1.1 →
Registration Server Login: Username: admin, Password: admin → Sign in
Now Move the Mouse Pointer towards Motion Detector by pressing on ALT
key
You can observe the Webcam on and detecting the object moving towards
motion detector.

6 B. Control a light source and Fan using web page.

Aim: Study and Implement to Control a light source and Fan using web page.
Objective: Student should get the knowledge to Control a light source and
Fan using web page.
Outcome: Student will develop a program to Control a light source and Fan
using web page.

14
Procedure to connect FAN and LIGHT LAMP to Home gateway.
Connect LAMP and the FAN using straight through cable with Ethernet connector.
Click on Home Gateway → Config → Interface→ Wireless →copy SSID :
HomeGateway
Click on SmartPhone → Config → Interface → Wireless → Paste the SSID : change the
default to HomeGateway
Now the Smartphone is connected to Home Gateway.
Click on FAN → Config → change Gateway/DNSIPV4 – DHCP

Then go to IOT Server → select Remote Server →Server Address :- 192.168.25.1


, Username: admin, Password: admin → click on Connect, --- Wait until it
changes to refresh.
Click on LAMP → Config → change Gateway/DNSIPV4 – DHCP

Then go to IOT Server → select Remote Server →Server Address :- 192.168.25.1


, Username: admin, Password: admin → click on Connect, --- Wait until it
changes to refresh.
Now click on server → Desktop → IoTMonitor → IOT Server Address :
192.168.25.1 → Username: admin, Password: admin → Sign in
Now the FAN and the LAMP are listed.
Select the FAN and change the speed of the FAN to LOW, HIGH and OFF
Select the LAMP and change the LIGHT to OFF, DIM, ON

15
7 A. Motion Detecting Sensor to open the room door and switch on the
light.

Aim: Study and Implement Motion Detecting Sensor to open the room door
and switch on the light.
Objective: Student should get the knowledge on Motion Detecting
Sensor to open the room door and switch on the light using Python
program.
Outcome: Student will develop a program using python to open the room
door and switch on the light when motion is detected in the room.

from gpio import *


import time

def main():
pinMode(0,IN)
pinMode(1,OUT)
pinMode(2,OUT)
print("Motion Sensing Started")
while True:
if (digitalRead(0)==HIGH):
digitalWrite(1,HIGH)
customWrite(2,HIGH)
else:
digitalWrite(1,LOW)
customWrite(2,LOW)
time.sleep(1)

if __name__ == "__main__":
main()

16
7 B. Get an Alarm and Sprinkle water if Fire is detected in the room.

Aim: Study and Implement to ring an Alarm and Sprinkle water if Fire is
detected in the room.
Objective: Student should get the knowledge on fire monitoring system and
sprinkle water if fire is detected using Python program.
Outcome: Student will develop a program using python to ring an Alarm and
Sprinkle water if Fire is detected in the room.

from gpio import *


from time import *

def main():
pinMode(0,IN)
pinMode(1,OUT) print("Fire
Alarm System") while True:
fire= digitalRead(0)
if(fire==1023):
customWrite(1,'1')
customWrite(2,"Fire Detected")
customWrite(3,HIGH)
digitalWrite(4,HIGH)
else:
customWrite(1,'0') customWrite(2,"Safe
No Fire Detected") customWrite(3,LOW)
digitalWrite(4,LOW)

print(fire)

if __name__ ==
"__main__": main()

Select Things -→ Things editors → component → select Fire Icon

Write a program in the Java script file by deleting the existing code and
add the new code as

function setup()
{
setDeviceProperty(getName(), ‘IR’, 900);
}

18
8 A. Set the siren and open the door if smoke is detected in the room.

Aim: Study and Implement a smoke detection monitoring system.


Objective: Student should get the knowledge on a smoke detection
Monitoring System.
Outcome: Student will construct a system which ring a siren and open the
door when smoke is detected in a room

Click on Home Gateway → Config → Interface → Wireless → copy SSID :


HomeGateway
Click on SmartPhone → Config → Interface → Wireless → Paste the SSID : change the
default to HomeGateway
Now the Smartphone is connected to Home Gateway.
Select Smoke detector → config → IN Gateway/DNS/IPV4 enable DHCP
→ IN Gateway/DNS/IPV6 enable DHCP → IoT Server Enable Home Gateway.
Select Siren → config → IN Gateway/DNS/IPV4 enable DHCP → IN
Gateway/DNS/IPV6 enable DHCP → IoT Server Enable Home Gateway.

Select Garage Door → config → IN Gateway/DNS/IPV4 enable DHCP →IN


Gateway/DNS/IPV6 enable DHCP → IoT Server Enable Home Gateway.
Move the old car near to smoke detector and press ALT key and click mouse
pointer the smoke from the car will be generated and then the siren will ring,
garage door will open.

19
8 B. Smart Room Temperature Monitoring System.

Aim: Study and Implement a Smart Room Temperature Monitoring System.


Objective: Student should get the knowledge on a Smart Room Temperature
Monitoring System using Python program.
Outcome: Student will develop a program for Smart Room Temperature
Monitoring System.

from gpio import *


import time

def main():
pinMode(0,IN)
pinMode(1, OUT)
pinMode(2,OUT)
pinMode(3,OUT)
print("SMART ROOM TEMPERATURE")
while True:
temp=digitalRead(0)
print("Temperature",temp)
if(temp>=520):
digitalWrite(1, HIGH)
digitalWrite(2,LOW)

20
customWrite(3,"AC-ON")
time.sleep(10)
else:
digitalWrite(2, HIGH)
digitalWrite(1,LOW)
customWrite(3,"HEATER-ON")
time.sleep(10)

if __name__ ==
"__main__": main()

21
ADDITIONAL EXPERIMENTS

1. Aim: Study and Implement Installing Django and creating a new Django
Project

Objective: Student should get the knowledge on installing Django


Outcome: Student will install Django
Install Python
Before you install Django, you must make sure that you have Python
installed. You can check out this guide I wrote: how to install python on
windows to learn how to install Python on Windows.

Install Django
The commands that we will run in this tutorial will work on both Windows
Command Prompt(CMD) and Powershell. I will use Powershell but you can
CMD if that’s what you prefer.

Step 1 - Open Powershell


You can search for Powershell in the Windows search box or (Win+R) and type
powershell and then click ok.

You should now have a Powershell window opened.

Step 2 - Verify Python Installation


Type python -V on the prompt to verify that Python has been
successfully installed

> python -V
you should see the Python version installed, being printed like below:

PS C:\Users\Stanley> python -V
Python 3.7.4
Step 3 - Upgrade Pip
Python now comes with pip by default. But most of the time, it comes with
an old version. it is always a good practice to upgrade pip to the latest version

> python -m pip install --upgrade pip

22
Step 4 - Create a Project Directory
let’s create a project directory. We will name it django_project since this tutorial
is just a demo but in the real world, the project directory’s name would be
forum, blog, etc.

To create the directory:

> mkdir django_project


Change into the django_project directory:

> cd django_project
Your prompt should now show you that you’re in
the “django_project” directory like below:

PS C:\Users\Username\django_project>

Step 5 - Create Virtual Environment


A virtual environment(virtualenv) is an isolated Python environment where
you can install packages and dependencies without affecting otherPython
projects. You can learn more about virtualenv here.

To create a virtual environment, type python -m venv venv and wait for a few
seconds:

> python -m venv venv

23
It will create a directory called venv in the project directory. Next,

we will activate the virtual environment.

Step 6 - Activate Virtual Environment


Run the following command to activate the virtualenv.

> venv\Scripts\activate
When virtualenv is activated, you will see a (venv) at the beginning of the prompt.

Now that virtual environment is activated, let’s install Django.

Step 7 - Install Django


We are going to use pip to install Django. So run the following command to
start the installation:

(venv)> pip install django

Step 8 - Start a New Project


We will use django-admin startproject to create our Django project structure
called “testsite”.

Run the following command:

(venv)> django-admin startproject testsite


Navigate into the testsite directory by running the following command:

(venv)> cd testsite

24
Step 9 - Run the Server
Let’s now run the development server using the manage.py runserver:

(venv)> python manage.py runserver

25
2. Aim: Study and Implement an intruder system that sends an alert to the
given email.
Objective: Student should get the knowledge to write a Python Program to
implement an intruder system that sends an alert to the given email. Outcome:
Student will implement an intruder system that sends an alert to the given
email.

Steps for sending email :

Import smtplib and RPi.GPIO.

Also import sleep , so that the button press operation will not be
instantaneous.

Initialize all parameters that are required to send email like from-mail, to-
mail, username,password, subject etc.

Now we have to set up the button to perform email sending operation on


pressing, for that first of all we have to set the mode of GPIO which is
actually byte form and it is GPIO.BCM .

Next setup the pin connected to the button, here we used 25 pin for button
pressing

Call the method send email whenever GPIO input is given 25, i.e
whenever the button is pressed the input will be taken as 25 and the
sendemail() method will be called.

In sendemail() method:

create your own way of message.

the smtp server for creating email is to be provided to create a session for
client and smtp server.

then start the session by using startls() method.

then inorder to send email we require login credentials of sender email and
authentication should be given in gmail settings to accept less secure apps
.

then by using sendmail method we can send mail using python program.

after sending mail inorder to terminate the session between client and smtp
server we use quit() method.

26
when ever if any keyboardInterrupt occurs then raise an exception
to exit() the program

Source Code:

import smtplib

from time import sleep

import RPi.GPIO as GPIO

from sys import exit

from_email=’<my-email>’

receipients_list=[‘<receipient-email>’]

cc_list=[]

subject=’Hello’

message=’Switch pressed on Raspberry pi’

username=’<Gmail-username>’

password=’<Password>’

server=’smtp.gmail.com:587’

GPIO.setmode(GPIO.BCM)

GPIO.setup(25, GPIO.IN)

Def sendemail(from_addr, to_addr_list, cc_addr_list, subject, message,


. login, password, smtpserver):

Header=’from: ’ + from__addr + ’\n’

Header+=’To: ‘ + ‘,’.join(to_addr_list) + ’\n’

Header+=’Cc: ’ + ‘.’.join(cc_addr_list) + ‘\n’

Message= header+message

Server=smtplib.SMTP(smtpserver) Server.startls()

Server.login(login, password)

Problem=server.sendmail(from_addr,to_addr_list,message)

27
Server.quit()

While True:

Try:

If(GPIO.input(25)==True):

Sendemail(from_email,receipients_list,cc_list,subject,

message,username,password,server)

Sleep(.01)

Except keyboardInterrupt: Exit()

28

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