Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

Internet of Things 20BEIT30012

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.
Pin Diagram

22
Internet of Things 20BEIT30012

( 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

`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

23
Internet of Things 20BEIT30012

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
● 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

24
Internet of Things 20BEIT30012

Code
const int ledPin = 13; const

int knockSensor = A0; const

int threshold = 100;

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

25
Internet of Things 20BEIT30012

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 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-
piezoelectricshock-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

26
Internet of Things 20BEIT30012

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.

Fig 2: Piezoelectric Accelerometer


2. Capacitive Effect:

27
Internet of Things 20BEIT30012

⮚ 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.

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:

28
Internet of Things 20BEIT30012

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:

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:

29
Internet of Things 20BEIT30012

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

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");
Serial.print(analogRead(zpin));

31
Internet of Things 20BEIT30012

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/accelerometersui

o http://artpluscode.com

https://learn.sparkfun.com/tutorials/accelerometer-basics

32
Internet of Things 20BEIT30012

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

33
Internet of Things 20BEIT30012

Fig-2 : DHT 11 Circuit Diagram

Application [2]:

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

Circuit Diagram:

34
Internet of Things 20BEIT30012

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:

35
Internet of Things 20BEIT30012

Fig-4: System architecture

Flow Chart:

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

36
Internet of Things 20BEIT30012

Serial.println ("Start"); // Write a message on the serial


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);
digitalWrite (buzzer, LOW);
delay (500);
}
delay (5000); // Wait 5 Seconds
digitalWrite (led, LOW); // Turn off the led
}

} // Close the loop else


} // Close the loop

37
Internet of Things 20BEIT30012

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-umidade-
comjumper-dht11.htmlData Sheet of Flex sensor - flex22.pdf (attached with this document)
8. http://www.spectrasymbol.com/flex-sensor

38
Internet of Things 20BEIT30012

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
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]:

39
Internet of Things 20BEIT30012

40
Internet of Things 20BEIT30012

Application 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:

Fig-3: System architecture

41
Internet of Things 20BEIT30012

Flow Chart:

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

// 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!

42
Internet of Things 20BEIT30012

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
}
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

43
Internet of Things 20BEIT30012

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

44
Internet of Things 20BEIT30012

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
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)

45
Internet of Things 20BEIT30012

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
• 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

46
Internet of Things 20BEIT30012

• 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:

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.

47
Internet of Things 20BEIT30012

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.

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.

48
Internet of Things 20BEIT30012

● PIN diagram:

● PIN specification:

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

53

● AT commands
Internet of Things 20BEIT30012

50
Internet of Things 20BEIT30012

51
Internet of Things 20BEIT30012

● 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)


{
String gprsr;
int flag = 0;

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

Flowchart:

52
Internet of Things 20BEIT30012

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.

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

53
Internet of Things 20BEIT30012

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.

3. Enter Project Name Click on NEXT.

54
Internet of Things 20BEIT30012

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

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

55
Internet of Things 20BEIT30012

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

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

56
Internet of Things 20BEIT30012

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”.

9. Now you created your first Hello Service. Let’s Test it..is it correct or not?
57
Internet of Things 20BEIT30012

Right click on project name then 1st Click on Deploy then again Right click on Project
Name click on TEST .

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.

58
Internet of Things 20BEIT30012

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.
59
Internet of Things 20BEIT30012

13. Enter Project Name Click on NEXT.

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

60
Internet of Things 20BEIT30012

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

61
Internet of Things 20BEIT30012

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.

62
Internet of Things 20BEIT30012

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

63
Internet of Things 20BEIT30012

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.

64
Internet of Things 20BEIT30012

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.

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

65
Internet of Things 20BEIT30012

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.

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

66
Internet of Things 20BEIT30012

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. Enter Project Name Click on NEXT.

67
Internet of Things 20BEIT30012

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

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

68
Internet of Things 20BEIT30012

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

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

69
Internet of Things 20BEIT30012

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”. We have to remove that method and need to create a another new method
steps as shown in figure.

9. 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).

70
Internet of Things 20BEIT30012

10. 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
71
Internet of Things 20BEIT30012

javax.mail.*; import
javax.mail.internet.*;
/**

* @author Anuj

*/

@WebService(serviceName = "sendNotification")

public class sendNotification {


private static String USER_NAME = "connectanuj4u@gmail.com"; // GMail user name
(just the part before "@gmail.com") private static String PASSWORD =
"25101994@anuj"; // GMail password private static String RECIPIENT =

"shahanuj4u@gmail.com";
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();

72
Internet of Things 20BEIT30012

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());
transport.close();

System.out.println("Sucessful..");

73
Internet of Things 20BEIT30012

catch (AddressException ae) {


ae.printStackTrace();
}

catch (MessagingException me) {


me.printStackTrace();
}

11. 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 .
12. 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.

13. 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.

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

74
Internet of Things 20BEIT30012

15. Enter Project Name Click on NEXT.

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

19. 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.

75
Internet of Things 20BEIT30012

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

22. 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.

76
Internet of Things 20BEIT30012

23. 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 {

77
Internet of Things 20BEIT30012

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>

24. Now Save This and Right click on Client Project and Deploy. Then again Right click on Client Project
and Click On Run .
25. 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.

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

78

You might also like