IoT Lab Manual
IoT Lab Manual
No:1 Develop an application for LED Blink and Pattern using Arduino
Aim:
To develop an application for LED Blink using Arduino.
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:
void loop() {
digitalWrite(LED_OUTPUT_PIN, HIGH); // turn LED on (output 5V)
delay(1000); // wait one second
digitalWrite(LED_OUTPUT_PIN, LOW); // turn LED off (output 0V)
delay(1000); // wait another second
}
Result:
Thus the application was developed for Blinking LED using Arduino.
Ex.No:2 Develop an application for LED Pattern with Push Button Control using Arduino
Aim:
To develop an application for LED Pattern with Push Button Control using Arduino.
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
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
void loop() {
if (buttonState != lastButtonState) {
lastButtonState = buttonState;
if (buttonState == LOW) {
digitalWrite(LED_PIN, ledState);
}
Result:
Thus the application was developed to toggle the LED on pressing the Push Control
Button.
Ex.No:3 Develop an application for LM35 Temperature Sensor to display temperature values
using Arduino or Raspberry Pi
Aim:
To develop an application for LM35 Temperature Sensor to display temperature values
using Arduino.
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:
Thus the application was developed to monitor the temperature using LM35 temperature
sensor.
Ex.No:4 Develop an application for Forest fire detection end node using Raspberry Pi
device and sensor
Aim:
To develop an application for forest fire detection using Arduino.
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:
Thus the application was developed for the detection of forest fire.
Ex.No:5 Develop an application for home intrusion detection web application
Aim:
To develop an application for home intrusion detection using Arduino.
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);
if (val == HIGH){
mySerial.println("AT");
updateSerial();
mySerial.println("AT+CMGF=1");
updateSerial();
mySerial.println("AT+CMGS=\"+YYxxxxxxxxx\"");//change YY with country code and
xxxxxxxxxxx with phone number to sms
updateSerial();
mySerial.print("Alert : INTRUDER ALERT || SILENT ALARM TRIGGERED || Location :
xxxxxx");
updateSerial();
mySerial.write(26);
lcd.backlight();
lcd.print("Alarm Activated");
delay(500);
lcd.clear();
lcd.print("Location : X");
delay(500);
lcd.clear();
delay(1000);
if (state == LOW) {
state = HIGH;
}
}
else {
Serial.println("Lamp Off!");
lcd.clear();
delay(200);
if (state == HIGH){
state = LOW;
}
}
}
void updateSerial()
{
delay(500);
while (Serial.available())
{
mySerial.write(Serial.read());
}
while(mySerial.available())
{
Serial.write(mySerial.read());
}
}
Result:
Thus the application was developed for home intrusion detection using Arduino.
Ex.No:6 Develop an application for Smart parking application using python and Django for
web application
Aim:
To develop an application for Smart parking system using python and Django for
web application.
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 cv2
import numpy as np
import math
import Main
import random
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
import cv2
import numpy as np
import math
import random
import Main
import Preprocess
import PossibleChar
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
#####################################################################################
##############
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
# 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)
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
del contours[:]
# within each possible plate, suppose the longest list of potential matching chars is the actual
list of chars
intLenOfLongestListOfChars = 0
intIndexOfLongestListOfChars = 0
# 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
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)
#####################################################################################
##############
# 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
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
# end for
return strChars
# end function
#####################################################################################
##############
def extractPlate(imgOriginal, listOfMatchingChars):
possiblePlate = PossiblePlate.PossiblePlate() # this will be the return value
intTotalOfCharHeights = 0
# 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 )
height, width, numChannels = imgOriginal.shape # unpack original image width and height
possiblePlate.imgPlate = imgCropped # copy the cropped plate image into the applicable member
variable of the possible plate
return possiblePlate
# end function
Main.py
import cv2
import numpy as np
import os
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]
# end if else
return
# end main
#####################################################################################
##############
def drawRedRectangleAroundPlate(imgOriginalScene, licPlate):
#####################################################################################
##############
def writeLicensePlateCharsOnImage(imgOriginalScene, licPlate):
ptCenterOfTextAreaX = 0 # this will be the center of the area the text will be written
to
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 __name__ == "__main__":
main()
# PossiblePlate.py
import cv2
import numpy as np
#####################################################################################
##############
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
import cv2
import numpy as np
import math
#####################################################################################
##############
def preprocess(imgOriginal):
imgGrayscale = extractValue(imgOriginal)
imgMaxContrastGrayscale = maximizeContrast(imgGrayscale)
#####################################################################################
##############
def extractValue(imgOriginal):
height, width, numChannels = imgOriginal.shape
return imgValue
# end function
#####################################################################################
##############
def maximizeContrast(imgGrayscale):
return imgGrayscalePlusTopHatMinusBlackHat
# end function
# PossibleChar.py
import cv2
import numpy as np
import math
#####################################################################################
##############
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:
Thus the web application was developed for Smart parking system using python.