100% found this document useful (1 vote)
167 views45 pages

Raspberry Pi-Lab Manual-2-46

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

Raspberry Pi-Lab Manual-2-46

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

Experiment 1: RASPBERRY PI 3 B+ Operating System flashing.

o Processor - SoC type Broadcom BCM2837B0 (ARMv8-A, 32/64-bit),


Quadcore.
o Graphic Processor Unit (GPU) - Broadcom Video Core IV 1080p60
o CPU unit - ARM Cortex-A53 Quad core 1.4 GHz
o RAM - 1 GB
o 4 x USB 2.0 ports
o 40 pin extended GPIO (General Purpose Input/Output)
o 4 pole Stereo output and Composite video port
o Full size HDMI output

INSTALLING RASPBIAN OS FOR RASPBERRY PI 3 B+ PROCEDURES:


https://www.raspberrypi.org/software/

2
Click on start and search Raspberry pi imager
• Select operating system as raspberry pi os (32Bit)
• Select SD CARD and click on WRITE
• Insert SD card in pi and update the raspberry pi.
• After write finished remove SD card.
• Change the following
• When you start your Raspberry Pi for the first time, the Welcome to
Raspberry Pi application will pop up and guide you through the initial setup.
Click Next to start the setup.

Language: English, Country and Time Zone: India and Kolkata

Enter a new password for your Raspberry Pi and click next. In this step, you need to plug a

keyboard into the Raspberry Pi to help you input the new password.
Connect to your WiFi network by selecting its name, entering the
password, and clicking next.
Click Next let the wizard check for updates to Raspbian and install them (this might
take a little while).

3
• From menu-->Preferences-->Raspberry Pi 4 B+ Configuration. Then Go To
Interfaces
• Enable Camera, SSH, VNC, SPI, I2C, Serial Port. Do not Enable Remaining Things.
• Connect to Wi-Fi. > Check the date and Time.
• Open the Terminal. > Execute following default commands.
• sudo apt-get update > sudo apt-get up grade
• Now you can write your programs at Thonny Python IDE. Menu→ Programming
• →Thonny Python IDE.
• File → New ….. You can write your Program here and save.
• Execute the program at terminal only by following command sudo python <program-
name>.py
PI PROGRAMMING:
Start Thonny by clicking on the Raspberry Pi icon followed by Programming >
Thonny Python IDE

Save program by .py extension on desktop


> click on terminal as shown in above picture
> cd Desktop/ cd code/ # we store code on desktop as code
> python filename.py. # to execute program

4
Sensor Description
1. Soil Moisture Sensor

The dielectric constant of soil increases as the water content of the soil increases.
The sensor is designed to estimate soil volumetric water content based on the
dielectric constant of the soil. The dielectric constant can be thought of as the soil's
ability to transmit electricity. The dielectric constant of soil increases as the water
content of the soil increases. This response is due to the fact that the dielectric
constant of water is much larger than the other soil components, including air.
Thus, measurement of the dielectric constant gives a predictable estimation of
water content.

Soil moisture

Specification:

• Input Voltage 3.3 – 5V.


• Output Voltage 0 – 4.2V.
• Input Current 35mA.
• Output signal both analog and digital.
Light Sensor
A Light Sensor generates an output signal indicating the intensity of light by measuring
the radiant energy that exists in a very narrow range of frequencies basically called “light”,
and which ranges in frequency from “Infrared” to “Visible” up to “Ultraviolet” light
spectrum.

The light sensor converts this “light energy” whether visible or in the infrared parts of the
spectrum into an electrical signal output. From “Infrared” to “Visible” up to “Ultraviolet”
light spectrum. Sensitivity can be adjusted through potentiometer.

5
Light sensor
Specificatio
n:
• Using photosensitive resistance sensor sensitive type.
• Working Voltage: 3.3V-5V.
• Output form: Digital Switch shows (0 for Brightness and 1 for darkness).
• Fixed Bolt Hole, easy installation.

Temperature and Humidity Sensor:


The DHT11 is a digital temperature and humidity sensor. It uses a humidity sensor
and a thermistor to measure the surrounding air, and spits out a digital signal on the
data pin. It is simple to use, but requires careful timing to grab data. You can only get
new data from it once every 2 seconds, so when using our library, sensor readings

can be up to 2 seconds old.


DHT11

Specification:
• Operating Voltage: 3.5V to 5.5V.
• Operating current: 0.3mA (measuring) 60uA (standby) Output: Serial data.
• Temperature Range: 0°C to 50°C. Humidity Range: 20% to 90%
• Resolution: Temperature and Humidity both are 16-bit. Accuracy: ±1°C and ±1%
Ultrasonic Distance Sensor:
An ultrasonic sensor is to measures the distance of an object using ultrasonic sound
waves. An ultrasonic sensor uses a transducer to send and receive ultrasonic pulses
that relay back information about an object’s proximity. High-frequency sound waves
reflect from boundaries to produce distinct echo patterns.

6
Ultrasonic sonic sensor
Specification:
• Working Voltage: DC 5V.
• Working Current: 15mA.
• Working Frequency: 40Hz.
• Max Range: 4m.
• Min Range: 2cm.
• Measuring Angle: 15 degree.
• Trigger Input Signal: 10µS TTL pulse.
• Echo Output Signal Input TTL level signal and the range in proportion.

RCWL-0516:
RCWL-0516 is a Doppler radar microwave motion sensor that can act as an alternative
to a PIR motion sensor. This get repository is an attempt to collect the rather scant
information on this board in one place.

Specification:
• Equipped with RCWL-9196 chip supporting 4-28V wide voltage input, high
level signal output when detecting the motion with active repeat trigger

7
• 360 degree no blind angle detection with 5-7m detecting distance, the
detection not affected by the surroundings, better performance than the IR
sensor
• Support night detecting function turn on /off, adjustable repeat trigger time and
detecting distance by add the SMD components to the corresponding pins
• Working Voltage: DC 4-28V, Board Size: 35.9 X 17.3mm/1.41 X 0.68inch

GAS Sensor
Gas Sensors (MQ2) are useful to detect the gas leakage (home and industry). It is
suitable for detecting the Smoke, CO, H2, LPG, CH4 and Alcohol. Due to fast response
time and its high sensitivity, measurement can be taken as soon as possible.
Potentiometer is used to adjust the sensitivity of the sensor.

Gas Sensor
Specification:
• Operating Voltage is +5V.
• Can be used to Measure or detect LPG, Alcohol, Propane, Hydrogen, CO
and even methane.
• Analog output voltage: 0V to 5V.
• Digital Output Voltage: 0V or 5V (TTL Logic).
• Preheat duration 20 seconds.
• Can be used as a Digital or analog sensor.
• The Sensitivity of Digital pin can be varied using the potentiometer
Analog to Digital converter:
The MCP3008 is a low cost 8-channel 10-bit analog to digital converter. The precision
of this ADC is similar to that of an Arduino Uno, and with 8 channels you can read
quite a few analog signals from the Pi. This chip is a great option if you just
need to read
simple analog signals, like from a temperature or light sensor.

8
Light Emitting Diode:
LEDs (Light Emitting Diodes) are semiconductor light sources that combine a P-type
semiconductor (larger hole concentration) with an N-type semiconductor (larger
electron concentration). Applying a sufficient forward voltage will cause the electrons
and holes to recombine at the P-N junction, releasing energy in the form of light.

9
Switches:
Switching happens reliably at specific and repeatable positions of the actuator, which
is not necessarily true of other mechanisms. They are very common due to their low
cost but high durability, greater than 1 million cycles and up to 10 million cycles for
heavy-duty models. This durability is a natural consequence of the design.

4x4 keypad:

10
TESTING of LDR SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Light Dependent Resistors (LDR) with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C1 to C13

Click on pi icon select programming Thonny

Write code as per requirement and save it with .py extension example ldr.py on

desktop. And then Run program output will display on Shell as shown below

11
CODE
#CONNECT C1 TO C14 WITH 4 PIN FEMALE CONNECTOR AND RUN
PROGRAM
import RPi.GPIO as GPIO
import time

light = 37 #Board number

def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(light,GPIO.IN)

def read_light():
while True:

12
def destroy(): #When program ending, the function is executed.
GPIO.cleanup()

if name == ' main ': #Program starting from here


try:
setup()

read_light()

except KeyboardInterrupt:

destroy() light_state = GPIO.input(light)

if light_state == 0:

print("Light Detected")

elif light_state == 1:

print("Light Not Detected")

time.sleep(.3)

def destroy(): #When program ending, the function is executed.


GPIO.cleanup()

if name == ' main ': #Program starting from here


try:
setup()
read_light()
except KeyboardInterrupt:
destroy()

13
TESTING of DHT11 SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Digital Humidity and Temperature (DHT) with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C12 to C7

Click on pi icon select programming Thonny

Write code as per requirement and save it with .py extension example dht11.py on

desktop. And then Run program output will display on Shell as shown below

14
CODE
#Before executing this program intsall Adafruit_DHT11 Library using follwing

command #sudo apt-get install Adafruit_DHT11

#connect rmc from c12 to

c7 import time

import Adafruit_DHT

#Set the type of sensor and the pin for

sensor sensor = Adafruit_DHT.DHT11

pin = 4 # gpio 4 board pin 7

while(1):

15
try:

humidity, temperature = Adafruit_DHT.read_retry(sensor,

pin) print ("Humidity ="+str(humidity))

print ("Temperature

="+str(temperature)) except ValueError:

print ("Unable to read data")

Note if unable to find bcm try with beagle bone then go for

Go to file > USR > LOCAL > LIB > 3.9 > distpackages > Adafruit_DHT > Platform_detect.py >

Right click on Adafruit_DHT open in terminal > ls > platfoem_detect.py is available

Type sudo nano platform_detech.py and add bcm2711 like below > ctrl+x to save & exit.

16
TESTING of SOILMOISTURE SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Soil Moisture with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C11 to C8

Click on pi icon select programming Thonny

Write code as per requirement and save it with .py extension example dht11.py on

desktop. And then Run program output will display on Shell as shown below

17
CODE
import RPi.GPIO as

GPIO import time

soil = 13 #Board number

relay = 12

def setup(): GPIO.setmode(GPIO.BOARD)

GPIO.setup(soil,GPIO.IN)

GPIO.setup(relay,GPIO.OUT)

def read_soil():
while True:

soil_state = GPIO.input(soil)

if soil_state == 0:
18
print("soil Moisture Not

Detected") print("Relay on")

GPIO.output(relay,True)

elif soil_state == 1:

print("Soil Moisture

Detected") print("Relay off")

GPIO.output(relay,False)

time.sleep(.3)

def destroy(): #When program ending, the function is executed.

GPIO.cleanup()

if name == ' main ': #Program starting from

here try:

setup()

read_soil()

except

KeyboardInterrupt:

destroy()

19
TESTING of RCWL MOTION DETECHTOR SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Motion Detecting sensor (RCWL) with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C16 to C9

20
CODE
import RPi.GPIO as GPIO

import time

rcwl = 11 #Board

number def setup():

GPIO.setmode(GPIO.BOARD)

GPIO.setup(rcwl,GPIO.

IN) def read_rcwl():

while True:

21
rcwl_state = GPIO.input(rcwl) if rcwl_state == 0:

print("motion not Detected") elif rcwl_state ==1:

print("motion Detected")

time.sleep(.3)

def destroy(): #When program ending, the function is executed.

GPIO.cleanup()

if name == ' main ': #Program starting from here try:

setup()

read_rcwl()

except

KeyboardInterrupt: destroy()

22
TESTING of ULTRASONIC SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Ultrasonic sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C15 to C10

23
CODE
# Program to test Ultrasonic Distance

Sensor # Connect from c15 to c10

import RPi.GPIO as GPIO #Import GPIO library import time #Import time library

GPIO.setmode(GPIO.BCM) #Set GPIO pin numbering

TRIG = 19 #Associate pin 35 to TRIG

ECHO = 13 #Associate pin 33 to ECHO

print ("Distance measurement in progress")

GPIO.setup(TRIG,GPIO.OUT) #Set pin as GPIO out

GPIO.setup(ECHO,GPIO.IN)

24
while True:

GPIO.output(TRIG, False) #Set TRIG as LOW print ("Waitng For Sensor To Settle")

time.sleep(2) #Delay of 2 seconds

GPIO.output(TRIG, True) #Set TRIG as HIGH

time.sleep(0.00001) #Delay of 0.00001

seconds GPIO.output(TRIG, False) #Set

TRIG as LOW

while GPIO.input(ECHO)==0: #Check whether the ECHO is LOW

pulse_start = time.time() #Saves the last known time of LOW pulse

while GPIO.input(ECHO)==1: #Check whether the ECHO is HIGH

pulse_end = time.time() #Saves the last known time of HIGH pulse

pulse_duration = pulse_end - pulse_start #Get pulse duration to a variable

distance = pulse_duration * 17150 #Multiply pulse duration by 17150 to get

distance distance = round(distance, 2) #Round to two decimal points

if distance > 2 and distance < 400: #Check whether the distance is

within range print ("Distance:",distance - 0.5,"cm")

else:

print ("Out Of Range") #display out of range

output can be seen in shell as distance.

25
TESTING of MQ2 GAS SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Gas Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C14 to C8

26
CODE
import RPi.GPIO as

GPIO import time

gas = 13 #Board number

relay = 12

def setup(): GPIO.setmode(GPIO.BOARD)

GPIO.setup(gas,GPIO.IN)

GPIO.setup(relay,GPIO.OUT)

27
def

read_gas():

while True: gas_state = GPIO.input(gas)

if gas_state == 0:

print("GAS Detected")

print("Relay on")

GPIO.output(relay,True)

elif gas_state == 1:

print("GAS NOT Detected")

print("Relay off")

GPIO.output(relay,False)

time.sleep(.3)

def destroy(): #When program ending, the function is executed.

GPIO.cleanup()

if name == ' main ': #Program starting from

here try:

setup()

read_gas

()

except

KeyboardInterrupt:

destroy()

28
TESTING of RELAY SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Relay Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C2 to C28

29
CODES:
import time
import RPi.GPIO as gpio

gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
gpio.setup(36, gpio.OUT)

try:
while(1):
gpio.output(36,0)
print("Relay OFF")
time.sleep(1)
gpio.output(36,1)
print("Relay ON")
time.sleep(1)
#gpio.cleanup()
except KeyboardInterrupt:
gpio.cleanup()
exit

30
TESTING of BUZZER SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Buzzer Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C2 to C27

31
CODES:
import time
import RPi.GPIO as gpio
gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
gpio.setup(36, gpio.OUT)
try:
while(1):
gpio.output(36,0)
print("Buzzer OFF")
time.sleep(1)
gpio.output(36,1)
print("Buzzer ON")
time.sleep(1)
#gpio.cleanup()
except KeyboardInterrupt:
gpio.cleanup()
exit

32
TESTING of IR SENSOR WITH RASPBERRY
PI CIRCUIT DIAGRAM
AIM: To Interface IR Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C8 to C22

33
CODES:
import RPi.GPIO as GPIO
import time
sensor1 = 11
sensor2 = 13
#sensor3 = 13
#sensor4 = 15
buzzer = 40

GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor1,GPIO.IN)
GPIO.setup(sensor2,GPIO.IN)
#GPIO.setup(sensor3,GPIO.IN)
#GPIO.setup(sensor4,GPIO.IN)
GPIO.setup(buzzer,GPIO.OUT)

GPIO.output(buzzer,False)
print "IR Sensor Ready .... "
print " "
try:
while True:
if GPIO.input(sensor1):
GPIO.output(buzzer,True)
print "Object Detected-1"

while GPIO.input(sensor1):
time.sleep(0.3)
else: GPIO.output(buzzer,False)

if GPIO.input(sensor2):
GPIO.output(buzzer,True)
print "Object Detected-2"

while GPIO.input(sensor2):
time.sleep(0.3)
else: GPIO.output(buzzer,False)

except KeyboardInterrupt:
GPIO.cleanup()

34
TESTING of LCD SENSOR WITH
RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface LCD Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C9 to C31 and C10 to C 29

35
CODES:.

# Connect from CN9 to CN31 and c10 to c29


import RPi.GPIO as GPIO
import time
LCD_RS = 35
LCD_E = 33
LCD_D4 = 23
LCD_D5 = 21
LCD_D6 = 19
LCD_D7 = 24

# Define some device constants


LCD_WIDTH = 16 # Maximum characters per line
LCD_CHR = True
LCD_CMD = False

LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line


LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line

# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005

def main():
# Main program block
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) # Use BCM GPIO numbers
GPIO.setup(LCD_E, GPIO.OUT) # E
GPIO.setup(LCD_RS, GPIO.OUT) # RS
GPIO.setup(LCD_D4, GPIO.OUT) # DB4
GPIO.setup(LCD_D5, GPIO.OUT) # DB5
GPIO.setup(LCD_D6, GPIO.OUT) # DB6
GPIO.setup(LCD_D7, GPIO.OUT) # DB7
# Initialise display
lcd_init()

while True:

# Send some test


lcd_string("Rasbperry Pi",LCD_LINE_1)
lcd_string("16x2 LCD Test",LCD_LINE_2)
time.sleep(3) # 3 second delay

36
# Send some text
lcd_string("1234567890123456",LCD_LINE_1)
lcd_string("abcdefghijklmnop",LCD_LINE_2)

time.sleep(3) # 3 second delay


# Send some text
lcd_string("RaspberryPi-spy",LCD_LINE_1)
lcd_string(".co.uk",LCD_LINE_2)
time.sleep(3)
# Send some text
lcd_string("Follow me on",LCD_LINE_1)
lcd_string("Twitter @RPiSpy",LCD_LINE_2)
time.sleep(3)

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)

def lcd_byte(bits, mode):


# Send byte to data pins
# bits = data
# mode = True for character
# False for command

GPIO.output(LCD_RS, mode) # RS

# High bits
GPIO.output(LCD_D4, False)
GPIO.output(LCD_D5, False)
GPIO.output(LCD_D6, False)
GPIO.output(LCD_D7, False)
if bits&0x10==0x10:
GPIO.output(LCD_D4, True)
if bits&0x20==0x20:
GPIO.output(LCD_D5, True)
if bits&0x40==0x40:
GPIO.output(LCD_D6, True)
if bits&0x80==0x80:
GPIO.output(LCD_D7, True)
37
# Toggle 'Enable' pin
lcd_toggle_enable()

# Low bits
GPIO.output(LCD_D4, False)
GPIO.output(LCD_D5, False)
GPIO.output(LCD_D6, False)
GPIO.output(LCD_D7, False)
if bits&0x01==0x01:
GPIO.output(LCD_D4, True)
if bits&0x02==0x02:
GPIO.output(LCD_D5, True)
if bits&0x04==0x04:
GPIO.output(LCD_D6, True)
if bits&0x08==0x08:
GPIO.output(LCD_D7, True)

# Toggle 'Enable' pin


lcd_toggle_enable()

def lcd_toggle_enable():
# Toggle enable
time.sleep(E_DELAY)
GPIO.output(LCD_E, True)
time.sleep(E_PULSE)
GPIO.output(LCD_E, False)
time.sleep(E_DELAY)

def lcd_string(message,line):
# Send string to display

message = message.ljust(LCD_WIDTH," ")

lcd_byte(line, LCD_CMD)
for i in range(LCD_WIDTH):
lcd_byte(ord(message[i]),LCD_CHR)
if name == ' main ':
try:
main()
except KeyboardInterrupt:
pass
finally:
lcd_byte(0x01, LCD_CMD)
lcd_string("Goodbye!",LCD_LINE_1)
38
GPIO.cleanup()

TESTING of LED & SWITCH SENSOR WITH


RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface LED & Switch Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C4 to C24 and C9 to C 25

39
CODES:

# Program to test LED and Switches


# Connect CN9 to CN4
# Dont forget to short the jumper pins
import time
import RPi.GPIO as gpio

gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)

led4 = 23 # pin is connected to LED and it should be OUT


led3 = 21 # pin is connected to LED and it should be OUT
led2 = 19 # pin is connected to LED and it should be OUT
led1 = 24 # pin is connected to LED and it should be OUT
switch4 = 22 # pin is connected to SWITC and it should be IN
switch3 = 18 # pin is connected to SWITC and it should be IN
switch2 = 16 # pin is connected to SWITC and it should be IN
switch1= 12 # pin is connected to SWITC and it should be IN

gpio.setup(led1,gpio.OUT,initial=0)
gpio.setup(led2,gpio.OUT,initial=0)
gpio.setup(led3,gpio.OUT,initial=0)
gpio.setup(led4,gpio.OUT,initial=0)
gpio.setup(switch1,gpio.IN)
gpio.setup(switch2,gpio.IN)
gpio.setup(switch3,gpio.IN)
gpio.setup(switch4,gpio.IN)

def glow_led(event):
if event == switch1 :
gpio.output(led1, True)
time.sleep(0.2)
gpio.output(led1, False)

40
elif event == switch2 :
gpio.output(led2, True)
time.sleep(0.2)
gpio.output(led2, False)

elif event == switch3 :


gpio.output(led3, True)
time.sleep(0.2)
gpio.output(led3, False)

elif event == switch4 :


gpio.output(led4, True)
time.sleep(0.2)
gpio.output(led4, False)

gpio.add_event_detect(switch1, gpio.RISING , callback = glow_led, bouncetime = 1)


gpio.add_event_detect(switch2, gpio.RISING , callback = glow_led, bouncetime = 1)
gpio.add_event_detect(switch3, gpio.RISING , callback = glow_led, bouncetime = 1)
gpio.add_event_detect(switch4, gpio.RISING , callback = glow_led, bouncetime = 1)

try:
while(True):
#to avoid 100% CPU usage
time.sleep(1)
except KeyboardInterrupt:
#cleanup GPIO settings before exiting
gpio.cleanup()

41
TESTING of KEYPAD MATRIX SENSOR
WITH RASPBERRY PI CIRCUIT DIAGRAM
AIM: To Interface Keypad Matrix Sensor with Raspberry Pi.

Connect as per picture below on PHYSITECH trainer C2 to C22 and C3 to C23

42
Codes:
# Connect CN9 to CN5
#sudo apt-get install pad4pi
import RPi.GPIO as GPIO
import time
from pad4pi import rpi_gpio
KEYPAD = [
["1","2","3","A"],
["4","5","6","B"],
["7","8","9","C"],
["*","0","#","D"],
]
ROW_PINS =[21,20,16,12] # pin num 40,38,36,32
COL_PINS =[7,8,25,24] # pin num 26,24,22,18
factory = rpi_gpio.KeypadFactory()
keypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS,
col_pins=COL_PINS)
def printKey(key):
print(key)
time.sleep(0.2)
keypad.registerKeyPressHandler(printKey)

def destroy(): #When program ending, the function is executed.


GPIO.cleanup()
if name == ' main ': #Program starting from here
try:
while True:
time.sleep(0.5)
except KeyboardInterrupt:
destroy()
except :
keypad.cleanup()

43
TESTING of ANALOG to DIDGTAL SENSOR WITH RASPBERRY
AIM: To Interface MCP3008 & Potentiometer with Raspberry Pi.

CIRCUIT DIAGRAM:

Connect as per picture below on PHYSITECH trainer C18 to POT OUT and C20 to C9

44
CODE:

import busio
import digitalio
import board
import time
import adafruit_mcp3xxx.mcp3008 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn

led = digitalio.DigitalInOut(board.D25) # board pin 22


led.direction = digitalio.Direction.OUTPUT
led1= digitalio.DigitalInOut(board.D24) # board pin 18
led1.direction = digitalio.Direction.OUTPUT
led2 = digitalio.DigitalInOut(board.D23) # board pin 16
led2.direction = digitalio.Direction.OUTPUT
led3 = digitalio.DigitalInOut(board.D18) # board pin 12
led3.direction = digitalio.Direction.OUTPUT

# create the spi bus


spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

# create the cs (chip select)


cs = digitalio.DigitalInOut(board.CE0)

# create the mcp object


mcp = MCP.MCP3008(spi, cs)

# create an analog input channel on pin 0


value1 = AnalogIn(mcp, MCP.P0)

while True:
value1 = AnalogIn(mcp, MCP.P0)
#print('Raw ADC Value: ', chan.value)
print('ADC Voltage: ' + str(value1.voltage) + 'V')
time.sleep(0.5)
if(value1.voltage<.5):
print('EMPTY')
led.value = False
led1.value = False
led2.value = False
led3.value = False
if(value1.voltage>0.5) & (value1.voltage<1):
print('LOW')
led.value = True
45
led1.value = False
led2.value = False
led3.value = False
if(value1.voltage>1) & (value1.voltage<2):
print('MEDIUM')
led.value = True
led1.value = True
led2.value = False
led3.value = False
if(value1.voltage>2) & (value1.voltage<3):
print('HIGH')
led.value = True
led1.value = True
led2.value = True
led3.value = False
if(value1.voltage>3):
print('FULL')
led.value = True
led1.value = True
led2.value = True
led3.value = True

Output will appear on shell vary potentiometer to observe variation of input signal.

46

You might also like