CP5292 Internet of Things
CP5292 Internet of Things
BONAFIDE CERTIFICATE
NAME :
YEAR/SEM :
BRANCH :
REGISTER NO :
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.
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:
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.
To install the Python library open a terminal and execute the following
With the library installed now open your favorite Python IDE (I recommend Thonny Python IDE
more information about using it here).
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.
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:
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 time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(17, GPIO.OUT)
GPIO.setup(18, GPIO.INPUT)
try:
while True:
if GPIO.input (18) == 0:
if GPIO.input (18) == 1:
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)
GPIO.setup(18, GPIO.INPUT)
ledstate = 0
try:
while True:
ledstate = 1
time.sleep (0.5)
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.
GPIO.setmode(GPIO.BOARD)
GPIO.setup(17, GPIO.OUT)
GPIO.setup(18, GPIO.INPUT)
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:
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.
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.
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.
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.
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:
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
Specification:
Arduino compares the signal and triggers the SIM800L in case of fire incidents. Through AT
commands, SIM800L communicates with thingspeak server.
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.
First, go to https://thingspeak.com/ and create a new free Mathworks account if you don’t have a
Mathworks account before.
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”.
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.
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.
Code
#include <SoftwareSerial.h>
#include <String.h>
int flag = 0;
void setup()
pinMode(9, OUTPUT);
pinMode(12, INPUT);
Module_Init();
void loop()
if (gprsSerial.available())
Serial.write(gprsSerial.read());
if (fire == 0)
digitalWrite(9, HIGH);
delay(6000);
ShowSerialData();
delay(4000);
ShowSerialData();
Result:
Aim:
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.
mkdir /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
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>
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);
Serial.println(“”);
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
}
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.
# 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:
Aim:
To Develop an application for smart Parking application using python and Django for
web application
Program Coding:
# 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()
def get_plate(self):
return self.plate
def get_entry_time(self):
return self.entry_time
def get_vehicle(self):
return self.type, self.plate, self.entry_time
# 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
output += border
output += border
# display all spaces with row selection numbers for user to choose from
def display_row_selection():
global spaces, avail_spaces, total_spaces, rows
output += border
for row in range(rows):
output += print_row(row)
output += " <" + str(row) + ">\n"
output += border
output += border
output += print_row(int(row)) + "\n"
output += "\n"
output += border
if linux == 1:
os.system("clear")
print(output)
return space_count
# 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
return ret
# used to removed a vehicle from the lot
def exit_lot(row, space):
global avail_spaces
# 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
# 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)
# 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)
if line.find("total_spaces") != -1:
total_spaces = int(line[13:16])
avail_spaces = total_spaces
# 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())
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
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)
def main():
command = input(">")
command_handler(command)
Result: