0% found this document useful (0 votes)
95 views25 pages

Iot 2019

The document contains code to interface a Raspberry Pi with various hardware components including LEDs, RFID reader, camera, GPS module, and fingerprint module. For each hardware component, it provides code snippets to initialize the component, read/write data, and display output. For example, with the fingerprint module, it includes code to enroll a fingerprint template, search for a fingerprint, and delete a fingerprint template. The code utilizes various Python libraries like RPi.GPIO, picamera, and pyfingerprint.

Uploaded by

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

Iot 2019

The document contains code to interface a Raspberry Pi with various hardware components including LEDs, RFID reader, camera, GPS module, and fingerprint module. For each hardware component, it provides code snippets to initialize the component, read/write data, and display output. For example, with the fingerprint module, it includes code to enroll a fingerprint template, search for a fingerprint, and delete a fingerprint template. The code utilizes various Python libraries like RPi.GPIO, picamera, and pyfingerprint.

Uploaded by

Raviraj kundekar
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/ 25

# SLIP 1: Q1) - Interface Raspberry Pi with 4 LEDS and blink in LEDS with 4 different patterns.

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

# init list with pin numbers

pinList = [5, 6, 13, 19, 26]

# loop through pins and set mode and state to 'high'

for i in pinList:

GPIO.setup(i, GPIO.OUT)

GPIO.output(i, GPIO.LOW)

# time to sleep between operations in the main

SleepTimeL = 2

# main loop

try:

GPIO.output(5, GPIO.HIGH)

print ("ONE")

time.sleep(SleepTimeL);

GPIO.output(6, GPIO.HIGH)

print ("TWO")

time.sleep(SleepTimeL);

GPIO.output(13, GPIO.HIGH)

print ("THREE")

time.sleep(SleepTimeL);

GPIO.output(19, GPIO.HIGH)

print ("FOUR")

time.sleep(SleepTimeL);

GPIO.output(26, GPIO.HIGH)

print ("FIVE")

time.sleep(SleepTimeL);
GPIO.cleanup()

print ("Good bye!")

# End program cleanly with keyboard

except KeyboardInterrupt:

print ("Quit")

# Reset GPIO settings

#SLIP 1: Q2) - Interface Raspberry Pi with RFID and write a program to read the RFID.

import time

import serial #import serial module

def read_rfid ():

ser = serial.Serial ("/dev/ttyUSB0") #Open named port

ser.baudrate = 9600 #Set baud rate to 9600

data = ser.read(12) #Read 12 characters from serial port to data

ser.close () #Close port

return data #Return data

try:

while True:

id = read_rfid () #Function call

print (id) #Print RFID

if id=="400034E165F0": #replace the ID number with your ID number

print("Acces Granted")

else:

print("Access Denied")

finally:

print("Bye")

#SLIP 2 : Q1) Interface Raspberry Pi with Pi Camera and write a program to capture image and video.
Save the image and video and then display image and play video.

#Image
import picamera

from time import sleep

#create object for PiCamera class

camera = picamera.PiCamera()

#set resolution

camera.resolution = (1024, 768)

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()

#$ sudo raspistill /home/pi/Desktop/image.jpg (to capture a picture; raspistill loads the image

#Video

import picamera

from time import sleep

camera = picamera.PiCamera()

camera.resolution = (640, 480)

print()

#start recording using pi camera

camera.start_recording("demo.h264")

#wait for video to record

camera.wait_recording(20)

#stop recording

camera.stop_recording()

camera.close()

print("video recording stopped")


#Q2.Interface Raspberry Pi with GPS module and write a program to display current location
(Latitude and Longitude).

Run this command: $ sudo ls /dev/ttyUSB*

$ sudo cat /dev/ttyUSB*

#SLIP 3 - Q1)-Interface Raspberry Pi with RFID and write a program to read the RFID

import time

import serial #import serial module

def read_rfid ():

ser = serial.Serial ("/dev/ttyUSB0") #Open named port "(To check the port, ls
/dev/ttyUSB*)"

ser.baudrate = 9600 #Set baud rate to 9600

data = ser.read(12) #Read 12 characters from serial port to data

ser.close () #Close port

return data #Return data

try:

while True:

id = read_rfid () #Function call

print (id) #Print RFID

if id=="400034E165F0": #replace the ID number with your ID number

print("Acces Granted")

else:

print("Access Denied")

finally:

print("Bye")

#Q2). Interface Raspberry Pi with Pi Camera and write a program to capture image and video. Save
the image and video and then display image and play video
#Image

import picamera

from time import sleep

#create object for PiCamera class

camera = picamera.PiCamera()

#set resolution

camera.resolution = (1024, 768)

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()

#$ sudo raspistill /home/pi/Desktop/image.jpg (to capture a picture; raspistill loads the image

#Video

import picamera

from time import sleep

camera = picamera.PiCamera()

camera.resolution = (640, 480)

print()

#start recording using pi camera

camera.start_recording("demo.h264")

#wait for video to record

camera.wait_recording(20)

#stop recording

camera.stop_recording()
camera.close()

print("video recording stopped")

#SLIP 5 - Interface Raspberry Pi with Fingerprint Module and write a program to capture and verify
finger print.

1) sudo bash

2 Then download some required packages by using given commands:

wget –O – http://apt.pm-codeworks.de/pm-codeworks.de.gpg | apt-key add –

wget http://apt.pm-codeworks.de/pm-codeworks.list -P /etc/apt/sources.list.d/

3) sudo apt-get update

sudo apt-get install python-fingerprint

4) ls /dev/ttyUSB*

mport 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()

#SLIP 6- Q1) Install Windows IoT Core on Raspberry Pi and using GPIO blink LED using sample
program.

"""Step 1 : Format the sd card

Step 2 : Download the IOt dashboard win 10 and then run the install and open dashboard and then
setup new device

Step 3 : Connect your Iot device and then click next next and DONE"""

GPIO BLINK CODE :

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

# init list with pin numbers

pinList = [5, 6, 13, 19, 26]

# loop through pins and set mode and state to 'high'

for i in pinList:

GPIO.setup(i, GPIO.OUT)

GPIO.output(i, GPIO.LOW)

# time to sleep between operations in the main


SleepTimeL = 2

# main loop

try:

GPIO.output(5, GPIO.HIGH)

print ("ONE")

time.sleep(SleepTimeL);

GPIO.output(6, GPIO.HIGH)

print ("TWO")

time.sleep(SleepTimeL);

GPIO.output(13, GPIO.HIGH)

print ("THREE")

time.sleep(SleepTimeL);

GPIO.output(19, GPIO.HIGH)

print ("FOUR")

time.sleep(SleepTimeL);

GPIO.output(26, GPIO.HIGH)

print ("FIVE")

time.sleep(SleepTimeL);

GPIO.cleanup()

print ("Good bye!")

# End program cleanly with keyboard

except KeyboardInterrupt:

print ("Quit")

# Reset GPIO settings

#Q2)Interface Raspberry Pi with 4-digit Seven Segment module and write a program to display
current time on it.

rom time import sleep

import tm1637
try:

import thread

except ImportError:

import _thread as thread

# Initialize the clock (GND, VCC=3.3V, Example Pins are DIO-20 and CLK21)

Display = tm1637.TM1637(CLK=21, DIO=20, brightness=1.0)

try:

print ("Starting clock in the background (press CTRL + C to stop:")

Display.StartClock(military_time=False)

print ('Continue Python script and tweak Display!')

sleep(5)

Display.ShowDoublepoint(False)

sleep(5)

loops = 3

while loops > 0:

for i in range(0, 10):

Display.SetBrightness(i / 10.0)

sleep(0.5)

loops -= 1

Display.StopClock()

thread.interrupt_main()

except KeyboardInterrupt:

print ("Properly closing the clock and open GPIO pins")

Display.cleanup()

"ALTERNATIVE"

import math
import RPi.GPIO as IO

import threading

from time import sleep, localtime

# from tqdm import tqdm

# IO.setwarnings(False)

IO.setmode(IO.BCM)

HexDigits = [0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d,

0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71]

ADDR_AUTO = 0x40

ADDR_FIXED = 0x44

STARTADDR = 0xC0

# DEBUG = False

class TM1637:

__doublePoint = False

__Clkpin = 0

__Datapin = 0

__brightness = 1.0 # default to max brightness

__currentData = [0, 0, 0, 0]

def __init__(self, CLK, DIO, brightness):

self.__Clkpin = CLK

self.__Datapin = DIO

self.__brightness = brightness

IO.setup(self.__Clkpin, IO.OUT)

IO.setup(self.__Datapin, IO.OUT)
def cleanup(self):

"""Stop updating clock, turn off display, and cleanup GPIO"""

self.StopClock()

self.Clear()

IO.cleanup()

def Clear(self):

b = self.__brightness

point = self.__doublePoint

self.__brightness = 0

self.__doublePoint = False

data = [0x7F, 0x7F, 0x7F, 0x7F]

self.Show(data)

# Restore previous settings:

self.__brightness = b

self.__doublePoint = point

def ShowInt(self, i):

s = str(i)

self.Clear()

for i in range(0, len(s)):

self.Show1(i, int(s[i]))

def Show(self, data):

for i in range(0, 4):

self.__currentData[i] = data[i]

self.start()

self.writeByte(ADDR_AUTO)

self.br()

self.writeByte(STARTADDR)
for i in range(0, 4):

self.writeByte(self.coding(data[i]))

self.br()

self.writeByte(0x88 + int(self.__brightness))

self.stop()

def Show1(self, DigitNumber, data):

"""show one Digit (number 0...3)"""

if(DigitNumber < 0 or DigitNumber > 3):

return # error

self.__currentData[DigitNumber] = data

self.start()

self.writeByte(ADDR_FIXED)

self.br()

self.writeByte(STARTADDR | DigitNumber)

self.writeByte(self.coding(data))

self.br()

self.writeByte(0x88 + int(self.__brightness))

self.stop()

def SetBrightness(self, percent):

"""Accepts percent brightness from 0 - 1"""

max_brightness = 7.0

brightness = math.ceil(max_brightness * percent)

if (brightness < 0):

brightness = 0

if(self.__brightness != brightness):

self.__brightness = brightness

self.Show(self.__currentData)
def ShowDoublepoint(self, on):

"""Show or hide double point divider"""

if(self.__doublePoint != on):

self.__doublePoint = on

self.Show(self.__currentData)

def writeByte(self, data):

for i in range(0, 8):

IO.output(self.__Clkpin, IO.LOW)

if(data & 0x01):

IO.output(self.__Datapin, IO.HIGH)

else:

IO.output(self.__Datapin, IO.LOW)

data = data >> 1

IO.output(self.__Clkpin, IO.HIGH)

# wait for ACK

IO.output(self.__Clkpin, IO.LOW)

IO.output(self.__Datapin, IO.HIGH)

IO.output(self.__Clkpin, IO.HIGH)

IO.setup(self.__Datapin, IO.IN)

while(IO.input(self.__Datapin)):

sleep(0.001)

if(IO.input(self.__Datapin)):

IO.setup(self.__Datapin, IO.OUT)

IO.output(self.__Datapin, IO.LOW)

IO.setup(self.__Datapin, IO.IN)

IO.setup(self.__Datapin, IO.OUT)
def start(self):

"""send start signal to TM1637"""

IO.output(self.__Clkpin, IO.HIGH)

IO.output(self.__Datapin, IO.HIGH)

IO.output(self.__Datapin, IO.LOW)

IO.output(self.__Clkpin, IO.LOW)

def stop(self):

IO.output(self.__Clkpin, IO.LOW)

IO.output(self.__Datapin, IO.LOW)

IO.output(self.__Clkpin, IO.HIGH)

IO.output(self.__Datapin, IO.HIGH)

def br(self):

"""terse break"""

self.stop()

self.start()

def coding(self, data):

if(self.__doublePoint):

pointData = 0x80

else:

pointData = 0

if(data == 0x7F):

data = 0

else:

data = HexDigits[data] + pointData

return data

def clock(self, military_time):


"""Clock script modified from:

https://github.com/johnlr/raspberrypi-tm1637"""

self.ShowDoublepoint(True)

while (not self.__stop_event.is_set()):

t = localtime()

hour = t.tm_hour

if not military_time:

hour = 12 if (t.tm_hour % 12) == 0 else t.tm_hour % 12

d0 = hour // 10 if hour // 10 else 0

d1 = hour % 10

d2 = t.tm_min // 10

d3 = t.tm_min % 10

digits = [d0, d1, d2, d3]

self.Show(digits)

# # Optional visual feedback of running alarm:

# print digits

# for i in tqdm(range(60 - t.tm_sec)):

for i in range(60 - t.tm_sec):

if (not self.__stop_event.is_set()):

sleep(1)

def StartClock(self, military_time=True):

# Stop event based on: http://stackoverflow.com/a/6524542/3219667

self.__stop_event = threading.Event()

self.__clock_thread = threading.Thread(

target=self.clock, args=(military_time,))

self.__clock_thread.start()

def StopClock(self):

try:

print ('Attempting to stop live clock')


self.__stop_event.set()

except:

print ('No clock to close')

if __name__ == "__main__":

"""Confirm the display operation"""

display = TM1637(CLK=21, DIO=20, brightness=1.0)

display.Clear()

digits = [1, 2, 3, 4]

display.Show(digits)

print ("1234 - Working? Press Key")

scrap = raw_input()

print ("Updating one digit at a time:")

display.Clear()

display.Show1(1, 3)

sleep(0.5)

display.Show1(2, 2)

sleep(0.5)

display.Show1(3, 1)

sleep(0.5)

display.Show1(0, 4)

print ("4321 - (Press Key)")

scrap = raw_input()

print ("Add double point\n")

display.ShowDoublepoint(True)

sleep(0.2)
print ("Brightness Off")

display.SetBrightness(0)

sleep(0.5)

print ("Full Brightness")

display.SetBrightness(1)

sleep(0.5)

print ("30% Brightness")

display.SetBrightness(0.3)

sleep(0.3)

# See clock.py for how to use the clock functions!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy