1.) Turning On An LED With Your Raspberry Pi's GPIO Pins: The Breadboard
1.) Turning On An LED With Your Raspberry Pi's GPIO Pins: The Breadboard
1.) Turning On An LED With Your Raspberry Pi's GPIO Pins: The Breadboard
A Breadboard
An LED
A 330 ohm resistor
Two Male-Female jumper wires
You can get all these, and more, in the £5 CamJam EduKit from The Pi Hut, which teaches you more about
LEDs, buzzers and switches, and includes all the hardware and eight well-written worksheets about using
the GPIO pins on your Pi.
The Breadboard
The breadboard is a way of connecting electronic components to each other without having to solder them
together. They are often used to test a circuit design before creating a Printed Circuit Board (PCB).
The holes on the breadboard are connected in a pattern.
With the breadboard in the CamJam EduKit, the top row of holes are all connected together – marked with
red dots. And so are the second row of holes – marked with blue dots. The same goes for the two rows of
holes at the bottom of the breadboard.
In the middle, the columns of wires are connected together with a break in the middle. So, for example, all
the green holes marked are connected together, but they are not connected to the yellow holes, nor the
purple ones. Therefore, any wire you poke into the green holes will be connected to other wires poked into
the other green holes.
The LED
LED stands for Light Emitting Diode, and glows when electricity is passed through it.
When you pick up the LED, you will notice that one leg is longer than the other. The longer leg (known as
the ‘anode’), is always connected to the positive supply of the circuit. The shorter leg (known as the
‘cathode’) is connected to the negative side of the power supply, known as ‘ground’.
LEDs will only work if power is supplied the correct way round (i.e. if the ‘polarity’ is correct). You will not
break the LEDs if you connect them the wrong way round – they will just not light. If you find that they do not
light in your circuit, it may be because they have been connected the wrong way round.
The Resistor
You must ALWAYS use resistors to connect LEDs up to the GPIO pins of the Raspberry Pi. The Raspberry
Pi can only supply a small current (about 60mA). The LEDs will want to draw more, and if allowed to they
will burn out the Raspberry Pi. Therefore putting the resistors in the circuit will ensure that only this small
current will flow and the Pi will not be damaged.
Resistors are a way of limiting the amount of electricity going through a circuit; specifically, they limit the
amount of ‘current’ that is allowed to flow. The measure of resistance is called the Ohm (Ω), and the larger
the resistance, the more it limits the current. The value of a resistor is marked with coloured bands along the
length of the resistor body.
You will be using a 330Ω resistor. You can identify the 330Ω resistors by the colour bands along the body.
The colour coding will depend on how many bands are on the resistors supplied:
If there are four colour bands, they will be Orange, Orange, Brown, and then Gold.
If there are five bands, then the colours will be Orange, Orange, Black, Black, Brown.
It does not matter which way round you connect the resistors. Current flows in both ways through them.
Jumper Wires
Jumper wires are used on breadboards to ‘jump’ from one connection to another. The ones you will be using
in this circuit have different connectors on each end. The end with the ‘pin’ will go into the Breadboard. The
end with the piece of plastic with a hole in it will go onto the Raspberry Pi’s GPIO pins.
Use one of the jumper wires to connect a ground pin to the rail, marked with blue, on the
breadboard. The female end goes on the Pi's pin, and the male end goes into a hole on the
breadboard.
Then connect the resistor from the same row on the breadboard to a column on the breadboard, as
shown above.
Next, push the LEDs legs into the breadboard, with the long leg (with the kink) on the right.
Lastly, complete the circuit by connecting pin 18 to the right hand leg of the LED. This is shown here
with the orange wire.
The Code
You are now ready to write some code to switch the LED on. Turn on your Pi and open the terminal
window.
Create a new text file “LED.py” by typing the following:
nano LED.py
Type in the following code:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print "LED on"
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
print "LED off"
GPIO.output(18,GPIO.LOW)
Once you have typed all the code and checked it, save and exit the text editor with “Ctrl + x” then “y” then
“enter”.
You will see the LED turn on for a second and then turn off.
If your code does not run and an error is reported, edit the code again using nano LED.py.
Components Required:
Here we are using Raspberry Pi 2 Model B with Raspbian Jessie OS. All the basic Hardware and
Software requirements are previously discussed, you can look it up in the Raspberry Pi Introduction, other
than that we need:
Connecting pins
220Ω or 1KΩresistor
LED
Bread Board
We will see the PYTHON program Code for LED Blinking, in detail, below.
Code
import RPi.GPIO as IO # calling header file for GPIO’s of PI
import time # calling for time to provide delays in program
IO.setmode (IO.BOARD) # programming the GPIO by BOARD pin numbers, GPIO21 is called as PIN40
IO.setup(40,IO.OUT) # initialize digital pin40 as an output.
IO.output(40,1) # turn the LED on (making the voltage level HIGH)
time.sleep(1) # sleep for a second
IO.cleanup() # turn the LED off (making all the output pins LOW)
time.sleep(1) #sleep for a second
#loop is executed second time
IO.setmode (IO.BOARD)
IO.setup(40,IO.OUT)
IO.output(40,1)
time.sleep(1)
IO.cleanup()
time.sleep(1)
#loop is executed third time
IO.setmode (IO.BOARD)
IO.setup(40,IO.OUT)
IO.output(40,1)
time.sleep(1)
IO.cleanup()
time.sleep(1)
Pract 2
Aim: Displaying Time over 4-Digit 7-Segment Display
using Raspberry Pi
Raspberry Pi Clock using 4-Digit 7-Segment Display and Raspberry Pi
We all know that Raspberry Pi is a wonderful Development platform based on ARM microprocessor. With
its high computational power it can work out wonders in hands of electronics hobbyists or students. All this
can be possible only if we know how to make it interact with the real world and analyse the data through
some output device. There are many sensors which can detect certain parameters from the real time world
and transfer it to a digital world and we analyse them viewing them either in a LCD screen or some other
display. But, it would always be not economical to use a LCD screen with PI for displaying small amount of
data. This is where we prefer to use 16x2 Alphanumeric LCD display or the 7-Segment display. We have
already learnt how to use a Alphanumeric LCD and a single segment 7-segment display with Raspberry pi.
Today we will Interface 4-digit Seven Segment Display Module with Raspberry Pi and display Time
over it.
Although 16x2 Alphanumeric LCD is much more comfortable than 7-segment display, there are few
scenarios where a 7-segment display would come in handier than a LCD display. LCD suffers from the
drawback of having low character size and will be overkill for your project if you are just planning to display
some numeric values. 7-segments also have the advantage against poor lighting condition and can be
viewed from lager angles than a normal LCD screen. So, let us start knowing it.
Now we know how to display our desired numeric character on a single 7-segment display. But, it is pretty
evident that we would need more than one 7-segment display to convey any information that is more than
one digit. So, in this tutorial we will be using a 4-digit 7-Segment Display Module as shown below.
As we can see there are Four Seven Segment Displays connected together. We know that each 7-segment
module will have 10 pins and for 4 seven segment displays there would be 40 pins in total and it would be
hectic for anyone to solder them on a dot board, so I would highly recommend anyone to buy a module or
make your own PCB for using a 4-digit 7-segment display. The connection schematic for the same is shown
below:
To understand how 4-digit seven segment module works we have to look into the above schematics, as
shown the A pins of all four display is connected to gather as one A and the same for B,C.... upto DP. So,
basically if trigger A on, then all four A's should go high right?
But, that does not happen. We have additional four pins from D0 to D3 (D0, D1, D2 and D3) which can be
used to control which display out of the four should go high. For example: If I need my output to be present
only on the second display then only D1 should be made high while keeping other pins (D0, D2, and D3) as
low. Simply we can select which display has to go active using the pins from D0 to D3 and what character to
be display using the pins from A to DP.
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 Rsp Pi PIN 7-Segment name 7-Seg pin number (here
number number in 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
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)
Pract No:3
AIM: Raspberry Pi Based Oscilloscope
Ras
pberry-Pi Oscilloscope
Hi guys, welcome to today’s post. One of the most fascinating thing about being a maker is knowing how to
develop makeshift tools, you will never get stuck working on any project when you have that kind of
versatility. So Today, I will be sharing how to build a Raspberry Pi based makeshift version of one of the
most important tools in Electrical/Electronics engineering; The Oscilloscope.
The oscilloscope is an electronic test instrument that allows the visualization and observation of varying
signal voltages, usually as a two dimensional plot with one or more signals plotted against time. Today’s
project will seek to replicate the signal visualization capabilities of the oscilloscope using the Raspberry Pi
and an analog to digital converter module.
Project Flow:
Replicating the signal visualization of the oscilloscope using the Raspberry Pi will require the following steps;
1. Perform Digital to analog conversion of the Input signal
2. Prepare the resulting data for representation
3. Plot the data on a live time graph
A simplified block diagram for this project would look like the diagram below.
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.
The ADC is an I2C based device and should be connected to the Raspberry Pi as shown in the schematics
below.
For clarity, the pin connection between the two components is also described below.
Step6: Install the Drawnow python module
Lastly, we need to install the drawnow python module. This module helps us provide live updates to the data
plot.
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
You should get an outcome like the image below after running it.
With all the dependencies installed, we are now ready to write the code.
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: 4
AIM: CONTROLLING RASPBERRY PI WITH WHATSAPP
INTRODUTION: WHATSAPP ON RASPBERRY PI
Introduction: WhatsApp on Raspberry Pi
In this tutorial we will see how to use WhatsApp with Raspberry Pi.
We will use the Yowsup library we had already used in these tutorials: WhatsApp
message from Phidgets SBC , Phidgets WhatsApp - ask the status of your sensors.
These days the library has been completely rewritten and improved, so we will see how
to install it and use it.
Yowsup is a python library that allows you to login and use the WhatsApp service and
provides you with all capabilities of an official WhatsApp client, allowing you to create a
full-fledged custom WhatsApp client.
You need: a Raspberry Pi B or B+, with the latest version of Raspbian, or our MIcroSD
Card 8GB Class 10 Raspbian preinstalled.
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 check your here mnc is Mobile Network Code check your here
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
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.
The possibilities of use are endless, for example you could use
WhatsApp to send messages in the home automation system seen in the tutorial Home
Automation Raspberry and Phidgets part 2 or Home Automation Raspberry and
Phidgets part 3
Practical No : - 5
Required Components:
The following components will be needed to set up a raspberry pi as a wireless access point:
1. Raspberry Pi 2
2. 8GB SD card
3. WiFi USB dongle
4. Ethernet cable
5. Power supply for the Pi.
6. Monitor (optional)
7. Keyboard (optional)
8. Mouse (optional)
While the Raspberry Pi 3 and Pi zero are widely available and could have been used, for this tutorial, I will
be using the Raspberry Pi 2 because my Pi3 is currently busy performing some heavy computer vision
related task, which I hope to share in a tutorial here soon. This procedure however, also works for the pi 3
and should (note the emphasis) also work for the Raspberry Pi zero W. When using the Raspberry Pi 3 or
the Zero W there won’t be a need for an external Wi-Fi module as these two boards already have Wi-Fi
on board.
To define the goals of this tutorial more intricately, we will be giving our Raspberry Pi the ability to serve as
a wireless access point and to achieve this, we will need to install and setup a software that equips the
raspberry pi with this functionality along with a DHCP server softwareto provide a network address for the
devices which will be connected to the access point. To satisfy this software requirement, we will be using
the dnsmasq and the hostapd softwares.
This tutorial will be based on the Raspbian stretch OS, so to proceed as usual, 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.
followed by;
followed by;
Step 3: Stop the software from Running
Since we don’t have the software configured yet there is no point running it, so we disable them from
running in the underground. To do this we run the following commands to stop the systemd operation.
Step 4: Configure a Static IP address for the wireless Port
Confirm the wlan port on which the wireless device being used is connected. For my Pi, the wireless is on
wlan0. Setting up the Raspberry Pi to act as a server requires us to assign a static IP address to the
wireless port. This can be done by editing the dhcpcd config file. To edit the configuration file, run;
Scroll to the bottom of the config file and add the following lines.
Interface wlan0
static ip_address=192.168.4.1/24
After adding the lines, the config file should look like the image below.
Step 5: Configure the dhcpcd server
With a static IP address now configured for the Raspberry Pi wlan, the next thing is for us to configure
the dhcpcd server and provide it with the range of IP addresses to be assigned to devices that connect
to the wireless access point. To do this, we need to edit the configuration file of the dnsmasq software but
the config file of the software contains way too much info and a lot could go wrong If not properly edited, so
instead of editing, we will be creating a new config file with just the amount of information that is needed to
make the wireless access point fully functional.
Before creating the new config file, we keep the old on safe by moving and renaming it.
with the editor launched, copy the lines below and paste in or type directly into it.
Interface = wlan0 #indicate the communication interface which is usually wlan0 for
wireless
the content of the file should look like the image below.
Save the file and exit. The content of this config file is just to specify the range of IP address that can be
assigned to devices connected to the wireless access point.
With this done, we will be able to give an identity to devices on our network.
The next set of steps will help us configure the access point host software, setup the ssid, select the
encrytpion etc.
Step 6: Configure hostapd for SSID and Password
We need to edit the hostapd config file(run sudo nano /etc/hostapd/hostapd.conf) to add the various
parameters for the wireless network being setup including the ssid and password. Its should be noted
that the password (passphrase) should be between 8 and 64 characters. Anything lesser won’t work.
interface=wlan0
driver=nl80211
ssid=piNetwork
hw_mode=g
channel=7
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=emmanuel # use a very secure password and not this
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCM
The content of the file should look like the image below.
Feel free to change the ssid and password to suit your needs and desire.
Save the config file and exit.
After the config file has been saved, we need to point the hostapd software to where the config file has been
saved. To do this, run;
Uncomment the DAEMON_CONF line and add the line below in between the quotes in front of the “equal to”
sign.
/etc/hostapd/hostapd.conf
Step 7: Fire it up
Since we disabled the two software initially, to allow us configure them properly, we need to restart the
system after configuration to effect the changes.
Use;
Step 8: Routing and masquerade for outbound traffic
We need to add routing and masquerade for outbound traffic.
To do this, we need to edit the config file of the systemctl by running:
Step 9: Create Wireless Access Point on startup:
For most wireless access point application, it is often desired that the access point comes up as soon as the
system boots. To implement this on the raspberry pi, one of the easiest ways is to add instructions to run the
software in the rc.local file so we put commands to install the iptable rules on boot in the rc.local file.
To edit the rc.local file, run:
Step 10: Reboot! and Use
At this stage, we need to reboot the system to effect all the changes and test the wireless access point
starting up on boot with the iptables rule updated.
Reboot the system using:
sudo reboot
As soon as the system comes back on, you should be able to access the wireless access point using any
Wi-Fi enabled device and the password used during the setup.
When a bridge is created, a higher level construct is created over the two ports being bridged and the bridge
thus becomes the network device. To prevent conflicts, we need to stop the allocation of IP addresses by
the DHCP client running on the Raspberry Pi to the eth0 and wlan0 ports. This will be done by editing the
config file of the dhcpcd client to include denyinterfaces wlan0 and denyinterfaces eth0 as shown in the
image below.
The file can be edited by running the command;
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)
So, first of all, we need to make the all the required connection as shown in Circuit Diagram below.
Connections are simple, we have just connected fingerprint module to Raspberry Pi USB port by using USB
to Serial converter. A 16x2 LCD is used for displaying all messages. A 10k pot is also used with LCD for
controlling the contrast of the same. 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. Four push buttons are connected to GPIO Pin 5, 6,
13 and 19 of Raspberry Pi. LED is also connected at pin 26 of RPI.
pin 26 of RPI.
Installing Library for Finger Print Sensor:
After making all the connections we need to power up Raspberry Pi and get it ready with terminal open.
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 3: After this, we need to update the Raspberry pi and install the downloaded finger print sensor
library:
sudo apt-get update
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*
Now replace the USB port no., with the USB port you got over the screen and replace it in the python
code. Complete Python code is given at the end of this project.
Now to enroll a finger Print, user needs to press enroll button and follow the instructions messages on
LCD screen.
If the user wants to delete any of fingerprints then the user needs to press delete button. After which, LCD
will ask for the position of the fingerprint which is to be deleted. Now by using another two push button for
increment and decrement, user can select the position of saved Finger Print and press enroll button (at this
time enroll button behave as Ok button) to delete that fingerprint. For more understanding have a look at
the video given at the end of the project.
Python Programming:
Python for interfacing Finger Print Sensor with RPi is easy with using fingerprint library functions. But if
the user wants to interface it himself, then it will be little bit difficult for the first time. In finger print sensor
datasheets, everything is given that is required for interfacing the same module. A GitHub code is available
to test your Raspberry pi with Finger Print sensor.
Here we have used the library so we just need to call library function. In code, first we need to import
libraries like fingerprint, GPIO and time, then we need to define pins for LCD, LED and push buttons.
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
After this, we need to initialize and give direction to the selected pins
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)
Now we have initialized fingerprint Sensor
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)
We have written some function to initialize and drive the LCD, check the complete code below in code
section:
def begin(), def lcdcmd(ch), def lcdwrite(ch), def lcdprint(Str), def setCursor(x,y)
After writing all LCD driver functions, we have placed functions for fingerprint enrolling, searching and
deleting.
def enrollFinger() function is used for enrol or save the new finger prints.
def searchFinger() function is used to searthc the already stored finger prints
def deleteFinger() functinos is used to deoted the already saved finger print by pressing the correspontind
push button.
All above function’s Code is given the in python code given below.
After this, finally, we need to initialize system by in while 1 loop by asking to Place Finger on finger print
sensor and then system will check whether this finger print it valid or not and display the results accordingly.
begin()
lcdcmd(0x01)
lcdprint("FingerPrint ")
lcdcmd(0xc0)
lcdprint("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()
Complete Python Code and a Working Video is given below.
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)
# Low bits
gpio.output(D4, 0)
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)
# Low bits
gpio.output(D4, 0)
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)
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()
PRACTICAL NO : - 7
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
Other than that we need to install GPS Daemon (GPSD) library, 16x2 LCD Adafruit library, which we install
later in this tutorial.
Here we are using Raspberry Pi 3 with Raspbian Jessie OS. All the basic Hardware and Software
requirements are previously discussed, you can look it up in the Raspberry Pi Introduction.
M Meter
Height Height
Checksum Checksum Data
To dive in, here’s a little explanation of How the Raspberry Pi 3 UART Works.
The Raspberry Pi has two built-in UARTs, a PL011 and a mini UART. They are implemented using different
hardware blocks so they have slightly different characteristics. On the raspberry pi 3 however, the
wireless/bluetooth module is connected to the PLO11 UART, while the mini UART is used for the linux
console ouptut. Depending on how you see it, I will define the PLO11 as the best of the two UART due to its
implementation level. So for this project we will be deactivating the Bluetooth module from the PLO11 UART
using an overlay available in the updated current version of the Raspbian Jessie.
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 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.
Ensure there are no typos or errors by double checking as an error with this might prevent your pi from
booting.
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 reason for this is to ensure consistency and integrity of the
serial data been received. Its important to note at this point that using force_turbo=1 will void the warranty
of your raspberry pi, but asides that, its pretty safe.
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;
Replace the content with;
The following commands can be used to enable it again if needed
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.
To easily parse the received data, we will make use of the pynmea2 library. It can be installed using;
change into the cloned directory and install it
cd ./Adafruit_Python_CharLCD
At this stage, I will suggest another reboot so we are ready to go on to connecting the components.
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
Code
import time
import serial
import string
import pynmea2
import RPi GPIO as gpio
#to add the LCD library
import Adafruit_CharLCD as LCD
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.
#create a serial object
ser = serial.Serial(port, baudrate = 9600, timeout = 0.5)
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)
#parse the latitude and print
latval = msg.lat
concatlat = "lat:" + str(latval)
print concatlat
lcd.set_cursor(0,0)
lcd.message(concatlat)
#parse the longitude and print
longval = msg.lon
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 : 8
AIM: IoT based Web Controlled Home Automation
using Raspberry Pi
Io
T based Web Controlled Home Automation using Raspberry Pi
Hi guys, welcome to today's tutorial, one of the good things about the Raspberry Pi is the great ability and
ease with which it gives you the opportunity to connect devices to the internet especially for Home
Automation Related Projects. Today we are going to explore the possibility of controlling AC appliances
with the click of buttons on a webpage using internet. Using this IoT based home automation system,
you can control your Home appliances from anywhere in the world. This web server can be run from any
device which can run HTML applications, like Smart Phone, tablet, computer etc.
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.
Also you dont need to code in Python for this Home Automation Project, WebIOPi will do all the work.
Preparing the Raspberry Pi:
Its an habit of some sort for me and i think it’s a good one, the first thing I do each time i want to use the
Raspberry Pi is to update the PI. For this project, this section will comprise of the Pi updating procedures
and installing the WebIOPi framework which will help us handle communication from the webpage to the
raspberry pi. I Should probably state that this can also be done in an arguably easier way using the python
Flask frame work but one of the interesting thing about DIY is when you take a look under the hood and
make the difficult work. Thats where all the joy of DIY comes.
To update the raspberry Pi below commands and then reboot the RPi;
With this done, the next thing is for us to install the webIOPi framework.
Make sure you are in home directory using;
cd ~
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;
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 and I couldn’t find a version of the WebIOPi that works
expressly with the Pi 3.
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
Then we can run the setup installation for the WebIOPi using;
sudo ./setup.sh
Keep saying yes if asked to install any dependencies during setup installation. When done, reboot your pi;
sudo reboot
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
This login can be removed later if desired but even your home automation system deserves some extra level
of security to prevent just anyone with the IP controlling appliances and IOT devices in your home
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. This
way we can control the Raspberry Pi GPIO using WebIOPi.
After the test, if everything worked as described, then we can go back to the terminal and stop the program
with CTRL + C. If you have any issue with this setup, then hit me up via the comment section.
More info on Webiopi can be found on its Wiki page (http://webiopi.trouch.com/INSTALL.html)
With the test complete, we are then set to start the main project.
With our files created lets move to writing the codes on our PC and from then move to the Pi via filezilla.
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.
Its important to note that for this project, our web app will consist of four buttons, which means we plan to
control just four GPIO pins, although we will be controlling just two relays in our demonstration. Check
the full Video at the end.
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); Append this code to any other code for the button created either in the html file or
elsewhere. More buttons can be created and will all have the same properties of this button. This is
especially useful when writing the CSS or Script.
After creating the JS files, we save it and then copy it using filezilla to webapp/html/scripts if you created
your files the same way I did mine.
With this done, we move to creating the CSS. You can whole download the code from the link given in the
Code section in the end.
The CSS Code:
The CSS helps us make our IoT Raspberry Pi home automation webpage look pretty.
I wanted the webpage to look like the image below and thus had to write the smarthome.cssstyle sheet to
achieve it.
Ps: Building is an Image from google.
Below we have explained the CSS code:
The CSS script feels too bulky to include here so I will just pick part of it and use them for the breakdown.
You can download the full CSS file from here. CSS is easy and you can understand it just by going
through the CSS code. You can easily skit this part and use our CSS code straight away.
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;
}
I want to believe the code above is self-explanatory, we set the background color as #ffffff which is white,
then we add a background image located at that folder location (Remember our earlier folder setup?), we
ensure the image doesn’t repeat by setting the background-repeat property to no-repeat, then instruct the
CSS to centralize the background. We then move to set the background size, font and color.
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 other part of the
button block has few extras for text shadow on the button and button shadow. It also has a slight transition
effect which helps it look nice and realistic when the button is pressed. These are defined separately for
webkit, firefox, opera etc just to ensure the web page performs optimally across all platforms.
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.
#gpio17.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.
CSS in the bag, lets save as smarthome.css, then move it via filezilla(or anyother SCP software you want to
use) to the styles folder on our raspberry pi and fix the final piece, the html code. 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.w3.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.
The line of code above enables the web app to be saved to a mobile desktop is using chrome or mobile
safari. This can be done via the chrome menu. This gives the app an easy launch feel from the mobile
desktop or home.
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.
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.
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 body section of the html code just contains break tags to ensure the buttons aligned properly with the
line below telling our html code to display what is written in the JavaScript file. The id=”content” should
remind you of the content declaration for our button earlier under the JavaScript code.
PRACTICAL NO : - 9
AIM: visitor Monitoring System with Raspberry Pi and Pi
Camera
Raspberry Pi is an ARM cortex based popular development board designed for Electronic Engineers and
Hobbyists. With the processing speed and memory, Raspberry Pi can be used for performing different
functions at a time, like a normal PC, and hence it is called Mini Computer in your palm. We have created
a series of Raspberry Pi tutorials, to start with Raspberry Pi from scratch and then create high level IoT
projects using Raspberry Pi.
This time we are here with our next interesting project which is Visitors Monitoring System with Image
capture functionality. Here we are interfacing Pi camera with Raspberry Pi to capture the image of
every visitor which has entered through the Gate or door. In this project, whenever any person is arrived at
the Gate, he has to press a button to open the Gate, and as soon as he/she press the button,
his/her picture will be captured and saved in the system with the Date and time of the entry . This can
be very useful for security and surveillance purpose.
This system is very useful in offices or factories where visitor entry record is maintained for visitors and
attendance record is maintained for employees. This Monitoring system will digitize and automate the whole
visitor entries and attendances, and there will be no need to maintain them manually. This system can be
either operated by the person himself or there can be operator for pressing the button for very visitor. This is
a good project for getting started with Pi camera and interface it with Raspberry Pi.
Components Required:
Raspberry Pi
Pi camera
16x2 LCD
DC Motor
IC L293D
Buzzer
LED
Bread Board
Resistor (1k,10k)
Capacitor (100nF)
Push Button
Connecting wires
10k Pot
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. A DC motor is used as a gate. Whenever
anyone wants to enter in the place then he/she needs to push the button. After pushing the button,
Raspberry Pi sends command to Pi Camera to click the picture and save it. 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. Means there is no need to save date and time separately at some other place as we have assigned
the time and date as the name of the captured picture, see the image below. We have here taken the image
of a box as visitor, check its full demonstration in the Video at the end.
Circuit Explanation:
Circuit of this Raspberry Pi Visitor Surveillance System is very simple. 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. Pi camera module is connected at camera slot of
the Raspberry Pi. A buzzer is connected to GPIO pin 26 of Raspberry Pi for indication purpose. LED is
connected to GPIO pin 5 through a 1k resistor and a push button is connected to GPIO pin 19 with respect
to ground, to trigger the camera and open the Gate. 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.
$ sudo raspi-config
Then user needs to reboot Raspberry Pi, by issuing sudo reboot, so that new setting can take. Now your Pi
camera is ready to use.
$ sudo reboot
The Python Program of this project plays a very important role to perform all the operations. First of all, we
include required libraries, initialize variables and define pins for LCD, LED, Motor and other components.
def capture_image():
lcdcmd(0x01)
lcdprint("Please Wait..");
data= time.strftime("%d_%b_%Y\%H:%M:%S")
camera.start_preview()
time.sleep(5)
Function def gate() is written for driving the DC motor which is used as a Gate here.
def gate():
lcdcmd(0x01)
lcdprint(" 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)
lcdcmd(0x01);
lcdprint(" Thank You ")
time.sleep(2)
Some functions are defined for LCD like def begin() function is used to initialize LCD, def
lcdcmd(ch) function is used for sending command to LCD, def lcdwrite(ch) function is used for sending data
to LCD and def lcdprint(Str) function is used to send data string to LCD. You can check all these functions in
Code given afterwards.
Then we have initialized the LCD and Pi Camera, and continuously read the Push
button using while loop. Whenever the push button is pressed, to open the gate for entry, image of the
visitor is captured and saved at the Raspberry pi with date & time and gate gets opened. Check the Full
code and Demonstration Video below.
while 1:
d= time.strftime("%d %b %Y")
t= time.strftime("%H:%M:%S")
lcdcmd(0x80)
lcdprint("Time: %s"%t)
lcdcmd(0xc0)
lcdprint("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)
This Camera Monitoring System has lot of scope to upgrade, like a software can be built in Computer
Vision or in OpenCV to match the captured picture of visitor with the already stored images and only
authorized the visitor if some match has been found, this will only open the gate for authorised people.
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():
lcdcmd(0x01)
lcdprint("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():
lcdcmd(0x01)
lcdprint(" 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)
lcdcmd(0x01);
lcdprint(" Thank You ")
time.sleep(2)
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)
# Low bits
gpio.output(D4, 0)
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)
# Low bits
gpio.output(D4, 0)
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 lcdprint(Str):
l=0;
l=len(Str)
for i in range(l):
lcdwrite(ord(Str[i]))
begin()
lcdcmd(0x01)
lcdprint("Visitor Monitoring")
lcdcmd(0xc0)
lcdprint(" Using RPI ")
time.sleep(3)
lcdcmd(0x01)
lcdprint("Circuit Digest")
lcdcmd(0xc0)
lcdprint("Saddam Khan")
time.sleep(3)
lcdcmd(0x01)
camera = picamera.PiCamera()
camera.rotation=180
camera.awb_mode= 'auto'
camera.brightness=55
lcdcmd(0x01)
lcdprint(" Please Press ")
lcdcmd(0xc0)
lcdprint(" Button ")
time.sleep(2)
while 1:
d= time.strftime("%d %b %Y")
t= time.strftime("%H:%M:%S")
lcdcmd(0x80)
lcdprint("Time: %s"%t)
lcdcmd(0xc0)
lcdprint("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)
PRACTICAL NO :- 10
Overview
RFID or Radio Frequency Identification is a way of communication over electromagnetic wave
(Radio Frequency Waves, to be specific). RFID Tags and RFID Cards are often used for
authentication and access control. You might have seen people swiping their identity cards at the
entrance of their offices. The identity card is in fact an RFID Card that has the personal information of
the employee. The moment he/she swipes the card, his check in time will be captured by a computer.
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. By default, the Serial Port of the Raspberry Pi is configured to access the
Linux Console i.e. as Console I/O pins.
But, we want to change this to act as a Serial Communication Port so that we can connected
external peripherals, like RFID Reader in this project, to communicate through serial
communication.
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.
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 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.
It is now a good time to note that Raspberry Pi works on 3.3V Logic. Hence, the RX Pin of the
Raspberry Pin must only be given with 3.3V Logic. In order to do that, we need to level convert
the TX line of the RFID Reader to 3.3V using a simple Voltage Divider Network consisting to
two resistors.
I have used 680Ω 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
A simple Python Script is written to read the values from the RFID Card, compare it with the
predefined values (I have already collected the data of all the RFID Cards beforehand) and
display specific information.
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()
#)
print " "
try:
while 1:
#x=data.readline()#print the whole data at once
#x=data.read()#print single data at once
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()
NOTE: In the “port=’/dev/ttyS0’” line, replace ttyS0 with the name of the serial device assigned
to you.
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”. When you place your RFID Card on the
RFID Reader, the RFID Reader Module it will read the data from the Card and sends the data
to the Raspberry Pi over Serial Communication.
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:
Access Control
Authentication
e-Ticket
e-Payment
e-Toll
Attendance