0% found this document useful (0 votes)
4 views49 pages

CP5292 Internet of Things

The document outlines a series of laboratory experiments conducted at Sri Venkateswara College of Engineering & Technology during the 2023-2024 academic year, focusing on applications developed using Arduino and Raspberry Pi. It includes detailed instructions for projects such as LED blinking, push button control for LEDs, and temperature measurement using an LM35 sensor. Each experiment specifies hardware requirements, circuit setup, and programming code necessary to achieve the desired outcomes.
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)
4 views49 pages

CP5292 Internet of Things

The document outlines a series of laboratory experiments conducted at Sri Venkateswara College of Engineering & Technology during the 2023-2024 academic year, focusing on applications developed using Arduino and Raspberry Pi. It includes detailed instructions for projects such as LED blinking, push button control for LEDs, and temperature measurement using an LM35 sensor. Each experiment specifies hardware requirements, circuit setup, and programming code necessary to achieve the desired outcomes.
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/ 49

SRI VENKATESWARAA

COLLEGE OF ENGINEERING & TECHNOLOGY

BONAFIDE CERTIFICATE

NAME :

YEAR/SEM :

BRANCH :

REGISTER NO :

Certified to be the bonafide record of work done by the student in the


Laboratory during the year 2023 - 2024

Lab-in-charge Head of the Department

Submitted for the practical Examination held on

Internal Examiner External Examiner


TABLE OF CONTENTS

Ex.No. Date Title of the Experiments Page No. Marks Signature

1 Develop an application for LED blink


and Pattern using Arduino or Rasperry
Pi

2 Develop an application for LED pattern


with Push Button Control using Arduino
or Raspberry Pi.

3
Develop an application for LM35
Temperature Sensor to display
temperature values using arduino or
raspberry Pi
4 Develop an application for Forest fire
detection end node using Raspberry Pi
device and Sensor.

5 Develop an application for home


intrusion detection web application

6 Develop an application for smart


Parking application using python and
Django for web application:

TOTAL
EX No: 1 Develop an application for LED blink and Pattern using Arduino or Rasperry Pi

Aim:

To Develop an application for LED blink and Pattern using Arduino or Rasperry Pi

Harware Requirements:

• Raspberry Pi 3 setup with monitor and USB Mouse & Keyboard


• Solderless breadboard
• Jumper wires for easy hookup
• Resistor pack
• Red LED
• Multimeter (optional)

Setting up the circuit

The first step in this project is to design a simple LED circuit. Then we will make the LED
circuit controllable from the Raspberry Pi by connecting the circuit to the general purpose
input/output (GPIO) pins on the Raspberry Pi.

A simple LED circuit consists of a LED and resistor. The resistor is used to limit the current that
is being drawn and is called a current limiting resistor. Without the resistor the LED would run at
too high of a voltage, resulting in too much current being drawn which in turn would instantly
burn the LED, and likely also the GPIO port on the Raspberry Pi.

To calculate the resistor value we need to examine the specifications of the LED. Specifically we
need to find the forward voltage (VF) and the forward current (IF). A regular red LED has a
forward voltage (VF) of 1.7V and forward current of 20mA (IF). Additionally we need to know
the output voltage of the Raspberry Pi which is 3.3V.

We can then calculate the resistor size needed to limit the current to the LED’s maximum
forward current (IF) using ohm’s law like this:

RΩ=VI=3.3–VFIF=3.3–1.720mA=80Ω
Unfortunately 80 ohm is not a standard size of a resistor. To solve this we can either combine
multiple resistors, or round up to a standard size. In this case we would round up to 100 ohm.

Important information: Since ohm’s law tells us that I (current) = V (voltage) / R (ohm) rounding
up the resistor value will lower the actual current being drawn a little. This is good because we
don’t want to run our system at the maximum current rating. Rounding down instead of up
would be dangerous, since it will actually increase the current being drawn. Increased current
would result in running our system over the maximum rating and potentially destroying or
damaging our components.
With the value calculated for the current limiting resistor we can now hook the LED and resistor
up to GPIO pin 8 on the Raspberry Pi. The resistor and LED needs to be in series like the
diagram below. To find the right resistor use the resistor color code – for a 100 ohm resistor it
needs to be brown-black-brown. You can use your multimeter to double check the resistor
value.

When hooking up the circuit note the polarity of the LED. You will notice that the LED has a
long and short lead. The long lead is the positive side also called the anode, the short lead is the
negative side called the cathode. The long should be connected to the resistor and the short lead
should be connected to ground via the blue jumper wire and pin 6 on the Raspberry Pi as shown
on the diagram.

To find the pin number refer to this diagram showing the physical pin numbers on the Raspberry

Pi.

Writing the Python Software to blink the LED


With the circuit created we need to write the Python script to blink the LED. Before we start
writing the software we first need to install the Raspberry Pi GPIO Python module. This is a
library that allows us to access the GPIO port directly from Python.

To install the Python library open a terminal and execute the following

$ sudo apt-get install python-rpi.gpio python3-rpi.gpio

With the library installed now open your favorite Python IDE (I recommend Thonny Python IDE
more information about using it here).

Our script needs to do the following:

• Initialize the GPIO ports


• Turn the LED on and off in 1 second intervals

To initialize the GPIO ports on the Raspberry Pi we need to first import the Python library, the
initialize the library and setup pin 8 as an output pin.

import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library


from time import sleep # Import the sleep function from the time module
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial
value to low (off)
Next we need to turn the LED on and off in 1 second intervals by setting the output pin to either
high (on) or low (off). We do this inside a infinite loop so our program keep executing until we
manually stop it.

while True: # Run forever


GPIO.output(8, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(8, GPIO.LOW) # Turn off
sleep(1) # Sleep for 1 second
Combining the initialization and the blink code should give you the following full Python
program:

import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library


from time import sleep # Import the sleep function from the time module
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial
value to low (off)

while True: # Run forever

GPIO.output(8, GPIO.HIGH) # Turn on

sleep(1) # Sleep for 1 second

GPIO.output(8, GPIO.LOW) # Turn off

sleep(1) # Sleep for 1 second

With our program finished, save it as blinking_led.py and run it either inside your IDE or in the
console with:

$ python blinking_led.py
With the program running you should see something like this:

Result:

Thus the output of the program is successfully verified.


Ex No:2 Develop an application for LED pattern with Push Button Control using Arduino
or Raspberry Pi.

Aim:

To Develop an application for LED pattern with Push Button Control using Arduino or
Raspberry Pi.

Hardware Required:

• Raspberry Pi
• Micro USB Power Adapter
• Bread Board
• LED
• Push Button
• Resistor -330 ohm and 10K ohm
• Jumper wires - Male to Female and Male to Male

Using a breadboard is the best way to do prototyping the electronic circuits rather soldering the
components together on a PCB.We use breadboard to test circuit design & it is easy to make the
changes as we just need to re-plug the wires.

The details for GPIO pins I have described in my previous post, refer the post my IoT devices .

Lets see how we need to do the connection or circuit for this raspberry pi push button led control.

I have used the GPIO pin 2 for 5 v , GPIO pin 6 for GND, GPIO pin 17 as Output and GPIO pin
18 as Input for the circuit. Connect the GPIO PIN 17 to the anode of LED & the GPIO PIN 18 to
the Push Button. Connect the resistors , GND and 5V as shown in the below diagram. Once we
have the circuit setup & the raspberry pi is powered on, it is now time to write the python code.
The real diagram of using a push button with Raspberry Pi GPIO.

Program Coding:

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(17, GPIO.OUT)

#LED is connected to Pin 17

GPIO.setup(18, GPIO.INPUT)

#PushButton is connected to Pin 18

try:

while True:

if GPIO.input (18) == 0:

print ("led is On")

GPIO.output (17, True)

if GPIO.input (18) == 1:

print ("led is OFF")

GPIO.output (17, False)

finally:

GPIO.cleanup ()

The above script will give print output continuously , lets modify this Push button to turn a led
on and stay on until pressed again script for better one.
import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(17, GPIO.OUT)

#LED is connected to Pin 17

GPIO.setup(18, GPIO.INPUT)

#PushButton is connected to Pin 18

ledstate = 0

try:

while True:

if GPIO.input (18) == 0 and ledstate == 0:

print ("led is On")

GPIO.output (17, True)

ledstate = 1

time.sleep (0.5)

if GPIO.input (18) == 1 and ledstate == 1:

print ("led is OFF")

GPIO.output (17, False)

ledstate =0

time.sleep(0.5)

finally:

GPIO.cleanup ()

I found out that there are multiple ways for writing python script for led projects with raspberry
pi and this depends also on the connection how we are setting up. We can have a different way of
connection for push button raspberry pi 3 and LED. Lets see the below circuit diagram
for connect push button to raspberry pi in a different way.
Output:

Lets see the below Python program to push button control led with direct connection.

import RPi.GPIO as GPIO


import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(17, GPIO.OUT)

#LED is connected to Pin 17

GPIO.setup(18, GPIO.INPUT)

#Push Button is connected to Pin 18

try:

while True:

button_state = GPIO.input(18)
if button_state == False:

GPIO.output(17, True)
print('Button is Pressed and LED is ON')
time.sleep(0.5)

else:

GPIO.output(17, False)

except:

GPIO.cleanup()

Result:

Thus the output of the program is successfully verified.


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 or raspberry Pi

Hardware Requirements:

VCC is the power supply pin of the LM35 temperature sensor IC that can be connected to 4V or
32V of the supply.

GND is the ground pin of the LM35 temperature sensor IC and it should be connected to the
supply ground.

OUT This is the temperature sensor analog output pin. This is the analog output pin of the
temperature sensor, the output voltage on this pin is directly proportional to the temperature.

LM35 Temperature Sensor


The LM35 is a low-power, low-cost, high-precision temperature sensor designed and
manufactured by Texas instruments. This IC provides a voltage output that is linearly
proportional to the change in temperature.
The LM35 sensor is moderately precise and its robust construction makes it suitable for various
environmental conditions. Additionally, you don't need any external component to calibrate this
circuit and it has a typical accuracy of ±0.5°C at room temperature and ±1°C over a full −55°C to
+155°C temperature range. It has an operating voltage of 4V to 30V and consumes 60-uA
current while it's in working state, this also makes it perfect for battery-powered applications.

There are two disadvantages of this sensor. The first big disadvantage of this sensor is that it
cannot measure negative temperature, for that you have to bias it with a dual polarity supply. If
your project requires negative temperature measurements, you can opt for a LM36 sensor. The
second disadvantage of this sensor is that it's very sensitive to noise because it outputs data in
analog format. If you want to learn more about this sensor you can check out the Datasheet of
LM35 Temperature Sensor IC.

How the LM35 Temperature Sensor Measures Temperature:

The LM35 temperature sensor uses the basic principle of a diode to measure known temperature
value. As we all know from semiconductor physics, as the temperature increases the voltage
across a diode increases at a known rate. By accurately amplifying the voltage change, we can
easily generate a voltage signal that is directly proportional to the surrounding temperature. The
screenshot below shows the internal schematic of LM35 temperature sensor IC according to the
datasheet.
In practice, this diode that they are using to measure the temperature is not actually a PN
Junction diode but its a diode-connected transistor. That is why the relationship between the
forward voltage and the transistor is so linear. The temperature coefficient vs collector current
graph below gives you a better understanding of the process.

LM35 Temperature Sensor Working Procedure


The working of the LM35 Temperature Sensor is very simple and easy to understand. We just
have to connect 5V and Ground to the sensor and we need to measure the output voltage from
the output pin.
According to the datasheet of the device, the sensor should give us 10mv/°C. So, if the
temperature of the room is 18°C then the sensor should give us 180mV at the output pin and the
animation above shows exactly that. If you connect a multimeter to the output pin of the sensor
and measure the output voltage you will get something similar. If you are getting wired voltage
output from the sensor then we would recommend you to go through our previous article
on LM35 Temperature Sensor Not Working? where we have encountered some weird issues that
we couldn't find any solution to.

Arduino LM35 Temperature Sensor Circuit Diagram


Now that we have understood how the LM35 Temperature Sensor works we can connect all the
required wires to Arduino UNO. The arduino lm35 connection diagram is shown below-

Connecting the LM35 sensor to the Arduino is really simple. You just need to connect 5V
power to the sensor and you need to connect the output of the sensor to the A0 pin of the
Arduino. Once the connection is done you need to write the code to convert the output voltage of
the sensor to temperature data. For that, first, you need to convert the ADC values to voltage and
multiply that voltage to 10 and you will get the output in temperature. With that, you’re now
ready to upload the code to Arduino. An image showing the actual Arduino LM35 hardware
setup is shown below.
Program Code
The Arduino Code for Interfacing the LM35 Temperature Sensor is very simple and easy to
understand. We just need to read the analog data out of the sensor and convert it to temperature
data.

We Initialize our code by defining the pin in which the LM35 Temperature sensor is connected.

#define sensor_pin A0 // LM35 is connected to this PIN

Next, we have our setup() function, in the setup, we just need to initialize the serial monitor for
debugging.

void setup() {
// Init serial at 9600 baud
Serial.begin(9600);
}

Next we have our loop function, in the loop function we read the pin and store the ADC data in
adcData variable. Next, we convert the ADC data to the voltage value and store it in a local
variable named voltage, and finally, we convert the voltage value to temperature and store it in a
variable named temperature and print that in the serial monitor window. At last, we added
800ms and finished the code.
void loop() {
//Read Raw ADC Data
int adcData = analogRead(sensorPin);
// Convert that ADC Data into voltage
float voltage = adcData * (5.0 / 1024.0);
// Convert the voltage into temperature
float temperature = voltage * 100;
// Print the temperature data
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println("*C");
delay(800); // wait a second between readings
}
Output:
The gif below shows the Arduino LM35 Temperature Sensor in action. On the left-hand side, we
have placed the Arduino with the temperature sensor connected to A0 pin of the Arduino and on
the right-hand side, we have our serial monitor window. When we warm up the temperature
sensor with the hot air station, you can see the temperature value rises on the serial monitor
window.

Result:

Thus the output of the program is successfully verified.


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 end node using Raspberry Pi device and
Sensor.

Hardware Required:

• Arduino Nano
• SIM800L GPS/GPRS Module
• 3.7V Li-ion Battery
• Flame sensor
• Dot matrix Perf board

SIM800L Module Working


SIM800L is a compact module that allows GPRS transmission, send/receive SMS, and making
voice calls. SIM800L module has two antennas included on it. The first is for a ring antenna
which can be soldered directly on the board and the other is meant for an external antenna.

Specification:

• Input voltage: 3.4V - 4.2V


• Interface: UART and AT commands
• Supported frequencies: Quad Band (850 / 950 / 1800 /1900 MHz)
• SIM card socket: micro SIM slot
• Antenna connector: IPX
• Working temperature range: -40 do + 85 ° C

Block Diagram for IoT Based Forest Fire Detection System


As shown in the schematic block diagram below, the project consists of Flame sensor, Arduino
Nano & SIM800L GSM/GPRS module as its primary components. The fire can be detected by
the flame sensor which gives a digital output that corresponds to the Fire status and is received
by the Arduino
Nano.

Arduino compares the signal and triggers the SIM800L in case of fire incidents. Through AT
commands, SIM800L communicates with thingspeak server.

Arduino IoT Fire Detection - Circuit Diagram

As shown in the circuit diagram, the Flame sensor is connected to the Digital Input pin of
Arduino Nano. You can also check out other simple fire alarm circuits which we have built
earlier if you are interested.

SIM800L is connected to Arduino Nano via Logic shifting resistors as SIM800L works on 3.3v
Logic. Separate power is given to SIM800L module because it works in 3.4-4.2V DC and 5V
DC external supply is given to Arduino Nano. Alternatively, a 3.7-5 V Boost converter can be
used here to avoid two power supplies.

Setup Thingspeak Account


After successful completion of hardware as per the above circuit diagram, the IoT platform needs
to be set up, where the real-time data will be received. Here Thingspeak is used to store the
parameters and show them in GUI. For creating an account in Thingspeak follow the steps
below:

Step 1: Sign up for Thingspeak

First, go to https://thingspeak.com/ and create a new free Mathworks account if you don’t have a
Mathworks account before.

Step 2: Sign in to Thingspeak

Sign in to Thingspeak using your credentials and click on “New Channel”. Now fill up the
details of the project like Name, Field names, etc. Then click on “Save channel”.

Step 3: Record the Credentials

Select the created channel and record the following credentials.


• Channel ID, which is at the top of the channel view.
• Write API key, which can be found on the API Keys tab of your channel view.

Step 4: Add widgets to your GUI

Click on “Add Widgets” and add four appropriate widgets like gauges, numeric displays, and
indicators. In my case, I have taken Indicator for Fire Alert. Select appropriate field names for
each widget.
Program Coding:
After completion of successful hardware connection as per the circuit diagram, now it’s time to
flash the code to Arduino. So the first step is to include all the required libraries in the code,
which are “SoftwareSerial.h” and “String.h” in my case.

#include <SoftwareSerial.h>
#include <String.h>

The next step is to define the RX, TX Pin of Arduino where SIM800L is connected.

SoftwareSerial gprsSerial(10, 11);

In the setup (), all the primary initializations are made such as Serial initializations, SIM800L
module initializations, and GPIO pin declarations.

void setup()
{
pinMode(12, OUTPUT);
pinMode(9, INPUT);
gprsSerial.begin(9600); // the GPRS baud rate
Serial.begin(9600); // the GPRS baud rate
Module_Init();
}

In the SIM800L module initialization function, several AT commands are called to initialize the
Module and know the status of the module. The functionalities of individual AT commands can
be found in AT command sheet of SIM800L. But the only concern here is in the statement
“gprsSerial.println("AT+CSTT=\"www\"")” where the access point of operator is defined. Make
sure that, correct Access point name is replaced with “www”.

void Module_Init()
{
gprsSerial.println("AT");
delay(1000);
gprsSerial.println("AT+CPIN?");
delay(1000);
gprsSerial.println("AT+CREG?");
delay(1000);
gprsSerial.println("AT+CGATT?");
delay(1000);
gprsSerial.println("AT+CIPSHUT");
delay(1000);
gprsSerial.println("AT+CIPSTATUS");
delay(2000);
gprsSerial.println("AT+CIPMUX=0");
delay(2000);
ShowSerialData();
gprsSerial.println("AT+CSTT=\"www\"");
delay(1000);
ShowSerialData();
gprsSerial.println("AT+CIICR");
delay(3000);
ShowSerialData();
gprsSerial.println("AT+CIFSR");
delay(2000);
ShowSerialData();
gprsSerial.println("AT+CIPSPRT=0");
delay(3000);
ShowSerialData();
}

Inside loop(), digital values from pin 12 are read and stored in a variable.
int fire = digitalRead(12);

Then, when the fire is detected, an if-else loop is used to detect the trigger of the SIM800L for
necessary action. As shown below, AT+CIPSTART is used to connect with Thingspeak server
and start the connection. The AT+CIPSEND is used to send the data to the server. Here one
important thing is to replace the “Thingspeak write API Key” with your actual key in the string
which was recorded earlier.

gprsSerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the conne


ction
delay(6000);
ShowSerialData();
gprsSerial.println("AT+CIPSEND");//begin send data to remote server
delay(4000);
ShowSerialData();
String str = "GET https://api.thingspeak.com/update?api_key=ER43PWXXXXXQF0I&field1="
+ String(1);
Serial.println(str);
gprsSerial.println(str);//begin send data to remote server

After completion of data transmission, AT+CIPSHUT is used to close the connection.

gprsSerial.println("AT+CIPSHUT");//close the connection


delay(100);
Output & Testing:

Code

#include <SoftwareSerial.h>

SoftwareSerial gprsSerial(10, 11);

#include <String.h>

int flag = 0;

void setup()

pinMode(9, OUTPUT);

pinMode(12, INPUT);

gprsSerial.begin(9600); // the GPRS baud rate

Serial.begin(9600); // the GPRS baud rate

Module_Init();

void loop()

if (gprsSerial.available())
Serial.write(gprsSerial.read());

int fire = digitalRead(12);

if (fire == 0)

digitalWrite(9, HIGH);

gprsSerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the con


nection

delay(6000);

ShowSerialData();

gprsSerial.println("AT+CIPSEND");//begin send data to remote server

delay(4000);

ShowSerialData();

Result:

Thus the output of the program is successfully verified.


ExNo: 5 Develop an application for home intrusion detection web application

Aim:

To Develop an application for home intrusion detection web application

Hardware Requirements:
• ESP12E NodeMCU board
• Raspberry Pi
• PIR sensor
• Light dependent Resistor
• Laser pointer
• Web cam
• Buzzer
• Some wires

Work-Flow:
Using all the above requirements, I am going to detect the intrusion that is:

• With the help of Light dependent resistor and PIR motion sensor, I am going to detect
the motions in the room.
• If a motion is detected, I intend to capture the image with the help of a webCam and
store locally
• Now the alerts are sent to the user with the captured image.
• Also I am using the buzzer which turns on in case of any intrusion.
Circuit Wiring:

We are ready with all the devices and made the circuit connections. Now to implement the above
methodology we need to install required software’s and libraries to accomplish our goal.

To start the Webcam surveillance we need to install the following libraries on to the Pi.

sudo apt-get install motion

mkdir /home/pi/motion

sudo cp /etc/motion/motion.conf /home/pi/motion

mkdir /home/pi/motion/media

I got this information about the video surveillance from the site [Reference]
http://hilpisch.com/rpi/05_webcam.html
We are done with all the software and libraries installation on both Arduino and Raspberry Pi.
Now we can start writing the code to collect the sensor data and publishing it on Pi. Also for
image capturing and sending an email alert

Collecting the sensor values on nodemcu and publishing it on Pi:

To collect the sensor values of PIR and LDR, first give power supply to the nodemcu with the
help of USB cable.

Program Coding:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

int ledPin = 14; // choose the pin for the LED


int inputPin = 13;
int LDRValue = 0;
// choose the input pin (for PIR sensor)
int val = 0; // variable for reading the pin status
const char* ssid = “Cisco48681”;
const char* password = “villanova”;
const char* mqtt_server = “153.104.206.108”;

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[150];
int value = 0;
char msg1[150];
void setup_wifi() {

delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print(“Connecting to “);
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {


delay(500);
Serial.print(“.”);
}

Serial.println(“”);
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {


Serial.print(“Message arrived [“);
Serial.print(topic);
Serial.print(“] “);
Serial.print(“came into callback. The published message from Pi is “);
Serial.println();
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();

// Switch on the LED if an 1 was received as first character


if ((char)payload[0] == ‘1’) {
digitalWrite(14, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
digitalWrite(14, HIGH); // Turn the LED off by making the voltage HIGH
}
}

void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);
// Attempt to connect
if (client.connect(“ESP8266Client”)) {
Serial.println(“connected”);
// Once connected, publish an announcement…
client.publish(“outTopic”, “hello world”);
// … and resubscribe
client.subscribe(“inTopic”);
} else {
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(” try again in 5 seconds”);
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
client.loop();
LDRValue=analogRead(A0);
delay(1000);
Serial.println(LDRValue);
String ldr=”LDRValue=”+String(LDRValue);
Serial.println(ldr);
String disp=ldr;
disp.toCharArray(msg1,disp.length());
snprintf(msg,150,msg1,value);
client.publish(“ldrvalue”,msg);
val = digitalRead(inputPin); // read input value
if (val == HIGH or LDRValue < 1000) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
// we have just turned on
client.publish(“outTopic”, “Motion detected”);
delay(2000);
// We only want to print on the output change, not state
}
else {
digitalWrite(ledPin, LOW); // turn LED OFF
// we have just turned of
//client.publish(“outTopic”, “Motion ended!”);
// We only want to print on the output change, not state
}
}
Pi collecting the Sensor data from nodemcu:
• Open LXTerminal and start the node-red by executing the command node-red-start.
• Open another LXTerminal and first stop the MQTT service with the below
command sudo /etc/init.d/mosquitto stop
• Now restart the mosquitto by just entering mosquitto command on LXTerminal.
Experiments and Output:
If there is a intrusion, Pi should capture the image of the intruder and send the image to the user.
To accomplish this we need to execute the below code in the Pi:

• To read the values from node-red on Pi, we need to install the paho-library onto the pi.
• The SMTP library helps to send the email to the user from raspberry Pi. So in the code
we need to import this library.

import paho.mqtt.client as mqtt


import time
import smtplib
from subprocess import call
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
USERNAME = “iotexperimentz@gmail.com”
PASSWORD = “XXXXXXXXX”
def sendMail(to, subject, text, files=[]):
assert type(to)==list
assert type(files)==list
msg = MIMEMultipart()
msg[‘From’] = USERNAME
msg[‘To’] = COMMASPACE.join(to)
msg[‘Date’] = formatdate(localtime=True)
msg[‘Subject’] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase(‘application’, “octet-stream”)
part.set_payload( open(file,”rb”).read() )
Encoders.encode_base64(part)
part.add_header(‘Content-Disposition’, ‘attachment; filename=”%s”‘
% os.path.basename(file))
msg.attach(part)
server = smtplib.SMTP(‘smtp.gmail.com:587’)
server.ehlo_or_helo_if_needed()
server.starttls()
server.ehlo_or_helo_if_needed()
server.login(USERNAME,PASSWORD)
server.sendmail(USERNAME, to, msg.as_string())
server.quit()
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
print(“Connected with result code “+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(“outTopic/#”)

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+” “+str(msg.payload))
call([“fswebcam”, “-d”, “/dev/video0”, “-r”, “1280*720”, “–no-banner”,
“test1.jpg”])
time.sleep(2)
sendMail( [“yamini.tella@gmail.com”],
“Detected Intrusion”,
“Someone broke into your room, picture attached”,
[“/home/pi/test1.jpg”] )
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
• client.connect(“10.0.0.24”, 1883, 60)
• # Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
In case of intrusion:

• We can observe that in the above figure if someone intrudes, there will be a breach in the
laser beam and the light level will be less than threshold value.
• This message will be sent to Pi
• Pi receives the message and captures the image of the intruder and send the alert email to
the user.
Graphical representation of LDR values in IBM Watson cloud:
• I have used IBM watson cloud to graphically represent my data.
• To send the values to the cloud I have used Watson IOT node in Node-red application.
• Node-red has an inbuilt node for IBM watson. Select that node and connect it to the LDR
MQTT node as shown
below: Reference

Email Alert:

Result:

Thus the output of the program is successfully verified.


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 application using python and Django for
web application

Program Coding:

# Parking Lot Project - Andrew Ragland


import os
import time

# lot information and data structure


spaces = []
avail_spaces = 0
total_spaces = 0
rows = 0

# display function variables


space_count = 0
border = ""

# flags
linux = 0

# vehicle class, has a type and a plate number, upon creation, stores current epoch time for later
fare calculation
class Vehicle:
def init (self, v_type, plate):
self.type = v_type
self.plate = plate
self.entry_time = time.time()

# return type value (int)


def get_type(self):
return self.type

# return type value (string)


def get_type_string(self):
return "Car" if self.type == 1 else "Truck" if self.type == 2 else "Motorcycle"

def get_plate(self):
return self.plate
def get_entry_time(self):
return self.entry_time

# set epoch time manually - used for demo mode


def set_entry_time(self, new_time):
self.entry_time = new_time

def get_vehicle(self):
return self.type, self.plate, self.entry_time

# space class, stores a vehicle object and current occupied status,


class Space:
def init (self):
self.vehicle = None
self.occupied = False

def add_vehicle(self, vehicle):


self.vehicle = vehicle
self.occupied = True

# remove a vehicle from a space and return object for final fare calculation
def remove_vehicle(self):
v_exit = self.vehicle
self.vehicle = None
self.occupied = False
return v_exit

def vehicle_info(self):
return self.vehicle

def is_available(self):
return self.occupied

def print_row(row):
output = ""
output += "|"
for s in range(space_count * row, space_count * (row + 1)):
if not spaces[s].is_available():
output += "[ ]"
else:
output += "["
output += "c" if spaces[s].vehicle_info().get_type() == 1 \
else "t" if spaces[s].vehicle_info().get_type() == 2 \
else "m"
output += "]"
if s < space_count * (row + 1) - 1:
output += " "
output += "|"

return output

# display all spaces with availability


def display_lot():
global spaces, avail_spaces, total_spaces, rows

# generate the interface


output = "SPOTS AVAILABLE: " + str(avail_spaces) + "\n"

output += border

for row in range(rows):


output += print_row(row) + "\n"

output += border

# only uncomment when running on linux machine


if linux == 1:
os.system("clear")
print(output)

# display all spaces with row selection numbers for user to choose from
def display_row_selection():
global spaces, avail_spaces, total_spaces, rows

# generate the interface


output = "SPOTS AVAILABLE: " + str(avail_spaces) + "\n"

output += border
for row in range(rows):
output += print_row(row)
output += " <" + str(row) + ">\n"
output += border

# only uncomment when running on linux machine


if linux == 1:
os.system("clear")
print(output)
# display a specified row with space selection numbers for user to choose from
def display_space_selection(row):
global spaces, avail_spaces, total_spaces, rows

output = "VIEWING ROW: " + row + "\n"

output += border
output += print_row(int(row)) + "\n"

output += " "


for count in range(space_count):
if count < 10:
output += "<" + str(count) + "> "
else:
output += "<" + str(count) + ">"

output += "\n"
output += border

if linux == 1:
os.system("clear")
print(output)

return space_count

# used to park a vehicle within the lot


def enter_vehicle(v_type, plate, row, space):
global spaces, avail_spaces, total_spaces, rows

# do not allow a user to park a vehicle with a full lot


if avail_spaces == 0:
display_lot()
print("Error: No Available Spaces")
time.sleep(2)
return

# check if a specified space is already occupied


if spaces[(int(row) * space_count) + int(space)].is_available():
display_space_selection(row)
print("Error: Vehicle Already In Space")
time.sleep(2)
return -1

# check if specified plate number is in the lot


for uniq in spaces:
if uniq.is_available():
if uniq.vehicle_info().get_plate() == plate:
display_lot()
print("Error: Vehicle Already In Lot")
time.sleep(2)
return

# add a valid vehicle to the specified space and show the time of entry
new_vehicle = Vehicle(v_type, plate)
spaces[(int(row) * space_count) + int(space)].add_vehicle(new_vehicle)
avail_spaces -= 1
display_lot()
print("Vehicle Added to Lot!\n"
"Time Entered: " + str(time.strftime('%I:%M %p',
time.localtime(new_vehicle.get_entry_time()))))
time.sleep(2)

return new_vehicle

# used to calculate the fare of a vehicle


def fare_calculation(vehicle):
# calculate the number of seconds which have passed since a vehicle was entered into the
system
# if less than one hour has passed, then a minimum fare of one hour is priced
total_time = time.time() - vehicle.get_entry_time()
if total_time < 3600:
hours = 1
else:
hours = int(total_time / 3600)+1

# calculate fare based on vehicle type


if vehicle.get_type() == 1:
rate = hours * 3.50
elif vehicle.get_type() == 2:
rate = hours * 4.50
else:
rate = hours * 2.00

ret = "Vehicle Removed!\n" \


"Your Total for " + "{:.2f}".format(hours) + " hours is $" + "{:.2f}".format(rate)

return ret
# used to removed a vehicle from the lot
def exit_lot(row, space):
global avail_spaces

# check if a specified space is occupied


if not spaces[(int(row) * space_count) + int(space)].is_available():
display_space_selection(row)
print("Error: No Vehicle In Space")
time.sleep(2)
return

# if the specified plate number is found within the lot, the vehicle is removed
removed = spaces[(int(row) * space_count) + int(space)].remove_vehicle()
avail_spaces += 1

# calculate fare if a vehicle is removed


display_lot()
print(fare_calculation(removed))
time.sleep(2)

# used to view a currently parked vehicle's information


def view_vehicle(row, space):

# check if a specified space is occupied


if not spaces[(int(row) * space_count) + int(space)].is_available():
display_space_selection(row)
print("Error: No Vehicle In Space")
time.sleep(2)

# collect vehicle information and display to user


else:
vehicle = spaces[(int(row) * space_count) + int(space)].vehicle_info()
display_space_selection(row)
input("Vehicle Type: " + vehicle.get_type_string() + "\n"
"Plate Number: " + vehicle.get_plate() + "\n"
"Entry Time: " + str(
time.strftime('%m-%d-%Y %I:%M %p',
time.localtime(vehicle.get_entry_time()))) + "\n"
"\nPress Enter to return to menu")

# handles user commands as determined in main


def command_handler(command):
# command to park a car
if command == "P":
while True:
display_lot()
new_type = input("Enter Vehicle Type:\n"
"1. Car\n"
"2. Truck\n"
"3. Motorcycle\n"
">")
if new_type == "1" or new_type == "2" or new_type == "3":
break

# program will accept any valid string as a plate number


display_lot()
new_plate = input("Enter New Vehicle Plate Number:\n"
">")

# allow user to select the space they want to park in


# while loop is in case the user selects a spot which already has a vehicle
# or if the user inputs a plate number that has already been added
ret_val = -1
while ret_val == -1:
while True:
display_row_selection()
row = input("Select Row to Park In:\n"
">")
if row.isnumeric():
if int(row) < rows:
break
while True:
display_space_selection(row)
space = input("Select Space to Park In:\n"
">")
if space.isnumeric():
if int(space) < space_count:
break
ret_val = enter_vehicle(int(new_type), new_plate, row, space)

# command for exiting the lot


elif command == "E":

# user can specify a row and space within the lot, if a selected space is occupied,
# vehicle information is returned
while True:
display_row_selection()
row = input("Select Row of Vehicle:\n"
">")
if row.isnumeric():
if int(row) < rows:
break

while True:
display_space_selection(row)
space = input("Select Space of Vehicle:\n"
">")
if space.isnumeric():
if int(space) < space_count:
break
# program will check for vehicle plate within system and remove if found, returns error if
no plate found
exit_lot(row, space)

# command for viewing a vehicle's information


elif command == "V":

# user can specify a row and space within the lot, if a selected space is occupied,
# vehicle information is returned
while True:
display_row_selection()
row = input("Select Row to View:\n"
">")
if row.isnumeric():
if int(row) < rows:
break

while True:
display_space_selection(row)
space = input("Select Space to View:\n"
">")
if space.isnumeric():
if int(space) < space_count:
break
view_vehicle(row, space)

# display current parking lot rates


elif command == "R":
display_lot()
input("Current Parking Rates:\n"
"Cars - $3.50/hour\n"
"Trucks - $4.50/hour\n"
"Motorcycles - $2.00/hour\n"
"\nPress Enter to return to menu")

# return if the quit command is given


elif command == "Q":
return

# display an error if an invalid command is given


else:
display_lot()
print("Error: Invalid Command")
time.sleep(1)

# read config file to determine lot size and enable features


def read_config():
global spaces, total_spaces, avail_spaces, rows, linux, space_count, border

config = open('config.txt', 'r')


while True:
line = config.readline()

if line.find("total_spaces") != -1:
total_spaces = int(line[13:16])
avail_spaces = total_spaces

elif line.find("rows") != -1:


rows = int(line[5:7])

# enables static interface on linux machines


elif line.find("linux") != -1:
linux = int(line[6:7])

# if demo mode is enabled, populate lot with demo cars, otherwise, populate lot based on
config
elif line.find("demo_mode") != -1:
if int(line[10:11]) == 1:
demo_mode()
break
else:
for i in range(total_spaces):
spaces.append(Space())

# calculate the number of spaces within a row


space_count = int(total_spaces / rows)

# generate the interface border


border = "|"
for i in range(space_count - 1):
for j in range(4):
border += "-"
border += "---|\n"
break

config.close()

def demo_mode():
global spaces, total_spaces, avail_spaces, rows, space_count, border

for i in range(total_spaces):
spaces.append(Space())

total_spaces = 20
avail_spaces = 20
rows = 4

# calculate the number of spaces within a row


space_count = int(total_spaces / rows)

# generate the interface border


border = "|"
for i in range(space_count - 1):
for j in range(4):
border += "-"
border += "---|\n"

v1 = enter_vehicle(1, "aaa-bbbb", 0, 3)
v2 = enter_vehicle(3, "ccc-dddd", 1, 2)
v3 = enter_vehicle(2, "eee-ffff", 2, 0)
v4 = enter_vehicle(1, "ggg-hhhh", 3, 1)
v5 = enter_vehicle(2, "iii-jjjj", 2, 4)

# custom epoch times


v1.set_entry_time(1620561600)
v2.set_entry_time(1620570600)
v3.set_entry_time(1620577800)
v4.set_entry_time(1620576000)
v5.set_entry_time(1620586800)

def main():

# read config file


read_config()
# begin accepting user commands
command = ""
while command != "Q":
display_lot()
print("Please Select An Option:\n"
"P - Park a Vehicle\n"
"E - Exit the Lot\n"
"V - View a Parked Vehicle\n"
"R - Display Vehicle Rates\n"
"Q - Quit Application\n")

command = input(">")
command_handler(command)

if name == ' main ':


main()
Output:

Result:

Thus the output of the program is successfully verified.

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