1
CHAPTER 1
                                INTRODUCTION
1.1 INTRODUCTION TO IoT
      The Internet of things (IoT) is the internetworking of physical devices,
vehicles, buildings and other items embedded with electronics, software,
sensors, actuators, and network connectivity that enable these objects to collect
and exchange data. In 2013 the Global Standards Initiative on Internet of Things
(IoT-GSI) defined the IoT as the infrastructure of the information society. The
IoT allows objects to be sense and control remotely existing network
infrastructure, creating opportunities for more direct integration of the physical
world into computer based systems, resulting in improved efficiency, accuracy
and economic benefit in addition to reduced human intervention. When IoT is
augmented with sensors and actuators, the technology becomes an instance of
the more general class of cyber-physical systems, which also encompasses
technologies such as smart grids, smart homes, intelligent transportation and
smart cities. Each thing is uniquely identifiable through its embedded computing
system but it is able to interoperate within the existing internet infrastructure.
      Early forms of ubiquitous information and communication networks are
evident in the widespread use of mobile phones, the number of mobile phones
worldwide surpassed 2 billion in mid-2005. These little gadgets have become an
integral and intimate part of everyday life for many millions of people, even
more so than the internet.
      Today, developments are rapidly under way to take this phenomenon an
important step further, by embedding short-range mobile transceivers into a
wide array of additional gadgets and everyday items, enabling new forms of
                                                                               2
communication between people and things and between things themselves. A
new dimension has been added to the world of information and communication
technologies (ICTs): from anytime, anyplace connectivity for anyone.
                         Fig.1.1 New Dimension of IoT
     Connections will multiply and create an entirely new dynamic network of
networks called an Internet of Things. The Internet of Things is neither science
fiction nor industry hype, but is based on solid technological advances and
visions of network ubiquity that are zealously being realized.
                                                                                 3
1.2 TECHNOLOGIES FOR THE IoT
      The Internet of Things is a technological revolution, that represents the
future of computing, communications and its development depends on dynamic
technical innovation in a number of important fields from wireless sensors to
nanotechnology. First, in order to connect everyday objects and devices to large
databases and networks and indeed to the network of networks. A simple,
unobtrusive and cost-effective system of item identification is crucial. Radio-
frequency identification (RFID) offers this functionality. Data collection will
benefit from the ability to detect changes in the physical status of things using
sensor technologies. Embedded intelligence in the things themselves can further
enhance the power of the network by devolving information processing
capabilities to the edges of the network. Finally, advances in miniaturization and
nanotechnology mean that smaller and smaller things will have the ability to
interact and connect in Fig. 1.2. A combination of all of these developments will
create an Internet of Things that connects the world’s objects in both a sensory
and an intelligent manner.
      Indeed, with the benefit of integrated information processing, industrial
products and everyday objects will take on smart characteristics and capabilities.
They may also take on electronic identities that can be queried remotely or be
equipped with sensors for detecting physical changes around them. Eventually,
every particle as small as dust might be tagged and networked. Such
developments will turn the merely static objects of today into newly dynamic
things, embedding intelligence in our environment and stimulating the creation
of innovative products and entirely new services.
    RFID technology, which uses radio waves to identify items. This is seen as
one of the pivotal enablers of the Internet of Things. Although it has been
labeled as the next-generation of bar codes. RFID systems offer much more in
that, they can track items in real-time to yield important information about their
                                                                               4
location and status. Early applications of RFID include automatic highway toll
collection, supply-chain management for large retailers, pharmaceuticals for the
prevention of counterfeiting and e-health for patient monitoring.
                    Fig 1.2 Miniaturization towards the IoT
   More recent applications range from sports and leisure ski passes to personal
security for tagging children at schools. RFID tags are even being implanted
under human skin for medical purposes, but also for VIP access to bars like the
Baja Beach Club in Barcelona. E-government applications such as RFID in
drivers’ licenses, passports or cash are under consideration. RFID readers are
now being embedded in mobile phones.
                                                                                 5
1.3 ABOUT BIOMEDICAL ENGINEERING
       Medical engineering is commonly known as biomedical engineering.
Medical engineering is an interdisciplinary field of study that combines
medicine and engineering, covering technical areas such as biology, calculus,
physiology, nanotechnology, biochemistry and anatomy. As a medical engineer,
primary responsibility will be to design and create new medical equipment and
instruments.
    Biomedical engineering (BME) is the application of engineering principles
and design concepts to medicine and biology for healthcare purposes such as
diagnostic or therapeutic. This field seeks to close the gap between engineering
and medicine, combining the design and problem solving skills of engineering
with medical biological sciences to advance health care treatment, including
diagnosis, monitoring and therapy.
    Biomedical engineering has recently emerged as its own study, as compared
to many other engineering fields. Such an evolution is common as a new field
transitions from being an interdisciplinary specialization among already-
established fields, to being considered a field in itself. Much of the work in
biomedical engineering consists of research and development, spanning a broad
array of subfields. Prominent biomedical engineering applications include the
development of biocompatible prostheses, various diagnostic and therapeutic
medical devices ranging from clinical equipment to micro-implants, common
imaging equipment such as MRIs and EKGs, regenerative tissue growth,
pharmaceutical drugs and therapeutic biological.
      During the heart attack, heart muscle is depraved of oxygen and it will
literally die if the artery is blocked. The first few hours are critical in saving
much of the dying heart muscle and preventing permanent heart damage.
Unfortunately, the symptoms vary and most common reason for critical delays
                                                                                  6
in medical treatment is lack of early warning and patient unawareness. This can
be prevented by using proposed technique. The patient heart rate and
temperature can be monitored regularly.
1.4 OBJECTIVES
      To design a cost effective, smarter and result oriented system to focus on
the patients with chronic heart disease to provide 24×7 health monitoring. The
goal is to provide early heart attack detection so that patient’s medical attention
will be given within the first few critical hours, thus greatly improving patient
chances of survival. By the use of this system the elderly living people no need
to go to hospital for checkup. Patients can check themselves in their homes. It
provides timely availability of information about health status. Medical attention
will be given earlier.
     Daily mobile health care service is more and more important for solitary
people, disabled and elderly people. From the system, sensing the variety of
physical parameters of the human body is possible.
                                                                                7
                                  CHAPTER 2
                           LITERATURE REVIEW
      Avitall, B et al., [1] (2001), “Remote Health Monitoring System”
proposed the life expectancy in most countries has been increasing continually
over the several few decades thanks to significant improvements in medicine,
public health, as well as personal and environmental hygiene. However,
increased life expectancy combined with falling birth rates are expected to
engender a large aging demographic in the near future that would impose
significant  burdens on the socio-economic structure of these countries.
Therefore, it is essential to develop cost-effective, easy-to-use systems for the
sake of elderly healthcare and well-being. Remote health monitoring, based on
non-invasive and wearable sensors, actuators and modern communication and
information technologies offers an efficient and cost-effective solution that
allows the elderly to continue to live in their comfortable home environment
instead of expensive healthcare facilities.
      These systems will also allow healthcare personnel to monitor important
physiological signs of their patients in real time, assess health conditions and
provide feedback from distant facilities. In this paper, we have presented and
compared several low-cost and non-invasive health and activity monitoring
systems that were reported in recent years. A survey on textile-based sensors
that can potentially be used in wearable systems is also presented. Finally,
compatibility of several communication technologies as well as future
perspectives and research challenges in remote monitoring systems will be
discussed.
      Cleland, J. G., Swedberg, K., and Beradi. [3] (2003), “Fuzzy
knowledge representation framework in medical consultation” Presented a
                                                                                   8
general view of the current applications of fuzzy logic in medicine and
bioinformatics. Particularly review the medical literature using fuzzy logic.
Then recall the geometrical interpretation of fuzzy sets as points in a fuzzy
hypercube and present two concrete illustrations in medicine that is drug
addictions and in bioinformatics, comparison of genomes. The diagnosis of
disease involves several levels of uncertainty and imprecision, and it is inherent
to medicine.
       A single disease may manifest itself quite differently, depending on the
patient, and with different intensities. A single symptom may correspond to
different diseases. On the other hand, several diseases present in a patient may
interact and interfere with the usual description of any of the diseases. The best
and most precise description of disease entities uses linguistic terms that are also
imprecise and vague. Moreover, the classical concepts of health and disease are
mutually exclusive and opposite. However, some recent approaches consider
both concepts as complementary processes in the same continuum. According to
the definition issued by the World Health Organization (WHO), health is a state
of complete physical, mental, and social well-being, and not merely the absence
of disease or infirmity. The loss of health can be seen in its three forms: disease,
illness, and sickness. To deal with imprecision and uncertainty, disposal fuzzy
logic is used. Fuzzy logic introduces partial truth values, between true and false.
      Hollands, R. J.[6]      (2008), “ Will the real smart city stand up on
Intelligent progressive or Entrepreneurial City” The Debates about the future of
urban development in many Western countries have been increasingly
influenced by discussions of smart cities. Yet despite numerous examples of this
urban labelling phenomenon, know surprisingly little about so-called smart
cities, particularly in terms of what the label ideologically reveals as well as
hides. Due to its lack of definitional precision, not to mention an underlying
self-congratulatory tendency, the main thrust of this article is to provide a
                                                                                 9
preliminary critical polemic against some of the more rhetorical aspects of smart
cities. The primary focus is on the labelling process adopted by some designated
smart cities, with a view to problematizing a range of elements that supposedly
characterize this new urban form, as well as question some of the underlying
assumptions/contradictions hidden within the concept. To aid this critique, the
article explores to what extent labelled smart cities can be understood as a high-
tech variation of     the ‘entrepreneurial city’, as well as speculates on some
general principles which would make them more progressive and inclusive.
      Kangavalli, M., and Sukumar, P.[9] (2015), “Asynchronous transfer
mode Im1plementation in Cardiac patient monitoring” Proposed the purpose of
this thesis was to design and implement communication equipment used for
telemedicine in Shisong Cardiac Center by hiring bandwidth from Camtel using
optical fiber as the transmission medium. Plastic optical fibers known to be very
cheap and very fast was able to produce quality signals that canbe used for video
conferencing.       A VSAT link was created as a standby to the optical fiber so
that if any destruction occurred on the optical fiber, the VSAT link will be used
to transmit the signals while the repairs on the fiber were going on.
      To produce quality signals and to maintain the functionality of the
Cardiac Center, the following steps were taken into consideration. Firstly, very
high bandwidth of plastic optical fiber was hired from Camtel and these signals
were given priority over any other signals provided by Camtel. Secondly, the
network was encrypted in such a manner that only two persons can have access
to the signals. Intruders cannot be able to have access to the network to cause
confusion within the signal transmission since all the finger prints of the two
users are snapped and an alarm is set to produce a sound if the finger prints
presented on the equipment are not the right finger prints registered.
                                                                                  10
      Meganathan, C and Sukumar, P, [10] (2013), “ Retinal Lesion
Detection by using points of Interest and Visual Dictionaries”, Presented an
algorithm to detect the presence of diabetic retinopathy (DR)-related lesions
from fundus images based on a common analytical approach that is capable of
identifying both red and bright lesions without requiring specific pre- or post-
processing. The visual words dictionary was applied to classifying bright and
red lesions with classical cross validation and cross dataset validation to indicate
the robustness of this approach. It can obtained an area under the curve (AUC)
of 95.3% for white lesion detection and an AUC of 93.3% for red lesion
detection using fivefold cross validation and our own data consisting of 687
images of normal retinae, 245 images with bright lesions, 191 with red lesions,
and 109 with signs of both bright and red lesions.
      For cross dataset analysis, the visual dictionary also achieves compelling
results using our images as the training set and the RetiDB and Messidor images
as test sets. In this case, the image classification resulted in an AUC of 88.1%
when classifying the RetiDB dataset and in an AUC of 89.3% when classifying
the Messidor dataset, both cases for bright lesion detection. The results indicate
the potential for training with different acquisition images under different setup
conditions with a high accuracy of referral based on the presence of either red or
bright lesions or both. The robustness of the visual dictionary against image
quality that is blurring, resolution, and retinal background, makes it a strong
candidate for DR screening of large, diverse communities with varying cameras
and settings and levels of expertise for image capture.
      Pandian, P. S et al., [11] (2008) ,“Wireless Sensor Network for Wearable
Physiological Monitoring” Presented wearable physiological monitoring
systems uses an array of sensors integrated into the fabric of the wearer to
continuously acquire and transmit the physiological data to a remote monitoring
station. The data acquired at the remote monitoring station is correlated to study
                                                                                 11
the overall health status of the wearer. The wearable monitoring systems allow
an individual to monitor patient vital signs remotely and receive feedback to
maintain a good health status. These systems alert medical personnel, when
abnormalities are detected. The conventional physiological monitoring system
used in hospitals cannot be used for wearable physiological monitoring
applications.
      Robert, G et al.,[14] (2008), “Wireless Device for Patient Monitoring”
Proposed the Rapid Response Service is an information service for those
involved in planning and providing health care in Canada. Rapid responses are
based on a limited literature search and are not comprehensive, systematic
reviews. The intent is to provide a list of sources of the best evidence on the
topic that CADTH could identify using all reasonable efforts within the time
allowed. Rapid responses should be considered along with other types of
information and health care considerations. The information included in this
response is not intended to replace professional medical advice, nor should it be
construed as a recommendation for or against the use of a particular health
technology.
      Readers are also cautioned that a lack of good quality evidence does not
necessarily mean a lack of effectiveness particularly in the case of new and
emerging health technologies, for which little information can be found, but
which may in future prove to be effective. While CADTH has taken care in the
preparation of the report to ensure that its contents are accurate, complete and up
to date, CADTH does not make any guarantee to that effect. CADTH is not
liable for any loss or damages resulting from use of the information in the
report.
      Ross, P. E., [15] (2004), “Managing care through the air or remote health
monitoring” suggested that, the remote patient monitoring field is a rapidly
                                                                                12
growing one given the advantages it offers for home healthcare, remote regions
and elderly care. However, with it comes a long list of considerations and
critical issues for designers and engineers to keep in mind. This article offers a
bird’s eye view of this sector and many of the factors on which to maintain
focus.
         The last decade has seen a rapid growth and adoption of mobile
computing devices, such as smartphones and tablets. It cannot be missed from
the view of the healthcare industry. Healthcare providers, clinicians and medical
device manufacturers are seeking new and innovative ways to use these
powerful platforms to improve the quality of patient care and lower healthcare
costs. A major area where this is directly impacting the patient consumer is in
remote patient monitoring (RPM) solutions.
                                                                                13
                                  CHAPTER 3
                             EXISTING METHOD
3.1 INTRODUCTION TO EXISTING METHOD
   Home based health care system is increasing trend in smart cities. The timely
availability of information about health status of chronic heart disease, patients
can play a significant role in decision making about diagnosis and needed
treatment in real time. Fuzzy logic has proved to be the remarkable tool for
building intelligent decision making systems based on the healthcare
practioner’s knowledge and observations. Fuzzy logic based home healthcare
system for the chronic heart disease patients in stable conditions is used for out
of hospital follow up and monitoring.
      The existing system can provide an innovative, timely resource and a
supplement for the existing healthcare systems helping practioner’s to treat
efficiently to cardiac patients who lived alone at their homes. Additionally this
model is anticipated to be cost effective, smarter and result oriented when
compare to other prevailing traditional methods. An analysis of structure and
evaluation of the system performance is presented along with the potential
applicability in real world system development
       Internet of Things (IoT) will be the most sought soon after enabling
technology from the domain of Intelligent City. Therefore, distant health-care
monitoring services aided with IoT tend to be valuable. A remote health
monitoring system mainly is made up of portable, wearable and battery pack
powered sensing unit that's assigned with the task of sensing a variety of
physical parameters of the human body. This unit boasts the responsibility
regarding transmit the sensed data for the remote environment with regard to
storage and diagnosis in the patient.
                                                                                14
3.2 ISSUES IN IoT BASED HEALTH CARE MONITORING SYSTEM
          Nowadays Smart City is the buzzword worldwide. Multinational
corporations are investing a lot on research of Smart City and countries spending
huge to user a new age in the name of Smart City. From policy making to
implementation, Europe is way ahead. It is poised to turn our surrounding smart
and day to day life smarter using cutting edge technologies in environment
friendly manner. Internet of Things (IoT) is the most popular technology in the
area of Smart City. With the booming population, smart cities must include a
policy for provisioning smart and efficient health care services to its citizens.
But there is a huge need-gap between the requirement of health care facilities
and actual scenario. Also, professional manpower is scarce.
      Building health-care infrastructure from scratch is long drawn procedure.
Moreover, it involves huge capital cost at one go. Therefore, in the area of smart
city using remote health care monitoring services aided with IoT are more
effective. A remote health monitoring system mainly consists of a portable,
wearable and battery powered sensing unit that is assigned with the task of
sensing various physical parameters of the human body, following a strict
sampling rate specified for the parameters. This unit also has the responsibility
of transmitting the sensed data to the remote environment for storage and
diagnosis of the patient.
           Therefore it should be utilized in an efficient manner, so that
communication as well as energy resources are not wasted due to unnecessary
actions. Doctors would be overburdened with task of monitoring if they have to
monitor each and every patient by monitoring all of their physical parameters.
So it would be quite beneficial if the sensing unit is given the intelligent
capability of performing a general diagnosis of the patient and only forward the
cases with some abnormal conditions to the doctors. Furthermore, diagnosis of
                                                                               15
diseases is based on the readings of a subset of the sensors and is usually
performed in a step by step manner. So, sensor data from all the sensors may not
be required at one go. This way, a lot of energy resources can be preserved.
3.3 BLOCK DIAGRAM OF REQUEST REPLY ALGORITHM
     The above mentioned issues have been addressed on an IoT based health
care monitoring system for determining abnormal conditions of a patient. The
existing scheme based on fuzzy inference rules will be boon for providing round
the clock health services in smart cities. The scheme is expected to help doctors
and other care givers to take decisions prudently. Doctors will now be freed
from the burden of checking each and every patient’s physical attributes. Instead
they will be able to focus on the patients who really need the care and advice.
Thus, the IoT based system can be used more efficiently without compromising
with the quality of service of the system is shown below the Fig.3.1.
               Fig.3.1. Block diagram of request reply algorithm
     Health care applications need to acquire different types of sensor data. The
sensors data need to be collected in precise and timely manner. When health
sensor data are forwarded to the data aggregator node, more sensing data may be
accumulated along the route. Thus, a huge traffic may be generated during data
collection. Handling such a large amount of data, while minimum data loss is
challenging. Improper handling may result in unbalanced and inefficient Energy
                                                                             16
dissipation. In most cases, the data is forwarded or collected through multiple
hops either in a request reply manner or in continuous streams. Furthermore, it
has also been observed in the back end system.
3.4 DRAWBACKS OF REQUEST REPLY ALGORITHM
    Huge amount of data may lead to burdened payload which results in packet
fragmentations. Due to packet fragmentation, the latency for data collection
becomes longer. To tackle the above issues, an event driven knowledge
collection technique is proposed.
                                                                               17
                                  CHAPTER 4
                               PROPOSED METHOD
4.1 INTRODUCTION
    The National Heart, Lung and Blood Institute states that more than a million
persons have heart attack and about half of them die in each year. About one
half of those who die within a hour of the start of symptoms before reaching the
hospital. The heart attack happens to a person when the blood flow and oxygen
supply to heart muscle is blocked and it is mostly caused by Coronary Artery
Disease (CAD). CAD occurs when the arteries that supply blood to the heart
muscle become hardened and narrowed. It often causes irregular heart beat or
rhythm blockage of blood stream. The National Heart, Lung and Blood Institute
suggest that everyone should know the warning signs of heart attack and how to
get emergency help.
    The symptoms of heart attack can be detected by observing the
Electrocardiogram (ECG) waveform. An ECG is an electrical recording of the
heart and it is used in the investigation of heart disease. An electrical impulse
initiates muscle contraction, which results in heart beating. The spacing between
pulses provides a measure of the heart’s rhythm, whereas the height of the
pulses is an indicator of pumping strength. The equipment with Heart attack
detection is specially designed to help the senior citizens who have the most
possibility of heart attack.
    The health-care monitoring system comprises several sensors connected to a
person. Different kinds of Sensors have been used in the health-care system
which is shown in the Fig 4.1. Furthermore, many supplementary sensors can be
integrated to this remote monitoring system as recommended by specialized
                                                                                  18
doctors. The data is uploaded to cloud through multi hop wireless
communication from the data aggregator and may be accessed and visualized.
4.2 EVENT DRIVEN APPROACH METHOD
    In this method the data collection is done by using event driven approach so
that the events are defined by means of given threshold conditions. It provides
step by step diagnosis and easy detection of physiological stages of patient body
without loss of packets. It can make sense of the health data, if we mention the
state of the particular parameters. Thus in this system, fuzzy rules are used
rather than the threshold parameters.
    Continuous data collection from the sensors is not required in event driven
approach. Usually, the data is gathered on occurred fusion center which makes
the decision. In this scheme, instead of implementing fusion centers, case
detection and choice mechanisms are executed by the sensor nodes. Events are
defined by means of some threshold values of the parameters. Assume three
sensor parameters I1, I2 and I3 which are defined for any health-care system M.
                                  M = {I1, I2, I3}
     In this event the values of the parameters rely on each other along with 1 st,
2nd and 3rd include the threshold values of I1, I2 along with I3 respectively.
4.3 BLOCK DIAGRAM OF EVENT DRIVEN APPROACH
     This system comprises two parts are local part and remote part. First the
local part deals with collection of information from the sensors connected to a
patient and the remote part enables storing and distributing the data to remote
service seekers like emergency service providers, doctors, and insurance
providers. Arduino based data aggregator is used to collect the sensor data
before sending to the data processing unit.
                                                                                19
     It also processes the collected raw data to generate meaningful information
that can be understood by specialists and doctors. Then, it displays the processed
information and sends it to the remote servers.
                Fig. 4.1 Block Diagram of event driven approach
       Heart beat monitor sensor is equipment, which is used to measure the
heartbeat of human in terms of Beats per Minute (BPM). It is also used to
evaluate the electrical activity of the heart which is called as Electrocardiogram
(ECG). The temperature sensor is a linear analog device, where the output
voltage varies linearly with change in temperature. The body position sensor is
                                                                                 20
used to measure the static acceleration of gravity in tilt-sensing applications, as
well as dynamic acceleration resulting from motion, shock or vibration.
4.4 BLOCK DESCRIPTION
       The following components present in block diagram of event driven
approach
            Heart rate sensor
            Temperature sensor
            Body position sensor
            Ethernet shield
            Arduino Uno board
      Ky039 Heart rate sensor is used to find the contracting and expanding
activity of heart. LM35 is a precision IC temperature sensor with its output
proportional to the temperature. ADXL335 is a small, thin, low power, complete
3-axis accelerometer to detect the body position. Esp8266 Wi-Fi shield is to
communicate with the server to remote part
   4.4.1 Heart Beat Sensor
                           Fig. 4.2 Heart beat sensor
                                                                                   21
            A person’s heartbeat is the sound of the valves in heart contracting or
expanding activity as they force blood from one region to another. The number
of times the heart beats is the heart beat rate and the beat of the heart that can be
felt in any artery that lies close to the skin is the pulse.
          4.4.1.1 Ways to Measure Heartbeat
                          Manual Way: Heart beat can be checked manually by
checking one’s pulses at two locations wrist and the neck. The procedure is to
place the two fingers are index and middle finger on the wrist or neck below the
windpipe and count the number of pulses for 30 seconds and then multiplying
that number by 2 to get the heart beat rate. However pressure should be applied
minimum and also fingers should be moved up and down till the pulse is felt.
                    Using a sensor: 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 beat changes.
         4.4.1.2 Principle of Heart Beat Sensor
                          The heartbeat sensor is based on the principle of photo
phlethysmography. It measures the change in volume of blood through any
organ of the body which causes a change in the light intensity through that organ
is a vascular region. In case of applications where heart pulse rate is to be
monitored, the timing of the pulses is more important.
                                                                                22
                          Fig.4.3 Heart beat sensor circuit
                       The flow of blood volume is decided by the rate of heart
pulses and light is absorbed by blood and so the signal pulses are equivalent to
the heart beat pulses. The signal is actually a DC signal relating to the tissues
and the blood volume with AC component synchronous the heart beat which
causes a pulsatile change in arterial blood volume with superimposition of the
DC signal. Thus the major requirement is to isolate that AC component as it is
of prime importance.
         4.4.1.3 ECG Measurement
                          Electrocardiography (ECG or EKG) is the process of
recording the electrical activity of the heart over a period of time using
electrodes placed on the skin. These electrodes detect the tiny electrical changes
on the skin that arise from the heart muscles electrophysiological pattern of
depolarizing during each heartbeat. It is a very commonly performed in
cardiology test. The overall magnitude of the heart's electrical potential is then
measured from the flow of blood from top to bottom of the heart and it is
recorded over a period of time usually 10 seconds. In this way, the overall
magnitude and direction of the heart's electrical depolarization is captured at
each moment throughout the cardiac cycle. The graph of voltage versus time
produced by this non invasive medical procedure is referred to as an
electrocardiogram.
                                                                                23
                           During each heartbeat, a healthy heart has an orderly
progression of depolarization that starts with pacemaker cells in the Sino atrial
node and it spreads out through the atrium, passes through the atrio ventricular
node and down into the Purkinje fibers. This orderly pattern of depolarization
gives rise to the characteristic ECG tracing. To the trained clinician, an ECG
conveys a large amount of information about the structure of the heart and the
function of its electrical conduction system.
               Among other things, an ECG can be used to measure the rate and
rhythm of heartbeats, the size and position of the heart chambers, the presence
of any damage to the heart's muscle cells or conduction system, the effects of
cardiac drugs, and the function of implanted pacemakers. Continuous ECG
monitoring is used to monitor critically ill patients, patients undergoing general
anesthesia, and patients who have an infrequently occurring cardiac dysrhythmia
that would be unlikely to be seen on a conventional ten second ECG.
       4.4.1.4 Electrocardiography
                     An electrocardiograph is a machine that is used to perform
electrocardiography      and    produces    the    electrocardiogram.   The   first
electrocardiographs are discussed above and are electrically primitive compared
to today's machines.
Some indications for performing electrocardiography includes,
       Suspected myocardial infarction
       Suspected pulmonary embolism
       A third heart sound, fourth heart sound, a cardiac murmur or other
        findings to suggest structural heart disease
       Perceived cardiac dysrhythmias
                                                                            24
   Fainting or collapse
   Seizures
   Monitoring the effects of a heart medication e.g. drug-induced QT
    prolongation
   Assessing severity of electrolyte abnormalities, such as hyperkalemia
   Hypertrophic cardiomyopathy screening in adolescents as part of a sports
    physical out of concern for sudden cardiac death
   Pre-operative monitoring is the method in which any form of anesthesia is
    involved e.g. monitored anesthesia care, general anesthesia typically both
    intraoperative and postoperative
   As a part of a pre operative assessment some time before a surgical
    procedure, especially for those with known cardiovascular disease or who
    are undergoing invasive or cardiac, vascular or pulmonary procedures.
   Cardiac stress testing
   Computed tomography angiography (CTA) and Magnetic resonance
    angiography (MRA) of the heart
   ECG is used to gate the scanning so that the anatomical position of the
    heart is steady
                                                                                 25
                          Fig. 4.4 ECG Waveform
       The fundamental component to electrocardiograph is the instrumentation
amplifier, which is responsible for taking the voltage difference between leads
and amplifying the signal. ECG voltages measured across the body are on the
order of hundreds of microvolts up to 1 millivolt, the small square on a standard
ECG is 100 microvolts. This low voltage necessitates a low noise circuit and
instrumentation amplifiers as a key.
             Early electrocardiographs were constructed with analog electronics
and the signal could drive a motor to print the signal on paper. Today,
electrocardiographs use analog to digital converters to convert to a digital signal
that can then be manipulated with digital electronics. This permits digital
recording of ECGs and makes use of computers.
There are other components to construct the electrocardiograph,
    Safety features that include voltage protection for the patient and operator.
      Since the machines are powered by mains power, it is conceivable that
      either person could be subjected to voltage capable of causing death.
      Additionally, the heart is sensitive to the AC frequencies typically used
      for mains power i.e.50 or 60 Hz.
                                                                              26
    Defibrillation protection in ECG used in healthcare may be attached to a
      person who requires defibrillation and the electrocardiograph needs to
      protect itself from this source of energy.
    Electrostatic discharge is similar to defibrillation discharge and requires
      voltage protection up to 18,000 volts.
    Additionally circuitry called the right leg driver can be used to reduce
      common mode interference i.e. typically the 50/60 Hz mains power.
    4.4.2 Temperature Sensor
                          Fig.4.5 LM35 Temperature sensor
            LM35 is an analog, linear temperature sensor whose output voltage
varies linearly with change in temperature. LM35 is three terminal linear
temperature sensors from National semiconductors. It can measure temperature
from-55 degree Celsius to +150 degree Celsius. The voltage output of the LM35
increases 10milli-volt per degree Celsius rise in temperature. LM35 can be
operated from a 5 volt supply and the stand by current is less than 60uA.
                                                                             27
                            Fig.4.6 LM interfacing
           The +5v for LM35 can be taken from the +5v out pin of arduino uno.
Also the ground pin of LM35 can be connected to GND pin of arduino uno.
Connect Vout ,the analog out of LM35 to any of the analog input pin of arduino
uno. In the above circuit diagram, Vout of LM35 is connected to A1 of arduino.
   4.4.3 Body Position Sensor and its interface
                The ADXL335 is a small, thin, low power, complete 3axis
accelerometer with signal conditioned voltage outputs. The product measures
acceleration with a minimum full-scale range of ±3g. It can measure the static
                                                                               28
acceleration of gravity in tilt sensing applications, as well as dynamic
acceleration resulting from motion, shock, or vibration.
                                Fig.4.7 ADXL335
         The user selects the bandwidth of the accelerometer using the C X, CY,
and CZ capacitors at the XOUT, YOUT, and ZOUT pins. Bandwidths can be selected
to suit the application with a range of 0.5 Hz to 1600 Hz for X and Y axes, and a
range of 0.5 Hz to 550 Hz for the Z axis.
                                                                        29
                               Fig 4.8 ADXL335 Pin out
      The ADXL335 is available in a small, low profile, 4 mm × 4 mm × 1.45
mm, 16-lead, plastic lead frame chip scale package.
                         Fig.4.9 ADXL335 Interfacing
                                                                               30
         4.4.3.1 Mechanical Sensor and its performance
                 The ADXL335 uses a single structure for sensing the X, Y, and
Z axes. As a result, the three axes sense directions which are highly orthogonal
and have little cross axis sensitivity. Mechanical misalignment of the sensor die
to the package is the chief source of cross-axis sensitivity. Mechanical
misalignment can be a course of calibration at the system level.
                        Rather than using additional temperature compensation
circuitry, innovative design techniques can ensure high performance to build
ADXL335. As a result, there is no quantization error or non-monotonic
behaviour and temperature hysteresis is very low typically less than 3 mg over
the −25°C to +70°C temperature range.
   4.4.4 Wi-Fi Shield and its module
           ESP8266 presently ESP8266EX is a chip with which manufacturers
are making wirelessly networkable microcontroller modules. More specifically,
ESP8266 is a system on chip (SOC) with capabilities for 2.4 GHz Wi-Fi,
General purpose input/output (16 GPIO), Inter Integrated Circuit (I²C), Analog
to Digital conversion is10-bit ADC, Serial Peripheral Interface (SPI), I²S
interfaces with DMA sharing pins with GPIO, UART on dedicated pins, plus a
transmit only UART can be enabled on GPIO2), and pulse-width modulation
(PWM).
           It employs a 32-bit RISC CPU based on the Tensilica Xtensa LX106
running at 80 MHz or over clocked to 160 MHz. It has a 64 KB boot ROM,
64 KB instruction RAM and 96 KB data RAM. External flash memory can be
accessed through SPI. Various vendors have consequently created a multiple
modules containing the ESP8266 chip at their cores. Some of these modules
have specific identifiers including Wi07c and ESP-01 through ESP-13, while
                                                                           31
other modules might be ill-labeled and merely referred to by a general
description e.g., ESP8266 Wireless Transceiver.
                  Fig. 4.10 ESP8266 WiFi shield
          ESP8266 based modules have demonstrated themselves as a capable,
low-cost, networkable foundation for facilitating end-point IoT developments.
Espressif's official module is presently the ESP-WROOM-02. The AI-Thinker
modules where labeled with ESP-01 through ESP-13. Node MCU boards extend
upon the AI-Thinker modules. Olimex, Adafruit, Sparkfun, WeMos, ESPert all
make various modules as well.
                  Fig 4.11 ESP8266 Arduino interface
                                                                               32
  4.4.5 Arduino UNO
          Arduino is open-source hardware. The hardware reference designs are
distributed under a creative common attribution like 2.5 licenses. Layout and
production files for some versions of the hardware are also available. The source
code for the IDE is released under the General Public License version 2 (GNU).
Nevertheless, an official bill of materials of arduino boards has never been
released by the staff of arduino.
                                    Fig 4.12 Arduino uno
                                                                               33
              An Arduino board consists of an Atmel 8, 16 or 32-bit AVR
microcontroller are ATmega8, ATmega168, ATmega328, ATmega1280,
ATmega 2560. The boards use single-row pins or female headers that facilitate
connections for programming and incorporation into other circuits. These may
connect with add-on modules termed shields. Multiple and possibly stacked
shields may be individually addressable via an I²C serial bus. Most boards
include a 5V linear regulator and a 16 MHz crystal oscillator or ceramic
resonator. Some designs, such as the Lily Pad, run at 8 MHz and dispense with
the onboard voltage regulator due to specific form-factor restrictions.
        4.4.5.1 ATmega328p Microcontroller
                     ATmega328/P is a low-power CMOS 8-bit microcontroller
based on the AVR® enhanced RISC architecture. By executing powerful
instructions in a single clock cycle, the ATmega328/P achieves throughputs
close to 1MIPS per MHz. This empowers system designed to optimize the
device for power consumption versus processing speed.
                 The Atmel AVR core combines a rich instruction set with 32
general purpose working registers. All the 32 registers are directly connected to
the Arithmetic Logic Unit (ALU), allowing two independent registers to be
accessed in a single instruction executed in one clock cycle. The resulting
architecture is more code efficient while achieving throughputs up to ten times
faster than conventional CISC microcontrollers. Features of Atmega328p
microcontroller are mentioned.
       Advanced RISC Architecture
               131 Powerful Instructions
               Most Single Clock Cycle Execution
               32 x 8 General Purpose Working Registers
                                                                    34
   High Endurance Non-volatile Memory Segments
           32KBytes of In-System Self-Programmable Flash program
             Memory
           1KBytes EEPROM
           2KBytes Internal SRAM
           Write/Erase Cycles: 10,000 Flash/100,000 EEPROM
           Data Retention: 20 years at 85°C/100 years at 25°C(1)
           Optional Boot Code Section with Independent Lock Bits
     I/O and Packages
           23 Programmable I/O Lines
           28-pin PDIP, 32-lead TQFP, 28-pad QFN/MLF and 32-pad
             QFN/MLF
                 Operating Voltage: 1.8 - 5.5V
                 Temperature Range: -40°C to 105°C
                 Speed Grade: 0 - 4MHz @ 1.8 - 5.5V
                                0 - 10MHz @ 2.7 - 5.5V
                                0 - 20MHz @ 4.5 - 5.5V
                                                                                35
                                  CHAPTER 5
                                  FUZZY LOGIC
5.1 INTRODUCTION TO FUZZY LOGIC
     Fuzzy logic is a form of many valued logic in which the truth values of
variables may be any real number between 0 and 1. By the contrast of Boolean
logic, the truth values of variables may only be the integer values 0 or 1. Fuzzy
logic has been employed to handle the concept of partial truth, where the truth
value may range between completely true and completely false. Furthermore,
when linguistic variables are used and the degrees can be managed by specific
membership functions.
   5.1.1 Applying Truth Values
                A basic application might characterize various sub ranges of a
continuous variable. For instance, a temperature measurement for anti lock
brakes might have several separate membership functions defining particular
temperature ranges needed to control the brakes properly. Each function maps
the same temperature value to a truth value in the 0 to 1 range. These truth
values can then be used to determine how the brakes should be controlled.
   5.1.2 Fuzzy Inputs and Results
          Since the fuzzy system output is a consensus of all of the inputs of the
rules, fuzzy logic systems can be well behaved when input values are not
available or are not trustworthy. Weightings can be optionally added to each rule
in the rule base and weightings can be used to regulate the degree to which the
rule affects the output values.
                                                                                 36
            These rule weightings can be based upon the priority, reliability or
consistency of each rule. These rule weightings may be static or can be changed
dynamically based upon the output from other rules.
   5.1.3 Process
        1. Fuzzify all input values into fuzzy membership functions.
          2. Execute all applicable rules in the rule base to compute the fuzzy
           output functions.
        3. De-fuzzify the fuzzy output functions to get “crisp” output values.
   5.1.4 Fuzzy System for Cardiac Diagnosis
             The modelling of any fuzzy expert system normally contains the
following steps,
(i) Selection of relevant input and output parameters
(ii) Selection of proper membership functions, fuzzy operators, reasoning
    mechanisms
(iii) Choosing of specific type of fuzzy inference system
(iv) Formulation of rule base.
         The basic fuzzy inference system can take either fuzzy inputs or crisp
inputs but the outputs produce fuzzy sets. The defuzzification task extracts the
crisp output that best represents the fuzzy set. With crisp inputs and outputs a
fuzzy inference system implements a nonlinear mapping from its input space to
output space through a number of fuzzy rules.
                                                                           37
 The model of proposed fuzzy system is shown in the Fig.5.1
                   Fig. 5.1 Model of proposed fuzzy system
   5.1.5 Fuzzy Scheme for Cardiac Disease Diagnosis
            The fuzzy logic toolbox is used to simulate the medical diagnosis
application. The input variables considered are blood pressure, body
temperature, ECG, heart rate, etc. Membership values are assigned to the
linguistic variables such as symptoms low, medium, high and very high.
                                                                                38
             The patient data is stored in a database and knowledge is retrieved
from the knowledge base by matching the symptoms and their severity against
the antecedent part of fuzzy rules. The fuzzy decision value is defuzzified by the
defuzzification component of the designed system to finally arrive at a crisp
decision for the disease diagnosis.
            This proposed system contains various sensors, which measure some
physical properties of a human body. Diagnosis is performed by studying
several parameters of a human body known as symptoms and several symptoms
are verified one after another before obtaining a final conclusion about a
particular disease. This fuzzy assisted scheme uses these rules of diagnosis and
follows the steps of diagnosis to take the decision regarding which sensor data is
required to be activated and when it is required to be activated. The system
activates few sensors which record some basic parameters of the human body.
The crisp values received from the sensors are transformed to fuzzy sets like
‘normal’, ‘above normal’, ‘low’ etc., using pre-defined knowledge base in which
rules defined by specialized doctors. These fuzzy variables become the input to
the decision making program which detects the true condition of the patient like
weak heart condition, shock, respiratory problem etc., According to these
outputs, actions and events like alerting doctors and activating more sensors for
further monitoring the patient are started.
   5.1.6 Area of Application
           The fuzzy assisted technique may be employed in wide area of health
applications. As a test case, we have tried to implement fuzzy assisted detection
of heart condition in a step by step manner as just as it is diagnosed in the real
world. Severe heart conditions like myocardial infarction, ischemic heart disease
have the symptoms like sweating, low peripheral body temperature and low
respiration rate etc.,
                                                                                   39
           Initially, the data from all the sensors are retrieved and the data
aggregator decides which particular data should be sent depending upon the
condition of the patient. All data are fed into the fuzzifier and the fuzzifier is
used to detect whether the parameters are normal, low or high fuzzy sets on the
basis of some predefined membership functions.
5.2 FUZZY SETS
    5.2.1 Implementation
            It helps in determining the physical condition of the patient, whether
the patient is in shock or not. If shock is detected, the data from heart rate sensor
and temperature sensor are checked to detect the specific cause of the shock.
The output from the fuzzy system is used to detect if the heart condition is bad,
critical or normal. Depending on these the fuzzy output, the actions and alerts
like starting the ECG, alerting heart specialist are generated.
                    Fig 5.2 Membership function of heart rate
                                                                              40
         The average heart rate ranges from 60 to 100 beats per minute. Here,
the heart rate parameter range is divided into three fuzzy sets namely, ‘Low’,
‘Medium’ and ‘High’.
         Electrocardiogram (ECG) is a test that measures the electrical activity
of the heart. It uses ultrasound to evaluate the heart muscle, heart valves, and
risk for the heart disease. ECG parameter range is divided into three fuzzy sets
namely, ‘Normal’, ‘ST-T Normal’ and ‘Hypertrophy’.
                               Fig 5.3 Membership function of ECG
        The membership criterion for body temperature is 37˚C but it may vary
during the daytime, so a range between 36.5˚C and 37.5˚C is considered as
normal body temperature.
                                                                               41
                   Fig 5.4 Membership function of body temperature
5.3 INTERFACE MECHANISM
    In this system, more than one fuzzy rules pertaining to the heart disease are
formed. The output shows the presence or absence of risk for the heart disease
subjected to given the values of input parameters. The rules consist of
antecedent and consequent parts. All the rules continuous to some extent in the
antecedent part of the fuzzy system. In the inference process, the values for the
premise of each rule is computed and applied to the conclusion part of each rule.
This results in one fuzzy subset to be assigned to each output variable for each
rule. The fuzzy expert system computes the probabilities and determines output
value in terms of percentage of the risk of heart disease from zero percent to
hundred percent. Decisions are described through the output membership
functions. These functions determine whether the alert will be generated or
normal monitoring is sufficient.
                                                                               42
                                  CHAPTER 6
                         RESULT AND DISCUSSION
6.1 SIMULATION OUTPUT
   The simulation output of patient health monitoring using IoT is shown in the
Fig. 6.1 It shows the fuzzy assisted health data visualization in real-time. From
this the cardiac patient health parameters such as body position, temperature and
heart rate are measured. The fuzzy system is programmed in the arduino board,
which is used as a data aggregator unit in the healthcare monitoring system. The
data aggregator transmits the sensor’s data according to the fuzzy rules.
                        Fig 6.1 Software Implementation
                                                                            43
6.2 HARDWARE ARRANGEMENT
    The health care monitoring system comprises several sensors connected to a
person. Different kinds of Sensors have been used in the health care system.
Furthermore, many supplementary sensors can be integrated to this remote
monitoring system as recommended by specialized doctors. The data is
uploaded to cloud through multi-hop wireless communication from the data
aggregator and may be accessed and visualized.
                      Fig 6.2 Complete Hardware Setup
     The way to save valuable energy of a portable monitoring device is by the
generation of accuracy of knowledge can enhance performance of whole system.
                                                                               44
                                 CHAPTER 7
         CONCLUSION AND FUTURE ENHANCEMENT
       In this technique a real-time heart monitoring system for heart patients
located in remote areas. The developed system is comprised of wearable
sensors, Android handheld device or a laptop and web interface. The system is
adaptable and has the ability to extract several cardiac parameters such as heart
rate, blood pressure, and temperature of multiple patients simultaneously. The
extracted data is being transmitted to Android handheld device using Wi Fi
which is then transmitted to web application for further processing. Web
application processes the received data to show medical status of the patient
along with personal information such as age, gender, address, and location on
web interface. An alarming system based on threshold values has also been
designed which sends alert message to the doctor in case of abnormalities such
as arrhythmia, hypotension, hypertension, fever, and hypothermia.
        In the near future, we plan to integrate the Data Stream Management
System (DSMS) technologies into the monitoring system in order to enrich its
functions, such as continuous query, windowing, and aggregation and so on.
Afterwards, data stream mining and context awareness technologies are also
considered so as to provide more powerful mobile services like early warning
and real-time knowledge support to patients.
                                              45
                                 APPENDIX I
1.Source coding
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
ESP8266WiFiMulti WiFiMulti;
#define SSID "SSID"
#define PSSWD "PASSWORD"
int pins[3] = {12,13,4};
const int VCCPin = A0;
const int xPin = A1;
const int yPin = A2;
const int zPin = A3;
const int GNDPin = A4;
// variables
int x = 0;
int y = 0;
int z = 0;
void setup() {
// put your setup code here, to run once:
 Serial.begin(9600);
                                                                                       46
    for(int i=0; i<3;i++){
    pinMode(pins[i], INPUT_PULLUP);
    }
// pin A0 (pin14) is VCC and pin A4 (pin18) in GND to activate the GY-61-
module
pinMode(A0, OUTPUT);
pinMode(A4, OUTPUT);
digitalWrite(14, HIGH);
digitalWrite(18, LOW);
// activating debugging for arduino UNO
Serial.begin(9600);
WiFiMulti.addAP(SSID, PSSWD);
    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
                                     // if you are powering the pulse sensor at voltage
less than the board voltage,
                                  // un-comment the next line and apply that voltage to
the a-ref pin
void loop() {
    // put your main code here, to run repeatedly:
    int motor1, motor2;
    if(digitalRead(pins[0])==0){ //Turn left
        Serial.println("left");
        motor1 = 50;
                                                                         47
        motor2 = 50;
    }
    else if(digitalRead(pins[1])==0){ //Go forward
        Serial.println("forward");
        motor1 = 50;
        motor2 = -50;
    }
    else if(digitalRead(pins[2])==0){ //Turn right
        Serial.println("right");
        motor1 = -50;
        motor2 = -50;
    }
    else{
        motor1 = 0;
        motor2 = 0;
    }
    if(WiFiMulti.run() == WL_CONNECTED){
        HTTPClient http;
        http.begin("http://192.168.0.46:5000/control/");
        http.addHeader("Content-Type", "application/json");
                                                  int         httpCode   =
http.POST("{\"motor1\":"+String(motor1)+", \"motor2\":"+String(motor2)+"}")
;
        String payload = http.getString();
        Serial.print('\t');
        Serial.println(httpCode);
        Serial.println(payload);
    }
                                                       48
 delay(40);
 x = analogRead(xPin);
y = analogRead(yPin);
z = analogRead(zPin);
// show x, y and z-values
Serial.print("x = ");
Serial.print(x);
Serial.print(" y = ");
Serial.print(y);
Serial.print(" z = ");
Serial.print(z);
// show angle
Serial.print(" angle = ");
Serial.println(constrain(map(x,349,281,0,90),0,90));
delay(2000);
Serial.print("X = ");
 Serial.println(accel.readx());
 Serial.print(" Y = ");
 Serial.println(accel.ready());
 Serial.print(" Z = ");
 Serial.println(accel.readz());
 Serial.print(" Ac. Total");
 Serial.println(accel.acceltol());
#include <LiquidCrystal.h>
                                                                                   49
// 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 = 8;            // pin to do fancy classy fading blink at each beat
int fadeRate = 0;           // used to fade LED on with PWM on fadePin
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                 // int that holds raw Analog in 0. updated every
2mS
volatile int Signal;           // holds the incoming raw data
volatile int IBI = 600;           // int that holds the time interval between beats!
Must be seeded!
volatile boolean Pulse = false;    // "True" when User's live heartbeat is detected.
"False" when not a "live beat".
volatile boolean QS = false;       // becomes true when Arduoino finds a beat.
// Regards Serial OutPut -- Set This Up to your needs
static boolean serialVisual = true; // Set to 'false' by Default. Re-set to 'true' to
see Arduino Serial Monitor ASCII Visual Pulse
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
                                                                                       50
volatile int thresh = 525;                 // 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
    serialOutput();
    if (QS == true) // A Heartbeat Was Found
     {
         // BPM and IBI have been Determined
         // Quantified Self "QS" true when arduino finds a heartbeat
           fadeRate = 255; // Makes the LED Fade Effect Happen, Set 'fadeRate'
Variable to 255 to fade LED with pulse
         serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
         QS = false; // reset the Quantified Self flag for next time
     }
    ledFadeToBeat(); // Makes the LED Fade Effect Happen
    delay(20); // take a break
}
void ledFadeToBeat()
{
    fadeRate -= 15;                    // set LED fade value
                                                                                    51
        fadeRate = constrain(fadeRate,0,255);   // keep LED fade value from going
into negative numbers!
    analogWrite(fadePin,fadeRate);          // fade LED
}
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
}
void serialOutput()
{ // Decide How To Output Serial.
if (serialVisual == true)
    {
        arduinoSerialMonitorVisual('-', Signal); // goes to function that makes Serial
Monitor Visualizer
    }
else
    {
         sendDataToSerial('S', Signal);   // goes to sendDataToSerial function
    }
}
                                                                                  52
void serialOutputWhenBeatHappens()
{
if (serialVisual == true) // Code to Make the Serial Monitor Visualizer Work
    {
        Serial.print("*** Heart-Beat Happened *** "); //ASCII Art Madness
        Serial.print("BPM: ");
        Serial.println(BPM);
        lcd.clear();
        lcd.print("BPM: ");
        lcd.print(BPM);
    }
else
    {
        sendDataToSerial('B',BPM); // send heart rate with a 'B' prefix
        sendDataToSerial('Q',IBI); // send time between beats with a 'Q' prefix
    }
}
void arduinoSerialMonitorVisual(char symbol, int data )
{
    const int sensorMin = 0;     // sensor minimum, discovered through experiment
     const int sensorMax = 1024;           // sensor maximum, discovered through
experiment
    int sensorReading = data; // map the sensor range to a range of 12 options:
    int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
    // do something different depending on the
    // range value:
    switch (range)
                                                       53
{
    case 0:
     Serial.println("");      /////ASCII Art Madness
     break;
    case 1:
     Serial.println("---");
     break;
    case 2:
     Serial.println("------");
     break;
    case 3:
     Serial.println("---------");
     break;
    case 4:
     Serial.println("------------");
     break;
    case 5:
     Serial.println("--------------|-");
     break;
    case 6:
     Serial.println("--------------|---");
     break;
    case 7:
     Serial.println("--------------|-------");
     break;
    case 8:
     Serial.println("--------------|----------");
     break;
    case 9:
                                                                                              54
         Serial.println("--------------|----------------");
         break;
        case 10:
         Serial.println("--------------|-------------------");
         break;
        case 11:
         Serial.println("--------------|-----------------------");
         break;
    }
}
void sendDataToSerial(char symbol, int data )
{
    Serial.print(symbol);
    Serial.println(data);
}
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
                                                                                             55
     {
         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 – lastBeatTim // 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
                                                                                        56
           {
               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
      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
  }
                                                                                          57
 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
                                                                      58
                          APPENDIX II
                         PUBLICATIONS
1. A.Shanmugapriya, N.Geetha, P.Mathumathi, N.Nagajothi & S.Anjali
  “A Home Health Care Monitoring Services for Cardiac Patient Using Iot”
  International Journal Of Science & Engineering Development Research
  (IJSDR), volume 3 issue 3, march 2018, ISSN:2455-2631.
                                                                             59
REFERENCES
 1. Avitall, B., Peterson, B., Kletch, J., Grisworld, B., and Moran, P. (2001)
    ‘Remote Health Monitoring System’, Proceeding of the 17th International
    Conference on,vol.29, No.1, pp.977-987.
 2. Boegl, K., Adlassni, K. P., Hayashi, K., Rothenfluh, T. E., Leitich. (2004)
    ‘Knowledge acquisition in the fuzzy knowledge representation framework
    of a medical consultation system’, International Conference on Artificial
    Intelligence in Medicine, vol.30, pp.1-26.
 3. Cleland, J. G., Swedberg, K., and Beradi. (2003) ‘Fuzzy knowledge
    representation framework in medical consultation’, Journal of Euro Heart
    Failure Survey Program, vol.24, No.2, pp.442-463.
 4. eHealth Website - Available: www.cookinghacks.com
 5. Haigh, K. Z., Kiff, L. M., and Ho, G. (2006) ‘The independent lifestyle
    assistant Lessons learned’, Conference on Assistive Technology, vol.18,
    No.3, pp.87-106.
 6. Hollands, R. J. (2008) ‘Will the real smart city stand up on Intelligent
    progressive or Entrepreneurial City’, Proceeding 7th International
    Conference on Assistive Environments, vol.12, No.3, pp.303-320.
 7. Hoseini, A. H. G, Dahlan, N. D., and Berardi, U. (2013) ‘The essence of
    Future Smart Houses from Embedding ICT to Adapting Sustainability
    Principles’, Review of     Renewable and Sustainable Energy, vol.24,
    No.21, pp.593-607.
                                                                              60
8.     ITU Report on Internet of Things Executive Summary. [Online].
     Available: www.itu.int/interneofthings
9. Kangavalli, M., and Sukumar, P. (2015) ‘Asynchronous transfer mode
     Implementation in Cardiac patient monitoring’, IEEE Transactions on,
     vol.13, pp.43-67.
10. Meganathan, C., and Sukumar, P. (2013) ‘Retinal Lesion Detection by
     using points of Interest and Visual Dictionaries’, International Journal of
     Advanced Research in Electronics and Communication Engineering,
     vol.2, pp.175-181.
11. Pandian, P. S., Safeer, K.P., Pragati Gupta, D. T., and Shakunthala.
     (2008)   ‘Wireless    Sensor   Network     for   Wearable     Physiological
     Monitoring’, Journal of Networks, vol.3, No.5, pp.121-18.
12. Prabhakher, S., and Sukumar, P. (2015) ‘Performance analysis of rotation
     invariant parts based object detection in High-Resolution Images’,
     International Journal of Engineering Science Invention, vol.4, No.5,
     pp.01-06.
13. Ravi, S., Vitaliy Mezhuyev, and Iyswarya Annapoorani, K.             (2016)
     ‘Design and Implementation of a Microcontroller based Buck Converter
     as an Ineffectual Region in Heart’, Journal of Electrical Engineering and
     Computer Science, vol.1, No.3, pp.566-574.
14. Robert, G., Lupu, Andrei Stan, Florina Ungureanu. (2008) ‘Wireless
     Device for Patient Monitoring’, Proceeding International Conference on
     vol.1, No.2, pp.521-366.
15. Ross, P. E. (2004) ‘Managing care through the air [remote health
     monitoring]’, IEEE Transactions on, vol.12, No.6, pp.26-31.
                                                                     61
16. Sukumar, P., and Dr. Ravi, S. (2016) ‘IoT Based Efficient Vehicle
  Location Help Line System Using NFC’, International Journal of
  Emerging Technologies in Engineering Research (IJETER), vol.4, No.5,
  pp.10-13.
17. Tamilselvi, S. and Sukumar, P. (2014) ‘Clock Power Reduction using
  Multi-BitFlip-Flop Technique’, IRACST – Engineering Science and
  Technology as an International Journal, vol.4, No.2, pp. 46-51.
18. Xiao-Fei Teng, Yuan-Ting. (2008) ‘Wearable Medical Systems for
  Patient Health’, IEEE Reviews in Biomedical Engineering, vol.1, No.3,
  pp.43-21.