iot lab print
iot lab print
6
Ex.No:1 Develop an application for LED Blink and Pattern using Date:
Arduino
Aim:
Components Required
• 1 × Breadboard
• 1 × Arduino Uno
• 1 × 220 Ω Resistor
• 1 × LED
• 2 × Jumper
Circuit Diagram:
Procedure:
1. Give Connections as per the circuit diagram.
2. Open the Arduino IDE.
3. Write the code.
4. Set the Arduino board and port in Tools -> Board and Tools -> Port.
5. Compile the code by clicking verify in the upper left corner.
6. Upload the code by just clicking the right arrow present just next to verify.
7. Once uploading is complete, the code automatically runs on the Arduino and the LED is
turned on. Coding:
setup() {
pinMode(LED_OUTPUT_PIN, OUTPUT);
}
void loop() {
Result:
Ex.No:2 Develop an application for LED Pattern with Push Button Date:
Control using Arduino
Aim:
Components Required
• 1 × Breadboard
• 1 × Arduino Uno
• 1 × 220 Ω Resistor
• 1 × LED
• 4 × Jumper
• 1 × Push Button Control
Circuit Diagram:
Procedure:
1. Give Connections as per the circuit diagram.
2. Open the Arduino IDE.
3. Write the code.
4. Set the Arduino board and port in Tools -> Board and Tools -> Port.
5. Compile the code by clicking verify in the upper left corner.
6. Upload the code by just clicking the right arrow present just next to verify.
7. Once uploading is complete, the code automatically runs on the Arduino and the LED is
turned on. Coding:
#define LED_PIN 8
#define BUTTON_PIN 7
byte lastButtonState = LOW; byte
ledState = LOW;
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
void loop() {
if (buttonState != lastButtonState) {
LOW) {
ledState);
}
}
}
Result:
Ex.No:3 Develop an application for LM35 Temperature Sensor to display Date:
temperature valuesusing Arduino or Raspberry Pi
Aim:
Components Required
• 1 × Breadboard
• 1 × Arduino Uno
• 1 × LM35 Temperature Sensor
• 4 × Jumper
Circuit Diagram:
Procedure:
1.
Give Connections as per the circuit diagram.
2.
Open the Arduino IDE.
3.
Write the code.
4.
Set the Arduino board and port in Tools -> Board and Tools -> Port.
5.
Compile the code by clicking verify in the upper left corner.
6.
Upload the code by just clicking the right arrow present just next to verify.
7.
Once uploading is complete, the code automatically runs on the Arduino and the LED is
turned on.
Coding:
const int lm35_pin = A1; /* LM35 O/P pin */
void setup() {
Serial.begin(9600);
}
void loop() { int temp_adc_val; float temp_val; temp_adc_val =
analogRead(lm35_pin); /* Read Temperature */ temp_val =
(temp_adc_val * 4.88); /* Convert adc value to equivalent voltage */ temp_val
= (temp_val/10); /* LM35 gives output of 10mv/°C */
Serial.print("Temperature = ");
Serial.print(temp_val);
Serial.print(" Degree Celsius\n");
delay(1000);
}
Result:
Ex.No:4 Develop an application for Forest fire detection end node using Date:
Raspberry Pidevice and sensor
Aim:
Components Required
• 1 × Breadboard
• 1 × Arduino Uno
• 1 × Flame Sensor Module
• 1 × Buzzer
• 2 × Jumper
Fire Sensor:
Buzzer:
Circuit Diagram:
Procedure:
1. Give Connections as per the circuit diagram.
2. Open the Arduino IDE.
3. Write the code.
4. Set the Arduino board and port in Tools -> Board and Tools -> Port.
5. Compile the code by clicking verify in the upper left corner.
6. Upload the code by just clicking the right arrow present just next to verify.
7. As soon as the flame is detected , the alert will be given
Coding:
const int buzzerPin = 5;
const int flamePin = 2;
int Flame = HIGH;
void setup()
{
pinMode(buzzerPin, OUTPUT); pinMode(flamePin,
INPUT);
Serial.begin(9600);
}
void loop()
{
Flame = digitalRead(flamePin);
if (Flame== LOW)
{
Serial.println("Fire is Detected"); digitalWrite(buzzerPin,
HIGH);
} else
{
Serial.println("No Fire is Detected");
digitalWrite(buzzerPin, LOW);
}
Result:
Ex.No:5 Develop an application for home intrusion detection web Date:
application
Aim:
Components Required
• 1 × Breadboard
• 1 × Arduino Uno
• 1 × PIR sensor (HC SR501)
• 1 x 16 x 2 LCD Module + I2C Module
• 1 × GSM Module (SIM 900A)
• 25 × Jumper wires
Circuit Diagram:
Procedure:
1. Give Connections as per the circuit diagram.
2. Open the Arduino IDE.
3. Write the code.
4. Set the Arduino board and port in Tools -> Board and Tools -> Port.
5. Compile the code by clicking verify in the upper left corner.
6. Upload the code by just clicking the right arrow present just next to verify.
7. As soon as a motion is detected, alarm will be given.
Coding:
include <SoftwareSerial.h>
SoftwareSerial mySerial(11, 10);
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup(){
pinMode(sensor, INPUT);
Serial.begin(9600);
lcd.begin();
mySerial.begin(9600);
Serial.println("Silent Alarm ");
Serial.println("Initializing System");
delay(100);
} void loop(){
val = digitalRead(sensor);
else {
Serial.println("Lamp Off!"); lcd.clear();
delay(200);
void updateSerial()
{ delay(500);
while
(Serial.avai
lable())
{
mySerial.write(Serial.read());
} while(mySerial.available())
{
Serial.write(mySerial.read());
}
}
Result:
Ex.No:6 Develop an application for Smart parking application using python Date:
and Django forweb application
Aim:
Components Required
• Raspberry Pi 3 Model B
• Raspberry Pi Camera Module
• Ultrasonic Sensor – HC-SR04
• SORACOM Air Global IoT SIM
• Jumper Wires
Coding:
# DetectPlates.py
import Preprocess
import DetectChars
import PossiblePlate
import PossibleChar
# module level
variables
##########################################################################
PLATE_WIDTH_PADDING_FACTOR = 1.3
PLATE_HEIGHT_PADDING_FACTOR = 1.5
####################################################################################
#
############## def detectPlatesInScene(imgOriginalScene):
listOfPossiblePlates = [] # this will be the return value height, width,
numChannels = imgOriginalScene.shape
imgGrayscaleScene = np.zeros((height, width, 1), np.uint8)
imgThreshScene = np.zeros((height, width, 1), np.uint8) imgContours =
np.zeros((height, width, 3), np.uint8)
cv2.destroyAllWindows() if
Main.showSteps == True: # show steps
####################################################### cv2.imshow("0",
imgOriginalScene)
# end if # show steps
#########################################################################
imgGrayscaleScene, imgThreshScene = Preprocess.preprocess(imgOriginalScene) # preprocess to get
grayscale and threshold images if Main.showSteps == True: # show steps
######################################################
# cv2.imshow("1a", imgGrayscaleScene) cv2.imshow("1b",
imgThreshScene)
# end if # show steps
#########################################################################
# DetectChars.py import os
kNearest = cv2.ml.KNearest_create()
# constants for checkIfPossibleChar, this checks one possible char only (does not compare to another
char)
MIN_PIXEL_WIDTH = 2
MIN_PIXEL_HEIGHT = 8
MIN_ASPECT_RATIO = 0.25
MAX_ASPECT_RATIO = 1.0
MIN_PIXEL_AREA = 80
MAX_CHANGE_IN_AREA = 0.5
MAX_CHANGE_IN_WIDTH = 0.8
MAX_CHANGE_IN_HEIGHT = 0.2
MAX_ANGLE_BETWEEN_CHARS = 12.0
# other constants
MIN_NUMBER_OF_MATCHING_CHARS = 3
RESIZED_CHAR_IMAGE_WIDTH = 20
RESIZED_CHAR_IMAGE_HEIGHT = 30
MIN_CONTOUR_AREA = 100
####################################################################################
#
############## def loadKNNDataAndTrainKNN(): allContoursWithData
= [] # declare empty lists,
validContoursWithData = [] # we will fill these shortly
try:
npaClassifications = np.loadtxt("classifications.txt", np.float32) # read in training classifications
except: # if file could not be opened
print("error, unable to open classifications.txt, exiting program\n") # show error message
os.system("pause")
return False # and return False
# end try
try:
npaFlattenedImages = np.loadtxt("flattened_images.txt", np.float32) # read in training
images
except: # if file could not be opened
print("error, unable to open flattened_images.txt, exiting program\n") # show error message
os.system("pause")
return False # and return False
# end try
return True # if we got here training was successful so return true # end function
####################################################################################
#
############## def
detectCharsInPlates(listOfPossiblePlates):
intPlateCounter = 0
imgContours = None
contours = []
# at this point we can be sure the list of possible plates has at least one plate
for possiblePlate in listOfPossiblePlates: # for each possible plate, this is a big for loop that takes up
most of the function possiblePlate.imgGrayscale,
possiblePlate.imgThresh =
Preprocess.preprocess(possiblePlate.imgPlate) # preprocess to get grayscale and threshold images
if Main.showSteps == True: # show steps
##################################################
# cv2.imshow("5a", possiblePlate.imgPlate) cv2.imshow("5b",
possiblePlate.imgGrayscale) cv2.imshow("5c",
possiblePlate.imgThresh)
# end if # show steps
#####################################################################
# increase size of plate image for easier viewing and char detection possiblePlate.imgThresh
= cv2.resize(possiblePlate.imgThresh, (0, 0), fx = 1.6, fy = 1.6)
Main.SCALAR_WHITE)
cv2.imshow("6", imgContours)
# end if # show steps
#####################################################################
# given a list of all possible chars, find groups of matching chars within the plate
listOfListsOfMatchingCharsInPlate = findListOfListsOfMatchingChars(listOfPossibleCharsInPlate)
possiblePlate.strChars = ""
continue # go back to top of for loop
# end if
# loop through all the vectors of matching chars, get the index of the one with the most chars
for i in range(0, len(listOfListsOfMatchingCharsInPlate)):
if len(listOfListsOfMatchingCharsInPlate[i]) > intLenOfLongestListOfChars:
intLenOfLongestListOfChars = len(listOfListsOfMatchingCharsInPlate[i])
intIndexOfLongestListOfChars = i
# end if
# end for
# suppose that the longest list of matching chars within the plate is the actual list of chars
longestListOfMatchingCharsInPlate =
listOfListsOfMatchingCharsInPlate[intIndexOfLongestListOfChars]
cv2.imshow("9", imgContours)
# end if # show steps
#####################################################################
possiblePlate.strChars = recognizeCharsInPlate(possiblePlate.imgThresh,
longestListOfMatchingCharsInPlate)
if Main.showSteps == True:
print("\nchar detection complete, click on any image and press a key to continue . . .\n")
cv2.waitKey(0)
# end if
return listOfPossiblePlates
# end function
####################################################################################
#
############## def findPossibleCharsInPlate(imgGrayscale, imgThresh):
listOfPossibleChars = [] # this will be the return value contours = [] imgThreshCopy
= imgThresh.copy()
return listOfPossibleChars
# end function
####################################################################################
#
############## def checkIfPossibleChar(possibleChar):
# this function is a 'first pass' that does a rough check on a contour to see if it could be a char,
# note that we are not (yet) comparing the char to other chars to look for a group
if (possibleChar.intBoundingRectArea > MIN_PIXEL_AREA and
possibleChar.intBoundingRectWidth > MIN_PIXEL_WIDTH and
possibleChar.intBoundingRectHeight > MIN_PIXEL_HEIGHT and
MIN_ASPECT_RATIO < possibleChar.fltAspectRatio and possibleChar.fltAspectRatio <
MAX_ASPECT_RATIO):
return True
else:
return False
# end if
# end function
####################################################################################
#
############## def findListOfListsOfMatchingChars(listOfPossibleChars):
# with this function, we start off with all the possible chars in one big list
# the purpose of this function is to re-arrange the one big list of chars into a list of lists of
matching chars,
# note that chars that are not found to be in a group of matches do not need to be considered
further listOfListsOfMatchingChars = [] # this will be the return value
for possibleChar in listOfPossibleChars: # for each possible char in the one big list of
chars listOfMatchingChars = findListOfMatchingChars(possibleChar, listOfPossibleChars) # find
all
chars in the big list that match the current char
listOfMatchingChars.append(possibleChar) # also add the current char to current possible list of matching
chars
if len(listOfMatchingChars) < MIN_NUMBER_OF_MATCHING_CHARS: # if current possible list of
matching chars is not long enough to constitute a possible plate continue that # jump back to the top of
the for loop and try again with next char, note
it's not necessary
# to save the list in any way since it did not have enough chars to be a possible plate
# end if
listOfPossibleCharsWithCurrentMatchesRemoved = []
# remove the current list of matching chars from the big list so we don't use
those same chars twice,
# make sure to make a new big list for this since we don't want to change
the original big list listOfPossibleCharsWithCurrentMatchesRemoved =
list(set(listOfPossibleChars) -
set(listOfMatchingChars))
recursiveListOfListsOfMatchingChars =
findListOfListsOfMatchingChars(listOfPossibleCharsWithCurrentMatchesRemoved) # recursive call
# end for
return listOfListsOfMatchingChars
# end function
####################################################################################
#
############## def findListOfMatchingChars(possibleChar, listOfChars):
# the purpose of this function is, given a possible char and a big list of possible chars,
# find all chars in the big list that are a match for the single possible char, and return those
matching chars as a list listOfMatchingChars = [] # this will be the return value
fltChangeInWidth = float(abs(possibleMatchingChar.intBoundingRectWidth -
possibleChar.intBoundingRectWidth)) / float(possibleChar.intBoundingRectWidth) fltChangeInHeight
= float(abs(possibleMatchingChar.intBoundingRectHeight - possibleChar.intBoundingRectHeight))
/ float(possibleChar.intBoundingRectHeight) # check if chars match if (fltDistanceBetweenChars <
(possibleChar.fltDiagonalSize *
MAX_DIAG_SIZE_MULTIPLE_AWAY) and fltAngleBetweenChars <
MAX_ANGLE_BETWEEN_CHARS and fltChangeInArea <
MAX_CHANGE_IN_AREA and fltChangeInWidth < MAX_CHANGE_IN_WIDTH
and fltChangeInHeight < MAX_CHANGE_IN_HEIGHT):
####################################################################################
# ##############
# use Pythagorean theorem to calculate distance between two chars
def distanceBetweenChars(firstChar, secondChar): intX
= abs(firstChar.intCenterX -
secondChar.intCenterX) intY =
abs(firstChar.intCenterY - secondChar.intCenterY)
####################################################################################
# ##############
# use basic trigonometry (SOH CAH TOA) to calculate angle between chars def
angleBetweenChars(firstChar, secondChar): fltAdj =
float(abs(firstChar.intCenterX - secondChar.intCenterX))
fltOpp = float(abs(firstChar.intCenterY - secondChar.intCenterY))
if fltAdj != 0.0: # check to make sure we do not divide by zero if the center X positions
are equal, float division by zero will cause a crash in Python fltAngleInRad =
math.atan(fltOpp / fltAdj) # if adjacent is not zero, calculate angle
else:
fltAngleInRad = 1.5708 # if adjacent is zero, use this as the angle, this is to be consistent with the
C++ version of this program
# end if fltAngleInDeg = fltAngleInRad * (180.0 / math.pi) # calculate angle in degrees
return fltAngleInDeg
# end function
####################################################################################
# ##############
# if we have two chars overlapping or to close to each other to possibly be separate chars, remove the
inner (smaller) char,
# this is to prevent including the same char twice if two contours are found for the same char, # for
example for the letter 'O' both the inner ring and the outer ring may be found as contours, but we
should only include the char once def removeInnerOverlappingChars(listOfMatchingChars):
listOfMatchingCharsWithInnerCharRemoved = list(listOfMatchingChars) # this will be the return
value
return listOfMatchingCharsWithInnerCharRemoved #
end function
####################################################################################
# ##############
# this is where we apply the actual char recognition
def recognizeCharsInPlate(imgThresh, listOfMatchingChars): strChars = ""
# this will be the return value, the chars in the lic plate height, width =
imgThresh.shape
# end for
return strChars
# end function
####################################################################################
#
############## def extractPlate(imgOriginal,
listOfMatchingChars):
possiblePlate = PossiblePlate.PossiblePlate() # this will be the return value
= fltPlateCenterX, fltPlateCenterY
intTotalOfCharHeights = 0
= int(fltAverageCharHeight * PLATE_HEIGHT_PADDING_FACTOR)
# pack plate region center point, width and height, and correction angle into rotated rect member
variable of plate possiblePlate.rrLocationOfPlateInScene = ( tuple(ptPlateCenter), (intPlateWidth,
intPlateHeight),
fltCorrectionAngleInDeg )
# get the rotation matrix for our calculated correction angle rotationMatrix =
cv2.getRotationMatrix2D(tuple(ptPlateCenter), fltCorrectionAngleInDeg, 1.0) height, width,
numChannels = imgOriginal.shape # unpack original image width and height
tuple(ptPlateCenter))
possiblePlate.imgPlate = imgCropped # copy the cropped plate image into the applicable member
variable of the possible plate
return possiblePlate #
end function
Main.py
import DetectChars
import DetectPlates
import PossiblePlate
showSteps = False
####################################################################################
#
############## def main():
# sort the list of possible plates in DESCENDING order (most number of chars to least number
of chars) listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse =
True)
# suppose the plate with the most recognized chars (the first plate in sorted by string length
descending order) is the actual plate licPlate
= listOfPossiblePlates[0]
cv2.imshow("imgPlate", licPlate.imgPlate) # show crop of plate and threshold of plate
cv2.imshow("imgThresh", licPlate.imgThresh)
# end if else
return
# end main
####################################################################################
#
############## def drawRedRectangleAroundPlate(imgOriginalScene, licPlate):
####################################################################################
#
############## def writeLicensePlateCharsOnImage(imgOriginalScene, licPlate):
ptCenterOfTextAreaX = 0 to # this will be the center of the area the text will be written
ptCenterOfTextAreaY = 0
ptLowerLeftTextOriginX = 0 # this will be the bottom left of the area that the text will
be written to ptLowerLeftTextOriginY =
0
# unpack roatated rect into center point, width and height, and angle
( (intPlateCenterX, intPlateCenterY), (intPlateWidth, intPlateHeight), fltCorrectionAngleInDeg ) =
licPlate.rrLocationOfPlateInScene intPlateCenterX = int(intPlateCenterX) # make sure center is an integer
intPlateCenterY =
int(intPlateCenterY)
ptCenterOfTextAreaX = int(intPlateCenterX) # the horizontal location of the text area is the same as the
plate
if intPlateCenterY < (sceneHeight * 0.75): # if the license plate is in the upper 3/4 of the image
ptCenterOfTextAreaY = int(round(intPlateCenterY)) + int(round(plateHeight * 1.6)) # write the chars in
below the plate else: # else if the license plate is in the lower 1/4 of the image ptCenterOfTextAreaY =
int(round(intPlateCenterY)) - int(round(plateHeight * 1.6)) # write the chars
in above the plate
# end if textSizeWidth, textSizeHeight = textSize # unpack text size width and height
####################################################################################
#
############## if name
== "main
":
main()
# PossiblePlate.py
####################################################################################
#
##############
class PossiblePlate:
# constructor
################################################################################# def
init(self):
self.imgPlate = None
self.imgGrayscale = None
self.imgThresh = None
self.rrLocationOfPlateInScene = None self.strChars
= ""
# end constructor
# end class
# Preprocess.py
####################################################################################
#
############## def preprocess(imgOriginal): imgGrayscale = extractValue(imgOriginal)
imgMaxContrastGrayscale = maximizeContrast(imgGrayscale) height, width = imgGrayscale.shape
imgBlurred = np.zeros((height, width, 1), np.uint8) imgBlurred =
cv2.GaussianBlur(imgMaxContrastGrayscale, GAUSSIAN_SMOOTH_FILTER_SIZE, 0)
####################################################################################
#
############## def extractValue(imgOriginal): height, width,
numChannels = imgOriginal.shape imgHSV = np.zeros((height,
width, 3), np.uint8) imgHSV = cv2.cvtColor(imgOriginal,
cv2.COLOR_BGR2HSV) imgHue, imgSaturation, imgValue =
cv2.split(imgHSV)
return imgValue
# end function
####################################################################################
#
############## def maximizeContrast(imgGrayscale):
height, width = imgGrayscale.shape
return imgGrayscalePlusTopHatMinusBlackHat #
end function
# PossibleChar.py
####################################################################################
#
############## class
PossibleChar:
# constructor
################################################################################# def
init(self, _contour):
self.contour = _contour
self.boundingRect = cv2.boundingRect(self.contour)
self.intBoundingRectX = intX
self.intBoundingRectY = intY
self.intBoundingRectWidth = intWidth
self.intBoundingRectHeight = intHeight
# end class
Result: