0% found this document useful (0 votes)
49 views51 pages

IOT Lab Manual Version 1.2

Uploaded by

vikycharu
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)
49 views51 pages

IOT Lab Manual Version 1.2

Uploaded by

vikycharu
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/ 51

GOVERNMENT COLLEGE OF TECHNOLOGY

(An Autonomous Institution Affiliated to Anna University)

COIMBATORE - 13.

DEPARTMENT OF INFORMATION TECHNOLOGY

IOT LABORATORY MANUAL


INDEX

EX.NO NAME OF THE EXPERIMENT PAGE NO

1 STUDY OF ARDUINO 1

2 STUDY OF RASPBERRY PI 8

3 INTERFACING WITH PIR SENSOR 14

4 INTERFACING WITH LIGHT SENSOR 15

5 IMPLEMENTATION OF BUZZER 17

6 DISPLAYING TEXT MESSAGE IN OLED 19

7 IMPLEMENTATION OF TRAFFIC LIGHTS IN LED 21

8 INTERFACING WITH IR SENSOR 24

9 IMPLEMENTATION OF VIBRATION SENSOR 26

10 INTERFACING WITH SOIL MOISTURE SENSOR 28

11 INTERFACING WITH RAIN SENSOR 30

12 IMPLEMENTATION OF TCP (MQTT) 32

13 IMPLEMENTATION OF UDP 36

14 INTERFACING BLUETOOTH MODULE 38

15 UPLOADING IOT DATA TO CLOUD 42


1

1. STUDY OF ARDUINO
AIM :
To study the basic components of Arduino and its advantages.

ARDUINO :
Arduino is an open-source platform used for building electronics projects.
Arduino consists of both a physical programmable circuit board (often referred to as a
microcontroller) and a piece of software, or IDE (Integrated Development
Environment) that runs on your computer, used to write and upload computer code to
the physical board.

ARDUINO UNO SYSTEM OVERVIEW :


Before we can understand the UNO's hardware, we must have a general
overview of the system first.
After your code is compiled using Arduino IDE, it should be uploaded to the
main micro controller of the Arduino UNO using a USB connection. Because the main
microcontroller doesn’t have a USB transceiver, you need a bridge to convert signals
between the serial interface (UART interface) of the micro controller and the host
USB signals.
The bridge in the latest revision is the ATmega16U2, which has a USB
transceiver and also a serial interface (UART interface).
To power your Arduino board, you can use the USB as a power source. Another
option is to use a DC jack. You may ask, “if I connect both a DC adapter and the USB,
which will be the power source?” The answer will be discussed in the “Power Part”
section from this article.
To reset your board, you should use a push button in the board. Another source
of reset should be every time you open the serial monitor from Arduino IDE.

THE MICROCONTROLLER :
It is important to understand that the Arduino board includes a microcontroller,
and this microcontroller is what executes the instructions in your program. If you
know this, you won't use the common nonsense phrase "Arduino is a microcontroller"
ever again.
2

The ATmega328 microcontroller is the MCU used in Arduino UNO R3 as a main


controller. ATmega328 is an MCU from the AVR family; it is an 8-bit device, which
means that its data-bus architecture and internal registers are designed to handle 8
parallel data signals.
ATmega328 has three types of memory:

• FLASH MEMORY : 32KB nonvolatile memory. This is used for storing


application, which explains why you don't need to upload your application every
time you unplug arduino from its power source.
• SRAM MEMORY : 2KB volatile memory. This is used for storing variables used
by the application while it is running.
• EEPROM MEMORY : 1KB nonvolatile memory. This can be used to store data
that must be available even after the board is powered down and then powered
up again.

PACKAGES :
This MCU is a DIP-28 package, which means that it has 28 pins in the dual in-line
package. These pins include power and I/O pins. Most of the pins are multi functional,
which means that the same pin can be used in different modes based on how you
configure it in the software. This reduces the necessary pin count, because the
microcontroller does not require a separate pin for every function. It can also make
your design more flexible, because one I/O connection can provide multiple types of
functionality.
Other packages of ATmega328 are available like TQFP-32 SMD package (Surface
Mount Device)

POWER :
The MCU accepts supply voltages from 1.8 to 5.5 V. However, there are restrictions on
the operating frequency; for example, if you want to use the maximum clock
frequency (20 MHz), you need a supply voltage of at least 4.5 V.
3

DIGITAL I/O :
This MCU has three ports: PORTC, PORTB, and PORTD. All pins of these ports can be
used for general-purpose digital I/O or for the alternate functions indicated in the pin
out below. For example, PORTC pin0 to pin5 can be ADC inputs instead of digital I/O.

ATmega168 pin out with Arduino labels; the ATmega168 and ATmega328 are pin compatible. Image
courtesy of Arduino.

Arduino UNO R3 pin out. Image courtesy of GitHub.


4

ADC INPUTS :
This MCU has six channels—PORTC0 to PORTC5—with 10-bit resolution A/D
converter. These pins are connected to the analog header on the Arduino board.
One common mistake is to conceive analog input as dedicated input for A/D function
only, as the header in the board states ”Analog”. The reality is that you can use them
as digital I/O or A/D.
As shown in the diagram above (via the red traces), the pins related to the A/D unit
are:
• AVCC: The power pin for the A/D unit.
• AREF: The input pin used optionally if you want to use an external voltage
reference for ADC rather than the internal Vref. You can configure that using an
internal register.

Internal register settings for selecting the Vref source.

UART PERIPHERAL :
A UART (Universal Asynchronous Receiver/Transmitter) is a serial interface. The
ATmega328 has only one UART module.
The pins (RX, TX) of the UART are connected to a USB-to-UART converter circuit and
also connected to pin0 and pin1 in the digital header. You must avoid using the UART
if you’re already using it to send/receive data over USB.

SPI PERIPHERAL :
The SPI (Serial Peripheral Interface) is another serial interface. The ATmega328 has
only one SPI module.
5

Besides using it as a serial interface, it can also be used to program the MCU using a
standalone programmer. You can reach the SPI's pins from the header next to the
MCU in the Arduino UNO board or from the digital header as below:
11<->MOSI
12<->MISO
13<→SCK

TWI :
The I2C or Two Wire Interface is an interface consisting of only two wires, serial data,
and a serial clock: SDA, SCL.
You can reach these pins from the last two pins in the digital header or pin4 and pin5
in the analog header.
Returning to the electronic design, the microcontroller section has the following:

• ATmega328-PU : The MCU we just talked about.


• IOL and IOH (Digital) Headers : These headers are the digital header for
pins 0 to 13 in addition to GND, AREF, SDA, and SCL. Note that RX and TX from
the USB bridge are connected with pin0 and pin1.
• AD Header : The analog pins header.
• 16 MHz Ceramic Resonator (CSTCE16M0V53-R0) : Connected with
XTAL2 and XTAL1 from the MCU.
• Reset Pin : This is pulled up with a 10K resistor to help prevent spurious
resets in noisy environments; the pin has an internal pull-up resistor, but
according to the AVR Hardware Design Considerations application note
(AVR042), “if the environment is noisy, it can be insufficient and reset may
occur sporadically.” Reset occurs if the user presses the reset button or if a
reset is issued from the USB bridge. You can also see the D2 diode. The role of
this diode is described in the same app note: “If not using High Voltage
Programming it is recommended to add an ESD protection diode from RESET to
Vcc, since this is not internally provided due to High Voltage Programming”.
• C4 and C6 100nF Capacitors : These are added to filter supply noise. The
impedance of a capacitor decreases with frequency:
Xc= 12πfC
• The capacitors give high-frequency noise signals a low-impedance path to
ground. 100nF is the most common value.
• PIN13 : This is connected to the SCK pin from the MCU and is also connected
to an LED. The Arduino board uses a buffer (the LMV358) to drive the LED.
• ICSP (In-Circuit Serial Programming) Header : This is used to program
the ATmega328 using an external programmer. It’s connected to the In-System
6

Programming (ISP) interface (which uses the SPI pins). Usually, you don’t need
to use this way of programming because boot loader handles the programming
of the MCU from the UART interface which is connected using a bridge to the
USB. This header is used when you need to flash the MCU, for example, with a
boot loader for the first time in production.

THE USB-to-UART BRIDGE :


As we discussed in the “Arduino UNO System Overview” section, the role of the
USB-to-UART bridge part is to convert the signals of USB interface to the UART
interface, which the ATmega328 understands, using an ATmega16U2 with an internal
USB transceiver. This is done using special firmware uploaded to the ATmega16U2.
From an electronic design perspective, this section is similar to the
microcontroller section. This MCU has an ICSP header, an external crystal with load
capacitors (CL), and a Vcc filter capacitor.

THE POWER :
For a power source, you have the option of using the USB or a DC jack. Now it’s
time to answer the following question: “If I connect both a DC adapter and the USB,
which will be the power source?”
The 5V regulator is the NCP1117ST50T3G and the Vin of this regulator is
connected via DC jack input through the M7 diode, the SMD version of the famous
1N4007 diode (PDF). This diode provides reverse-polarity protection.
The output of the 5V regulator is connected to the rest of 5V net in the circuit
and also to the input of the 3.3V regulator, LP2985-33DBVR. You can access 5V
directly from the power header 5V pin.
Another source of 5V is USBVCC which is connected to the drain of an FDN340P,
a P-channel MOSFET, and the source is connected to the 5V net. The gate of the
transistor is connected to the output of an LMV358 op-amp used as a comparator. The
comparison is between 3V3 and Vin/2. When Vin/2 is larger, this will produce a high
output from the comparator and the P-channel MOSFET is off. If there is no Vin
applied, the V+ of the comparator is pulled down to GND and Vout is low, such that
the transistor is on and the USBVCC is connected to 5V.
The LP2985-33DBVR is the 3V3 regulator. Both the 3V3 and 5V regulators are
LDO (Low Dropout), which means that they can regulate voltage even if the input
voltage is close to the output voltage. This is an improvement over older linear
regulators, such as the 7805.
7

As mentioned above, VIN from a DC jack is protected from reverse polarity by


using a serial M7 diode in the input. Be aware that the VIN pin in the power header is
not protected. This is because it is connected after the M7 diode. Personally, I don’t
know why they decided to do that when they could connect it before the diode to
provide the same protection.
When you use USB as a power source, and to provide protection for your USB
port, there is a PTC (positive temperature coefficient) fuse (MF-MSMF050-2) in series
with the USBVCC. This provides protection from over current, 500mA. When an over
current limit is reached, the PTC resistance increases a lot. Resistance decreases after
the over current is removed.

ADVANTAGES :
• INEXPENSIVE - Arduino boards are relatively inexpensive compared to other
microcontroller platforms. The least expensive version of the Arduino module
can be assembled by hand, and even the pre-assembled Arduino modules cost
less than $50

• CROSS - PLATFORM - The Arduino Software (IDE) runs on Windows,


Macintosh OSX, and Linux operating systems. Most microcontroller systems are
limited to Windows.
• Simple, clear programming environment - The Arduino Software (IDE)
is easy-to-use for beginners, yet flexible enough for advanced users to take
advantage of as well. For teachers, it's conveniently based on the Processing
programming environment, so students learning to program in that
environment will be familiar with how the Arduino IDE works.
• Open source and extensible software - The Arduino software is
published as open source tools, available for extension by experienced
programmers. The language can be expanded through C++ libraries, and people
wanting to understand the technical details can make the leap from Arduino to
the AVR C programming language on which it's based. Similarly, you can add
AVR-C code directly into your Arduino programs if you want to.
• Open source and extensible hardware - The plans of the Arduino
boards are published under a Creative Commons license, so experienced circuit
designers can make their own version of the module, extending it and
improving it. Even relatively inexperienced users can build the breadboard
version of the module in order to understand how it works and save money.

RESULT :
Thus the Arduino and its basic components are successfully studied.
8

2. STUDY OF RASPBERRY-PI
AIM :
To study about raspberry pi

DEFINITION :
The Raspberry pi is a low cast,credit-card sized computer that plugs
into a computer monitor or TV,and uses a standard keyboard and mouse.
It is a capable little device that enables people of all ages to explore
computing and to learn how to program. ETS IoT kit is an all-in-one
prototyping platform for sensor based IoT projects.

HARDWARE SPECIFICATION :
1. CPU: 4× ARM Cortex-A53, 1.2GHz.
2. GPU: Broadcom VideoCore IV.
3. RAM: 1GB LPDDR2 ( 900 MHz ).
4. Communication Interfaces : Ethernet , Bluetooth.
5. Inertial Sensors : Accelerometer , Gyroscope.
6. Environmental sensors : Temperature , Humidity , Pressure.
7. User interfaces : 3x3 channel relay , 3 RGB LED , 2 Push button ,
Buzzer , OLED display.
8. Ports : HDMI , 4 USB 2.0 port , Micro SD card , power supply , 8
Analog I/O , UART , SPI , I2C , 31 GPIOs , 3.5mm analog audio-video
jack , 5x5V port , 3x3.3V port.

INTERNAL PIN CONFIGURATION :

1. for LCD : pin 0 – pin 8


2. for switch : pin 9 and pin 10
3. for buzzer : pin 11
4. for relay : pin 36 , pin 38 , pin 40
9

OS FOR RASPBERRY PI:


1. Raspbian OS : General purpose OS. (used in this lab)
2. Linutop : secure Rasbian based web kisok, best for
deploy public internet stalls.
3. Lakka : Best interface , Best for gamer.
4. Windows IOT Core : Windows 10 itself perform Raspberry pi.
5. Ubuntu Core : Linux itself perform Raspberry pi.

APPLICATION EXAMPLES :
1. ETS IoT KIT has 3 RGB LEDs which has been connected to raspberry
pi through MCP23017.

2. ETS IoT KIT has 2 PUSH BUTTON which has been connected to
raspberry pi through MCP23017.
10

3. ETS IoT KIT has a BUZZER which has been connected to raspberry pi
through MCP23017.

4. ETS IoT KIT has 3 RELAY which has been connected to raspberry pi.
11

5. ETS IoT KIT has an OLED DISPLAY which has been connected to
raspberry pi through I2C address 0x3C
12

RASPBERRY PI 3 MODEL-B :

PIN CONFIGURATION :
13

EXTERNAL PINS :
1. ANALOG INPUTS: Pin A0 – A7.
2. RPI GPIO : RPIO is an advanced GPIO ( General Purpose Input
Output ) module for the Raspberry Pi . Pins are RPI07 , RPI11 ,
RPI12 , RPI13 , RPI15 , RPI16 , RPI18 , RPI22 , RPI29 , RPI37 ,
RPI35.
3. UART : Universal Asynchronous Receiver Transmitter is an
asynchronous serial communication protocol, meaning that it
takes bytes of data and transmits the individual bits in a
sequential fashion. Pins are GND , TXD , RXD , 5V.
4. SPI : The Serial Peripheral Interface is a communication
protocol used to transfer data between micro-computers like
the Raspberry Pi and peripheral devices. Pins are MOSI
( Master Out Slave In ) , MISO ( Master In Slave Out ) , CE0
( clk ) , CE1 ( Gnd ).
5. I2C : Inter Integrated Circuit bus allows multiple devices to be
connected to your Raspberry Pi . Pins are SDA ( Serial Data
Line ) , SCL ( Serial Clock Line ).
6. MCP GPIO : MCP230xx GPIO .Pins are GPA0 – GPA7 , GPB0 –
GPB7 , M0GPB4 – M0GPB7.

RESULT :
Thus the study of RASPBERRY PI has been completed.
14

3. INTERFACING WITH PIR SENSOR


AIM :
To detect the motion of objects using PIR sensor.

PROCEDURE :
1. Include necessary RPi.GPIO as GPIO , time packages.
2. Using GPIO.setwarnings(False) function disable warnings.
3. Using the functions GET.setmode()for specify a number-system and GET.setup()
for setting the pin mode.
4. Set 16th pin as input and 18th pin as output using GET.setup().
5. If 16th pin is true,
Print intruder is detected and turn on the LED.
6. Else if 16th pin is false,
Print intruder is not detected and turn off the LED.
7. Stop the execution.

PROGRAM :
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.IN) #Read output from PIR motion sensor
GPIO.setup(18, GPIO.OUT) #LED output pin
while True:
i=GPIO.input(16)

if i==0: #When output from motion sensor is LOW


print "No intruders",i
GPIO.output(18, 0) #Turn OFF LED/Buzzzer
time.sleep(0.1)
elif i==1: #When output from motion sensor is HIGH
print "Intruder detected",i
GPIO.output(18, 1) #Turn ON LED/Buzzer
time.sleep(0.1)
15

OUTPUT :

No intruders
Intruder detected
No intruders
Intruder detected

RESULT :
Thus implementing the PIR sensor is executed successfully.
16

4. INTERFACING WITH LIGHT SENSOR

AIM :
To detect the brightness using light sensor.

PROCEDURE :
1.Connect VCC pin of IR with Rpi2 in Raspberry pi.
2.Connect GND pin of IR with Rpi6 in Raspberry pi.
3.Connect D0 pin of IR with Rpi11 in Raspberry pi.
4.Run the source code to detect the brightness using light sensor.

ALGORITHM :
1.Import RPi.GPIO and time packages.
2.Set mode as GPIO.BOARD using setmode() function.
3.Set RPi11 as GPIO.IN using setup() function.
4.Get input from LIGHT sensor using input() function.
5.If it is true,then print TRUE else print FALSE.

PROGRAM :
#import the packages
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
#get input from 11 th pin
17

GPIO.setup(11,GPIO.IN)
while(1):
print GPIO.input(11)
if i==1:
print "TRUE"
time.sleep(1)
elif i==0:
print “FALSE"
time.sleep(1)

OUTPUT:

TRUE
FALSE
TRUE
TRUE

RESULT :
Thus to detect the brightness using Light sensor has been
performed.
18

5. IMPLEMENTATION OF BUZZER

AIM :
To implement the alert for the reach of maximum number in input using Buzzer.

PROCEDURE :
1) Include all necessary modules including sys and time.
2) Include the packages from the system path.
3) Configure the Pin no.11 for Buzzer output.
4) Get the input from the user and store it in n.
5) Check whether the value of n is less than or equal to 10,
i) If it is true, print the n value.
ii) or else, print "OOPS!! you entered the wrong number" and activate
the buzzer by giving PIN as 11 and setting the state as 1.
6) Stop the execution

PROGRAM :
#mcp23017 library path
import sys
sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code-
legacy/Adafruit_MCP230xx')
from Adafruit_MCP230XX import Adafruit_MCP230XX
import time
#mcp IC configuration
mcp = Adafruit_MCP230XX(busnum = 1, address = 0x20, num_gpios = 16) # MCP23017
#mcp input/output configuration
mcp.config(11, mcp.OUTPUT)
while True:
n=input("Enter a number")
if (n>=0 and n<=10):
print("You have entered:\t",n)
19

else:
print("OOPS!! Your input is wrong")
mcp.output(11, 1)
time.sleep(3)
mcp.output(11, 0)

OUTPUT :

Enter a number : 9
You have entered 9
Enter a number : 11
OOPS!! Your input is wrong

RESULT :
Thus the implement of alert for the reach of maximum number in input using
Buzzer was executed and verified.
20

6. DISPLAYING TEXT MESSAGE IN OLED


AIM :
To display text message in OLED in raspberry pi .

PROCEDURE :
1. Include the header files of time, Adafruit_SSD1306, PIL.
2. Declare the required pin configuration(pin 24).*
3. Change the i2C address by passing an i2c_address parameter.
4. Create blank image for drawing with mode 1 for 1-bit color.
5. Align the image by using padding.
6. Set the font.
7. Finally display the image.

PROGRAM :
#Header files
import time
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
#Pin configuration
RST = 24
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)
#Display
disp.begin()
disp.clear()
disp.display()
width = disp.width
21

height = disp.height
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
draw.rectangle((0,0,width,height), outline=0, fill=0)
padding = 20
top = padding
x = padding
font = ImageFont.load_default()
draw.text((x, top), ‘Hello World’ , font=font, fill=1)
disp.image(image)
disp.display()
time.sleep(10)

OUTPUT :

Hello World

Drawing 1: OLED Display

RESULT :
Thus the display the text message in OLED in raspberry pi has been
successfully executed and verified.
22

7. IMPLEMENTATION OF TRAFFIC LIGHTS IN LED

AIM :
To implement the alert for the reach of maximum number in input using Buzzer.

PROCEDURE :
1) Include the necessary modules including sys and time.
2) Include the packages from the system path.
3) Configure IC MCP23017 for LED.
4) Configure three LED's by configuring pins starting from 0 to 8.
5) Get the input of the color and store it in the variable called n.
6) Check whether the value of n is equal to Red if it is true,
i) Set the output pin 6 as True.
7) If n is not equal to Red, check whether the value of n is equal to Yellow, if it is
true,
i) Set the output pin 0,4,5,6 as True.
8) If n is not equal to both red and Yellow, check whether the value of n is equal
to Green, if it is true,
i) Set the output pin 1,3,6 as True.
9) Set corresponding pins as False in regular interval of time by using sleep
function.
10) Stop the execution.

PROGRAM :
#mcp23017 library path
import sys
sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code-
legacy/Adafruit_MCP230xx')
23

from Adafruit_MCP230XX import Adafruit_MCP230XX


import time

#mcp IC configuration
mcp = Adafruit_MCP230XX(busnum = 1, address = 0x20, num_gpios = 16) # MCP23017

#mcp input/output configuration


mcp.config(0, mcp.OUTPUT)
mcp.config(1, mcp.OUTPUT)
mcp.config(2, mcp.OUTPUT)
mcp.config(3, mcp.OUTPUT)
mcp.config(4, mcp.OUTPUT)
mcp.config(5, mcp.OUTPUT)
mcp.config(6, mcp.OUTPUT)
mcp.config(7, mcp.OUTPUT)
mcp.config(8, mcp.OUTPUT)
while True:
n=raw_input("Enter color\t")
if n=='Red':
mcp.output(6, 1)
time.sleep(5)
mcp.output(6, 0)
elif n=='Yellow':
mcp.output(0, 1)
mcp.output(4, 1)
mcp.output(5, 1)
mcp.output(6, 1)
24

time.sleep(5)
mcp.output(0, 0)
mcp.output(4, 0)
mcp.output(5, 0)
mcp.output(6, 0)
elif n=='Green':
mcp.output(1, 1)
mcp.output(3, 1)
mcp.output(6, 1)
time.sleep(5)
mcp.output(1, 0)
mcp.output(3, 0)
mcp.output(6, 0)
else:
print("Incorrect Signal Color")

OUTPUT :
Enter color : Red Enter color : Green

Enter color : Yellow

RESULT :
Thus the Demonstration of Traffic lights in LED was implemented and executed
successfully.
25

8. INTERFACING WITH IR SENSOR


AIM :
To detect the presence of any obstacle in front of the sensor module
using IR sensor.

PROCEDURE :
1. Connect VCC pin of IR with Rpi2 in Raspberry pi.
2. Connect GND pin of IR with Rpi6 in Raspberry pi.
3. Connect D0 pin of IR with Rpi11 in Raspberry pi.
4. Run the source code to Identify the obstacle using IR Sensor.

ALGORITHM :
1. Import RPi.GPIO and time packages.
2. Set mode as GPIO.BOARD using setmode() function.
3. Set RPi11 as GPIO.IN using setup() function.
4. Get input from IR sensor using input() function.
5. If it is true,then print obstacle not detected else print obstacle
detected.

PROGRAM :
#import the packages
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
26

#get input from 11 th pin


GPIO.setup(11,GPIO.IN)
while (True):
i=GPIO.input(11)
if i==1:
print "Obstacle not detected"
time.sleep(1)
elif i==0:
print "Obstacle detected"
time.sleep(1)

OUTPUT :

Obstacle detected…..
Obstacle not detected…..

RESULT :
Thus to detect the presence of any obstacle infront of the sensor
module using IR sensor has been performed.
27

9. IMPLEMENTATION OF VIBRATION SENSOR


AIM :
To detect the vibration using vibration sensor.

PROCEDURE :
1. Include necessary RPi.GPIO as GPIO , time packages.
2. Configure channel 17 pin for interfacing vibration sensor to detect the
vibration.
3. Using the functions GET.setmode()for specify a number-system and GET.setup()
for setting the pin mode.
4. Creating a function def_callback() for detecting a vibration in sensor.

i)if vibration is detected


print movement detected
ii)else
print movement not detected.

5. Call the functions GPIO.add_event_detect(),GPIO.add_event_callback() for


returning values to the function def_callback.

6. Stop the execution

PROGRAM :
import RPi.GPIO as GPIO
import time
channel=17
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel,GPIO.IN)
def callback(channel):
if GPIO.input(channel):
print"Movement detected!"
else:
print"Movement not detected!"
GPIO.add_event_detect(channel,GPIO.BOTH,bouncetime=300)
GPIO.add_event_callback(channel,callback)
while True:
time.sleep(1)
28

OUTPUT :

Movement detected!
Movement not detected…..

RESULT :
Thus implementing the vibration sensor is executed successfully.
29

10. INTERFACING WITH SOIL MOISTURE SENSOR


AIM :
To check the moisture in the soil using soil moisture sensor.

PROCEDURE :
1. Include the necessary modules spidev and time.
2. Import Spidev function from Spidev module.
3. Assign the function to a object spi.
4. Create a new function Readchannel and return the data by
calculating data= ((adc[1]&3) << 8) + adc[2]
5. Create a new function ConvertVolts and convert the data into volts.
6. Call the Readchannel function by passing the moisture_channel as
argument and store the return data in moisture_level.
7. Call the ConvertVolts function by passing moisture_level as
arguments and store the returned data in moisture_volts.
8. Print the moisture_level and moisture_volts data.
PROGRAM :
import spidev
import time
spi = spidev.SpiDev()
spi.open(0,0)
def ReadChannel(channel):
adc = spi.xfer2([1,(8+channel)<<4,0])
data= ((adc[1]&3) << 8) + adc[2]
return data
def ConvertVolts(data,places):
30

volts = (data * 3.3) / float(1023)


volts = round(volts,places)
return volts
moisture_channel = 0 ##connect with A0
delay = 5

while True:
moisture_level = ReadChannel(moisture_channel)
moisture_volts = ConvertVolts(moisture_level,2)
print "____________________________________________"
print ("Moisture: {} ({}V)".format(moisture_level,moisture_volts))
time.sleep(delay)

OUTPUT :

Moisture: 5 0.10V
Moisture: 2 0.01V

RESULT :
Thus the soil moisture was successfully interfered and executed
using soil moisture sensor.
31

11. INTERFACING WITH RAIN SENSOR

AIM :
To detect the presence of rain in the sensor plate using the Rain
sensor.

PROCEDURE :
1.Connect VCC pin of IR with Rpi2 in Raspberry pi.
2.Connect GND pin of IR with Rpi6 in Raspberry pi.
3.Connect D0 pin of IR with Rpi11 in Raspberry pi.
4.Run the source code to Identify the obstacle using IR Sensor.

ALGORITHM :
1. Import RPi.GPIO and time packages.
2. Set mode as GPIO.BOARD using setmode() function.
3. Set RPi11 as GPIO.IN using setup() function.
4. Get input from IR sensor using input() function.
5. If it is true,then print obstacle not detected else print obstacle
detected.

PROGRAM :
#import the packages
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
32

GPIO.setmode(GPIO.BOARD)
#get input from 11 th pin
GPIO.setup(11,GPIO.IN)
while (True):
i=GPIO.input(11)
if i==1:
print "Rain not detected"
time.sleep(1)
elif i==0:
print "Rain detected"
time.sleep(1)

OUTPUT :

Rain detected…..
Rain not detected…..

RESULT :
Thus to detect the presence of Rain in the sensor plate module using
Rain sensor has been performed.
33

12. IMPLEMENTATION OF TCP (MQTT)


AIM :
To transfer the messages using MQTT-TCP protocol.

PROCEDURE :
1. Install MQTT Dashboard app from google playstore
2. Establish the network connection between mobile and pc by
hotspot.
3. Enter into the app and create the connection by using client
ID(IP Address of pc),Server(test.mosquito.org) and port.
4. Make subscription by giving topic.
5. Run the program to start the MQTT.
6. Go to publish option and type any text to transfer then publish
it.
7. Your text message will be displayed in PC.

ALGORITHM :
1. include the header file paho.mqtt.client.
2. Create the MQTT client and attach our routine(on_connect,
on_message).
• On_connection routine is used to callback the
subscription.
• On_message routine is used to callback the publish
message.
3.Connect the client to the server using port number.
4.Run the loop as infinite.
34

PROGRAM:
#Header file
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from
the server.
def on_connect(client, userdata, flags, rc):
print("Connected with MQTT server... "+str(rc))
# Subscribing in on_connect() - if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("IoT")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
if msg.payload == "Hello":
print("Command Received do something")
# Create an MQTT client and attach our routines to it.
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("test.mosquitto.org", 1883, 60)
client.loop_forever()
35

OUTPUT:

APPLICATION PREVIEW

CREATING CONNECTION
36

DASH BOARD VIEW

Connected with MQTT server…..


IOT Hello
Command Received do something

OUTPUT IN TERMINAL

RESULT :
Thus the message had been transferred by using MQTT-TCP
Protocol.
37

13. IMPLEMENTATION OF UDP

AIM :
To interfacing LED and BUZZER using UDP.

PROCEDURE :
1. Include necessary sys ,time ,socket packages.
2. Configure 11th pin for interfacing the Buzzer and 0 to 9 pins for interfacing the
LED.
3. Get the IP address from the system and set as the UDP_IP address and set the
UDP port no=”5005”
4. Create a socket and bind the IP address.
5. Install UDP sender application on mobile then enter the IP address of the
system and port number.
6. Enter the data in application as sender.
7. Get the data from the sender and using if condition check whether the user
data and stored data.
i)If it is equal or same
Enable the LED pin 1,4,7 as true and print Login successful.
ii)If condition fails
Enable the LED pin 0,3,6 as true,BUZZER pin 11 as true and print Login failed.
8. Stop the execution

PROGRAM :
import sys
sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code-legacy/Adafruit_MCP230xx')
from Adafruit_MCP230XX import Adafruit_MCP230XX
import time
import socket
#mcp IC configuration
mcp = Adafruit_MCP230XX(busnum = 1, address = 0x20, num_gpios = 16) # MCP23017
#mcp input/output configuration
mcp.config(11, mcp.OUTPUT)
#mcp input/output configuration
mcp.config(0, mcp.OUTPUT)
mcp.config(1, mcp.OUTPUT)
mcp.config(3, mcp.OUTPUT)
mcp.config(4, mcp.OUTPUT)
mcp.config(6, mcp.OUTPUT)
38

mcp.config(7, mcp.OUTPUT)
UDP_IP = "192.168.43.38" #Reciever IP
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
print("Password for User")

data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes


if data=="admin":
print("Login sucessfully")
mcp.output(1, 1)
mcp.output(4,1)
mcp.output(7, 1)
time.sleep(5)
mcp.output(1, 0)
mcp.output(4, 0)
mcp.output(7,0)
time.sleep(1)
else:
print("login failed")
mcp.output(11,1)
mcp.output(0, 1)
mcp.output(3, 1)
mcp.output(6, 1)
time.sleep(5)
mcp.output(11,0)
mcp.output(0, 0)
mcp.output(3, 0)
mcp.output(6, 0)
time.sleep(1)

OUTPUT :
39

RESULT :
Thus interfacing LED and BUZZER using UDP is executed successfully.
40

14. INTERFACING BLUETOOTH MODULE

AIM :
To interfacing Bluetooth module for transferring message between
Pi3 Bluetooth Manager application and raspberry Pi kit.

PROCEDURE :
1. Install Pi3 Bluetooth Manager Application from google playstore in
Mobile phone.
2. You will need to install Blue manager in the Pi3: sudo apt-get install
bluetooth bluez blueman.
3. Pair you mobile device and the Pi3 using Bluetooth.
4. Run a terminal window on the Pi and get your MAC address: sudo
hciconfig.
5. Execute the script from the folder you saved it: sudo python
btpi3_receiver.py.
6. Now go back to the app main screen and select your Pi3 mac
address, you should be connected shortly to the Pi.
7. Enter data to send to the Pi3 either by typing or using voice
commands, once sent you will get the same data replied from the
pi.

ALGORITHM :
1. Import the “bluetooth” package.
2. Create Socket using BluetoothSocket() function
3. Then bind the socket using MAC address and port number.
4. Listen for the request and after getting the request accept it.
41

5. Then receive message from Mobile device.


6. This will be displayed in terminal window.
7. Finally close the Socket.

PROGRAM :
#import the package
import bluetooth
print "Bluetooth Terminal with Voice"
print "Follow instructions on app to connect"
print "Waiting for connection..."
#creation of server socket.
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
#binding the socket.
port=bluetooth.PORT_ANY
server_sock.bind(("",port))
server_sock.listen(1)
#creation of client socket.
client_sock,address = server_sock.accept()
print "Accepted connection from",address
#receiving message from the application.
while True:
data = client_sock.recv(1024)
print "received: %s" % data
client_sock.send(data);
42

#closing the socket connection.


client_sock.close()
server_sock.close()

OUTPUT :

APPLICATION LOGO

CONNECTING DEVICE VIA BLUETOOTH


43

MESSAGE TO BE SENT THROUGH


BLUETOOTH

Bluetooth Terminal with Voice


Follow instructions on app to connect.
Waiting for connection…
Accepted connection from fe80::f57b:ab2a:9a39:5d85
Received : Hii..
Received : Hello..

OUTPUT IN THE TERMINAL

RESULT :
Thus the interfacing Bluetooth module for transferring message
between Pi3 Bluetooth Manager application and raspberry Pi kit had
been executed and verified.
44

15. UPLOADING IOT DATA TO THE CLOUD

AIM :
To upload the IOT data to the cloud (ETSIOT CLOUD).

PROCEDURE :
1. Login to the ETSIOT cloud.
2. Use the given API key for connection.
3. Run the python code for establishing cloud connection using the
API key.
4. Then the corresponding output will be displayed in dashboard.

ALGORITHM :
1. Import time,request,math and random packages.
2. Get the output value from sensor.
3. Creates the headers for the HTTP requests.
4. Makes the HTTP requests.
5. Process results.

PROGRAM :
#import the required packages
import time
import requests
import math
import random
45

import RPi.GPIO as GPIO


import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.IN)

#Put your TOKEN here


TOKEN = "ZTY1MDC3ZDLJZTA2ZTI5OTVJMTIWOTLLYJY3OGYWMDI="
DEVICE_LABEL = "Obstacle" # Put your device label here
VARIABLE_LABEL_1 = "IR " # Put your first variable label here
VARIABLE_LABEL_2 = "IR2 "

def build_payload(variable_1,variable_2):
# Creates two random values for sending data
value_1 = GPIO.input(11)
value_2=random.randint(1,100)
payload = {variable_1: value_1,variable_2: value_2}
return payload

def post_request(payload):
# Creates the headers for the HTTP requests
url = "https://www.etsiot.io"
url = "{}/update?TOKEN={}&device={}".format(url,TOKEN,
DEVICE_LABEL)
headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
46

# Makes the HTTP requests


status = 400
attempts = 0
while status >= 400 and attempts <= 5:
req = requests.post(url=url, headers=headers, json=payload)
status = req.status_code
attempts += 1
#time.sleep(1)

# Processes results
if status >= 400:
print("[ERROR] Could not send data after 5 attempts, please check \
your token credentials and internet connection")
return False

print("[INFO] request made properly, your device is updated")


return True
def main():
payload = build_payload(VARIABLE_LABEL_1,VARIABLE_LABEL_2)

print("[INFO] Attemping to send data")


post_request(payload)
print("[INFO] finished")
47

if __name__ == '__main__':
while True:
main()
time.sleep(5)
OUTPUT :

GETTING API KEY FROM ETSIOT CLOUD APPLICATION

AVAILABLE WIDGETS
48

EXAMPLE : TIME WIDGET

RESULT :
Thus the IOT data has been uploaded to the cloud.
49

You might also like