0% found this document useful (0 votes)
103 views45 pages

Iot Practical

This document describes an experiment displaying the current time on a 4-digit 7-segment display using a Raspberry Pi. It provides details on connecting the display to the Raspberry Pi GPIO pins and programming the Raspberry Pi to retrieve the current time and display it as four digits on the 7-segment display by turning on the relevant segments. Arrays are created to represent the segment patterns for each digit from 0 to 9. The program then loops continuously, retrieving the time and displaying the hours and minutes digits on the four displays sequentially to create a continuous 4-digit display of the current time.

Uploaded by

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

Iot Practical

This document describes an experiment displaying the current time on a 4-digit 7-segment display using a Raspberry Pi. It provides details on connecting the display to the Raspberry Pi GPIO pins and programming the Raspberry Pi to retrieve the current time and display it as four digits on the 7-segment display by turning on the relevant segments. Arrays are created to represent the segment patterns for each digit from 0 to 9. The program then loops continuously, retrieving the time and displaying the hours and minutes digits on the four displays sequentially to create a continuous 4-digit display of the current time.

Uploaded by

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

PRACTICAL REPORT

SUBMITTED IN PARTIAL FULFILMENT OF THE


REQUIREMENTS OF THE AWARD OF THE DEGREE

BACHELOR OF SCIENCE (INFORMATION TECHNOLOGY)


BY
NAME OF THE STUDENT: UMESH RAJARAM KADAM
CLASS: T.Y. B.SC - IT (SEM V)
SUBJECT: INTERNET OF THINGS
PRN NO: 2021016401698925

DEPARTMENT OF INFORMATION TECHNOLOGY

“KAMAL GAURI HIRU PATIL SHIKSHAN SANSTHA’S”


SADGURU VAMANBABA COLLEGE OF ARTS,
COMMERCE & SCIENCE
(Affiliated to University of Mumbai)
PLOT NO 29, SECTOR-11, TALOJA,
NAVI MUMBAI – 410208,
MAHARASHTRA 2023 - 2024.
SADGURU VAMANBABA COLLEGE OF ARTS, COMMERCE & SCIENCE
(Affiliated to University of Mumbai)
TALOJA, NAVI MUMBAI – 410208
MAHARASHTRA 2023 - 2024
DEPARTMENT OF INFORMATION TECHNOLOGY
PRACTICAL REPORT

CERTIFICATE

This is to certify that the practical entitled “ INTERNET OF THINGS ” is


a bonafied work of UMESH RAJARAM KADAM bearing PRN No :
2021016401698925 submitted in partial fulfilment of the requirements for the
award of degree of BACHELOR OF SCIENCE in INFORMATION
TECHNOLOGY from University of Mumbai.

Internal Guide Coordinator

External Examiner

Date: - College Seal


INDEX

Sr. No Practical Name Date Remark

1 Displaying Time over 4-Digit 7-Segment Display using Raspberry


Pi.

2 Raspberry Pi Based Oscilloscope.

3 Controlling Raspberry Pi with WhatsApp.

4 Fingerprint Sensor interfacing with Raspberry Pi.

5 Raspberry Pi GPS Module Interfacing.

6 IoT based Web Controlled Home Automation using Raspberry Pi.

7 Visitor Monitoring with Raspberry Pi and Pi Camera.

8 Interfacing Raspberry Pi with RFID.


PRACTICAL NO. 1
AIM : Displaying Time over 4-Digit 7-Segment Display using Raspberry Pi.
Let us see how, how we can connect this 4-digit 7-segment module with our Raspberry
Pi. The 7-segment module has 16 pins as shown below. You module might have lesser,
but don’t worry it will still have the following for sure
1. 7 or 8 segment pins (here pins starting from 1 to 8)
2. Ground pin (here pin 11)
3. 4 digit pins (here pins 13 to 16)

The following table will also help you in making the connections and verifying it to be as
per the schematics shown above.
S.No Rsp Pi GPIO number Rsp Pi PIN number 7-Segment 7-Seg pin number (in
name this module )
1 GPIO 26 PIN 37 Segment a 1
2 GPIO 19 PIN 35 Segment b 2
3 GPIO 13 PIN 33 Segment c 3
4 GPIO 6 PIN 31 Segment d 4
5 GPIO 5 PIN 29 Segment e 5
6 GPIO 11 PIN 23 Segment f 6
7 GPIO 9 PIN 21 Segment g 7
8 GPIO 10 PIN 19 Segment DP 8
9 GPIO 7 PIN 26 Digit 1 13
10 GPIO 8 PIN 24 Digit 2 14
11 GPIO 25 PIN 22 Digit 3 15
12 GPIO 24 PIN 18 Digit 4 16
13 Ground Ground Ground 11
 Programming your Raspberry Pi:
First we are going to import GPIO file from library, below function enables us to
program GPIO pins of PI. We are also renaming “GPIO” to “IO”, so in the program
whenever we want to refer to GPIO pins we will use the word ‘IO’. We have also
imported time and datetime to read the value of time from Rsp Pi.
import RPi.GPIO as GPIO
import time, datetime Sometimes,
when the GPIO pins, which we are trying to use, might be doing some other functions.
In that case, we will receive warnings while executing the program. Below command
tells the PI to ignore the warnings and proceed with the program.
IO.setwarnings(False)
We can refer the GPIO pins of PI, either by pin number on board or by their function
number. Like ‘PIN 29’ on the board is ‘GPIO5’. So we tell here either we are going to
represent the pin here by ‘29’ or ‘5’. GPIO.BCM means we will represent using 5 for
GPIO5 pin 29.
IO.setmode (GPIO.BCM)
As always we should begin by initialising the pins, here both the segment pins and the
digit pins are output pins. For programming purpose we form arrays for segment pins
and initialize them to ‘0’ after declaring them as GPIO.OUT
segment8 = (26,19,13,6,5,11,9,10)
for segment in segment8 :
GPIO.setup(segment, GPIO.OUT)
GPIO.output(segment, 0)
Similarly for the digit pins we declare them as output pins and make them ‘0’ by default
#Digit 1
GPIO.setup(7, GPIO.OUT)
GPIO.output(7, 0) #Off initially
#Digit 2
GPIO.setup(8, GPIO.OUT)
GPIO.output(8, 0) #Off initially
#Digit 3
GPIO.setup(25, GPIO.OUT)
GPIO.output(25, 0) #Off initially
#Digit 4
GPIO.setup(24, GPIO.OUT)
GPIO.output(24, 0) #Off initially
We have to form arrays to display each number on a seven segment display. To display
one number we have to control all 7 segment pins (dot pin excluded), that is they either
has to be turned off or turned on. For example to display the number 5 we have make
the following arrangement
S.N Rsp Pi GPIO Number 7- Segment name Status to display ‘5’. (0-> OFF, 1->ON)
o
1 GPIO 26 Segment a 1
2 GPIO 19 Segment b 1
3 GPIO 13 Segment c 0
4 GPIO 6 Segment d 1
5 GPIO 5 Segment e 1
6 GPIO 11 Segment f 0
7 GPIO 9 Segment g 1
Similarly we have sequence number for all numbers and alphabets. You can write on
your own or use the chart below.
With these data we can form the arrays for each number in our python program as
shown below.
null = [0,0,0,0,0,0,0]
zero = [1,1,1,1,1,1,0]
one = [0,1,1,0,0,0,0]
two = [1,1,0,1,1,0,1]
three = [1,1,1,1,0,0,1]
four = [0,1,1,0,0,1,1]
five = [1,0,1,1,0,1,1]
six = [1,0,1,1,1,1,1]
seven = [1,1,1,0,0,0,0]
eight = [1,1,1,1,1,1,1]
nine = [1,1,1,1,0,1,1]
If you follow the program there will be a function to display each character to our 7-
segment display but, lets skip this for now and get into the while infinite loop. Where
read the present time from Raspberry Pi and split the value of time between four
variables. For example if the time is 10.45 then the variable h1 will have 1, h2 will have
0, m1 will have 4vand m2 will have 5.
now = datetime.datetime.now()
hour = now.hour minute = now.minute
h1 = hour/10 h2 = hour % 10
m1 = minute /10 m2 = minute % 10
print (h1,h2,m1,m2)
We have to display these four variable values on our four digits respectively. To write a
value of variable to a digit we can use the following lines. Here we are display on digit 1
by making it go high then the function print_segment (variable) will be called to display
the value in variable on the segment display. You might be wondering why we have a
delay after that and why we turn this digit off after this.
GPIO.output(7, 1) #Turn on Digit One
print_segment (h1) #Print h1 on segment
time.sleep(delay_time) GPIO.output(7, 0) #Turn off Digit One
The reason is, as we know we can display only one digit at a time, but we have four
digits to be displayed and only if all the four digits are displayed the complete four digit
number will be visible for the user.
The last thing to learn it to know how the print_segment(variable) function works.
Inside this function we use the arrays that we have declared so far. So whatever variable
that we send to this function should have the value between (0-9), the variable character
will receive this value and compare it for real value. Here the variable is compared with
‘1’. Similarly we compare with all number from 0 to 9. If it is a match we use the arrays
and assign each value to its respective segment pins as shown below.
def print_segment(charactor):
if charactor == 1:
for i in range(7):
GPIO.output(segment8[i], one[i])
 Display time on 4-Digit 7-segment using Raspberry Pi:
Use the schematic and code given here to make the connections and program your
raspberry pi accordingly. After everything is done just launch the program and you
should find the current time being displayed in the seven segment display. But, there
are few things that you have to check before this
1. Make sure you have set your Raspberry Pi with current time just in case if it running
on offline time.
2. Power your Raspberry pi with a Adapter and not with your Laptop/computer
because the amount of current drawn by the 7-segment display is high and your USB
port cannot source it.
Code:
import RPi.GPIO as GPIO
import time, datetime
now = datetime.datetime.now()
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#GPIO ports for the 7seg pins
segment8 = (26,19,13,6,5,11,9,10)
for segment in segment8:
GPIO.setup(segment, GPIO.OUT)
GPIO.output(segment, 0)
#Digit 1
GPIO.setup(7, GPIO.OUT)
GPIO.output(7, 0) #Off initially
#Digit 2
GPIO.setup(8, GPIO.OUT)
GPIO.output(8, 0) #Off initially
#Digit 3
GPIO.setup(25, GPIO.OUT)
GPIO.output(25, 0) #Off initially
#Digit 4
GPIO.setup(24, GPIO.OUT)
GPIO.output(24, 0) #Off initially
null = [0,0,0,0,0,0,0]
zero = [1,1,1,1,1,1,0]
one = [0,1,1,0,0,0,0]
two = [1,1,0,1,1,0,1]
three = [1,1,1,1,0,0,1]
four = [0,1,1,0,0,1,1]
five = [1,0,1,1,0,1,1]
six = [1,0,1,1,1,1,1]
seven = [1,1,1,0,0,0,0]
eight = [1,1,1,1,1,1,1]
nine = [1,1,1,1,0,1,1]
def print_segment(charector):
if charector == 1:
for i in range(7):
GPIO.output(segment8[i], one[i])
if charector == 2:
for i in range(7):
GPIO.output(segment8[i], two[i])
if charector == 3:
for i in range(7):
GPIO.output(segment8[i], three[i])
if charector == 4:
for i in range(7):
GPIO.output(segment8[i], four[i])
if charector == 5:
for i in range(7):
GPIO.output(segment8[i], five[i])
if charector == 6:
for i in range(7):
GPIO.output(segment8[i], six[i])
if charector == 7:
for i in range(7):
GPIO.output(segment8[i], seven[i])
if charector == 8:
for i in range(7):
GPIO.output(segment8[i], eight[i])
if charector == 9:
for i in range(7):
GPIO.output(segment8[i], nine[i])
if charector == 0:
for i in range(7):
GPIO.output(segment8[i], zero[i])
return;
while 1:
now = datetime.datetime.now()
hour = now.hour
minute = now.minute
h1 = hour/10
h2 = hour % 10
m1 = minute /10
m2 = minute % 10
print (h1,h2,m1,m2)
delay_time = 0.001 #delay to create virtual effect
GPIO.output(7, 1) #Turn on Digit One
print_segment (h1) #Print h1 on segment
time.sleep(delay_time)
GPIO.output(7, 0) #Turn off Digit One
GPIO.output(8, 1) #Turn on Digit One
print_segment (h2) #Print h1 on segment
GPIO.output(10, 1) #Display point On
time.sleep(delay_time)
GPIO.output(10, 0) #Display point Off
GPIO.output(8, 0) #Turn off Digit One
GPIO.output(25, 1) #Turn on Digit One
print_segment (m1) #Print h1 on segment
time.sleep(delay_time)
GPIO.output(25, 0) #Turn off Digit One
GPIO.output(24, 1) #Turn on Digit One
print_segment (m2) #Print h1 on segment
time.sleep(delay_time)
GPIO.output(24, 0) #Turn off Digit One
#time.sleep(1)
PRACTICAL NO. 2
AIM : Raspberry Pi Based Oscilloscope.

 Project Requirements
The requirement for this project can be classified into two:
1. Hardware Requirements
2. Software Requirements
 Hardware requirements
To build this project, the following components/part are required;
1. Raspberry pi 2 (or any other model)
2. 8 or 16GB SD Card
3. LAN/Ethernet Cable
4. Power Supply or USB cable
5. ADS1115 ADC
6. LDR (Optional as its meant for test)
7. 10k or 1k resistor
8. Jumper wires
9. Breadboard
10. Monitor or any other way of seeing the pi’s Desktop(VNC inclusive)
 Software Requirements
The software requirements for this project are basically the python modules
(matplotlib and drawnow) that will be used for data visualization and the Adafruit
module for interfacing with the ADS1115 ADC chip. I will show how to install these
modules on the Raspberry Pi as we proceed.
While this tutorial will work irrespective of the raspberry pi OS used, I will be using
the Raspberry Pi stretch OS and I will assume you are familiar with setting up the
Raspberry Pi with the Raspbian stretch OS, and you know how to SSH into the
raspberry pi using a terminal software like putty. If you have issues with any of this,
there are tons of Raspberry Pi Tutorials on this website that can help.
With all the hardware components in place, let's create the schematics and connect the
components together.
 Circuit Diagram:
To convert the analog input signals to digital signals which can be visualized with the
Raspberry Pi, we will be using the ADS1115 ADC chip. This chip becomes important
because the Raspberry Pi, unlike Arduino and most micro-controllers, does not have an
on-board analog to digital converter(ADC). While we could have used any raspberry pi
compatible ADC chip, I prefer this chip due to its high resolution(16bits) and its well
documented datasheet and use instructions by Adafruit. You can also check our
Raspberry Pi ADC tutorial to learn more about it.
ADS1115 and Raspberry Pi Connections:
VDD – 3.3v
GND – GND
SDA – SDA
SCL – SCL
Install Dependencies for Raspberry Pi Oscilloscope:
Before we start writing the python script to pull data from the ADC and plot it on a live
graph, we need to enable the I2C communication interface of the raspberry pi and
install the software requirements that were mentioned earlier. This will be done in
below steps so its easy to follow:
Step 1: Enable Raspberry Pi I2C interface
To enable the I2C, from the terminal, run;
sudo raspi-config
When the configuration panels open, select interface options, select I2C and click
enable.
Step 2: Update the Raspberry pi
The first thing I do before starting any project is updating the Pi. Through this, I am
sure every thing on the OS is up to date and I won’t experience compatibility issue with
any latest software I choose to install on the Pi. To do this, run below two commands:
sudo apt-get update
sudo apt-get upgrade
Step 3: Install the Adafruit ADS1115 library for ADC
With the update done, we are now ready to install the dependencies starting with the
Adafruit python module for the ADS115 chip. Ensure you are in the Raspberry Pi home
directory by running;
cd ~
then install the build-essentials by running;
sudo apt-get install build-essential python-dev python-smbus git
Next, clone the Adafruit git folder for the library by running;
git clone https://github.com/adafruit/Adafruit_Python_ADS1x15.git
Change into the cloned file’s directory and run the setup file;
cd Adafruit_Python_ADS1x1z
sudo python setup.py install
After installation, your screen should look like the image below.
Step 4: Test the library and 12C communication.
Before we proceed with the rest of the project, it is important to test the library and
ensure the ADC can communicate with the raspberry pi over I2C. To do this we will use
an example script that comes with the library.
While still in the Adafruit_Python_ADS1x15 folder, change directory to the examples
directory by running;
cd examples
Next, run the sampletest.py example which displays the value of the four channels on
the ADC in a tabular form.
Run the example using:
python simpletest.py
If the I2C module is enabled and connections good, you should see the data as shown in
the image below.

If an error occurs, check to ensure the ADC is well connected to the PI and I2C
communication is enabled on the Pi.
Step 5: Install Matplotlib
To visualize the data we need to install the matplotlib module which is used to plot all
kind of graphs in python. This can be done by running;
sudo apt-get install python-matplotlib
You should see an outcome like the image below.

Step6: Install the Drawnow python module


Lastly, we need to install the drawnow python module.
We will be installing drawnow via the python package installer; pip, so we need to
ensure it is installed. This can be done by running;
sudo apt-get install python-pip
We can then use pip to install the drawnow package by running:
sudo pip install drawnow
You should get an outcome like the image below after running it.

 Python Code for Raspberry Pi Oscilloscope:


The python code for this Pi Oscilloscope is fairly simple especially if you are familiar
with the python matplotlib module.
At this stage it is important to switch to a monitor or use the VNC viewer, anything
through which you can see your Raspberry Pi’s desktop, as the graph being plotted
won’t show on the terminal.
With the monitor as the interface open a new python file. You can call it any name you
want, but I will call it scope.py.
sudo nano scope.py
With the file created, the first thing we do is import the modules we will be using;
import time
import matplotlib.pyplot as plt
from drawnow import *
import Adafruit_ADS1x15
Next, we create an instance of the ADS1x15 library specifying the ADS1115 ADC
adc = Adafruit_ADS1x15.ADS1115()
Next, we set the gain of the ADC. There are different ranges of gain and should be
chosen based on the voltage you are expecting at the input of the ADC. For this tutorial,
we are estimating a 0 – 4.09v so we will be using a gain of 1. For more info on gain you
can check the ADS1015/ADS1115 datasheet.
GAIN = 1
Next, we need to create the array variables that will be used to store the data to be
plotted and another one to serve as count.
Val = [ ]
cnt = 0
Next, we make know our intentions of making the plot interactive known so as to enable
us plot the data live.
plt.ion()
Next, we start continuous ADC conversion specifying the ADC channel, in this case,
channel 0 and we also specify the gain.
It should be noted that all the four ADC channels on the ADS1115 can be read at the
same time, but 1 channel is enough for this demonstration.
adc.start_adc(0, gain=GAIN)
Next we create a function def makeFig, to create and set the attributes of the graph
which will hold our live plot.We first of all set the limits of the y-axis using ylim, after
which we input the title of the plot, and the label name before we specify the data that
will be plotted and its plot style and color using plt.plot(). We can also state the channel
(as channel 0 was stated) so we can identify each signal when the four channels of the
ADC are being used. plt.legend is used to specify where we want the information about
that signal(e.g Channel 0) displayed on the figure.
plt.ylim(-5000,5000)
plt.title('Osciloscope')
plt.grid(True)
plt.ylabel('ADC outputs')
plt.plot(val, 'ro-', label='lux')
plt.legend(loc='lower right')
Next we write the while loop which will be used constantly read data from the ADC and
update the plot accordingly.
The first thing we do is read the ADC conversion value
value = adc.get_last_result()
Next we print the value on the terminal just to give us another way of confirming the
plotted data. We wait a few seconds after printing then we append the data to the list
(val) created to store the data for that channel.
print('Channel 0: {0}'.format(value))
time.sleep(0.5)
val.append(int(value))
We then call drawnow to update the plot.
drawnow(makeFig)
To ensure the latest data is what is available on the plot, we delete the data at index 0
after every 50 data counts.
cnt = cnt+1 if(cnt>50):
val.pop(0)
 Raspberry Pi Oscilloscope in Action:
Copy the complete python code and paste in the python file we created earlier,
remember we will need a monitor to view the plot so all of this should be done by either
VNC or with a connected monitor or screen.
Save the code and run using;
sudo python scope.py
Occasionally you may get a warning from matplotlib (as shown in the image below)
which should be suppressed but it doesn’t affect the data being displayed or the plot in
anyway. To suppress the warning however, the following lines of code can be added
after the import lines in our code.
Import warnings
import matplotlib.cbook
warnings.filterwarnings(“ignore”, category=matplotlib.cbook.mplDeprecation)
Code:
import time
import matplotlib.pyplot as plt
#import numpy
from drawnow import *
# Import the ADS1x15 module.
import Adafruit_ADS1x15
# Create an ADS1115 ADC (16-bit) instance.
adc = Adafruit_ADS1x15.ADS1115()
GAIN = 1
val = [ ]
cnt = 0
plt.ion()
# Start continuous ADC conversions on channel 0 using the previous gain value.
adc.start_adc(0, gain=GAIN)
print('Reading ADS1x15 channel 0')
#create the figure function
def makeFig():
plt.ylim(-5000,5000)
plt.title('Osciloscope')
plt.grid(True)
plt.ylabel('ADC outputs')
plt.plot(val, 'ro-', label='Channel 0')
plt.legend(loc='lower right')
while (True):
# Read the last ADC conversion value and print it out.
value = adc.get_last_result()
print('Channel 0: {0}'.format(value))
# Sleep for half a second.
time.sleep(0.5)
val.append(int(value))
drawnow(makeFig)
plt.pause(.000001)
cnt = cnt+1
if(cnt>50):
val.pop(0)
PRACTICAL NO. 3

AIM : Controlling Raspberry Pi with WhatsApp.

 Step 1: Installation

Update the packages with


sudo apt-get update
sudo apt-get upgrade
Update firmware
sudo rpi-update
Prepare the system with the necessary components to Yowsup
sudo apt-get install python-dateutil
sudo apt-get install python-setuptools
sudo apt-get install python-dev
sudo apt-get install libevent-dev
sudo apt-get install ncurses-dev
Download the library with the command
git clone git://github.com/tgalal/yowsup.git
navigate to the folder
cd yowsup
and install the library with the command
sudo python setup.py install

 Step 2: Registration

After installing the library we have to register the device to use WhatsApp. Yowsup
comes with a cross platform command-line frontend called yowsup-cli. It provides you
with the options of registration, and provides a few demos such as a command line
client.
WhatsApp registration involves 2 steps. First you need to request a registration code.
And then you resume the registration with code you got.
Request a code with command
python yowsup-cli registration --requestcode sms --phone 39xxxxxxxxxx --cc 39
--mcc 222 --mnc 10
Replace with your data ,
cc is your country code in this example 39 is for Italy,
mcc is Mobile Country Code
mnc is Mobile Network Code
You should receive on your phone a sms message with a code like xxx-xxx
Send a message to request registration with this command, (replace xxx-xxx with code
you received)
python yowsup-cli registration --register xxx-xxx --phone 39xxxxxxxxxx --cc 39
If all goes well, we should get a message like this
status: ok
kind: free
pw: xxxxxxxxxxxxxxxxxx=
price: € 0,89
price_expiration: 1416553637
currency: EUR cost: 0.89
expiration: 1445241022
login: 39xxxxxxxxxxx
type: existing

 Warning

WhatsApp requires the registration of a number, and with that number you can use
WhatsApp on only one device at a time, so it is preferable to use a new number.
WhatsApp can be used on one device at a time and if you will make many attempts to
register the number, it could be banned. We recommend you using Telegram.

 Step 3: Utilization

Create a file to save your credentials


sudo nano /home/pi/yowsup/config
with this content
## Actual config starts below ##
cc=39 #if not specified it will be autodetected
phone=39xxxxxxxxxx
password=xxxxxxxxxxxxxxx=
Ok, we're ready for the test, Yowsup has a demo application in
/home/pi/yowsup/yowsup/demos
Navigate to yowsup folder
cd /home/pi/yowsup
Start yowsup-cli demos with the command
yowsup-cli demos --yowsup --config config
You can see Yowsup prompt
If type "/help" you can see all available commands
First use the '/L' command for login; to send a message type
/message send 39xxxxxxxxxx "This is a message sent from Raspberry Pi"
replace xxx with the recipient number
If you respond with a message it will be displayed on Raspberry.
PRACTICAL NO. 4

AIM : Fingerprint Sensor interfacing with Raspberry Pi.

Finger Print Sensor, which we used to see in Sci-Fi moives few years back, is now
become very common to verify the identity of a person for various purposes. Using this
Raspberry Pi FingerPrint System, we can enroll new finger prints in the system and can
delete the already fed finger prints
 Required Components:
1. Raspberry Pi
2. USB to Serial converter
3. Fingerprint Module
4. Push buttons
5. 16x2 LCD
6. 10k pot
7. Bread Board or PCB (ordered from JLCPCB)
8. Jumper wires
9. LED (optional)
10. Resistor 150 ohm -1 k ohm (optional)
 Circuit Diagram and Explanation:
In this Raspberry Pi Finger Print sensor interfacing project, we have used a 4 push
buttons: one for enrolling the new finger pring, one for deleting the already fed finger
prints and rest two for increment/decrement the position of already fed Finger
prints .interfaced this fingerprint module with Raspberry Pi using a USB to Serial
converter.

Circuit Diagram below. A 16x2 LCD is used for displaying all messages. 16x2 LCD pins
RS, EN, d4, d5, d6, and d7 are connected with GPIO Pin 18, 23, 24, 25, 8 and 7 of
Raspberry Pi respectively. 4 push buttons are connected to GPIO Pin 5, 6, 13 and 19 of
Raspberry Pi.

 Installing Library for Finger Print Sensor:


Now we need to install fingerprint library for Raspberry Pi in python language by
following the below steps.
Step 1: To install this library, root privileges are required. So first we enter in root by
given command: sudo bash
Step 2: Then download some required packages by using given commands:
wget –O – http://apt.pm-codeworks.de/pm-codeworks.de.gpg | apt-key add –
wget http://apt.pm-codeworks.de/pm-codeworks.list -P /etc/apt/sources.list.d/

Step 3: After this, we need to update the Raspberry pi and install the downloaded finger
print sensor library: sudo apt-get update
sudo apt-get install python-fingerprint –yes

Step 4: After installing library now we need to check USB port on which your finger
print sensor is connected, by using given the command: ls /dev/ttyUSB*
 Operation of Fingerprint Sensor with Raspberry Pi:

Now to enroll a finger Print, user needs to press enroll button and follow the
instructions messages on LCD screen.

 Python Programming:
import time
from pyfingerprint.pyfingerprint
import PyFingerprint
import RPi.GPIO as gpio
RS =18
EN =23
D4 =24
D5 =25
D6 =8
D7 =7
enrol=5
delet=6
inc=13
dec=19
led=26
HIGH=1 LOW=0
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(RS, gpio.OUT) gpio.setup(EN, gpio.OUT)
gpio.setup(D4, gpio.OUT) gpio.setup(D5, gpio.OUT)
gpio.setup(D6, gpio.OUT) gpio.setup(D7, gpio.OUT)
gpio.setup(enrol, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setup(delet, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setup(inc, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setup(dec, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setup(led, gpio.OUT)
try:
f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
if ( f.verifyPassword() == False ):
raise ValueError('The given fingerprint sensor password is wrong!')
except Exception as e:
print('Exception message: ' + str(e))
exit(1)
Code :-
begin()
lcdcmd(0x01)
lcdprint("FingerPrint ")
lcdcmd(0xc0)
Icdprint("Interfacing ")
time.sleep(3)
lcdcmd(0x01)
lcdprint("Circuit Digest")
lcdcmd(0xc0)
lcdprint("Welcomes You ")
time.sleep(3)
flag=0
lcdclear()
while 1:
gpio.output(led, HIGH)
lcdcmd(1)
lcdprint("Place Finger")
if gpio.input(enrol) == 0:
gpio.output(led, LOW)
enrollFinger()
elif gpio.input(delet) == 0:
gpio.output(led, LOW)
while gpio.input(delet) == 0:
time.sleep(0.1)
deleteFinger()
else:
searchFinger()
Code :-
import time
from pyfingerprint.pyfingerprint import PyFingerprint
import RPi.GPIO as gpio
RS =18
EN =23
D4 =24
D5 =25
D6 =8
D7 =7
enrol=5
delet=6
inc=13
dec=19
led=26
HIGH=1 LOW=0
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(RS, gpio.OUT) gpio.setup(EN, gpio.OUT)
gpio.setup(D4, gpio.OUT) gpio.setup(D5, gpio.OUT)
gpio.setup(D6, gpio.OUT) gpio.setup(D7, gpio.OUT)
gpio.setup(enrol, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setup(delet, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setup(inc, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setup(dec, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setup(led, gpio.OUT)
try:
f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
if ( f.verifyPassword() == False ):
raise ValueError('The given fingerprint sensor password is wrong!')
except Exception as e:
print('Exception message: ' + str(e))
exit(1)
def begin():
lcdcmd(0x33)
lcdcmd(0x32)
lcdcmd(0x06)
lcdcmd(0x0C)
lcdcmd(0x28)
lcdcmd(0x01)
time.sleep(0.0005)
def lcdcmd(ch):
gpio.output(RS, 0)
gpio.output(D4, 0) gpio.output(D5, 0)
gpio.output(D6, 0) gpio.output(D7, 0)
if ch&0x10==0x10:
gpio.output(D4, 1)
if ch&0x20==0x20:
gpio.output(D5, 1)
if ch&0x40==0x40:
gpio.output(D6, 1)
if ch&0x80==0x80:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
gpio.output(D4, 0) # Low bits
gpio.output(D5, 0) gpio.output(D6, 0)
gpio.output(D7, 0)
if ch&0x01==0x01:
gpio.output(D4, 1)
if ch&0x02==0x02:
gpio.output(D5, 1)
if ch&0x04==0x04:
gpio.output(D6, 1)
if ch&0x08==0x08:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
def lcdwrite(ch):
gpio.output(RS, 1)
gpio.output(D4, 0) gpio.output(D5, 0)
gpio.output(D6, 0) gpio.output(D7, 0)
if ch&0x10==0x10:
gpio.output(D4, 1)
if ch&0x20==0x20:
gpio.output(D5, 1)
if ch&0x40==0x40:
gpio.output(D6, 1)
if ch&0x80==0x80:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
gpio.output(D4, 0) # Low bits
gpio.output(D5, 0) gpio.output(D6, 0)
gpio.output(D7, 0)
if ch&0x01==0x01:
gpio.output(D4, 1)
if ch&0x02==0x02:
gpio.output(D5, 1)
if ch&0x04==0x04:
gpio.output(D6, 1)
if ch&0x08==0x08:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
def lcdclear():
lcdcmd(0x01)
def lcdprint(Str):
l=0;
l=len(Str)
for i in range(l):
lcdwrite(ord(Str[i]))
def setCursor(x,y):
if y == 0:
n=128+x
elif y == 1:
n=192+x
lcdcmd(n)
def enrollFinger():
lcdcmd(1)
lcdprint("Enrolling Finger")
time.sleep(2)
print('Waiting for finger...')
lcdcmd(1)
lcdprint("Place Finger")
while ( f.readImage() == False ):
pass
f.convertImage(0x01)
result = f.searchTemplate()
positionNumber = result[0]
if ( positionNumber >= 0 ):
print('Template already exists at position #' + str(positionNumber))
lcdcmd(1)
lcdprint("Finger ALready")
lcdcmd(192)
lcdprint(" Exists ")
time.sleep(2)
return
print('Remove finger...')
lcdcmd(1)
lcdprint("Remove Finger")
time.sleep(2)
print('Waiting for same finger again...')
lcdcmd(1)
lcdprint("Place Finger")
lcdcmd(192)
lcdprint(" Again ")
while ( f.readImage() == False ):
pass
f.convertImage(0x02)
if ( f.compareCharacteristics() == 0 ):
print "Fingers do not match"
lcdcmd(1)
lcdprint("Finger Did not")
lcdcmd(192)
lcdprint(" Mactched ")
time.sleep(2)
return
f.createTemplate()
positionNumber = f.storeTemplate()
print('Finger enrolled successfully!')
lcdcmd(1)
lcdprint("Stored at Pos:")
lcdprint(str(positionNumber))
lcdcmd(192)
lcdprint("successfully")
print('New template position #' + str(positionNumber))
time.sleep(2)
def searchFinger():
try:
print('Waiting for finger...')
while( f.readImage() == False ):
#pass time.sleep(.5)
return
f.convertImage(0x01)
result = f.searchTemplate()
positionNumber = result[0]
accuracyScore = result[1]
if positionNumber == -1 :
print('No match found!')
lcdcmd(1)
lcdprint("No Match Found")
time.sleep(2)
return
else:
print('Found template at position #' + str(positionNumber))
lcdcmd(1)
lcdprint("Found at Pos:")
lcdprint(str(positionNumber))
time.sleep(2)
except Exception as e:
print('Operation failed!')
print('Exception message: ' + str(e))
exit(1)
def deleteFinger():
positionNumber = 0
count=0
lcdcmd(1)
lcdprint("Delete Finger")
lcdcmd(192)
lcdprint("Position: ")
lcdcmd(0xca)
lcdprint(str(count))
while gpio.input(enrol) == True: # here enrol key means ok
if gpio.input(inc) == False:
count=count+1 if count>1000:
count=1000 lcdcmd(0xca)
lcdprint(str(count))
time.sleep(0.2)
elif gpio.input(dec) == False:
count=count-1
if count<0:
count=0
lcdcmd(0xca)
lcdprint(str(count))
time.sleep(0.2)
positionNumber=count
if f.deleteTemplate(positionNumber) == True :
print('Template deleted!')
lcdcmd(1)
lcdprint("Finger Deleted");
time.sleep(2)
begin()
lcdcmd(0x01)
lcdprint("FingerPrint ")
lcdcmd(0xc0)
lcdprint("Interfacing ")
time.sleep(3)
lcdcmd(0x01)
lcdprint("Circuit Digest")
lcdcmd(0xc0)
Icdprint("Welcomes You ")
time.sleep(3)
flag=0
lcdclear()
while 1:
gpio.output(led, HIGH)
lcdcmd(1)
lcdprint("Place Finger")
if gpio.input(enrol) == 0:
gpio.output(led, LOW)
enrollFinger()
elif gpio.input(delet) == 0:
gpio.output(led, LOW)
while gpio.input(delet) == 0:
time.sleep(0.1)
deleteFinger()
else:
searchFinger()

PRACTICAL NO. 5

AIM : Raspberry Pi GPS Module Interfacing.


 Required Components:
1. Raspberry Pi 3
2. Neo 6m v2 GPS Module
3. 16 x 2 LCD
4. Power source for the Raspberry Pi
5. LAN cable to connect the pi to your PC in headless mode
6. Breadboard and Jumper cables
7. Resistor / potentiometer to the LCD
8. Memory card 8 or 16Gb running Raspbian Jessie
 GPS Module and Its Working:
GPS stands for Global Positioning System and used to detect the Latitude and
Longitude of any location on the Earth, with exact UTC time (Universal Time
Coordinated). GPS module is the main component in our vehicle tracking system
project. GPS module sends the data related to tracking position in real time, and it
sends so many data in NMEA format.
Now these latitude and longitude can be put in other arrays.

Identifier Description
$GPGGA Global Positioning system fix da
HHMMSS.SSS Time in hour minute se milliseconds format.
Latitude Latitude (Coordinate)
N Direction N=North, S=South
Longitude Longitude(Coordinate)
E Direction E= East, W=West
FQ Fix Quality Data
NOS No. of Satellites being Used
HDP Horizontal Dilution of Precision
Altitude Altitude from sea level
M Meter
Height Height
Checksum Checksum Data
 Preparing the Raspberry Pi to communicate with GPS:
 Step 1: Updating the Raspberry Pi:
The first thing I like I like to do before starting every project is updating the raspberry
pi. So lets do the usual and run the commands below;
sudo apt-get update
sudo apt-get upgrade
hen reboot the system with;
sudo reboot
 Step 2: Setting up the UART in Raspberry Pi:
The first thing we will do under this is to edit the /boot/config.txt file. To do this, run the
commands below:
sudo nano /boot/config.txt
at the bottom of the config.txt file, add the following lines
dtparam=spi=on
dtoverlay=pi3-disable-bt
core_freq=250
enable_uart=1
force_turbo=1
ctrl+x to exit and press y and enter to save.

What are the reasons for these commands, force_turbo enables UART to use the
maximum core frequency which we are setting in this case to be 250.
The dtoverlay=pi3-disable-bt disconnects the bluetooth from the ttyAMA0, this is to
allow us access to use the full UART power available via ttyAMAO instead of the mini
UART ttyS0.
Second step under this UART setup section is to edit the boot/cmdline.txt I will suggest
you make a copy of the cmdline.txt and save first before editing so you can revert back
to it later if needed. This can be done using;
sudo cp boot/cmdline.txt boot/cmdline_backup.txt
sudo nano /boot.cmdline.txt
Replace the content with;
dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=
deadline fsck.repair=yes rootwait quiet splash plymouth.ignore-serial-consoles
Save and exit. With this done then we will need to reboot the system again to effect
changes (sudo reboot).
 Step3: Disabling the Raspberry Pi Serial Getty Service
The next step is to disable the Pi’s serial the getty service, the command will prevent it
from starting again at reboot:
sudo systemctl stop [email protected]
sudo systemctl disable [email protected]
The following commands can be used to enable it again if needed
sudo systemctl enable [email protected]
sudo systemctl start [email protected] Reboot the system.
 Step 4: Activating ttyAMAO:
We have disabled the ttyS0, next thing is for us to enable the ttyAMAO.
sudo systemctl enable [email protected]
 Step5: Install Minicom and pynmea2:
We will be minicom to connect to the GPS module and make sense of the data. It is also
one of the tools that we will use to test is our GPS module is working fine. An alternative
to minicom is the daemon software GPSD.
sudo apt-get install minicom
To easily parse the received data, we will make use of the pynmea2 library. It can be
installed using;
sudo pip install pynmea2
 Step 6: Installing the LCD Library:
For this tutorial we will be using the AdaFruit library. The library was made for
AdaFruit screens but also works for display boards using HD44780. If your display is
based on this then it should work without issues.
I feel its better to clone the library and just install directly. To clone run;
git clone https://github.com/adafruit/Adafruit_Python_CharLCD.git
change into the cloned directory and install it
cd ./Adafruit_Python_CharLCD
sudo python setup.py install
 Connections for Raspberry Pi GPS module Interfacing:
Connect the GPS Module and LCD to the Raspberry Pi as shown in the Circuit
Diagram below.

Testing before Python Script:


Its important to test the GPS module connection before proceeding to the python script,
We will employ minicom for this. Run the command:
sudo minicom -D/dev/ttyAMA0 -b9600
where 9600 represents the baud rate at which the GPS module communicates. This may
be used for once we are sure of data communication between the GPS and the RPI, its
time to write our python script.
The test can also be done using cat
sudo cat /dev/ttyAMA0

Code :
import time
import serial
import string
import pynmea2
import RPi GPIO as gpio
import Adafruit_CharLCD as LCD #to add the LCD library
gpio.setmode(gpio.BCM) #declaring LCD pins
lcd_rs = 17
lcd_en = 18
lcd_d4 = 27
lcd_d5 = 22
lcd_d6 = 23
lcd_d7 = 10
lcd_backlight = 2
lcd_columns = 16 #Lcd column
lcd_rows = 2 #number of LCD rows
lcd = LCD.Adafruit_CharLCD(lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4,
lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight)
port = "/dev/ttyAMA0" # the serial port to which the pi is connected.
ser = serial.Serial(port, baudrate = 9600, timeout = 0.5) #create a serial object
while 1:
try:
data = ser.readline()
except: print("loading") #wait for the serial port to churn out data
if data[0:6] == '$GPGGA': # the long and lat data are always contained in the
GPGGA string of the NMEA data
msg = pynmea2.parse(data)
latval = msg.lat #parse the latitude and print
concatlat = "lat:" + str(latval)
print concatlat
lcd.set_cursor(0,0)
lcd.message(concatlat)
longval = msg.lon #parse the longitude and print
concatlong = "long:"+ str(longval)
print concatlong
lcd.set_cursor(0,1)
lcd.message(concatlong)
time.sleep(0.5) #wait a little before picking the next data.
PRACTICAL NO. 6
AIM : IoT based Web Controlled Home Automation using Raspberry Pi.
 Required Components:
For this project, the requirements will fall under two categories, Hardware and
Software:
I. Hardware Requirements:
1. Raspberry Pi 3 (Any other Version will be nice)
2. Memory card 8 or 16GB running Raspbian Jessie
3. 5v Relays
4. 2n222 transistors
5. Diodes
6. Jumper Wires
7. Connection Blocks
8. LEDs to test.
9. AC lamp to Test
10. Breadboard and jumper cables
11. 220 or 100 ohms resistor
II. Software Requirements:
Asides the Raspbian Jessie operating system running on the raspberry pi, we will also
be using the WebIOPi frame work, notepad++ running on your PC and filezila to copy
files from the PC to the raspberry pi, especially the web app files.

Preparing the Raspberry Pi:


To update the raspberry Pi below commands and then reboot the RPi;
sudo apt-get update
sudo apt-get upgrade
sudo reboot
With this done, the next thing is for us to install the webIOPi framework. Make sure
you are in home directory using; cd ~
Use wget to get the file from their sourceforge page;
wget http://sourceforge.net/projects/webiopi/files/WebIOPi-0.7.1.tar.gz
When download is done, extract the file and go into the directory;
tar xvzf WebIOPi-0.7.1.tar.gz
cd WebIOPi-0.7.1/
At this point before running the setup, we need to install a patch as this version of the
WebIOPidoes not work with the raspberry pi 3 which I am using .
Below commands are used to install patch while still in the WebIOPi directory, run;
Wget https://raw.githubusercontent.com/doublebind/raspi/master/webiopi
pi2bplus.patch
patch -p1 -i webiopi-pi2bplus.patch
Then we can run the setup installation for the WebIOPi using; E-next
sudo ./setup.sh
Keep saying yes if asked to install any dependencies during setup installation. When
done, reboot your pi;
sudo reboot
Test WebIOPi Installation:
Before jumping in to schematics and codes, With the Raspberry Pi back on, we will
need to test our WebIOPi installation to be sure everything works fine as desired. Run
the command;
sudo webiopi -d-c/etc/webiopi/config
After issuing the command above on the pi, point the web browser of your computer
connected to the raspberry pi to http://raspberrypi.mshome.net:8000 or
http://thepi'sIPaddress: 8000. The system will prompt you for username and password.
Username is webiopi
Password is raspberry
After the login, look around, and then click on the GPIO header link.

For this test, we will be connecting an LED to GPIO 17, so go on and set GPIO 17 as an
output.
With this done, connect the led to your raspberry pi as shown in the schematics below.

After the connection, go back to the webpage and click the pin 11 button to turn on or
off the LED.
Building the Web Application for Raspberry Pi Home Automation:
Make sure you are in home directory using, then create the folder, go into the created
folder and create html folder in the directory:
Cd~
mkdir webapp
cd webapp
mkdir html
Create a folder for scripts, CSS and images inside the html folder
mkdir html/css
mkdir html/img
mkdir html/scripts
The JavaScript Code:
The first piece of code we will write is that of the javascript. Its a simple script to
communicate with the WebIOPi service.
webiopi().ready(function() {
webiopi().setFunction(17,"out");
webiopi().setFunction(18, "out");
webiopi().setFunction(22,"out");
webiopi().setFunction(23,"out");
var content, button:
content = $("#content");
button = webiopi().createGPIOButton(17," Relay 1");
content.append(button);
button webiopi().createGPIOButton(18, "Relay 2");
content.append(button);
button webiopi().createGPIOButton(22, "Relay 3");
content.append(button);
button = webiopi().createGPIOButton(23,"Relay 4");
content.append(button);
} );
The code above runs when the WebIOPi is ready.
Below we have explained the JavaScript code:
webiopi().ready(function(): This just instructs our system to create this function and
run it when the webiopi is ready.
webiopi().setFunction(23,"out"); This helps us tell the WebIOPi service to set GPIO23
as output. We Have four buttons here, you could have more of it if you are
implementing more buttons.
var content, button; This line tells our system to create a variable named content and
make the variable a button.
content = $("#content"); The content variable is still going to be used across our html
and css. So when we refer to #content, the WebIOPi framework creates everything
associated with it.
button webiopi().createGPIOButton(17, "Relay 1"); WebIOPi can create different
kinds of buttons. The piece of code above helps us to tell the WebIOPi service to create a
GPIO button that controls the GPIO pin in this case 17 labeled "Relay 1". Same goes
for the other ones. content.append(button);
The CSS Code:
The first part of the script represent the stylesheet for the body of the web app and its
shown below;
body {
background-color:#ffffff;
background-image:url('/img/smart.png');
background-repeat:no-repeat;
background-position:center;
background-size:cover;
font: bold 18px/25px Arial, sans-serif;
color:LightGray;
}
With the body done, we written the css for buttons to look pretty.
button {
display: block;
position: relative;
margin: 10px;
padding: 0 10px;
text-align: center;
text-decoration: none;
width: 130px;
height: 40px;
font: bold 18px/25px Arial, sans-serif;
color: black;
text-shadow: 1px 1px 1px rgba(255,255,255, 22);
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
border-radius: 30px;
}
To keep this brief, every other thing in the code was also done to make it look good. You
can change them up see what happens, I think its called learning via trial and error but
one good thing about CSS is things being expressed in plain English which means they
are pretty easy to understand.The next block of code is for the WebIOPi service to tell it
that this is an input to the WebIOPi service.
input[type="range"] {
Display: block;
width: 160px;
Height : 45px;
}
The last thing we want to do is give some sort of indication when button has been.
pressed. So you can sort of look at the screen and the color of the buttons let you know
the current state. To do this, the line of code below was implemented for every single
button.
#gpio 17.LOW {
background-color: Gray;
color: Black;
}
#gpio17.HIGH {
background-color: Red;
color: LightGray;
}
The lines of codes above simply changes the color of the button based on its current
state. When the button is off(LOW) the buttons background color becomes gray to
show its inactive and when its on(HIGH) the background color of the button becomes
RED. Remember to download full CSS from here.
HTML Code:
The html code pulls everything together, javascript and the style sheet.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w 3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="mobile-web-app-capable" content="yes">
<meta name="viewport" content="height = device-height, width=device-width,
user-scalable no"/>
<title>Smart Home</title>
<script type="text/javascript" src="/webiopi.js"></script>
<script type="text/javascript" src="/scripts/smarthome.js"></script>
<link rel="stylesheet" type="text/css" href="/styles/smarthome.css">
<link rel="shortcut icon" sizes="196x196" href="/img/smart.png"/>
</head>
<body>
</br>
</br> <div id="content" align="center"></div>
</br>
</br>
</br>
<p align="center">Push button; receive bacon</p>
</br>
</br>
</body>
</html>
Within the head tag exist some very important features.
<meta name="mobile-web-app-capable" content="yes">
The next line of code below gives some sort of responsiveness to the web app. It enables
it occupy the screen of any device on which its launched.
<meta name="viewport" content="height = device-height, width=device-width,
user-s calable=no"/>
The next line of code declares the title shown on the title bar of the web page.
<title>Smart Home</title>
The next four line of codes each perform the function of linking the html code to several
resources it needs to work as desired.
<script type="text/javascript" src="/webiopi.js"></script>
<script type="text/javascript" src="/scripts/smarthome.js"></script>
<link rel="stylesheet" type="text/css" href="/styles/smarthome.css">
<link rel="shortcut icon" sizes="196x196" href="/img/smart.png"/>
The first line above calls the main WebIOPi framework JavaScript which is hard-coded
in the server root. This needs to be called every time the WebIOPi is to be used.
The second line points the html page to our jQuery script, the third points it in the
direction of our style sheet. Lastly the last line helps set up an icon to be used on the
mobile desktop in case we decide to use it as a web app or as a favicon for the webpage.
The id="content" should remind you of the content declaration for our button earlier
under the JavaScript code.
<div id="content" align="center"></div>
WebIOPi Server Edits for Home Automation:
To edit the configuration run the following with root permission;
sudo nano /etc/webiopi/config
Look for the http section of the config file, check under the section where you have
something like, #Use doc-root to change default HTML and resource files
locationsomething like, #Use doc-root to change default HTML and resource files
location Comment out anything under it using # then if your folder is setup like mine,
point your doc-root to the path of your project file
doc-root=/home/pi/webapp/html
Save and exit.
Its Important to note that you can change the password of the WebIOPi service using
the command;
sudo webiopi-passwd
It will prompt you for a new username and password. This can also be removed totally
but security is important right?
Lastly run the WebIOPi service by issuing below command:
sudo /etc/init.d/webiopi start
The server status can be checked using;
sudo /etc/init.d/webiopi status
It can be stopped from running using;
sudo /etc/init.d/webiopi stop
To setup WebIOPi to run at boot, use;
sudo update-rc.d webiopi defaults
If you want to reverse and stop it from running at boot, use;
sudo update-rc.d webiopi remove.
PRACTICAL NO. 7
AIM : Visitor Monitoring with Raspberry Pi and Pi Camera.
 Components Required:
1. Raspberry Pi
2. Pi camera
3. 16x2 LCD
4. DC Motor
5. IC L293D
6. Buzzer
7. LED
8. Bread Board
9. Resistor (1k,10k)
10. Capacitor (100nF)
11. Push Button
12. 10k Pot
13. Connecting wires
14. Power supply
Working Explanation :
Working of this Raspberry Pi Monitoring System is simple. In this, a Pi camera is used
to capture the images of visitors, when a push button is pressed or triggered. After it,
the gate is opened for a while and then gets closed again. The buzzer is used to generate
sound when button pressed and LED is used for indicating that Raspberry Pi is ready to
accept Push Button press, means when LED is ON, system is ready for operation.
Here the pictures of visitors are saved in Raspberry Pi with the name which itself
contains the time and date of entry.

Circuit Explanation:
Here a Liquid Crystal Display(LCD) is used for displaying Time/Date of visitor entry
and some other messages. LCD is connected to Raspberry Pi in 4-bit mode. Pins of LCD
namely RS, EN, D4, D5, D6, and D7 are connected to Raspberry Pi GPIO pin number
18, 23, 24, 16, 20 and 21. DC motor (as Gate) is connected with Raspberry Pi GPIO pin
17 and 27 through Motor Driver IC (L293D). Rest of connections are shown in circuit
diagram.

To connect the Pi Camera, insert the Ribbon cable of Pi Camera into camera slot,
slightly pull up the tabs of the connector at RPi board and insert the Ribbon cable into
the slot, then gently push down the tabs again to fix the ribbon cable.
Raspberry Pi Configuration and Programming Explanation:
After successfully installing Raspbian OS on Raspberry Pi, we need to install Pi camera
library filesfor run this project in Raspberry pi. To do this we need to follow given
commands: $ sudo apt-get install python-picamera
$ sudo apt-get install python3-picamera

After it, user needs to enable Raspberry Pi Camera by using Raspberry Pi Software
Configuration Tool (raspi-config): $ sudo raspi-config .

Then user needs to reboot Raspberry Pi, by issuing sudo reboot, so that new setting can
take. $ sudo reboot
Python program :-
import RPi.GPIO as gpio
import picamera
import time
m11-17
m12-27
led-5
buz=26
button=19
RS =18
def capture_image():
lcdcmd(0x01)
ledprint("Please Wait..");
data=time.strftime("%d_%b_%Y %H:%M:%S")
camera.start_preview()
time.sleep(5)
print data
camera.capture('/home/pi/Desktop/Visitors/%s.jpg'% data)
camera.stop_preview()
lcdcmd(0x01)
lcdprint("Image Captured")
lcdcmd(0xc0)
lcdprint(" Successfully ")
time.sleep(2)
def gate():
ledemd(0x01)
Icdprint(" Welcome ")
gpio.output(m11, 1)
gpio.output(m12, 0)
time.sleep(1.5)
gpio.output(m11, 0)
gpio.output(m12, 0)
time.sleep(3)
gpio.output(m11, 0)
gpio.output(m12, 1)
time.sleep(1.5)
gpio.output(m11, 0)
gpio.output(m12, 0)
ledcmd(0x01);
Icdprint(" Thank You ")
while 1:
d= time.strftime("%d %b %Y")
t= time.strftime("%H:%M:%S")
ledcmd(0x80)
ledprint("Time: %s"%t)
lcdcmd(0xc0)
Icdprint("Date:%s"%d)
gpio.output(led, 1)
if gpio.input(button)==0:
gpio.output(buz, 1)
gpio.output(led, 0)
time.sleep(0.5)
gpio.output(buz, 0)
capture_image()
gate()
time.sleep(0.5)
Code:
import RPi.GPIO as gpio
import picamera
import time
m11-17
m12-27
led-5
buz-26
button=19
RS-18
EN =23
D4-24
D5=16
D6-20
D7-21
HIGH=1
LOW=0
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(RS, gpio.OUT)
gpio.setup(EN, gpio.OUT)
gpio.setup(D4, gpio.OUT)
gpio.setup(D5, gpio.OUT)
gpio.setup(D6, gpio.OUT)
gpio.setup(D7, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(buz, gpio.OUT)
gpio.setup(m11, gpio.OUT)
gpio.setup(m12, gpio.OUT)
gpio.setup(button, gpio.IN)
gpio.output(led, 0)
gpio.output(buz, 0)
gpio.output(m11.0)
gpio.output(m12, 0)
data=""
def capture_image():
ledcmd(0x01)
Icdprint("Please Wait..");
data= time.strftime("%d_%b_%Y %H:%M:%S")
camera.start_preview()
time.sleep(5)
print data
camera.capture('/home/pi/Desktop/Visitors/%s.jpg'%data) Text
camera.stop_preview()
Icdcmd(0x01)
Icdprint("Image Captured")
lcdcmd(0xc0)
Icdprint(" Successfully ")
time.sleep(2)
def gate():
lcdcmd(0x01)
Icdprint(" Welcome ")
gpio.output(m11, 1)
gpio.output(m12, 0)
time.sleep(1.5)
gpio.output(m11, 0)
gpio.output(m12, 0)
time.sleep(3)
gpio.output(m11, 0)
gpio.output(m12, 1)
time.sleep(1.5)
gpio.output(m11, 0)
gpio.output(m12, 0)
ledemd(0x01):
Icdprint(" Thank You ")
time.sleep(2)
def begin():
ledemd(0x33)
lcdcmd(0x32)
lcdcmd(0x06)
lcdcmd(0x0C)
lcdcmd(0x28)
lcdcmd(0x01)
time.sleep(0.0005)
def ledcmd(ch):
gpio.output(RS, 0)
gpio.output(D4, 0)
gpio.output(D5, 0)
gpio.output(D6, 0)
gpio.output(D7, 0)
if ch&0x10-0x10:
gpio.output(D4, 1)
if ch&0x200x20:
gpio.output(D5, 1)
if ch&0x40-0x40:
gpio.output(D6, 1)
if ch&0x800x80:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
gpio.output(D4, 0) # Low bits
gpio.output(D5, 0)
gpio.output(D6, 0)
gpio.output(D7, 0)
if ch&0x01-0x01:
gpio.output(D4, 1)
if ch&0x02-0x02:
gpio.output(D5, 1)
if ch&0x04 0x04:
gpio.output(D6, 1)
if ch&0x08 0x08:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
def lcdwrite(ch):
gpio.output(RS, 1)
gpio.output(D4, 0)
gpio.output(D5, 0)
gpio.output(D6, 0)
gpio.output(D7, 0)
if ch&0x10-0x10:
gpio.output(D4, 1)
if ch&0x200x20:
gpio.output(D5, 1)
if ch&0x40-0x40:
gpio.output(D6, 1)
if ch&0x800x80:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
gpio.output(D4, 0) # Low bits
gpio.output(D5, 0)
gpio.output(D6, 0)
gpio.output(D7, 0)
if ch&0x01-0x01:
gpio.output(D4, 1)
if ch&0x02-0x02:
gpio.output(D5, 1)
if ch&0x04 0x04:
gpio.output(D6, 1)
if ch&0x08-0x08:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
def Icdprint(Str):
1=0;
1=len(Str)
for i in range(I):
Icdwrite(ord(Str[i]))
begin()
lcdcmd(0x01)
ledprint("Visitor Monitoring")
lcdcmd(0xc0)
Icdprint(" Using RPI ")
time.sleep(3)
lcdcmd(0xc0)
lcdprint("Saddam Khan")
time.sleep(3)
ledcmd(0x01)
camera picamera.PiCamera()
camera.rotation=180
camera.awb mode= 'auto'
camera.brightness-55
Icdcmd(0x01)
Icdprint(" Please Press ")
lcdcmd(0xc0)
Icdprint(" Button ")
time.sleep(2)
while 1:
d=time.strftime("%d %b %Y")
t= time.strftime("%H:%M:%S") ledcmd(0x80)
Icdprint("Time: %s"%t)
ledemd(0xc0)
lcdprint("Date:%s"%d)
gpio.output(led, 1)
if gpio.input(button) 0:
gpio.output(buz, 1)
gpio.output(led,
time.sleep(0.5)
gpio.output(buz, 0)
capture_image()
gate()
time.sleep(0.5)

PRACTICAL NO. 8
AIM : Interfacing Raspberry Pi with RFID.

 Setting up Raspberry Pi for Serial Communication


Before proceeding with the Interface of Raspberry Pi and RFID Reader Module, there
are a few things you need to do in your Raspberry Pi in order to enable the Serial
Communication in Raspberry Pi.
In Raspberry Pi, the Serial Port can be used or configured in two ways: Access Console
and Serial Interface.
In order to do this, first login to your Raspberry Pi using SSH (Putty). Enter the
Raspberry Pi Configuration Tool by entering the following command.
sudo raspi-config
In the “Interfacing Options”, select the “Serial” option.
Now, it asks whether you would like to access the login shell over serial communication.
Select “No” option. Then, it asks do you want to enable the Serial Port Hardware. Select
“Yes” option.

Finish the process and Reboot the Raspberry Pi. After the Raspberry Pi is powered up,
once agin login using Putty and in order to check whether the Serial Port is Enabled or
not, enter the following command.
dmesg | grep tty

At the bottom, you can see, “ttyS0” is configured as Serial. Now, you can proceed with
Interfacing RFID Reader Module with Raspberry Pi to communicate over Serial.
 Circuit Diagram of Raspberry Pi RFID Reader Interface
The following image shows the connections between the Raspberry Pi and the EM-18
RFID Reader.

 Components Required
1. Raspberry Pi 3 Model B
2. EM-18 RFID Reader Module
3. RS232-to-USB Adapter (as my RFID Reader has only RS232 Output)
4. Few RFID Cards or RFID Tags
5. Power Supply for RFID Reader (my RFID Reader has a 5V Regulator)
6. Connecting Wires
7. 5V Supply for Raspberry Pi and RS232-USB Adapter
8. 6802 Resistor (1/4 Watt)
9. 1.5ΚΩ Resistor (1/4 Watt)
 Circuit Design
On Raspberry Pi, the GPIO14 and GPIO14 i.e. Physical Pins 8 and 10 are the UART
TX and RX Pins respectively. As we have already enabled the Serial Port of the
Raspberry Pi, you can connect these pins to the external peripherals.
I have used 6802 and 1.5KΩ resistors. The output of the voltage divider is connected to
the UART RXD pin of the Raspberry Pi i.e. GPIO15. Make a common ground
connection between the Raspberry Pi and the RFID Reader Module.
Code
import time
import serial
data serial.Serial (
port=/dev/ttyS0',
baudrate 9600,
parity serial.PARITY_NONE,
stopbits serial.STOPBITS_ONE,
bytesize serial.EIGHTBITS )
#timeout=1 # must use when using data.readline() )
try:
while 1:
#x=data.readline() #print the whole data at once
#x=data.read() #print single data at once
print "Place the card"
x=data.read(12) #print upto 10 data at once and the
#remaining on the second line
if x="13004A29E191":
print "Card No-",x
print "Welcome Bala"
print " "
elif x="13006F8C7282":
print "Card No - ",x
print "Welcome Teja"
print " "
else:
print "Wrong Card....."
print ""
#print x
except KeyboardInterrupt:
data.close()
 Working
The Working of the Raspberry Pi RFID Reader Module Interface is very simple. After
enabling the Serial Port on the Raspberry Pi, we must assign the rest of the parameters
associated with UART Communication i.e. Baud Rate, Parity, Stop Bits and the Size of
the Data. All these values are set in the Python code.
After this, you will get a message as "Place the Card".
This data is further analyzed by the Raspberry Pi and appropriate messages are
displayed in the screen.

 Applications
Interfacing RFID Reader with Raspberry Pi can be very useful as you can implement a
wide range of applications like:
1. Access Control
2. 2. Authentication
3. e-Ticket
4. e-Payment
5. e-Toll
6. Attendance

You might also like