Raspberry Practical Manual - 3
Raspberry Practical Manual - 3
x=1
numTimes=int(input("Enter tottal number of times to blink"))
speed=float(input("Enter length of each blink(seconds) : "))
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.OUT)
GPIO.setup(10,GPIO.OUT)
GPIO.setup(19,GPIO.OUT)
GPIO.setup(26,GPIO.OUT)
GPIO.setup(29,GPIO.OUT)
def Blink(numTimes,speed):
for i in range(0,numTimes):
GPIO.output(5,True)
print ("Iteration ", (i+1))
GPIO.output(10,True)
print ("Iteration ", (i+1))
GPIO.output(19,True)
print ("Iteration ", (i+1))
GPIO.output(26,True)
print ("Iteration ", (i+1))
GPIO.output(29,True)
print ("Iteration ", (i+1))
GPIO.output(29,False)
print ("Iteration ", (i+1))
time.sleep(speed)
GPIO.output(26,False)
print ("Iteration ", (i+1))
T.Y.B.Sc. (I.T.) 2024
time.sleep(speed)
GPIO.output(19,False)
print ("Iteration ", (i+1))
time.sleep(speed)
GPIO.output(10,False)
print ("Iteration ", (i+1))
time.sleep(speed)
GPIO.output(5,False)
print ("Iteration ", (i+1))
time.sleep(speed)
Blink(numTimes,speed)
print("Done")
T.Y.B.Sc. (I.T.) 2024
TM1637 script
In order to control the LED, we use a special script with pre-defined functions. Various
functions are available in the script, for example you can display numbers and adjust the
intensity of the LEDs. Download the script with the command:
wget https://raspberrytips.nl/files/tm1637.py
T.Y.B.Sc. (I.T.) 2024
Code:
import sys
import time
import datetime
import RPi.GPIO as GPIO
import tm1637
Display = tm1637.TM1637(23,24,tm1637.BRIGHT_TYPICAL)
Display.Clear()
Display.SetBrightnes(1)
while(True):
now = datetime.datetime.now()
hour = now.hour
minute = now.minute
second = now.second
currenttime = [ int(hour / 10), hour % 10, int(minute / 10), minute % 10 ]
Display.Show(currenttime)
Display.ShowDoublepoint(second % 2)
time.sleep(1)
T.Y.B.Sc. (I.T.) 2024
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;
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
T.Y.B.Sc. (I.T.) 2024
documented datasheet and use instructions by Adafruit. You can also check
our Raspberry Pi ADC tutorial to learn more about it.
sudo raspi-config
When the configuration panels open, select interface options, select I2C and click enable.
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:
cd ~
Next, clone the Adafruit git folder for the library by running;
Change into the cloned file’s directory and run the setup file;
cd Adafruit_Python_ADS1x15
sudo python setup.py install
After installation, your screen should look like the image below.
T.Y.B.Sc. (I.T.) 2024
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:
T.Y.B.Sc. (I.T.) 2024
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.
You should get an outcome like the image below after running it.
T.Y.B.Sc. (I.T.) 2024
With all the dependencies installed, we are now ready to write the code.
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. Before showing us the whole code, I will try to break
it into part and explain what each part of the code is doing so you can have enough
knowledge to extend the code to do more stuffs.
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.
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,
T.Y.B.Sc. (I.T.) 2024
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')
T.Y.B.Sc. (I.T.) 2024
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))
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)
That’s all!
The complete Python code is given at the end of this tutorial.
If you used a different name other than scope.py, don’t forget to change this to match.
After a few minutes, you should see the ADC data being printed on the terminal.
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)
T.Y.B.Sc. (I.T.) 2024
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')
T.Y.B.Sc. (I.T.) 2024
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)
T.Y.B.Sc. (I.T.) 2024
/start
1.5 Create a new Bot
Look at your Pi, you can see the LED on and off when you send "on" and "off" to our bot.
Code:
import sys
import time
import random
import datetime
import telepot
import RPi.GPIO as GPIO
#LED
def on(pin):
GPIO.output(pin,GPIO.HIGH)
return
def off(pin):
GPIO.output(pin,GPIO.LOW)
return
# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)
# set up GPIO output channel
GPIO.setup(11, GPIO.OUT)
T.Y.B.Sc. (I.T.) 2024
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
if command == 'on':
bot.sendMessage(chat_id, on(11))
elif command =='off':
bot.sendMessage(chat_id, off(11))
while 1:
time.sleep(10)
5
Raspberry Pi GPS Module Interfacing.
T.Y.B.Sc. (I.T.) 2024
code:
import time
import serial
import string
import pynmea2
import RPi.GPIO as gpio
gpio.setmode(gpio.BCM)
port = "/dev/ttyAMA0" # the serial port to which the pi is connected.
if data[0:6] == '$GPGGA':
msg = pynmea2.parse(data)
print msg
time.sleep(2)
T.Y.B.Sc. (I.T.) 2024
The I2c module can be powered with either 5V or 3.3V but the screen works best if it
provided with 5V. However the Pi’s GPIO pins aren’t 5V tolerant so the I2C signals
need to be level shifted. To do this I used an I2C level shifter.
This requires a high level voltage (5V) and a low level voltage (3.3V) which the device
uses as a reference. The HV pins can be connected to the screen and two of the LV pins
to the Pi’s I2C interface.
Level I2C
Shifter Pi Backpack
LV 3.3V –
LV1 SDA –
LV2 SCL –
HV 5V VCC
HV1 SDA
HV2 SCL
While experimenting I found that it worked fine without the level shifting but I couldn’t
be certain this wasn’t going to damage the Pi at some point. So it’s probably best to play
it safe!
The example script will allow you to send text to the screen via I2C. It is very similar to
my scripts for the normal 16×2 screen. To download the script directly to your Pi you
can use :
wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/lcd_i2c.py
In order to use I2C devices you must enable the interface on your Raspberry Pi. This can
be done by following my “Enabling The I2C Interface On The Raspberry Pi” tutorial. By
default the I2C backpack will show up on address 0x27.
Code:
import smbus
import time
LCD_BACKLIGHT = 0x08 # On
#LCD_BACKLIGHT = 0x00 # Off
# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005
def lcd_init():
# Initialise display
lcd_byte(0x33,LCD_CMD) # 110011 Initialise
lcd_byte(0x32,LCD_CMD) # 110010 Initialise
lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction
lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off
lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size
lcd_byte(0x01,LCD_CMD) # 000001 Clear display
time.sleep(E_DELAY)
# High bits
bus.write_byte(I2C_ADDR, bits_high)
lcd_toggle_enable(bits_high)
# Low bits
bus.write_byte(I2C_ADDR, bits_low)
lcd_toggle_enable(bits_low)
T.Y.B.Sc. (I.T.) 2024
def lcd_toggle_enable(bits):
# Toggle enable
time.sleep(E_DELAY)
bus.write_byte(I2C_ADDR, (bits | ENABLE))
time.sleep(E_PULSE)
bus.write_byte(I2C_ADDR,(bits & ~ENABLE))
time.sleep(E_DELAY)
def lcd_string(message,line):
# Send string to display
lcd_byte(line, LCD_CMD)
for i in range(LCD_WIDTH):
lcd_byte(ord(message[i]),LCD_CHR)
def main():
# Main program block
# Initialise display
lcd_init()
while True:
time.sleep(3)
time.sleep(3)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
finally:
lcd_byte(0x01, LCD_CMD)
T.Y.B.Sc. (I.T.) 2024
7
IoT based Web Controlled Home Automation using Raspberry Pi
Code:
try:
while True:
GPIO.output(relay_pin, 0)
sleep(5)
GPIO.output(relay_pin, 1)
sleep(5)
except KeyboardInterrupt:
pass
GPIO.cleanup()
8
Interfacing Raspberry Pi with Pi Camera.
To capture image:
import picamera
from time import sleep
camera.brightness = 60
camera.start_preview()
#add text on image
camera.annotate_text = 'Hi Pi User'
sleep(5)
#store image
camera.capture('image1.jpeg')
camera.stop_preview()
To capture video:
import picamera
from time import sleep
camera = picamera.PiCamera()
camera.resolution = (640, 480)
print()
#start recording using pi camera
camera.start_recording("/home/pi/demo.h264")
#wait for video to record
camera.wait_recording(20)
#stop recording
camera.stop_recording()
camera.close()
print("video recording stopped")
To Play the video:
Omxplayer demo.h264
T.Y.B.Sc. (I.T.) 2024
9
Interfacing Raspberry Pi with RFID.
sudo raspi-config
cd ~
wget http://dl.bintray.com/nfc-tools/sources/libnfc-1.7.1.tar.bz2
tar -xf libnfc-1.7.1.tar.bz2
cd libnfc-1.7.1
./configure --prefix=/usr --sysconfdir=/etc
make
sudo make install
cd /etc
sudo mkdir nfc
sudo nano /etc/nfc/libnfc.conf
allow_intrusive_scan = false
device.name = "_PN532_I2c"
device.connstring = "pn532_i2c:/dev/i2c-1"
6. Wiring
SEL SEL
0 1
H L
Connect the devices:
PN532 Raspberry
5V 5V 4
GND GND 6
SDA SDA0 3
SCL SCL0 5
If yes, it means both the module and the wiring work well.
Then type in nfc-list to check the NFC module:
T.Y.B.Sc. (I.T.) 2024
Run nfc-poll to scan the RFID tag and you can read information on the card:
sudo raspi-config
cd ~
wget http://dl.bintray.com/nfc-tools/sources/libnfc-1.7.1.tar.bz2
tar -xf libnfc-1.7.1.tar.bz2
cd libnfc-1.7.1
./configure --prefix=/usr --sysconfdir=/etc
make
sudo make install
# To set a default device, you must set both name and connstring for your device
# Note: if autoscan is enabled, default device will be the first device available in
device list.
device.name = "_PN532_SPI"
device.connstring = "pn532_spi:/dev/spidev0.0:500000"
#device.name = "_PN532_I2c"
#device.connstring = "pn532_i2c:/dev/i2c-1"
6. Wiring
Toggle the switch to the SPI mode
SEL0 SEL1
L H
Connect the devices:
PN532 Raspberry
5V 5V
GND GND
SCK SCKL
MISO MISO
MOSI MOSI
NSS CE0
7. Run ls /dev/spidev0.* to check whether the SPI is opened or not.
If yes, it means both the module and the wiring work well.
Then type in nfc-list to check the NFC module:
/dev/spidev0.0 /dev/spidev0.1
If two devices are detected, it means the SPI is already opened.
Then type in nfc-list to check the NFC module:
device.connstring = "pn532_spi:/dev/spidev0.0:50000"
Run nfc-poll to scan the RFID tag and you can read information on the card:
Code:
import subprocess
import time
def nfc_raw():
lines=subprocess.check_output("/usr/bin/nfc-poll",
stderr=open('/dev/null','w'))
return lines
def read_nfc():
lines=nfc_raw()
return lines
try:
T.Y.B.Sc. (I.T.) 2024
while True:
myLines=read_nfc()
buffer=[]
for line in myLines.splitlines():
line_content=line.split()
if(not line_content[0] =='UID'):
pass
else:
buffer.append(line_content)
str=buffer[0]
id_str=str[2]+str[3]+str[4]+str[5]
print (id_str)
except KeyboardInterrupt:
pass
cd files
cd pyfingerprint
sudo apt-get -f install
sudo usermod -a -G dialout pi
try:
f = PyFingerprint('/dev/ttyUSB1', 57600, 0XFFFFFFFF, 0X00000000)
except Exception as e:
print('Exception Message :' + str(e))
def enrollFinger():
print ('Enrolling Finger')
time.sleep(3)
print('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))
time.sleep(2)
return
print('Remove finger')
print('Waiting for same finger')
time.sleep(3)
while(f.readImage()==False):
pass
f.convertImage(0X02)
if(f.compareCharacteristics()==0):
print('Fingers do not match')
time.sleep(2)
return
else:
T.Y.B.Sc. (I.T.) 2024
f.createTemplate()
positionNumber=f.storeTemplate()
print('Finger enrolled successfully')
print('Stored at pos: ' +str(positionNumber))
time.sleep(2)
def searchFinger():
try:
print('Waiting for finger...')
time.sleep(2)
while(f.readImage()==False):
time.sleep(4)
return
f.convertImage(0X01)
result = f.searchTemplate()
positionNumber = result[0]
if positionNumber==-1:
print('No Match found')
time.sleep(4)
return False
else:
print('Found template at position ' + str(positionNumber))
time.sleep(4)
return True
except Exception as e:
print('Operation failed')
print('Exception message: ' +str(e))
exit(1)
return
T.Y.B.Sc. (I.T.) 2024
def deleteFinger():
try:
print('Waiting for finger...')
time.sleep(2)
while(f.readImage()==False):
time.sleep(4)
return
f.convertImage(0X01)
result = f.searchTemplate()
positionNumber = result[0]
if positionNumber==-1:
print('No Match found')
time.sleep(4)
return False
else:
if(f.deleteTemplate(positionNumber)==True):
print('Finger Deleted')
time.sleep(4)
return True
except Exception as e:
print('Operation failed')
print('Exception message: ' +str(e))
exit(1)
time.sleep(1)
print('Start')
while True:
i = int (input("\nEnter :\n1.Enroll\n2.Search\n3.Delete\n4.Exit\n"))
T.Y.B.Sc. (I.T.) 2024
if i==1:
enrollFinger()
elif i==2:
searchFinger()
elif i==3:
deleteFinger()
elif i==4:
break
else:
print("Invalid option !!!Enter Correct")
Output:
If any module error after doing these step so do the below steps:
T.Y.B.Sc. (I.T.) 2024
Then write the same above code in Python Thonny IDLE and
save the Program with suitable name with the extension .py
Note : Don’t forget to enable the the SPI and I2c.