0% found this document useful (0 votes)
48 views94 pages

20 Beit 30098

This document provides details about a practical lab on introducing Arduino boards, the Arduino IDE, and cables. It lists 10 practical exercises to implement various sensors including RFID, flex, IR, vibration, accelerometer, temperature, flame, buzzer, and more. It also provides an overview of the Arduino board layout, descriptions of the Arduino IDE interface and features, and brief explanations of uploading sketches, libraries, third-party hardware support, serial monitoring, and language support.

Uploaded by

nekod74098
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)
48 views94 pages

20 Beit 30098

This document provides details about a practical lab on introducing Arduino boards, the Arduino IDE, and cables. It lists 10 practical exercises to implement various sensors including RFID, flex, IR, vibration, accelerometer, temperature, flame, buzzer, and more. It also provides an overview of the Arduino board layout, descriptions of the Arduino IDE interface and features, and brief explanations of uploading sketches, libraries, third-party hardware support, serial monitoring, and language support.

Uploaded by

nekod74098
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/ 94

Internet of Things 20BEIT30098

Information Technology

Subject Name: Internet of Things Subject Code:IT802-N

List of Practicals

Sr. Initial of
Title Date Remarks
No faculty
Introduction to Arduino Board, Arduino IDE and
1
Cables
Perform Practical to blink LED on Arduino Board
2
and external LED as well.
Design an IOT application to use the concept of R
3
FID Sensor.
4 Design and implement the concept of Flex Sensor.
5 Implement the concept of IR Sensor
Implement the concept of Piezo Vibration Sensor.
6

7 Implement the concept of Accelerometer.


Implement the concept of Temperature and Humi
8
dity Sensor.
9 Implement the concept of flame Sensor.
10 Implement the concept of buzzer Sensor.

1
Internet of Things 20BEIT30098

Practical: 1
Aim: Introduction to Arduino Board, Arduino IDE and Cables.
Introduction to Arduino:
Arduino is an open-source prototyping platform based on easy-to-use hardware and
software.
Looking at the board from the top down, this is an outline of what you will see (parts of the
board you might interact with in thecourse of normal use are highlighted)

Starting clockwise from the top centre:


• Analog Reference pin (orange)
• Digital Ground (light green)
• Digital Pins 2-13 (green)
• Digital Pins 0-1/Serial In/Out - TX/RX (dark green) - These pins cannot be used for digital
i/o (digitalRead and digitalWrite) if youare also using serial communication.
• Reset Button - S1 (dark blue)
• In-circuit Serial Programmer (blue-green)
• Analog In Pins 0-5 (light blue)
• Power and Ground Pins (power: orange, grounds: light orange)
• External Power Supply In (9-12VDC) - X1 (pink)
• Toggles External Power and USB Power SV1 (purple)
• USB (used for uploading sketches to the board and for serial communication between the
board and the computer; can be used topower the board) (yellow)

2
Internet of Things 20BEIT30098

Arduino IDE:

The Arduino Integrated Development Environment - or Arduino Software (IDE) - contains a text
editor for writing code, a message area, a text console, a toolbar with buttons for common functions
and a series of menus. It connects to the Arduino and Genuino hardware to upload programs and
communicate with them.

• Writing Sketches
- File
- Edit
- Sketch
- Tools
- Help
• Sketchbook
• Tabs, Multiple Files, and Compilation
• Uploading
• Libraries
• Third-Party Hardware
• Serial Monitor
• Preferences
• Language Support
• Boards

Writing Sketches:

Programs written using Arduino Software (IDE) are called sketches. These sketches are written in
the text editor and are saved with the file extension.ino. The editor has features for cutting/pasting
and for searching/replacing text. The message area gives feedback while saving and exporting and
also displays errors. The console displays text output by the Arduino Software(IDE), including
complete error messages and other information. The bottom right hand corner of the window
displays the configured board and serial port. The toolbar buttons allow you to verify and upload
programs, create, open, and save sketches, and open the serial monitor.

Sketchbook:

The Arduino Software (IDE) uses the concept of a sketchbook: a standard place to store your
programs (or sketches). The sketches in your sketchbook can be opened from the File >Sketchbook
menu or from the Open button on the toolbar. The first time you run the Arduino software, it will
automatically create a directory for your sketchbook. You can view or change the location of the
sketchbook location from with the Preferences dialog. Beginning with version 1.0, files are saved
with a.ino file extension. Previous versions use the .pde extension. You may still open .pde named
files in version 1.0 and later, the software will automatically rename the extension to .ino.

Tabs, Multiple Files, and Compilation:

3
Internet of Things 20BEIT30098

Allows you to manage sketches with more than one file (each of which appears in its own tab).
These can be normal Arduino code files (no visible extension), C files (.c extension), C++ files
(.cpp), or header files (.h).

Uploading:

Before uploading your sketch, you need to select the correct items from the Tools > Board and Tools
> Port menus. The boards are described below. On the Mac, the serial port is probably something like
/dev/tty.usbmodem241 (for an Uno or Mega2560 or Leonardo) or /dev/tty.usbserial-1B1 (for a Due
milanove or earlier USB board), or /dev/tty.USA19QW1b1P1.1 (for a serial board connected with a
Keyspan USB-to-Serial adapter). On Windows, it's probably COM1 or COM2 (for a serial board) or
COM4, COM5, COM7, or higher (for a USB board) - to find out, you look for USB serial device in
the ports section of the Windows Device Manager. On Linux, it should be /dev/ttyACMx ,
/dev/ttyUSBx or similar. Once you've selected the correct serial port and board, press the upload
button in the toolbar or select the Upload item from the File menu. Current
Arduino boards will reset automatically and begin the upload. With older boards (pre-Diecimila) that
lack auto-reset, you'll need to press the reset button on the board just before starting the upload. On
most boards, you'll see the RX and TX LEDs blink as the sketch is uploaded. The Arduino Software
(IDE) will display a message when the upload is complete, or show an error. When you upload a
sketch, you're using the Arduino bootloader, a small program that has been loaded on to the
microcontroller on your board. It allows you to upload code without using any additional hardware.
The bootloader is active for a few seconds when the board resets; then it starts whichever sketch was
most recently uploaded to the microcontroller. The bootloader will blink the on-board (pin 13) LED
when it starts (i.e. when the board resets).

Libraries:
Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating
data. To use a library in a sketch, select it from the Sketch > Import Library menu. This will insert
one or more #include statements at the top of the sketch and compile the library with your sketch.
Because libraries are uploaded to the board with your sketch, they increase the amount of space it
takes up. If a sketch no longer needs a library, simply delete its #include statements from the top of
your code.
There is a list of libraries in the reference. Some libraries are included with the Arduino software.
Others can be downloaded from a variety of sources or through the Library Manager. Starting with
version 1.0.5 of the IDE, you do can import a library from a zip file and use it in an open sketch.
See these instructions for installing a third-party library.

Third-Party Hardware:

Support for third-party hardware can be added to the hardware directory of your
sketchbookdirectory. Platforms installed there may include board definitions (which appear in the
board menu), core libraries, bootloaders, and programmer definitions. To install, create the hardware
directory, then unzip the third-party platform into its own sub-directory. (Don't use "arduino" as the
4
Internet of Things 20BEIT30098

sub-directory name or you'll override the built-in Arduino platform.) To uninstall, simply delete its
directory.

Serial Monitor
Displays serial data being sent from the Arduino board. To senddata to the board, enter text and
click on the "send" button or press enter. Choose the baud rate from the drop-down that matches the
rate passed to Serial.begin in your sketch. Note that onWindows, Mac or Linux, the Arduino or
Genuino board will reset when you connect with the serial monitor.

Preferences:

Some preferences can be set in the preferences dialog (found under the Arduino menu on the Mac,or
File on Windows and Linux). The rest can be found in the preferences file, whose location is shown
in the preference dialog.

Language Support:

Since version 1.0.1, the Arduino Software (IDE) has been translated into 30+ different languages.
By default, the IDE loads in the language selected by your operating system. (Note: on Windows
and possibly Linux, this is determined by the locale setting which controls currency and date
formats, not by the language the operating system is displayed in.) If you would like to change the
language manually, start the Arduino Software (IDE) and open the Preferences window. Next to the
Editor Language there is a dropdown menu of currently supported languages. Select your preferred
language from the menu, and restart the software to use the selected language. If your operating
system language is not supported, the Arduino Software (IDE) will default to English.

Boards:

The board selection has two effects: it sets the parameters (e.g. CPU speed and baud rate) used when
compiling and uploading sketches; and sets and the file and fuse settings used by the burn bootloader
command. Some of the board definitions differ only in the latter, so even if you've been uploading
successfully with a particular selection you'll want to check it before burning the bootloader.

- Arduino/Genuino Uno: An ATmega328 running at 16 MHz with auto-reset, 6 Analog


In, 14 Digital I/O and 6 PWM.
- Arduino Mega: An ATmega1280 running at 16 MHz with auto-reset, 16 Analog In, 54
Digital I/O and 15 PWM.
- Arduino Micro: An ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20
Digital I/O and 7 PWM.

Arduino Cables:

5
Internet of Things 20BEIT30098

Arduino is great but sometimes connecting interesting things to it can be a pain. Here are some
things that may make it easier for you. Here are some of the cables and pins that are available, and
below we'll show you how to use them for many different applications.

Standard issue USB 2.0 cables. This is the most common A to B Male/Male type peripheral cable.
Compatible with most Arduino boards such as Arduino Mega, Romeo, Arduino Duemilanove. Often
used for printers and other peripherals. While still a little bulky in shape for small embedded
systems, this is a standard cable found everywhere. Use this cable with Arduino UNO and others,
but not for Arduino Leonardo based boards. May come in White or Black.

6
Internet of Things 20BEIT30098

Practical: 2
Aim:Perform Practical to blink LED on Arduino Board and external LED as
well.

Hardware Required:

• Arduino or Genuino Board


• LED
• 220 ohm resistor

Circuit:

To build the circuit, connect one end of the resistor to Arduino pin 13. Connect the long leg of the
LED (the positive leg, called the anode) to the other end of the resistor. Connect the short leg of
the LED (the negative leg, called the cathode) to the Arduino GND, as shown in the diagram and
the schematic below Most Arduino boards already have an LED attached to pin 13 on the board
itself. If you run this example with no hardware attached, you should see that LED blink The value
of the resistor in series with the LED may be of a different value than 220 ohm; the LED will lit up
also with values up to 1K ohm.

Code:

After you build the circuit plug your Arduino or Genuino board into your computer, start
the Arduino Software (IDE) and enter the code below. You may also load it from the menu

7
Internet of Things 20BEIT30098

File/Examples/01.Basics/Blink . The first thing you do is to initialize pin 13 as an output pin


with the Line

pinMode (13, OUTPUT);

In the main loop, you turn the LED on with the line:

digitalWrite(13, HIGH);

This supplies 5 volts to pin 13. That creates a voltage difference across the pins of the LED, and
lights it up. Then you turn it off with the line:

digitalWrite(13, LOW);

That takes pin 13 back to 0 volts, and turns the LED off. In between the on and the off, you want
enough time for a person to see the change, so the delay() commands tell the board to do nothing
for 1000 milliseconds, or one second. When you use the delay() command, nothing else happens for
that amount of time.

// the setup function runs once when you press reset or power the board

void setup() {

// initialize digital pin 13 as an output.

pinMode(13, OUTPUT);

// the loop function runs over and over again forever

void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

8
Internet of Things 20BEIT30098

Practical: 3

Aim: Implement the concept of RFID Sensor.

Sensor type: Digital Sensor


Working:
➔ RFID belongs to a group of technologies referred to as Automatic Identification and Data
Capture (AIDC). AIDC methods automatically identify objects, collect data about them, and
enter those data directly into computer systems with little or no human intervention. RFID
methods utilize radio waves to accomplish this.
➔ At a simple level, RFID systems consist of three components: an RFID tag or smart label,
an RFID reader, and an antenna.
➔ RFID tags contain an integrated circuit and an antenna, which are used to transmit data to
the RFID reader (also called an interrogator). The reader then converts the radio waves to a
more usable form of data. Information collected from the tags is then transferred through a
communications interface to a host computer system, where the data can be stored in a
database and analyzed at a later time.

9
Internet of Things 20BEIT30098

RFID Pin Details:

PIN PIN NAME DETAILS

RX Receive Pin for Data Reception

TX Transmit Pin for Data Transmission

EN Enable Pin for Enabling/Disabling the Reader (internally pulled up)

5V Power Supply Power Supply Input(5V)

GND Ground Ground Level Of supply

10
Internet of Things 20BEIT30098

RFID Circuit Diagram:

Application Description:
Functionality:
The system reads data from a RFID tag which can store 12 bit data and displays it on video display.
Circuit Design:

There are three components in the system.

RFID Tag RFID Reader


Video Display

Description:
→ RFID Reader is made of components like Oscillator, Modulator, Amplifier, Filter,
Demodulator and Antenna.
→ Antenna provides power and data based on type of data. Antenna and Tag both contain a
loop of copper wire. Antenna is supplied with power supply and tag may or may not have
its own power supply.

11
Internet of Things 20BEIT30098

→ RFID Reader contains a transmitter and a receiver. It receives the data from Tag and after
decoding the data it sends it to Video Display Module.
→ Video Display Module is mostly a LCD Display which is used to display the data received
from RFID Reader.

Components of RFID System:


RFID Reader:
→ RFID reader contains components like oscillator, modulator, amplifier, transmitter, receiver,
Decoder, Demodulator and antenna.
→ RFID readers, also called interrogators query RFID tags in order to obtain identification,
location, and other information about the device or product the tag is embedded in. The RF
energy from the reader antenna is collected by the RFID tag antenna and used to power up
the microchip. There are two types of RFID readers:
→ RFID read-only readers: As the name suggests, these devices can only query or read
information from a nearby RFID tag. These readers are found in fixed, stationery
applications as well as portable, handheld varieties.
→ RFID read-write readers: Also known as encoders, these devices read and also write
(change) information in an RFID tag. Such RFID encoders can be used to program
information into a "blank" RFID tag. A common application is to combine such a RFID
reader with a barcode printer to print "smart labels". Smart labels contain a UPC bar code
on the front with an RFID tag embedded on the back.

RFID Tags:
→ RFID tags are tiny microchips with memory and an antenna coil, thinner than paper and
some only 0.3mm across.
→ RFID tags listen for a radio signal sent by a RFID reader.
→ When a RFID tag receives a query, it responds by transmitting its unique ID code and other
data back to the reader.
→ There are two types of RFID tags—passive and active.

1) Active RFID:

12
Internet of Things 20BEIT30098

➔ Active RFID systems use self-powered RFID


tags that continuously broadcast their own signal.
➔ Active RFID tags are commonly used as
“beacons” to accurately track the real-time
location of assets or in high speed environments
such as tolling.
➔ Active tags provide a much longer read range
than passive tags.

2) Passive RFID:

➔ Passive RFID systems use tags that are


powered by the electromagnetic energy transmitted
from an RFID reader.

➔ Passive RFID tags have applications including


access control, file tracking, race timing, supply
chain management, smart labels, and more.

➔ The lower price point per tag make employing


passive RFID systems economical for many
industries.

RFID Applications:
➔ Store product identification - RFID technology can be used within shops and stores as a
form of alert for goods that have / have not been paid for.
➔ Asset tracking - RFID systems can monitor when RFID tags pass given points and in this way
track the assets.
➔ Airline baggage identification - airlines need to monitor where baggage is and route it to
the required destination. RFID tags can be attached to the bags to automate baggage
routing
➔ Parts identification - Data can be written to an RFID tags defining the identity of a part.
This can then be used within a manufacturing, stock holding or other process to identify
and locate parts.

13
Internet of Things 20BEIT30098

➔ Production control - when items are manufactured they pass through many stages. RFID
tags can be attached to items. These can be updated each time the item passes through a
stage in production. This will enable the manufacturing system to track all items and know
what stage they are at, and any other information such as test failures, etc.
➔ Employee access control - many companies today require intelligent access control
systems. RFID technology is able to provide control as well as tracking, noting when cards
pass particular access points, etc.
➔ Supply chain control - with manufacturing working to much tighter timescales with items
such as Just-In-Time techniques being involved tracking of the items in a supply chain
becomes more critical. RFID tags can be added to items to enable this to be undertaken
accurately and more quickly.
➔ Vehicle tracking - RFID technology can be used to determine when vehicles have passed
particular points and in this way their location can be approximately determined.
➔ Livestock identification - RFID tags can be injected into animals, under the skin and this
enables accurate determination of which animal is which so that injections, etc. can be
given to the correct animal.

Frequency Based Usage:


➔ There are 4 major frequency ranges that RFID systems operate at.
oLow Frequency (LF) 125 to 148 KHz
oHigh Frequency (HF) 13.56 MHz oUltra
High Frequency (UHF) 915 MHz
oMicrowave 2.45 GHz
➔Generally, low-frequency systems are distinguished by short reading ranges, slow read
speeds, and lower cost while Higher-frequency RFID systems are used where longer read
ranges and fast reading speeds are required, such as for vehicle tracking and automated
Toll collection. Microwave requires the use of active RFID tags.
System Diagram:

14
Internet of Things 20BEIT30098

Flow Chart:

Wait Till Tag


is Found

Initialize val []
& Counter i

Read Bit Print Val []

Append Bit If Counter


No Yes
To Val [] i< = 12

Flow Chart for RFID Tag Reader System

15
Internet of Things 20BEIT30098

RFID.INO

#include <SoftwareSerial.h>
#define Rx 10 //software serial on digital pin 10,11. #define Tx 11
intval[12];
//Real time data holder.
SoftwareSerialmySerial(10,11);

//make object myserial of softwareserial data type.rxtx

void setup()
{
Serial.begin(9600); //begin hardware serial at 9600 baud rate. Serial.println("System
up."); //send data over hardware serial to database. mySerial.begin(9600); //begin
software serial at 9600 baud rate. }
void loop()
{ id_chk(); //check for RFID tag.
}
voidid_chk()
{ inti; if (mySerial.available()) //check for RFID card available.
{ for(i=0;i<12;i++) //check for data base.
{ val[i] = mySerial.read(); //getting data from RFID module.
delay(5);

Serial.print(val[i]);
}
Serial.println();
}
}

Predefined Library:

SoftwareSerial.h

➔ The SoftwareSerial library has been developed to allow serial communication on other
digital pins of the Arduino, using software to replicate the functionality.
➔ It is possible to have multiple software serial ports.

Example:

SoftwareSerialmySerial(10,11) //RX,TX
/*

16
Internet of Things 20BEIT30098

Receives from the hardware serial, sends to software serial. Receives


from software serial, sends to hardware serial.
* RX is digital pin 10 (connect to TX of other device)
* TX is digital pin 11 (connect to RX of other device)
*/

References:

• Lehpamer, H., Microwave Transmission Networks; Planning, Design, and Deployment,


New York: McGraw-Hill, 2004.
• Microchip, “13.56 MHz RFID System Design Guide,” 2004

17
Internet of Things 20BEIT30098

Practical: 4

Aim: Implement the concept of Flex Sensor.

Fig-1 : Flex Sensor

Sensor Type: Analog sensor

Working [1]:
The Flex Sensor is based on resistive carbon elements. As a variable printed resistor, the Flex Sensor
achieves great form-factor on a thin flexible substrate. When the substrate is bent, the sensor
produces a resistance output correlated to the bend radius—the smaller the radius, the higher the
resistance value.

Pin Details [1]:

Board has 3-pin connector for using the sensor. Details are marked on PCB.

Pin Name Details


1 GND Power Supply Ground
2 +5V Power supply Positive input
3 OUT Analog output

Application [3]:
To ring buzzer when the flex sensor bent beyond some limit.

18
Internet of Things 20BEIT30098

Circuit Diagram:

Fig-2: Circuit diagram for buzzer system using Flex sensor

Application Description:

Functionality:

Ring buzzer when value of flex sensor is beyond limit.


19
Internet of Things 20BEIT30098

Circuit design:
• One leg of Flex sensor (mentioned as red color) is attached with Analog +5V on Arduino
board.
• Second leg of Flex sensor (mentioned as yellow) is attached with resistance and Analog-A0
pin of Arduino board)
• Second leg of resistance (mentioned with black color) is attached with Analog-GND pin
• One leg of piezo buzzer or other speaker is attached with output digital pin (here pin no-9)
and second leg is attached with GND.
System Diagram:

Flex Arduino
Buzzer
Sensor Board

Fig-3: System architecture

Flow Chart:

Get Flex Sensor Reading


(A0 pin on Arduino)

No
Reading >
Threshold

Yes

Ring Buzzer
(Write HIGH Data on Digital
Pin on Arduino)
Code:

const int Piezo = 9; //for activating buzzer

20
Internet of Things 20BEIT30098

const int Bend_Sensor = A0; //for reading sensor data


int pause;

void setup()
{
pinMode (Piezo, OUTPUT);
Serial.begin(9600);{
}

void loop()
{
int sensorValue = analogRead(A0); //Read sensor
Serial.println(sensorValue); //Display reading
//Following method is used to put sensor data in range
int thisPitch = map (sensorValue, 230,800, 120, 1500);
tone(9, thisPitch, 100); //Ring a Buzzer
//in place of tone, digitalWrite(Piezo, HIGH); can be used
delay(100);
}

Pre defined function’s description (used in code):


• tone(pin, frequency, duration) [2]
Parameters
pin: the pin on which to generate the tone
frequency: the frequency of the tone in hertz - unsigned int
duration: the duration of the tone in milliseconds (optional) - unsigned long

Applications can be designed:


• Robotics [5] – Controlling joint movement or placement is easy with flex sensors. You can
also use these products as bumper switches for efficient wall detection.
• Bio-metrics – Manufacturers of athletic equipment use flex sensors to indicate placement
or movement.
• Virtual Reality Gaming Gloves – The sensors are important components used in
manufacturing virtual reality gloves. The Nintendo Power Glove is a good example.
• Other Applications – Flex sensors are common in different technological products, such as
automotive and industrial controls, computer peripherals, joysticks, and measuring devices.
These are also present in fitness products, musical instruments, and assistive technology
systems of modern vehicles.

Reference:
1. https://www.pantechsolutions.net/sensors/user-manual-for-flex-sensor
21
Internet of Things 20BEIT30098

2. https://www.arduino.cc/en/Reference/Tone
3. http://www.instructables.com/id/Bend-Sensor/step7/Bend-Sensor-and-Piezo/
4. Data Sheet of Flex sensor - flex22.pdf (attached with this document)
5. http://www.spectrasymbol.com/flex-sensor

22
Internet of Things 20BEIT30098

Practical: 5

Aim: Implement the concept of IR Sensor.

Fig-1 : IR Sensor Board


Sensor Type: Analog sensor

Working [1]: IR Sensors work by using a specific light sensor to detect a select light wavelength
in the Infra-Red (IR) spectrum. By using an LED which produces light at the same wavelength as
what the sensor is looking for, you can look at the intensity of the received light. When an object is
close to the sensor, the light from the LED bounces off the object and into the light sensor. This
results in a large jump in the intensity, which we already know can be detected using a threshold.

23
Internet of Things 20BEIT30098

Pin Details [1]:

Board has 3-pin connector for using the sensor. Details are marked on PCB.

Pin Name Details


1 GND Power Supply Ground
2 +5V Power supply Positive input
3 OUT Analog output

Application [3]:

• Detecting Brightness
Since the sensor works by looking for reflected light, it is possible to have a sensor that can
return the value of the reflected light. This type of sensor can then be used to measure how
"bright" the object is. This is useful for tasks like line tracking.

24
Internet of Things 20BEIT30098

Circuit Diagram:

Fig-2: Circuit diagram for IR sensor

Application Description://NEED TO CHANGE

Functionality:
Ring buzzer when object is detected.

Circuit design:
• One leg of IR sensor (mentioned as red color) is attached with Analog +5V on Arduino
board.
• Second leg of IR sensor (mentioned as green) is attached with resistance and Analog-A0
pin of Arduino board)
• Second leg of resistance (mentioned with black color) is attached with Analog-GND pin
• One leg of piezo buzzer or other speaker is attached with output digital pin (here pin no-9)
and second leg is attached with GND.

25
Internet of Things 20BEIT30098

Flow Chart:

start

Input IR Sensor
reading
(SensorValue)

Calculate distance in cm

Yes cm>threshold No

Buzzer ON Buzzer OFF

Code:

/*
DigitalReadSerial
Reads a digital input on pin 2, prints the result to the serial monitor and rings buzzer.

This example code is in the public domain.


*/

int pushButton = 2;// digital pin 2 has a pushbutton attached to it. Give it a name:
const int Piezo = 9;

void setup() // the setup routine runs once when you press reset:

{
26
Internet of Things 20BEIT30098

pinMode(piezo, OUTPUT);
Serial.begin(9600); // initialize serial communication at 9600 bits per second:

pinMode(pushButton, INPUT); // make the pushbutton's pin an input:


}

void loop() // the loop routine runs over and over again forever:
{
int buttonState = digitalRead(pushButton); // read the input pin.
Serial.println(buttonState); // print out the state of the button.
digitalWrite(Piezo, HIGH);

delay(100); // delay in between reads for stability


}

Pre-defined function’s description (used in code):


• pinMode(
• Serial.begin
• Serial.println
• digitalRead
• digitalWrite

Applications can be designed:


➢ Proximity Sensors: Proximity sensors find use in Touch Screen phones, apart from many other
devices. In a Touch Screen Phone, the touch screen needs to disabled when it is held near the ear,
while in use, so that even if the cheek makes contact with the tough screen, there is no effect.

➢ Line Follower Robots: The IR LED emits IR radiation, which in normal state gets reflected
back to the module from the white surface around the black line, which gets incident on the
photodiode. But, as soon as the IR radiation falls on the black line, the IR radiation gets
absorbed completely by the black color, and hence there is no reflection of the IR radiation
going back to the sensor module.

➢ Item Counter: Whenever an item obstructs the invisible line of IR radiation, we make an
increment in the value of a stored variable in a computer/microcontroller which may be
indicated by LEDs, Seven Segment Displays, LCDs etc.

➢ Burglar Alarm: This mechanism is used extensively in security systems and is replicated
on a smaller scale for smaller objects, such as exhibits in an exhibition, etc.

Reference:

27
Internet of Things 20BEIT30098

1. http://maxembedded.com/2013/08/how-to-build-an-ir-sensor/
2.http://www.instructables.com/id/Infrared-Transmitter-and-Receiver/
3.http://www.electronicshub.org/motion-detector-circuit/

28
Internet of Things 20BEIT30098

Practical: 6

Aim: Implement the concept of Piezo Vibration Sensor.

Introduction
Grove- Piezo Vibration Sensor is suitable for measurements of flexibility, vibration, impact and
touch. The module is based on PZT film sensor LDT0-028. When the sensor moves back and forth,
a certain voltage will be created by the voltage comparator inside of it. A wide dynamic range
(0.001Hz~1000MHz) guarantees an excellent measuring performance. And, you can adjust its
sensitivity by adjusting the on-board potentiometer with a screw. (Gabay, 2011)

Sensor Diagram

Fig. 1

Working
The piezoelectric sensor is used for flex, touch, vibration and shock measurement. Its basic
principal, is as follows: whenever a structure moves, it experiences acceleration. A piezoelectric
shock sensor, in turn, can generate a charge when physically accelerated. This combination of
properties is then used to modify response or reduce noise and vibration.
The piezoelectric effect was discovered by Pierre and Jacques Curie in the latter part of the 19th
century. They discovered that minerals such as tourmaline and quartz could transform mechanical
energy into an electrical output. The voltage induced from pressure (Greek: piezo) is proportional
to that applied pressure, and piezoelectric devices can be used to detect single-pressure events as
well as repetitive events. Several materials can be used to make piezoelectric sensors, including
tourmaline, gallium phosphate, salts, and quartz. Most electronic applications use quartz since its
growth technology is far along, thanks to development of the reverse application of the piezoelectric
effect; the quartz oscillator. Sensors based on the piezoelectric effect can operate from transverse,
longitudinal, or shear forces, and are insensitive to electric fields and electromagnetic radiation. The
response is also very linear over wide temperature ranges, making it an ideal sensor for rugged
environments. For example, gallium phosphate and tourmaline sensors can have a working
temperature range of 1,000°C.

29
Internet of Things 20BEIT30098

Pin Diagram

(arduino, 2015)
Fig. 2
PIN1 of the Piezo connected to GND on Arduino
PIN2 of the Piezo connected to 1M Ohm resistor that goes to AnalogIn pin (example uses A0) on
Arduino and to 5V on Arduino

30
Internet of Things 20BEIT30098

`Circuit Diagram:

Fig. 3
The piezo sensor works very well with the Arduino. It 2 pins simply go into analog terminal A0 and
A1 of the Arduino. A0 will be configured to be ground and A1 will be the positive sense pin of the
vibration sensor. This pin will detect whether there is any vibration or not.With this hardware setup,
we will program the software so that this LED lights up when vibration above a certain threshold is
reached.Now that we have our circuit setup, we now just need to connect the Arduino to a computer
via a USB. The type A connector goes into the computer and the type B goes into the Arduino.
(Mutiis, 2012)

Hardware
• Arduino Board
• Breadboard

31
Internet of Things 20BEIT30098

• Piezo Vibration Sensor


• LED
• Resistor

Steps
• This circuit reads a piezo element to detect a knocking sound.
• It reads an analog pin and compares the result to a set threshold.
• If the result is greater than the threshold, it writes
• "knock" to the serial port, and toggles the LED

Flow Diagram:

Fig. 4

Code
const int ledPin = 13;
const int knockSensor = A0;
const int threshold = 100;
32
Internet of Things 20BEIT30098

int sensorReading = 0;
int ledState = LOW;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}void loop() {
sensorReading = analogRead(knockSensor);
if (sensorReading >= threshold) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
Serial.println("Knock!");
}
delay(100);

Description:
The first block of code defines the pin connections. A variable called threshold is defined next. This
is a very important variable because it represents the analog level at which the LED will be triggered
to turn on. The Arduino can detect and measure analog values from 0 to 1023. We created it so that
once an analog sound vibration reaches 100 or greater, the LED will be triggered on. You can modify
this value to be less or greater depending on the amplitude of the vibration you want to be the trigger
point. However, a value near 100 is good for all practical purposes. If you lower the threshold value,
then the circuit will detect vibrations easier. If you raise the threshold value, the circuit will need
greater vibrations in order to trigger. The LED Pin serves as a digital output pin for the LED we
connect to D13, so it must be declared output. The next part of code is the loop() function. The
reading variable measures the actual voltage on the sense Pin of the vibration sensor. If the reading
is larger than the threshold value, the LED will be triggered to high and turned on. If not, it does not
turn on. With this code, we only turn the LED on when the vibration is a large enough amount. If
you want, you can set the threshold to a higher amount, so that the LED only turns on for a greater
impact force to the sensor. Play around with this to suit your needs. And this is how a vibration
sensor works integrated with an Arduino board. With this circuit, the LED will turn on for a second
with each vibration above the given threshold and then turn off. Again, several variations of this
circuit can be done to fit your needs. Maybe you don't want an LED to light when vibration is

33
Internet of Things 20BEIT30098

detector. Maybe you want a buzzer to sound. In that case, you replace the LED with a buzzer. Maybe
you don't want a buzzer. You want a fan to go off. There are many ways the circuit can operate.

Applications

▪ Vibration Sensing in Washing Machine


▪ Low Power Wakeup Switch
▪ Low Cost Vibration Sensing
▪ Car Alarms
▪ Body Movement
▪ Security Systems (seeedwiki, 2015)

References
1. arduino. (2015, 07 29). Arduino - Knock. Retrieved from www.arduino.cc:
https://www.arduino.cc/en/Tutorial/Knock
2. Gabay, J. (2011, 01 12). Fundamentals of Piezoelectric Shock and Vibration Sensors.
Retrieved from www.digikey.com:
http://www.digikey.com/en/articles/techzone/2011/dec/fundamentals-of-piezoelectric-
shock-and-vibration-sensors
3. Mutiis, M. D. (2012, 10 9). ubiquitousmusic - Piezo Vibration Sensor. Retrieved from
www.ubiquitousmusic.com: http://ubiquitousmusic.wikispaces.com/Piezo+Sensors
4. seeedwiki. (2015, 10 17). Grove - Piezo Vibration Sensor - Wiki. Retrieved from
www.seeedstudio.com: http://www.seeedstudio.com/wiki/Grove_-
_Piezo_Vibration_Sensor

34
Internet of Things 20BEIT30098

Practical: 7
Aim: Implement the concept of Accelerometer.

Fig. 1: Accelerometer

Sensor Type: Analog and Digital Sensor

Working:

The accelerometer consists of many different parts and works in many ways, two of which are:

1. The piezoelectric effect


2. The capacitive effect

1. Piezoelectric Effect:
➢ The piezoelectric effect is the most common form of accelerometer and uses microscopic
crystal structures that become stressed due to accelerative forces.
➢ These crystals create a voltage from the stress, and the accelerometer interprets the voltage
to determine velocity and orientation.
➢ Piezoelectric accelerometers only respond to AC phenomenon such as vibration or shock.

35
Internet of Things 20BEIT30098

Fig 2: Piezoelectric Accelerometer


2. Capacitive Effect:
➢ Accelerometers that implement capacitive sensing output a voltage dependent on the
distance between two planar surfaces.
➢ One or both of these “plates” are charged with an electrical current.
➢ Changing the gap between the plates changes the electrical capacity of the system, which
can be measured as a voltage output.
➢ This method of sensing is known for its high accuracy and stability.

Fig 3: Capacitive Accelerometer

o Typical accelerometers are made up of multiple axes, two to determine most two-
dimensional movement with the option of a third for 3D positioning.

MEMS (Micro-Electro-Mechanical Sensors):


➢ Most accelerometers are Micro-Electro-Mechanical Sensors (MEMS).
➢ The basic principle of operation behind the MEMS accelerometer is the displacement of a
small proof mass etched into the silicon surface of the integrated circuit and suspended by
small beams.

36
Internet of Things 20BEIT30098

Pin Details:
Board has 5-pin connector for using the sensor. Details are marked on PCB.

Pin Name Details Arduino Board Pin


1 Z-axis Reading of Z-axis Dimension A2
2 y-axis Reading of Y-axis Dimension A1
3 x-axis Reading of X-axis Dimension A0
4 GND Power Supply Ground 18
5 VCC(+5 V) Power supply Positive Input 19

Application:
In the computing world, IBM and Apple have recently started using accelerometers in their laptops
to protect hard drives from damage.
Other Applications are:
o Human activities :
➢ walking, running, dancing or skipping
o Working machines :
➢ inside a building or in the surrounding area
o Construction work :
➢ driving piles, demolition, drilling and excavating
o Moving loads on bridges
o Vehicle collisions
o Collapse of structural elements
o Wind loads and wind gusts
o Air blast pressure
o Earthquakes and aftershocks

Circuit diagram:

37
Internet of Things 20BEIT30098

Fig. 4: Circuit Diagram

Application description:
➢ An accelerometer can help analyze problems in a car engine using vibration testing, or you
could even use one to make a musical instrument.
➢ In the computing world, IBM and Apple have recently started using accelerometers in their
laptops to protect hard drives from damage.
➢ In high g accelerometers are the industry standard way of detecting car crashes and
deploying airbags at just the right time.

Functionality:
Rings buzzer, open airbags in automobile, operate Grinder can measure the motion of human hand.

Circuit design:
➢ The 3-Axis Accelerometer contains three acceleration-sensing integrated circuits (IC’s),
along with the associated electronics.
➢ These axises and 3 outputs are labeled X, Y & Z.
➢ ARDUINO GND is attached with Accelerometer GND (Red wire).
➢ ARDUINO VCC (3V3) is attached with Accelerometer VCC (Black wire).
➢ ARDUINO A0 is attached with Accelerometer X-axis (Yellow wire).
➢ ARDUINO A1 is attached with Accelerometer Y-axis (Green wire).
➢ ARDUINO A2 is attached with Accelerometer Z-axis (Blue wire).
➢ For that, we set both ground pin and power pin to output mode.
➢ For accuracy we set power pin to High and ground pin to Low.Accelerometers will
communicate over an analog, digital, or pulse-width modulated connection interface.

Block diagram:

Readings of 3 axises and take


Accelerometer Arduino Board actions in respective attached
device

Fig. 5: System diagram

38
Internet of Things 20BEIT30098

Flow chart:

Get Accelerometer
Reading

No

Reading Threshold

Yes

Take appropriate actions

Fig. 6: Flow Chart Diagram

Code:
Reads an Analog Devices ADXL3xx accelerometer and communicates the acceleration to the
computer. The pins used are designed to be easily compatible with the breakout boards from
Sparkfun:

The circuit:
analog 0: accelerometer self test
analog 1: z-axis
analog 2: y-axis
analog 3: x-axis
analog 4: ground
analog 5: vcc

39
Internet of Things 20BEIT30098

This example code is in the public domain.


*/
// these constants describe the pins. They won't change:
const int groundpin = 18; // analog input pin 4 -- ground
const int powerpin = 19; // analog input pin 5 -- voltage
const int xpin = A3; // x-axis of the accelerometer
const int ypin = A2; // y-axis
const int zpin = A1; // z-axis (only on 3-axis models)

void setup()
{
// initialize the serial communications:
Serial.begin(9600);

// Provide ground and power by using the analog inputs as normal


// digital pins. This makes it possible to directly connect the
// breakout board to the Arduino. If you use the normal 5V and
// GND pins on the Arduino, you can remove these lines.
pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT);
digitalWrite(groundpin, LOW);
digitalWrite(powerpin, HIGH);
}

void loop()
{
// print the sensor values:
Serial.print(analogRead(xpin));
// print a tab between values:
Serial.print("\t");
Serial.print(analogRead(ypin));
// print a tab between values:
Serial.print("\t");
40
Internet of Things 20BEIT30098

Serial.print(analogRead(zpin));
Serial.println();
// delay before next reading:
delay(100);
}

Application can be designed:


▪ In the computing world, IBM and Apple have recently started using accelerometers in their
laptops to protect hard drives from damage.
▪ Most smartphones typically make use of 3-axis models, whereas cars simply use only a 2-
axis to determine the moment of impact.
▪ If the laptop were to sudden free fall and immediately turn off the hard drive to hitting the
reading heads into the hard drive platter.
▪ Accelerometers have been used to calculate gait parameters, such as stance and swing phase.
▪ It can be used to design instruments for measuring vibrations, air blast pressure and
earthquake.

References:
http://www.learningaboutelectronics.com/
http://www.dimensionengineering.com/info/accelerometersuio
http://artpluscode.com
https://learn.sparkfun.com/tutorials/accelerometer-basics

41
Internet of Things 20BEIT30098

Practical: 8
Aim: Implement the concept of Temperature and Humidity Sensor.

Fig-1 : DHT 11 Humidity and Temperature Sensor

Sensor Type:Digital sensor

Working [1]:
This DHT11 Temperature and Humidity Sensor features a calibrated digital signal output with the
temperature and humidity sensor capability. It is integrated with a high-performance 8-bit
microcontroller. Its technology ensures the high reliability and excellent long-term stability. This
sensor includes a resistive element and a sensor for wet NTC temperature measuring devices. It has
excellent quality, fast response, anti-interference ability and high performance.

Pin Details [1]:


Board has 3-pin connector for using the sensor. Details are marked on PCB.

Pin Name Details


1 GND Power Supply Ground
2 +5V Power supply Positive input
3 DATA Digital output

42
Internet of Things 20BEIT30098

Fig-2 : DHT 11 Circuit Diagram

Application [2]:

To ring buzzer when the flex sensor bent beyond some limit.

Circuit Diagram:

43
Internet of Things 20BEIT30098

Fig-3: Circuit diagram for buzzer system using DHT 11 sensor

Application Description:

Functionality:

Ring buzzer and blink led when value of Temperature and/or Humidity is beyond
the limit of the threshold value.

Circuit design:

• One leg(Vcc) of DHT 11 sensor (mentioned as red color) is attached with +5V on
Arduino board.
• Second leg(Data) of DHT 11 sensor (mentioned as green) is attached with Digital
pin 2 of Arduino board.
• Third leg(GND) of DHT 11 sensor (mentioned with black color) is attached with
GND pin of Arduino Board.
• One leg of piezo buzzer or other speaker is attached with output digital pin 7 and
second leg is attached with GND of Arduino board.
• One Terminal of LED is connected digital pin 6 and other is connected to GND of
Arduino Board.

System Diagram:

DHT11 Arduino Buzzer &


Sensor Board LED

Fig-4: System architecture

44
Internet of Things 20BEIT30098

Flow Chart:

Get DHT11 Sensor Reading


(pin 2 on Arduino)

No

Temperature >
TempMax OR
Moisture < HumiMin

Yes

Ring Buzzer & Blink LED


(Write HIGH Data on Digital
Pin 6 & 7 on Arduino)
Fig-5: Flow of System

Code:

#include "DHT.h"
#define DHTPIN 2 // pin which will be connected to output sensor data

int led = 6;
int buzzer = 7;
int TempMax = 35;
int HumiMin = 50;

#define DHTTYPE DHT11 // Sets the sensor used

DHT DHT (DHTPIN, DHTTYPE); // From a name for the Sensor

void setup ()
{
Serial.begin (9600); // Initialize the serial conexion
dht.begin (); // Starts communication with the sensor
Serial.println ("Start"); // Write a message on the serial
45
Internet of Things 20BEIT30098

pinMode (LED, OUTPUT); // Set the LED pins as output and buzzer
pinMode (buzzer, OUTPUT);
}

void loop () {
int humidity = dht.readHumidity(); // Set a variable to moisture
int temperature = dht.readTemperature(); // Set a variable to Temperature
// If mSQL failure in reading
if (isnan (temperature) || isnan (humidity))
{
Serial.println ("Error in sensor reading"); // Send an error message
delay (500); // Wait a time
}

else // If not mSQL error ...


{

Serial.print ("humidity"); // Write moisture in serial


Serial.print (humidity);
Serial.print ("% \ t");
Serial.print ("Temperature"); // Write the temperature in the serial
Serial.print (temperature);
Serial.println ("C *");

if (temperature> TempMax) // Condition:


{
digitalWrite (LED, HIGH); // League Led
digitalWrite (buzzer, HIGH); // gives a "beep" at the buzzer
delay (5000);
digitalWrite (buzzer, LOW);
delay (5000); // Wait 10 Seconds
digitalWrite (led, LOW); // Turn off the led
}

if (moisture <HumiMin) // condition:


{
digitalWrite (LED, HIGH);
for (int buz = 0; buz <= 3; buz ++) // gives 3 "Beeps" at the buzzer
{
digitalWrite (buzzer, HIGH);
delay (500);

46
Internet of Things 20BEIT30098

digitalWrite (buzzer, LOW);


delay (500);
}
delay (5000); // Wait 5 Seconds
digitalWrite (led, LOW); // Turn off the led
}

} // Close the loop else


} // Close the loop

Pre-defined function’s description (used in code):


DHT Name (dhtpin , dht type)
dhtpin: the pin on which the DHT is connected on Arduino.
dht type: It is the type of DHT sensor. Ex DHT 11,DHT 22 etc.

Applications can be designed:


• Food Temperatures, Food Temperature Sensors and Food Safety
Use of a wide range of different types of temperature sensors in the measurement of food
temperature in many aspects of cooking, not the least of which is in assuring that various
food types are cooked sufficiently to kill any dangerous organisms that may be in them.
• Safety System – In such safety system to detecting the fire there is a sudden change in
temperature so that can be easily identify by temperature Sensor.
• Virtual Reality Gaming Gloves – The sensors are important components used in
manufacturing virtual reality gloves. The Nintendo Power Glove is a good example.
• Other Applications – Flex sensors are common in different technological products, such as
automotive and industrial controls, computer peripherals, joysticks, and measuring devices.
These are also present in fitness products, musical instruments, and assistive technology
systems of modern vehicles.
Reference:
6. http://www.robot-r-us.com/vmchk/sensor-temp/humid/dht11-temperature-and-humidity-
sensor.html
7. http://www.usinainfo.com.br/module/csblog/detailpost/81-81-sensor-de-temperatura-e-u

47
Internet of Things 20BEIT30098

8. midade-com-jumper-dht11.htmlData Sheet of Flex sensor - flex22.pdf (attached with this


document)
9. http://www.spectrasymbol.com/flex-sensor

48
Internet of Things 20BEIT30098

Practical: 9

Aim: Implement the concept of Pulse Rate Sensor.

Fig-1 : Heart Rate Sensor

Sensor Type: Analog sensor


Working [1]:
Heart Beat can be measured based on optical power variation as light is scattered or absorbed during
its path through the blood as the heart beats, using this HeartRate Sensor.Heart beat sensor is
designed to give digital output of heat beat when a finger is placed on it. When the heart beat detector
is working, the beat LED flashes in unison with each heart beat. This digital output can be connected
to microcontroller directly to measure the Beats Per Minute (BPM) rate. It works on the principle
of light modulation by blood flow through finger at each pulse.

Pin Details [1]:


Board has 3-pin connector for using the sensor. Details are marked on PCB.

Pin Name Details


1 GND Power Supply Ground
2 +5V Power supply Positive input

49
Internet of Things 20BEIT30098

3 OUT Analog output

Application:
To notify the caretaker with a message when the heart rate is measured to be above or below the
normal range.

Circuit Diagram[3]:

50
Internet of Things 20BEIT30098

Applicat
ion Description:

Functionality[2]:

The sensor consists of a super bright red LED and light detector. The LED needs to be super bright
as the maximum light must pass spread in finger and detected by detector. Now, when the heart
pumps a pulse of blood through the blood vessels, the finger becomes slightly more opaque and so
less light reached the detector. With each heart pulse the detector signal varies. This variation is
converted to electrical pulse. This signal is amplified and triggered through an amplifier which
outputs +5V logic level signal. The output signal is also indicated by a LED which blinks on each
heart beat.

Circuit design:
Connect regulated DC power supply of 5 Volts.
Black wire is Ground, Next middle wire is Brown which is output and Red wire is positive supply.
These wires are also marked on PCB. To test sensor you only need power the sensor by connect two
wires +5V and GND.
You can leave the output wire as it is.
• One leg of Heart rate sensor (mentioned as red color) is attached with Analog +5V on
Arduino board.
• Second leg of Heart rate sensor (mentioned as purple) is attached with Analog-A0 pin of
Arduino board)
• Third leg of Heart rate Sensor (mentioned with black color) is attached with Analog-GND
pin.

• System Diagram:

51
Internet of Things 20BEIT30098

Fig-3: System architecture

Flow Chart:

52
Internet of Things 20BEIT30098

Code[3]:

// VARIABLES
int pulsePin = 0; // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 13; // pin to blink led at each beat
int fadePin = 5; // pin to do fancy classy fading blink at each beat
int fadeRate = 0; // used to fade LED on with PWM on fadePin

53
Internet of Things 20BEIT30098

// these variables are volatile because they are used during the interrupt service routine!
volatile int BPM; // used to hold the pulse rate
volatile int Signal; // holds the incoming raw data
volatile int IBI = 600; // holds the time between beats, must be seeded!
volatile boolean Pulse = false; // true when pulse wave is high, false when it's low
volatile boolean QS = false; // becomes true when Arduoino finds a beat.
void setup(){
pinMode(blinkPin,OUTPUT); // pin that will blink to your heartbeat!
pinMode(fadePin,OUTPUT); // pin that will fade to your heartbeat!
Serial.begin(115200); // we agree to talk fast!
interruptSetup(); // sets up to read Pulse Sensor signal every 2mS
// UN-COMMENT THE NEXT LINE IF YOU ARE POWERING The Pulse Sensor AT LOW
VOLTAGE,
// AND APPLY THAT VOLTAGE TO THE A-REF PIN
//analogReference(EXTERNAL);
}
void loop(){
sendDataToProcessing('S', Signal); // send Processing the raw Pulse Sensor data
if (QS == true){ // Quantified Self flag is true when arduino finds a heartbeat
fadeRate = 255; // Set 'fadeRate' Variable to 255 to fade LED with pulse
sendDataToProcessing('B',BPM); // send heart rate with a 'B' prefix
sendDataToProcessing('Q',IBI); // send time between beats with a 'Q' prefix
QS = false; // reset the Quantified Self flag for next time
}

ledFadeToBeat();

delay(20); // take a break


}
void ledFadeToBeat(){
fadeRate -= 15; // set LED fade value
fadeRate = constrain(fadeRate,0,255); // keep LED fade value from going into negative numbers!
analogWrite(fadePin,fadeRate); // fade LED
54
Internet of Things 20BEIT30098

}
void sendDataToProcessing(char symbol, int data ){
Serial.print(symbol); // symbol prefix tells Processing what type of data is coming
Serial.println(data); // the data to send culminating in a carriage return
}

//interrupt code.
volatile int rate[10]; // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0; // used to determine pulse timing
volatile unsigned long lastBeatTime = 0; // used to find IBI
volatile int P =512; // used to find peak in pulse wave, seeded
volatile int T = 512; // used to find trough in pulse wave, seeded
volatile int thresh = 512; // used to find instant moment of heart beat, seeded
volatile int amp = 100; // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true; // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false; // used to seed rate array so we startup with reasonable BPM

void interruptSetup(){
// Initializes Timer2 to throw an interrupt every 2mS.
TCCR2A = 0x02; // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC
MODE
TCCR2B = 0x06; // DON'T FORCE COMPARE, 256 PRESCALER
OCR2A = 0X7C; // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
TIMSK2 = 0x02; // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
sei(); // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

// THIS IS THE TIMER 2 INTERRUPT SERVICE ROUTINE.


// Timer 2 makes sure that we take a reading every 2 miliseconds
ISR(TIMER2_COMPA_vect){ // triggered when Timer2 counts to 124
cli(); // disable interrupts while we do this
55
Internet of Things 20BEIT30098

Signal = analogRead(pulsePin); // read the Pulse Sensor


sampleCounter += 2; // keep track of the time in mS with this variable
int N = sampleCounter - lastBeatTime; // monitor the time since the last beat to avoid noise

// find the peak and trough of the pulse wave


if(Signal < thresh && N > (IBI/5)*3){ // avoid dichrotic noise by waiting 3/5 of last IBI
if (Signal < T){ // T is the trough
T = Signal; // keep track of lowest point in pulse wave
}
}

if(Signal > thresh && Signal > P){ // thresh condition helps avoid noise
P = Signal; // P is the peak
} // keep track of highest point in pulse wave

// NOW IT'S TIME TO LOOK FOR THE HEART BEAT


// signal surges up in value every time there is a pulse
if (N > 250){ // avoid high frequency noise
if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ){
Pulse = true; // set the Pulse flag when we think there is a pulse
digitalWrite(blinkPin,HIGH); // turn on pin 13 LED
IBI = sampleCounter - lastBeatTime; // measure time between beats in mS
lastBeatTime = sampleCounter; // keep track of time for next pulse

if(secondBeat){ // if this is the second beat, if secondBeat == TRUE


secondBeat = false; // clear secondBeat flag
for(int i=0; i<=9; i++){ // seed the running total to get a realisitic BPM at startup
rate[i] = IBI;
}
}

if(firstBeat){ // if it's the first time we found a beat, if firstBeat == TRUE


firstBeat = false; // clear firstBeat flag
56
Internet of Things 20BEIT30098

secondBeat = true; // set the second beat flag


sei(); // enable interrupts again
return; // IBI value is unreliable so discard it
}

// keep a running total of the last 10 IBI values


word runningTotal = 0; // clear the runningTotal variable

for(int i=0; i<=8; i++){ // shift data in the rate array


rate[i] = rate[i+1]; // and drop the oldest IBI value
runningTotal += rate[i]; // add up the 9 oldest IBI values
}

rate[9] = IBI; // add the latest IBI to the rate array


runningTotal += rate[9]; // add the latest IBI to runningTotal
runningTotal /= 10; // average the last 10 IBI values
BPM = 60000/runningTotal; // how many beats can fit into a minute? that's BPM!
QS = true; // set Quantified Self flag
// QS FLAG IS NOT CLEARED INSIDE THIS ISR
}
}

if (Signal < thresh && Pulse == true){ // when the values are going down, the beat is over
digitalWrite(blinkPin,LOW); // turn off pin 13 LED
Pulse = false; // reset the Pulse flag so we can do it again
amp = P - T; // get amplitude of the pulse wave
thresh = amp/2 + T; // set thresh at 50% of the amplitude
P = thresh; // reset these for next time
T = thresh;
}

if (N > 2500){ // if 2.5 seconds go by without a beat


thresh = 512; // set thresh default
57
Internet of Things 20BEIT30098

P = 512; // set P default


T = 512; // set T default
lastBeatTime = sampleCounter; // bring the lastBeatTime up to date
firstBeat = true; // set these to avoid noise
secondBeat = false; // when we get the heartbeat back
}

sei(); // enable interrupts when youre done!


}// end isr

Applications can be designed[2]:


>>Fitness: It is used in daily gym workout to prevent your body from Over training.
It is also uses for the finding human body stress level.

>>Crime: It is also useful in lie-detection test during any criminal case investigation.

>>Body Treatment: It is also prevent your body before getting sick with giving a perfect
measurement of your pulse.

>>Emergency: Reduce many critical and emergency cases during heart attack.
Reference:
1. http://www.elprocus.com/heartbeat-sensor-working-application/
2. Data Sheet of heart beat sensor - datasheet.pdf (attached with this document)
3. www.pulseRateSensor.com

58
Internet of Things 20BEIT30098

Practical: 10

Aim: Perform practical to send SMS using GSM Module and Arduino Board.

Introduction:

A GSM modem is one of the wireless modem that is devised to work with a GSM wireless network.
It works with the same frequency of GSM wireless network.The GSM wireless modem works in
the way like a dial-up modem. The main difference between the GSM modem and dial up modem
is that a dial-up modem sends and receives data through a fixed telephone line while a GSM wireless
modem sends and receives data through radio wave propagation. A GSM modem can be an external
device, a PC Card or a PCMCIA Card.A GSM modem can be connected to a computer using a serial
cable or a usb cable. It works similar to a GSM mobile phone, and also GSM modem requires a SIM
card for operation. It can be used for internet purpose also depending on various subscriptions to the
service provider. There are so many feature and operations that can be performed using GSM
modems.
Features:
• Quad Band GSM/GPRS : 850 / 900 / 1800 / 1900 MHz
• Configurable Baud Rate

59
Internet of Things 20BEIT30098

• SMA (SubMiniature version A) connector with GSM L Type Antenna


• Built in SIM (Subscriber Identity Module) Card holder
• Built in Network Status LED
• Inbuilt Powerful TCP / IP (Transfer Control Protocol /
Internet Protocol) support for GPRS (General Packet
Radio Service)

• Inbuilt Mic
• Most Status and Controlling pins are available

• Normal Operation Temperature : -20 °C to +55 °C


• Input Voltage : 5 V to 12V DC
• LDB9 connector (Serial Port) provided for easy interfacing
Functions:
• Voice transmission through calling.
• Data transfer through GPRS (General Packet Radio Service).
• Data transfer through SMS(Short Message Service).

Hardware Description:

60
Internet of Things 20BEIT30098

SIM (Subscriber Identity Module) Card Slot:

This onboard SIM card slot provide User functionality of insert a SIM (GSM only) card of any
service provider. While inserting in and removing out SIM card from SIM card slot, User needs
to take precaution that power supply should be OFF so that after making Power supply ON it

will be easy to reinitialize with SIM for this module.

Power On/Off and GSM On Switch:

Power On/Off switch is type of push-on push-off switch which is used to provide power supply
on/off provided through AC/DC Socket indicated by ‘Power LED’.

Power Supply Socket:

This power supply socket which actually named as AC/DC Socket provides the functionality
to user to connect external power supply from Transformer, Battery or Adapter through DC
jack. User can provide maximum of 12V AC/DC power supply through AC/DC socket.

61
Internet of Things 20BEIT30098

Indicator LEDs:

Indicator LEDs just used to indicate status accordingly. These are three LEDs represents
Power On/Off Status, Network Status and Module On/Off Status respectively.

RXD, TXD and GND pins (JP2):

Here pins are used to connect devices which needs to be connected to GSM module
through USART (Universal Synchronous Asynchronous Receiver and Transmitter)
communication.

62
Internet of Things 20BEIT30098

• PIN diagram:

Pin Name Details


1 GND Power supply ground
2 TX transmitter
3 RX receiver
4 Line r & Line l Line input
5 Spk_p&spk n Speaker positive & negative
6 Mic_p& mic n Mic positive & negative

• PIN specification:
• AT commands

63
Internet of Things 20BEIT30098

64
Internet of Things 20BEIT30098

65
Internet of Things 20BEIT30098

• Messaging:

➢ Code:

String smsNo = "+919601862146";


String smsString = "Hello World";
void sendTextMessage();
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
}

void loop()
{
sendTextMessage();
while(1);
}
void sendTextMessage()
{
msgSend("AT+CMGF=1"); //Because we want to send the SMS in text mode
delay(1000);
msgSend("AT + CMGS = \"" + smsNo +"\""); //send sms message, be careful need to add
a country code before the cellphone number
delay(1000);
msgSend(smsString); //the content of the message
delay(1000);
//msgSend((char)26);
Serial1.println((char)26);//the ASCII code of the ctrl+z is 26
delay(1000);
Serial1.println();
}

void msgSend(String atCommand)

66
Internet of Things 20BEIT30098

{
String gprsr;
int flag = 0;

Serial1.println(atCommand);
while(Serial1.available()==0);
gprsr=Serial1.readString();
Serial.println(gprsr);
}

Flowchart:

Applications:

GSM module is generally used with other sensors and Microcontroller.


➢ Used in real time applications such as:
➢ In refrigerators to notify owners about empty stock
➢ In smart electric meters for sending readings remotely
➢ For security purposes to notify a user about any security breach at home.
➢ To track GPS location of buses and trains.

67
Internet of Things 20BEIT30098

Reference:

• https://www.arduino.cc/en/Reference/GSM
• https://www.arduino.cc/en/Reference/GSMSMSRead
• tronixstuff.com/2014/01/08/tutorial-arduino-and-sim900-gsm-modules

68
Internet of Things 20BEIT30098

Practical: 11

Aim: Create a simple Web Service to print Hello World.

Requirements:
1: NetBeans IDE(Any Version)
2. JDK (Any Version)
Steps:

1. Open NetBeans IDE.


2. File ->New Project ->Java WEB -> Web Application click on NEXT.

69
Internet of Things 20BEIT30098

3. Enter Project Name Click on NEXT.

4. Select Glassfish Server(any version) and must chose JAVA EE 6 click on FINISH.

70
Internet of Things 20BEIT30098

5. It will open Index.jsp(By Default File) File in NetBeans and create some directory structure
as shown in figure.

6. Right Click on Project Name and choose New -> Web Service ORNew -> Other ->
WebService -> WebService

71
Internet of Things 20BEIT30098

7. It will open prompt shown in the figure. Fill all the details and click on FINISH.

8. Now you can see the package and your java file of webservice. Open that file .there will be
a default method name as “Public String Hello( String Parameter)” Which take a string
as a parameter and return the “Hello + String Parameter which is passed as input”.

72
Internet of Things 20BEIT30098

9. Now you created your first Hello Service. Let’s Test it..is it correct or not?
Right click on project name then 1st Click on Deploy then again Right click on Project
Name click on TEST .

73
Internet of Things 20BEIT30098

10. It will open output in web browser as shown in figure. It contains one text box to get the
input and other button to submit that text box data. When we submit any data it will show
output message and also show SOAP request and Response as shown in figure.

74
Internet of Things 20BEIT30098

11. We successfully created the webservice and also test it but it is not useful until there is no
client to consume it. So Let’s make HelloService Client to consume this Service.

12. Again File ->New Project ->Java WEB -> Web Application click on NEXT.

13. Enter Project Name Click on NEXT.

14. Select Glassfish Server(any version) and must chose JAVA EE 6 click on FINISH.

75
Internet of Things 20BEIT30098

15. It will open Index.jsp(By Default File) File in NetBeans and create some directory structure
as shown in figure.

16. Right Click on Project Name and choose New -> Web Service Client OR New -> Other ->
WebService -> WebServiceClient

76
Internet of Things 20BEIT30098

17. It will open following Prompt and you have to select the webservice by click on Browse(As
shown in figure) and select your suitable web service then click on FINISH. It will directly
parse the WSDL file.

77
Internet of Things 20BEIT30098

18. You will show folder named WebService References in Client project as shown in
figure.There is also a hello web service.

78
Internet of Things 20BEIT30098

19. Open Index.jsp file of Client and make a one simple form which contain the simple text box
and a submit button.

20. Simple Right click any where in Index.jsp then select Web Service Client Resourse -> Call
Web Service Operation. It will open following prompt. Select hello service From this.

79
Internet of Things 20BEIT30098

21. It will add following code in Index.jsp file.

22. Here you have to set the value of “name ” parameter according to your form. For mine it
will be as following.

80
Internet of Things 20BEIT30098

23. Now Save This and Right click on Client Project and Deploy. Then again Right click on
Client Project and Click On Run .

24. It will open tab in web browser and you have to enter a string and it will show Hello message
as we defined earlier In web service method.

81
Internet of Things 20BEIT30098

25. We successfully created Hello Web Service and also consume it by creating Web Service
Client.

82
Internet of Things 20BEIT30098

Practical: 12

Aim: Create a web service to display alert message / Notification when


temperature goes beyond limit
Requirements:
1: NetBeans IDE(Any Version)
2. JDK (Any Version)
Steps:

1. Open NetBeans IDE.


2. File ->New Project ->Java WEB -> Web Application click on NEXT.

3.

4. Enter Project Name Click on NEXT.

83
Internet of Things 20BEIT30098

5. Select Glassfish Server(any version) and must chose JAVA EE 6 click on FINISH.

6. It will open Index.jsp(By Default File) File in NetBeans and create some directory structure
as shown in figure.

84
Internet of Things 20BEIT30098

7. Right Click on Project Name and choose New -> Web Service OR New -> Other ->
WebService -> WebService

8. It will open prompt shown in the figure. Fill all the details and click on FINISH.

85
Internet of Things 20BEIT30098

9. Now you can see the package and your java file of webservice. Open that file . there will be
a default method name as “Public String Hello( String Parameter)” Which take a string as
a parameter and return the “Hello + String Parameter which is passed as input”. We have
to remove that method and need to create a another new method steps as shown in figure.

10. Now You have to click on Design tab from above left side corner and then click on Add
Operation. It will open one prompt and you have to enter Name ,Return type of method
and add required parameters and their data types as shown below.(Here we take two input
parameter like temp of Int type and set return type to Void).

86
Internet of Things 20BEIT30098

11. Click on OK. Then again move to Source tab.Here you can show that new method is added
in source code as we defined earlier.We have to check condition for temperature beyond
the limit and then send Email Notification to ADMIN.

Index.JSP

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package TEMP;
import javax.jws.Oneway;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
/**
*
* @author Anuj
*/
87
Internet of Things 20BEIT30098

@WebService(serviceName = "sendNotification")
public class sendNotification {
private static String USER_NAME = "[email protected]"; // GMail user name (just
the part before "@gmail.com")
private static String PASSWORD = "25101994@anuj"; // GMail password
private static String RECIPIENT = "[email protected]";
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Temperature Notification.";
String body = "Temperature Beyond The Predefined Limit..";
/**
* Web service operation
*/
@WebMethod(operationName = "operation")
@Oneway
public void operation(@WebParam(name = "temp") int temp) {
if(temp>25)
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String
body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
System.out.println("getting HOST..");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
System.out.println("getting message..");
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
88
Internet of Things 20BEIT30098

transport.close();
System.out.println("Sucessful..");
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

12. Now you created your first Hello Service. Let’s Test it..is it correct or not?
Right click on project name then 1st Click on Deploy then again Right click on Project
Name click on TEST .
13. It will open output in web browser as shown in figure. It contains one text box to get the
input and other button to submit that text box data. When we submit any data it will
show output message and also show SOAP request and Response as shown in figure.

14. We successfully created the webservice and also test it but it is not useful until there is no client
to consume it. So Let’s make TempClient to consume this Service.

15. Again File ->New Project ->Java WEB -> Web Application click on NEXT.

89
Internet of Things 20BEIT30098

16. Enter Project Name Click on NEXT.

17. Select Glassfish Server(any version) and must chose JAVA EE 6 click on FINISH.
18. It will open Index.jsp(By Default File) File in NetBeans and create some directory structure
as shown in figure.
19. Right Click on Project Name and choose New -> Web Service Client OR New -> Other ->
WebService -> WebServiceClient

20. It will open following Prompt and you have to select the webservice by click on Browse and select
your suitable web service then click on FINISH. It will directly parse the WSDL file.

90
Internet of Things 20BEIT30098

21. You will show folder named WebService References in Client project.There is also a hello web
service.
22. Open Index.jsp file of Client and make a one simple form which contain the simple text box and a
submit button.

23. Simple Right click any where in Index.jsp then select Web Service Client Resourse -> Call Web
Service Operation. It will open following prompt. Select sendNotification service From this.

91
Internet of Things 20BEIT30098

24. Here is complete Index.JSP file of CLIENT you have to change like this.
<%--
Document : index
Created on : Nov 4, 2015, 9:43:48 PM
Author : Anuj
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Temperature Notification</title>
</head>
<body>
<h1> It will send Email to ADMIN when temperature is above 25 Celcius.</h1>
<form action="index.jsp">
Enter The Value Of Temperature: <input type='text' name='txt1' value="">
<input type='submit' value="Get Notfication">
</form>

<%-- start web service invocation --%><hr/>


<%
try {
92
Internet of Things 20BEIT30098

temp.SendNotification_Service service = new temp.SendNotification_Service();


temp.SendNotification port = service.getSendNotificationPort();
// TODO initialize WS operation arguments here
int temp = Integer.parseInt(request.getParameter("txt1").toString());
port.operation(temp);
out.println("SUCESSFUL");
} catch (Exception ex) {
// TODO handle custom exceptions here
}
%>
<%-- end web service invocation --%><hr/>
</body>
</html>

25. Now Save This and Right click on Client Project and Deploy. Then again Right click on Client Project
and Click On Run .
26. It will open tab in web browser and you have to enter two number as parameter and it will show
Addidtion of two number as we defined earlier In web service method.

27. We successfully created Hello Web Service and also consume it by creating Web Service Client

93
Internet of Things 20BEIT30098

94

You might also like