ecg monitoring of a cardiac patient using embedded system

Upload: manoj-jax-m-r

Post on 14-Oct-2015

40 views

Category:

Documents


0 download

DESCRIPTION

A embedded system is designed for cardiac patients to monitor ECG signal and give a alarm if any abnormal

TRANSCRIPT

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    CHAPTER 1

    INTRODUCTION AND BACKGROUND

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    1.1 INTRODUCTIONMedical Technologies have grown rapidly over the years along with other

    fields. In fact, today, access to medical care in the form of clinics and hospitals has

    become a lot easier for most of the population; modern medical equipment and

    advanced techniques for curing diseases have increased life expectancy all over the

    world. Many maladies that were once written off as incurable are now being treated

    efficiently, and people affected by these are returning to their normal lives. Yet,

    Cardiovascular Diseases (CVDs) remain to be the major cause of death, globally, and

    cannot be eradicated or made obsolete. More people die annually from CVDs than

    from any other cause. An estimated 17.3 million people died from CVDs in 2008,

    representing 30% of all global deaths [1]. Of these deaths, an estimated 7.3 million

    were due to coronary heart disease and 6.2 million were due to cardiac arrhythmia

    (heart stroke) [2]. Low- and middle-income countries are disproportionally affected,

    over 80% of CVD deaths take place in low- and middle-income countries and occur

    almost equally in men and women [1].

    The most common test for a cardiac arrhythmia is an Electrocardiogram

    (ECG). However, it is difficult to diagnose many arrhythmias with a standard resting

    ECG, because it can only provide a snapshot of the patients cardiovascular activity in

    time, as a result an intermittent arrhythmia can go unnoticed. So, physicians must rely

    on self-monitoring and symptoms reported by patients to support their final diagnosis.

    Although they can lead to a diagnosis and therapy that may greatly improve the

    quality of life for the patient, they can be inconvenient for both the patient and the

    physician. To overcome this problem, ECG data can be collected over extended

    periods of time using Holter Monitors [3], which acquires the electrical activity of a

    freely moving person's heart generally for one to two days. After the measurement of

    the patients ECG using this device, the signal analysis is then carried out offline by

    the physician. This device lacks in real time diagnosis of ECG. Another solution is to

    utilize telemedical functionalities via a remote real-time monitoring system where the

    ECG is extracted using Personal Digital Assistants (PDAs) and transmitted to

    monitoring centre to analyse and classify the data [3]. But, this system uses more

    resources and it is expensive.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    A possible solution is to integrate the portability of the Holter Monitor and

    real-time processing capability of the resting ECG machine using smartphones which

    helps in monitoring the patients health by the physician and the patient himself [3].

    This particular system enables the patient to move freely and carry on his (restricted)

    daily activities as suggested by the physician.

    The work described in this report is based on the above mentioned solution to

    monitor a patients ECG by means of his smartphone. This work is carried out by

    assuming that the patients ECG is measured by a portable device similar to Holter

    Monitor and the ECG is readily available for further processing. After acquiring the

    ECG, the signal is fed into a PIC16F877A microcontroller for converting it into

    digital data and then transmitted to patients smartphone through Bluetooth Serial Port

    Profile (SPP) communication. This data is received in real-time by an application,

    installed on the Android-based smartphone. This application monitors the ECG data

    using Pan Tompkins algorithm [4] and raises alerts in case of abnormalities with

    respect to only the heart rate. The received data is also backed up in the external

    memory of the mobile for further reference.

    1.2 OVERVIEWThe report is organised as follows:

    Chapter 2 gives an overview of Electrocardiogram (ECG) and ECG feature

    extraction algorithm. Chapter 3 briefly explains the PIC16F877A microcontroller

    concepts, namely Analog to Digital (A/D) conversion and serial communication

    (USART), for interfacing the ECG extraction module to patients smartphone.

    Chapter 4 deals with the Android operating system and the Bluetooth Serial Port

    Profile (SPP) communication. Chapter 5 gives a detailed description of the system

    implementationinterfacing module, Android application and results of the modified

    algorithm. Chapter 6 discusses future scope of this work and concludes the report.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    CHAPTER 2

    ELECTROCARDIOGRAM

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    2.1 BRIEF INTRODUCTION OF ELECTROCARDIOGRAMElectrocardiography is a transthoracic (across the thorax or chest)

    interpretation of the electrical activity of theheart over a period of time,as detected

    by electrodes attached to the surface of the skin and recorded by an external device.

    The recording produced by this non-invasive procedure is termed an

    electrocardiogram (ECG). An ECG is used to measure the rate and regularity of

    heartbeats, as well as the size and position of the chambers, the presence of any

    damage to the heart, and the effects of drugs or devices used to regulate the heart,

    such as a pacemaker. An ECG is a way to measure and diagnose abnormal rhythms of

    the heart, particularly abnormal rhythms caused by damage to the conductive tissue

    that carries electrical signals, or abnormal rhythms caused by electrolyte imbalances.

    In a Myocardial Infarction (MI), also known as heart attack, the ECG can identify if

    the heart muscle has been damaged in specific areas.

    The ECG device detects and amplifies the tiny electrical changes on the skin

    that are produced when the heart muscle depolarizes during each heartbeat. At rest,

    each heart muscle cell has a negative charge, called the membrane potential, across its

    cell membrane. Decreasing this negative charge towards zero, via the influx of the

    positive cations, Na+ and Ca++, is called depolarization, which activates the

    mechanisms in the cell that cause it to contract. During each heartbeat, a healthy heart

    will have an orderly progression of a wave of depolarisation that is triggered by the

    cells in the Sinoatrial (SA) node, spreads out through the atrium, and passes through

    the Atrioventricular (AV) node and then spreads all over the ventricles. This is

    detected as tiny rises and falls in the voltage between two electrodes placed either side

    of the heart which is displayed as a wavy line, known as ECG, either on a screen or on

    paper. This display indicates the overall rhythm of the heart and weaknesses in

    different parts of the heart muscle.

    2.2 PARAMETERS IN ECG SIGNALA typical ECG tracing of a cardiac cycle consists of a P wave, QRS complex,

    a T wave, U wave which is normally visible in 50% to 75% of ECGs as shown in Fig.

    2.1. The baseline of the ECG (flat segments) is portion of the tracing following the T

    wave and preceding the next P wave. In a normal healthy heart, the baseline is almost

    equivalent to isoelectric line.

    http://en.wikipedia.org/wiki/Human_thoraxhttp://en.wikipedia.org/wiki/Hearthttp://en.wikipedia.org/wiki/Timehttp://en.wikipedia.org/wiki/Cardiac_striated_musclehttp://en.wikipedia.org/wiki/Cardiac_striated_musclehttp://en.wikipedia.org/wiki/Timehttp://en.wikipedia.org/wiki/Hearthttp://en.wikipedia.org/wiki/Human_thorax
  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    Fig 2.1 Representation of ECG signal

    The P wave and the QRS complex tell us about the atria and ventricles

    respectively. The T wave evaluates the recovery stage of the ventricles while they are

    refilled with blood. The time it takes for electric charge to travel from the SA node to

    the AV node is measured by the PR interval. The QRS interval measures electric

    charge travel time through the ventricles and the QT interval measures how long it

    takes for the ventricles to recover and prepare to beat again. The number of P-QRS-T

    sequences gives the heart rate.

    Certain facts about these parameters are as follows:

    Table 2.1List of features used in ECG diagnosis

    FEATURES DESCRIPTION DURATION

    RR Interval

    The interval between an R wave and the next

    R wave is RR interval. This gives us the heart

    rate.

    0.6 to 1.2s

    P wave

    During normal atrial depolarization, the

    electrical ion is directed from the SA node

    towards the AV node, and spreads from the

    right atrium to left atrium. This turns into P

    wave on the ECG.

    80ms

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    PR interval

    The PR interval is measured from the

    beginning of the P wave to the beginning of

    the QRS complex. The PR interval reflects the

    time the electrical impulse takes to travel fromthe sinus node through the AV node and

    entering the ventricles. The PR interval is,

    therefore, a good estimate of AV node

    function.

    120 to 200ms

    PR segment

    The PR segment connects the P wave and

    QRS complex.50 to 120ms

    QRS complex

    The QRS complex reflects the rapid

    depolarization of the right and left ventricles.

    They have a large muscle mass compared to

    the atria, so the QRS complex usually has

    much larger amplitude than the P-wave.

    80 to 120ms

    ST segment

    The ST segment connects QRS complex and

    T wave. It represents the period of ventricles

    depolarized and it is isoelectric.

    80 to 120ms

    T wave

    The T wave represents the repolarization of

    the ventricles.160ms

    ST interval

    It is measured from end of QRS complex to

    the end of the T wave.320ms

    QT interval

    It is measured from the beginning of the QRS

    complex to end of T wave. A prolonged QT

    interval is a highly risk factor for ventricular

    tachyarrhythmia and sudden death.

    Up to 420ms

    in heart rate

    of 60bpm

    ECG analysis is mostly carried out by detecting the QRS complex as it gives

    information regarding the heart rate which is a necessary condition in determining a

    patients cardiac health. There are few existing QRS detection algorithms, of which

    Pan Tompkins algorithm [4] is chosen to carry out the work described in this report

    because of its low computational complexity and reliability under ambulatoryconditions.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    2.3 QRS DETECTION ALGORITHMQRS detection is difficult because various types of noise can be present in the

    ECG signal. Noises include muscle noise, power-line interference, baseline wander

    and T waves with high frequency characteristics similar to QRS complexes. The most

    popular algorithm for ambulatory ECG QRS detection is the Pan-Tompkins

    Algorithm [4] mainly because it is computationally efficient and is accurate enough to

    check for abnormal heart activity. Also, certain measures are incorporated for

    reducing influence of noise sources, and thereby increasing the signal-to-noise ratio.

    We detect the QRS complexes using this algorithm in real-time and measure various

    parameters of the ECG like the heart rate, RR interval, number of R peaks to sense

    abnormalities in the heart activity of the individual being monitored.

    The Pan-Tompkins QRS detection algorithm includes three different types of

    processing steps: linear digital filtering, nonlinear transformation and decision rule

    algorithm [4]. Linear processes include a band-pass filter, a derivative and a moving

    average filter. The nonlinear transformation uses signal amplitude squaring. The

    decision rule algorithm deals with adaptive thresholds.

    2.3.1

    BAND-PASS FILTER

    First, the signal is fed into an integer coefficient digital band-pass filter, which

    is a linear digital filtering process, composed of cascaded low-pass and high-pass

    filters. The band-pass filter reduces the influence of muscle noise, 60 Hz interference,

    baseline wander and T-wave interference. The desirable passband to maximize the

    QRS energy is approximately 5-15 Hz.

    Low-Pass Filter:

    The transfer function of the second-order low-pass filter is

    () ( )

    ( )

    The difference equation of the filter is

    () ( ) ( ) () ( ) ( )

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    where, T is the sampling period and the cutoff frequency is about 11 Hz and the gain

    is 36. This filter has a processing delay of 6 samples.

    High-Pass Filter

    The design of the high-pass filter is based on subtracting the output of the low

    pass filter from the all-pass filter which is delayed by 16T ( i.e. z -16 ) to compensate

    the low-pass filter delay.

    The transfer function of the high-pass filter is

    ()

    The difference equation of the high-pass filter is

    () ( ) () () () ( )

    where, the cutoff frequency is about 5 Hz. This filter has a processing delay of 16

    samples.

    2.3.2 DERIVATIVEAfter the filtering, the signal is processed using a derivative function, another

    linear digital filtering process, in order to extract the QRS complex slope information.

    A five-point derivative is used with transfer function

    () ()( )

    The difference equation is

    () () ( ) ( ) ( ) ( )

    A delay of two samples occurs at the end of this derivative function.

    2.3.3 SQUARING FUNCTIONAfter differentiation, the signal is squared point by point. The equation of this

    operation is

    () ()

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    The squaring function makes all the data points positive and does nonlinear

    amplification of the output of the derivative, emphasizing the higher frequencies (i.e.,

    predominantly the ECG frequencies).

    2.3.4 MOVING-WINDOW INTEGRATIONThe main objective in using moving-window integration is to obtain waveform

    feature information in addition to the slope of theRwave. It is calculated from

    () () ( ( )) ( ( )) ()

    where,Nis the number of samples in the width of the integration window.

    The number of samples N in the moving window is important. If the window

    is too wide, the integration waveform will merge the QRSand T complexes together.

    If the window is too narrow, some QRScomplexes will produce several peaks in the

    integration waveform which are known as false peaks.

    2.3.5 MODIFIED DECISION ALGORITHMThe original Pan-Tompkins algorithm includes two thresholds to detect the R

    peak. Initially, the higher threshold is used for the first analysis of the signal. Thelower threshold is used if no QRScomplex is detected in 166 percent of the current

    RR interval i.e. the algorithm back traces the signal to detect the missing QRS

    complex using the lower threshold. But, since such back tracing will overload the

    Android device, a simple and relaxed version of the above mentioned algorithm is

    employed as follows:

    Firstly, we normalize the output of the moving window integrator. Then, we

    set the mean of the signal as our threshold for detecting the R peak. Then, we find the

    interval in which all the signal values cross this threshold and decide the local

    maximum in the interval as the R peak. This simplifies the computations involved and

    is accurate enough for mobile ECG monitoring.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    CHAPTER 3

    INTERFACING MODULEPIC MICROCONTROLLER

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    3.1 OVERVIEWThe interfacing module between the ECG extraction module and the patients

    smartphone consists of a PIC microcontroller (PIC16F877A) and Bluetooth device

    (Rhydolabz Technologies Bluelink). Microcontroller is used to convert the analog

    ECG signal to digital form which requires the in-built Analog-to-Digital conversion

    module (A/D). This digital ECG signal is then transmitted to the Bluetooth device

    serially using the in-built UART communication module of the microcontroller. This

    chapter deals with the concepts of A/D conversion and the serial communication.

    Bluetooth Serial Port Profile will be explained in section 4.2.

    3.2 ANALOG TO DIGITAL CONVERISONThe analog-to-digital (A/D) converter on PIC16F877A microcontroller has 5

    input pins. The A/D conversion of the analog input signal by this module results in a

    corresponding 10-bit digital number. This means that when it measures an incoming

    voltage, it compares that voltage to a reference voltage, and gives us the comparison

    represented as a 10-bit number (0-1023).

    The A/D module has four registers. These registers are:

    A/D Result High Register (ADRESH) A/D Result Low Register (ADRESL) A/D Control Register 0 (ADCON0) A/D Control Register 1 (ADCON1)

    The ADCON0 register controls the operation of the A/D module. The

    ADCON1 register configures the functions of the port pins. The result obtained after

    the conversion is stored in ADRESH and ADRESL.

    The ADRESH and ADRESL registers contain the 10-bit result of the A/D

    conversion. When the A/D conversion is complete, the result is loaded into this A/D

    result register pair, the GO/ DONE bit is cleared and the A/D interrupt flag bit ADIF

    is set.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    The steps for doing an A/D Conversion are as follows:

    1. Configure the A/D module: Configure analog pins/voltage reference and digital I/O (ADCON1) Select A/D input channel (ADCON0) Select A/D conversion clock (ADCON0) Turn on A/D module (ADCON0)

    2. Configure A/D interrupt (if desired): Clear ADIF bit Set ADIE bit Set PEIE bit Set GIE bit

    3. Wait the required acquisition time4. Start conversion:

    Set GO/ DONE bit (ADCON0)5. Wait for A/D conversion to complete, by either:

    Polling for the GO/ DONE bit to be cleared (with interrupts enabled);OR

    Waiting for the A/D interrupt6. Read A/D result register pair (ADRESH:ADRESL), clear bit ADIF if required7. For the next conversion, go to step 1 or step 2, as required

    3.3 SERIAL TRANSMISSION (USART)The Universal Synchronous Asynchronous Receiver Transmitter (USART)

    module is one of the serial I/O modules in PIC16F877A. USART is also known as a

    Serial Communications Interface or SCI. The USART can be configured as a full-

    duplex asynchronous system that can communicate with peripheral devices, such as

    CRT terminals and personal computers, or it can be configured as a half-duplex

    synchronous system that can communicate with peripheral devices, such as Analog-

    to-Digital (A/D) or Digital-to-Analog (D/A) integrated circuits, serial EPROMs, and

    so on. The USART can be configured in the following modes:

    Asynchronous (full duplex)

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    Synchronous - Master (half duplex) Synchronous - Slave (half duplex)

    The following registers are used in serial transmission of data (USART):

    Transmit Status and Control Register (TXSTA) Receive Status and Control Register (RCSTA) USART Transmit Register (TXREG) Baud Rate Generator Register (SPBRG) Interrupt Registers like INTCON, PIR1, PIE1

    When setting up an Asynchronous Transmission, follow these steps:

    1. Initialize the SPBRG register for the appropriate baud rate. If a high speedbaud rate is desired, set bit BRGH

    2. Enable the asynchronous serial port by clearing bit SYNC and setting bitSPEN

    3. If interrupts are desired, then set enable bit TXIE4. If 9-bit transmission is desired, then set transmit bit TX95. Enable the transmission by setting bit TXEN, which will also set bit TXIF6. If 9-bit transmission is selected, the ninth bit should be loaded in bit TX9D7. Load data to the TXREG register (starts transmission)8. If using interrupts, ensure that GIE and PEIE (bits 7 and 6) of the INTCON

    register are set.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    CHAPTER 4

    ANDROID PLATFORM

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    4.1 WHAT IS ANDROID?Android is a Linux-based Operating System (OS) designed

    for touchscreen mobile devices such as smartphones and tablet computers. Google

    was the first to release Android Application under the Apache License. This License

    allows the software to be freely modified and distributed by the device manufactures.Google currently uses their Google Bouncer malware scanner to watch over and scan

    the Google Play store apps. Android is written in the customized version of the Java

    programming language using the Android Software Development Kit (SDK). The

    SDK performs various operations such as debugger, software libraries, a handset

    emulator based on QEMU, documentation, sample code etc. Other development tools

    are also available, including Native Development Kit for Applications or extensions

    in C or C++. The first Android phone was sold in October 2008. Since 2008, Android

    has seen many updates which have improved the operating system, adding new

    features and fixing bugs. The latest release is 4.2 Jelly Bean. Androids user interface

    is based on direct manipulation using touch inputs that perform operations like

    swiping, tapping, pinching etc.Android devicesboot to the homescreen, the primarynavigation, and information point on the device are similar to the desktop found on

    PCs. Android applications run in a sandbox, an isolated area of the system that doesnot have access to the rest of the system's resources, unless access permissions are

    explicitly granted by the user when the application is installed. Android smartphones

    have the ability to report the location of Wi-Fi access points, encountered as phone

    users move around, to build databases containing the physical locations of hundreds

    of millions of such access points. These databases form electronic maps to locatesmartphones, allowing them to run apps like Foursquare, Google Latitude, Facebook

    Places, and to deliver location-based ads. Multi-threading, a concept which helps inrunning several processes simultaneously, is exploited in the android applications.

    This helps in reducing the overall time required for executing all processes.

    4.2 BLUETOOTH SERIAL PORT PROFILE (SPP)The Serial Port Profile defines the protocols and procedures that shall be used

    by devices using Bluetooth for RS232 (or similar) serial cable emulation. A profile is

    dependent upon another profile if it re-uses part of that profile, by implicitly or

    explicitly referencing it. Setting up virtual serial ports (or equivalent) on two devices

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    (e.g. PCs) and connecting these with Bluetooth emulates a serial cable between the

    two devices. Any legacy application may be run on either device using the virtual

    serial port, as if there were a real serial cable connecting the two devices (with RS232

    control signalling).Only one connection at a time is dealt with in this profile. Also,only point-to-point configurations are considered. For the execution of this profile,use of security features such as authorization, authentication and encryption is

    optional. Establishment of this communication with reference to Android is dealt with

    next to provide a better understanding of the project flow description in Chapter 5.The interface for Bluetooth socket is similar to that of TCP sockets: socket and

    Server socket. On the server side, a BluetoothServerSocket object is used to listen for

    any incoming connections. In Android, this is implemented using the

    listenUsingRfcommWithServiceRecord(NAME,SERIAL_UUID) method where

    NAME refers to any name by which the server application is to be called and

    SERIAL_UUID is a unique identity for communication between the two peer

    applications. Once Bluetooth is turned on, the application starts the thread to listen for

    incoming connections using this method. This is a blocking call where the rest of the

    code is executed only after receiving a connection. A sample code is given below:

    try{

    tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("SPP",

    SERIAL_UUID);

    }catch(IOException e) {

    System.out.println("Listening Failed");

    }

    mmServerSocket= tmp;

    where, mBluetoothAdapter is the BluetoothAdapter object used to handle all

    Bluetooth related operations of the Android phone and mmServerSocket is the final

    established ServerSocket object; it will be null if no incoming connections were

    present. Once another peer requests connection through this ServerSocket, the socket

    (of the client) is accepted to acknowledge and establish the connection. As and when

    this socket is accepted, the peers are said to be connected and data exchange can

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    now take place over the serial Bluetooth link established for this communication. The

    following code is self-explanatory; it refers to accepting the socket from the device:

    if(mmServerSocket!= null) {

    try{

    socket = mmServerSocket.accept();

    device= socket.getRemoteDevice();

    } catch(IOException e) {

    System.out.println("Socket not received");

    break;

    }

    The object device can be used to get all essential information (related to

    Bluetooth SPP) of the client device Ex. Devices Bluetooth Name, address. Having

    established the connection, the sockets input and output streams need to be accessed

    to transmit and receive data over the serial link. This is done as follows:

    InputStream tmpIn = null;

    OutputStream tmpOut = null;

    try{

    tmpIn = socket.getInputStream();

    tmpOut = socket.getOutputStream();

    } catch(IOException e) {

    }

    mmInStream = tmpIn;

    mmOutStream = tmpOut;

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    The last two assignments ensure that reliable InputStream and OutputStream

    are available with the final objects mmInStream and mmOutStream. Data can be

    received as bytes through the input stream, grouped using characteristic delimiters and

    used elsewhere in the application. Ideally, delimiters arent required; data can be

    received every time as a set of bytes (ASCII values) and converted back into the

    required datatype. But, this works only for applications like chat where the human

    typing speed is slow compared to the processing speed. But, for real-time data

    reception, data often gets chopped out due to synchronization issues. Thus, delimiters

    help in grouping data reliably and processing them.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    CHAPTER 5

    SYSTEM IMPLEMENTATION DETAILS

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    6.1 OVERVIEWThe following block diagram gives a complete recap of what has been

    discussed separately in the previous three chapters. The subsequent sections will

    explain the logical flow of our project providing intermediate results to give a good

    understanding of how the complete system was successfully developed.

    6.2 BLUETOOTH MODULEGiven that the ECG extraction system is available, it must be interfaced with the

    PIC microcontroller for data sampling and ultimately transmitted to the Bluetooth

    Assumed to be available as input to our system

    Electrodes (attached

    to the patient)ECG Extraction

    Circuit

    PIC Microcontroller ADC

    (using internal RC Clock)

    PIC MicrocontrollerUSART Module (9600 bps)

    Bluetooth ModuleUSART Rx

    Bluetooth Module(SPP) Transmitter

    Android Bluetooth

    (SPP) Receiver

    Android

    Application

    Dynamic Graph Plot &

    Data Backup in SD card

    Monitoring & Alerting Systemusing Pan-Tompkins Algorithm

    Band Pass

    FilterDifferentiator

    Sample

    Squaring

    Moving Window

    Integrator

    R-peak detectionusing our (modified)

    thresholds

    Heart Rate(HR)

    Calculation

    Average HRover 5

    R peak pairs

    Raisealarm if

    abnormal

    F ig 5.1Block Diagram

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    module for further transmission to the Android phone over the serial Bluetooth link.

    For this to be successfully established, a reliable and convenient Bluetooth module is

    required. The choice of such a module for our project is the BLueLINK Bluetooth

    module manufactured by Rhydolabz Technologies Private Limited. This module

    supports only the Serial Port Profile (SPP) feature of the Bluetooth technology. It has

    essentially five pins for establishing communication with any Bluetooth SPP enable

    device or application: Vcc (5V) and Ground pins, UART transmit and receive pins,

    and a RESET pin.

    The datasheet provided along with the module gives a good description of the

    working of the module. A separate file also lists the set of external AT (Attention)

    commands used to configure the module. Once the module is powered up, it returns

    \r\nOK\r\n, where \r\n represents Carriage Return and Line Feed (CRLF). The

    module then sets a 60sec. timer within which it expects the command LLL to enter

    command mode. Once it successfully enters command mode, it can be configured

    using the provided AT commands. Essential commands alone are listed below to

    provide a sense of completion:

    LLL Enter command mode

    \r\nAT+MODE=1\r\n Set the device in master mode (only transmit over the link)

    \r\nAT+BPAIR=?\r\n Obtain details of the currently paired device

    \r\nAT+CON\r\n Connect with this paired device (to start data transmission)

    For each of these commands, there is a characteristic reply from the module,

    the details of which are given in the external commands list provided by Rhydolabz.

    All these commands, and subsequently data, are input to the module using the UART

    F ig 5.2.Bluelink Bluetooth Module

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    (Universal Asynchronous Transmitter Receiver) pins. Once the device has been

    successfully connected to a SPP supported application, data is also transmitted using

    wired, serial UART link. The module, when operated in the master mode, blindly

    transmits the data received through UART over the serial Bluetooth link established

    with its peer application. An important point here is that the data rates of both the

    UART and Bluetooth serial link have to be synchronised to avoid data loss.

    Understanding the Bluetooth module:

    The crux of interfacing the Bluetooth module for data transmission has been

    provided above. The experiments conducted to understand this communication

    perfectly will be described next.

    To prevent any hardware mistakes from interfering with our experiment, a

    laptop was used to serially connect with the module, provide commands and transmit

    data reliably. But, the problem with directly interfacing with a laptop is the difference

    in power logic implemented i.e. the laptop supports only USB communication while

    the module supports only 5V serial TTL. To overcome this mismatch and establish a

    proper interface, a USB to RS232 converting cable was used to connect with the

    laptop. At the other end, a MAX232 IC was used to convert RS232 logic to 5V TTLand thus interface with the Bluetooth module. Having established connections, the

    application called AccessPort137 (similar to the standard HyperTerminal application

    but a freeware and also better than it in a few aspects) was used in the laptop end to

    transmit and receive data via UART communication. The well-known loopback test

    was executed (by shorting the Tx and Rx pins of the RS232 cable) to ensure proper

    connections. Having done the wiring perfectly, the port (where the USB side of the

    cable was connected) was opened in the application and subsequently, the Bluelink

    module was powered-up. As expected, the module returned \r\Nok\r\n thereby

    confirming proper working. Then, various commands were tested with the module

    and with time, the modules working was comprehended accurately. To determine the

    status of the module, a green LED is also provided; it glows when powered-up

    confirming SPP support and is put off when data transmission takes place.

    Once powered-up, the module is detectable by any other Bluetooth-enabled

    device. To keep things simpler, the laptop itself was chosen to be the SPP receiver for

    the module. Firstly, the module was paired with the laptop using its default passcode

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    after which two dedicated virtual COM ports was assigned by the laptop for

    communicating with the module once for transmission and the other for reception.

    Since the requirement is to just receive data transmitted via the module, the virtual

    COM port assigned for SPP reception was opened in another AccessPort137 window.

    The following steps were executed sequentially to receive data in this port:

    1. As an example, assume that COM9 is the port in which the USB side of thecable is attached and COM24 is the virtual COM port for SPP reception.

    2. Open COM9, power-up the module and give command LLL.3. Command the module to be in master mode.4. Check if the laptop is the currently paired device; else pair with it5. Open COM24 in a separate window and give Connect command via COM9.6. Check if the green light is not glowing to ensure that data can now be sent via

    the module. Once this is done, proceed to the next step.

    7. Transmit any data via COM9 and see it being received via COM24.8. This ends the series of steps to establish data communication via the module.

    Interfacing Bluelink with PIC Microcontroller:

    Once the Bluetooth module was mastered using the previously described

    experiment, the same procedure was automated using the PIC16F877A

    microcontroller. The module was directly connected to RC6 and RC7 (Pins 6 & 7 for

    USART Tx and Rx) of the controller as there is no power logic conversion required

    between the module and the microcontroller. As the replies from the module (for

    various commands) need to be checked before providing subsequent commands,

    assembly language coding would be tedious and unsuited for the microcontroller.

    Hence, the codes were written in C language using the MikroC Pro for PIC

    software developed by MikroElektronika Inc. and tested using Proteus 7

    Professional simulation software developed by Labcenter Electronics Inc. before

    being implemented in hardware. Even though the Proteus simulation worked well, the

    communication was not as expected in hardware. It was observed that, the command

    were executed perfectly and data were also received properly. But, the code didnt

    end there and it started transmitting the command strings as data through the module.

    This was debugged to understand that the main( ) program in MikroC is always put in

    an infinite loop and executed. So, once connection is established via commands, the

    data is transmitted and that ends only the first iteration. Then, the main( ) program is

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    executed again which is when all the commands sent via UART are interpreted as

    data by the module (since its already connected) and sent to the receiver application.

    As the simplest possible solution, an infinite while loop was put at the end of data

    transmission. To assist in debugging, LEDs were also extensively used.

    Finally, the same process was repeated by setting the SPP receiver as the

    Android application. This will be explained in more detail after the next section.

    6.3 ANDROID APPLICATIONThe most challenging aspect of the project was undoubtedly the development

    of an Android application tailored to the requirement in hand. As a first step in this

    venture, the exposure to a one day workshop on Android App Developmentconducted by Gatik Solutions Private Limited was very useful and effective in

    providing a clear roadmap for developing a good application on the Android platform.

    The knowledge gained from the workshop is consolidated as follows:

    Basic knowledge on the Android framework Installation of the popular software Eclipse and integration of the Android

    Software Development Kit (SDK) with Eclipse

    Elementary Java coding for Android applications

    Creating and developing an Android application using Eclipse Some conventions and structured Android programming Exporting the application as an Android Application Package (APK) Installing the application on an Android phone and working with it Some online communities and forums for discussion related to Android

    With the insight got into Android application development as a result of this

    workshop, a simple chat application was developed to familiarize with this newknowledge. In the process of developing this very basic application, some

    fundamental concepts of Java and Android were mastered which include but are not

    limited to: layout design, setting permissions for the application, accessing external

    memory, Java libraries for Android.

    The experience gained from developing this application provided the

    confidence to start the ultimate application required for the ECG monitoring system.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    But, it required more features in addition to those already stated. These are listed as

    follows along with the methodology adopted for enabling them1:

    5.3.1 STATIC GRAPH PLOTTo retrieve previously backed up ECG data of the patient and plot it. Since this

    is done offline (with respect to the real-time Bluetooth communication), it is termed

    as a static graph plot.

    The primary tool for plotting any kind of graph on Android platform is the

    Canvas class. It provides sufficient resources for plotting graphs of various types

    like line graph and bar graph. As line graph perfectly suited the requirement, it was

    chosen for graph plotting. The idea of plotting is very simple: the screen is taken as a

    two dimensional space, each point represented using x and y coordinates. The only

    peculiar thing of this Canvas is that the origin (0,0) is taken as the top left corner

    instead of the conventional bottom left corner of the screen. Initially, this led to some

    confusion while coding but through practice it was familiarized. The method called

    drawLine(start_x, start_y, end_x, end_y, paint) provides an easy way of drawing a

    simple line segment given the coordinates of two points to be joined. Here, paint is a

    variable which has associated characteristics like line thickness, line colour etc. Then,the y axis of the screen was divided in both axes based on the minimum and

    maximum entries of the data matrix to be plotted. For convenience, the x axis was

    chosen to be representing the sample index of each data value in the data matrix.

    (Ultimately, since the sampling frequency for the ECG data is known, these indices

    can be directly mapped to time values). All these are coded as a separate class which

    is then instantiated in the code running the main application. When a valid file is

    selected for plotting, the values present in the file are extracted into one matrix and

    fed into this class to obtain the graph for that particular set of ECG data. As will be

    explained later, the Pan-Tompkins algorithm is applied over this data, peaks are

    detected and the average heart rate for the dataset is calculated and displayed along

    with the graph plot.

    1The online community called Stack Overflow was of immense help in developing the application

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    5.3.2 DYNAMIC GRAPH PLOTECG data have to be received in real-time over the Bluetooth SPP link with

    the Bluetooth module and be plotted incessantly. As this refers to a dynamically

    changing graph, its termed as a dynamic graph plot.

    The logic used for dynamic graph plotting is the same as that for static graph

    plotting. The only change is that, while graph plotting only takes place once for the

    static plot, it is executed repetitively as more and more data becomes available for

    plotting. The graph is shown moving the same way as a series of photos are

    converted into a video. This is done as follows: the whole screen is divided equally by

    7200 lines and the data matrix size is also fixed as 7200 (a number decided upon for

    better visual appearance). This matrix is firstly initialized with zeros. As and whennew data is available over the SPP link, it is appended to the end of matrix and a left

    shift is executed to keep the size constant at 7200. Each value of the matrix is plotted

    on each vertical line and the height is decided by comparing it with the vertical labels

    (data values dynamically decided using the current entries in the data matrix). Also,

    the Pan-Tompkins algorithm is applied on every (refreshed) data matrix to determine

    average heart rate and analyse it for abnormal behaviour. In real-time, this is

    accomplished using the concept of multi-threading which will be explained next.

    5.3.3 MULTI-THREADINGIn the application that is required, there are two main tasks to be carried out in

    parallel and that too in real-time. In Java terminology, such multi-tasking is called as

    multi-threading, where each of the tasks are implemented as threads (which is

    essentially just another Java class). The two parallel tasks that need to be run are:

    dynamic graph plotting and data backing up in external memory; and, data monitoringusing the Pan-Tompkins algorithm (which will be explained later).

    For the required application, once Bluetooth SPP communication is

    established (which by itself requires two threads), the graph plotting and monitoring

    threads are turned on. Backing up of data is done in the graph plotting thread itself. A

    Boolean variable is associated with each thread to have control over it i.e. only if the

    variable is set to true, the thread is allowed to run. When the application is

    terminated, all threads are cancelled.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    5.3.4 BLUETOOTH SPP COMMUNICATIONAll Android phones will support Bluetooth but they need not have a Serial

    Port Profile supported application running in them to enable this feature of the

    Bluetooth technology. Since the Bluelink module supports only SPP communication,

    it is required that this is enabled in the phone through the application so as to

    successfully establish connectivity with the module. Preliminary testing of this

    communication was done by pairing the phone with a laptop. Then, to obtain a virtual

    COM port for the phone, the application was run (on the phone) by which the laptop

    acknowledged the SPP capability of the phone. Once assigned the COM port, data

    was transmitted through this port (using AccessPort137 software) and received in the

    Android application. This experiment provided the knowledge of establishing thiscommunication. The complete explanation of how SPP communication is established

    has already been explained in section 4.2 of this report.

    The explanation for every feature of the application is described below

    supplemented with snapshots to provide better understanding and appeal.

    Home Screen:

    The screen shown below (left) is the one loaded when the application is run.

    Fig 5.3 (left) Home Screen; (right) Home Screen after enabling Bluetooth

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    The files present in the applications folder in external memory are retrieved as

    a list and displayed. Here, the file ecg_csv.csv has been chosen. The button names

    Plot Graph is used to perform Static Graph Plot with the chosen file. Once

    Bluetooth is enabled and the button Access your devices is pressed, the devices

    already paired with this phone are displayed as a list as shown in the figure (right).

    Since the need is to communicate only with the Bluelink module, communication has

    been restricted only to this modulein the code running this home screen. The button

    named Dynamic Signal will start SPP communication with the module and plot real -

    time ECG data incessantly.

    Static Graph:

    The following figure shows the screen where ECG data is retrieved from the

    sample file ecg_csv.csv and plotted.

    The x axis represents the sample index while the y axis represents the ECG

    strength (voltage) as received from the SPP link. It can also be observed that the blue

    lines represent the R-peaks detected by running the Pan-Tompkins algorithm on the

    chosen dataset. The average heart rate is calculated (as explained in section 2.2 of this

    report) and displayed too for diagnosis. Some more features have also been

    incorporated for better user interface (which is of paramount importance according to

    the Android community). The graph can be zoomed using two-finger gesture to look

    into intricate details. (Two-finger gesture: press screen with two fingers and drag the

    Fig 5.4(a) From sample file

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    fingers in opposite directions to each other to zoom in; drag them towards each other

    to zoom out). The axes auto-adjusts during zoom-in and zoom-out.

    Dynamic Graph:

    A screenshot of dynamic data reception is given below in the figure.

    Once connection has been established (as described in section 4.2) with theBluelink module, the thread for dynamic graph plotting is triggered. As and when data

    Fig 5.4(b) From dynamically backed up data

    Fig 5.5 Dynamic Graph Plot

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    is received, the screen is updated with the new value and refreshed. This provides the

    moving feeling for the user. The Pan-Tompkins algorithm is run in real-time which

    detects the R-peaks, measures RR intervals and updates the heart rate as the average

    of five successive heart rates. This is done to ensure that there is no erroneous heart

    rate displayed since it can change by a high margin for two consecutive R-peak pairs

    i.e. the heart rate measured using two consecutive R-peaks can be very different from

    the one obtained from the next two consecutive R-peaks. The heart rate measured is

    continuously updated on screen. It is important to note that this is the only parameter

    being monitored for abnormality.

    The results of the modified algorithm, tested using MIT-BIH Arrhythmia database are

    discussed below:

    Table 5.1Results of Modified Pan Tompkins Algorithm

    Sample

    ID

    Actual

    number of

    R peaks

    Number

    of R peaks

    detected

    Actual

    average RR

    interval (sec)

    Calculated

    average RR

    interval (sec)

    Error

    %

    100 13 13 0.7606 0.7056 -7.23

    102 12 12 0.7808 0.7807 -0.01280

    105 14 14 0.7565 0.7125 -5.8

    112 14 14 0.6701 0.6757 0.83

    114 9 9 0.9011 1.1030 22.4059118 12 12 0.7785 0.7858 0.937

    121 10 10 0.9389 0.93944 0.0574

    123 8 8 1.1315 1.1415 0.88

    201 14 14 0.6885 0.6888 0.0551

    203 19 20 0.5065 0.48083 -5.06811

    205 15 14 0.7564 0.6699 -11.43

    207 10 10 0.9325 0.92722 -0.56621

    209 15 15 0.6276 0.58537 -6.7288

    210 16 16 0.6012 0.6063 0.845

    212 15 15 0.657 0.6564 -0.091215 18 18 0.5244 0.5248 0.0762

    219 13 130 0.7385 0.7388 0.0406

    221 13 13 0.7530 0.7536 0.07968

    223 12 12 0.7875 0.7365 0.06793

    228 12 12 0.7875 0.7877 0.02539

    231 10 10 0.9501 0.9502 0.010525

    232 8 11 1.0646 0.7747 -6.7288

    234 15 15 0.5956 0.6416 7.7233

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    The original Pan Tompkins algorithm detects 99.3% of QRS complexes when

    tested with standard 24 hours MIT-BIH arrhythmia database but has the disadvantage

    of back tracing ECG data if no R peak is detected within 166% of the current RR

    interval. This increases complexity when implemented for real time systems. But, the

    modified algorithm sets simple thresholds to detect R peaks which have produced the

    above mentioned results. Moreover, these results are obtained when tested with 10

    second samples from the MIT-BIH arrhythmia database. When compared with results

    obtained with 24 hour samples the error will definitely be higher as the number of R

    peaks (used for calculating average RR interval) is lesser. But it is found that the

    accuracy is still 93.75% which is satisfactory for preliminary ECG monitoring in

    ambulatory conditions.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    CHAPTER 6

    FUTURE SCOPE AND CONCLUSION

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    6.1 FUTURE SCOPEThe work described in this report is just a first step towards developing a

    concrete system for continuous surveillance of cardiac patients. There is a lot of scope

    for research in various aspects of the described system which include but are not

    limited to the following:

    1. The Bluetooth communication protocol is not very suitable for biomedicalapplications as the frequency of operation is very high (2.4 2.45 GHz) which

    could itself be injurious to the patients health as signals are continuously

    transmitted over this frequency range.

    2. The Serial Port Profile communication is not very reliable for continuous datatransmission. As explained earlier in section 4.2, a delimiter is appended to

    every sample when transmitted from the microcontroller. At the receiver end,

    bytes of data are combined until a delimiter is reached. This works fine for

    applications like chat where user input is far slower than the processing speed.

    But, for real-time data transmission, the issue of speed synchronization causes

    critical problems with respect to data integrity. For example, if a value

    0.69542 is transmitted, there is a good possibility that the SPP receiver

    decodes it as 0.69 and 542 separately even when delimiters are used. For an

    application like ECG monitoring, such issues are impermissible. However, this

    could be overcome by slowing down the speed of transmission which in turn

    implies that the data sampling rate gets affected. This could result in loss of

    critical values and ensuing alarms could be erroneous. Thus, a dedicated

    communication protocol needs to be established for reliable reception of data,

    especially for such short range biomedical applications. Evidently, this is a tall

    task which could spawn a lot of research areas.

    3. The Pan Tompkins algorithm implemented in this system is a good starttowards developing an efficient ECG feature extraction algorithm but need not

    be the best. Algorithms specific to ambulatory ECG monitoring could be

    devised as a result of which the processing speed could be increased.

    4. PIC16F877A microcontroller is one of the simplest options chosen here toprovide just a proof of concept. Advanced controllers could be manufactured

    tailor-made to such biomedical applications so that problems such as

    customized sampling rate and data transmission could be avoided making the

    system more robust, convenient and also commercial.

  • 5/24/2018 ECG MONITORING OF A CARDIAC PATIENT USING EMBEDDED SYSTEM

    5. This work assumes that an ECG extraction module is already available forambulatory conditions. Ultimately, the whole system depends on the accuracy

    of this module. Since it needs to be attached permanently to the patient, the

    module needs to be compact, accurate and user-friendly thereby not causing

    much inconvenience to the patient while engaging in daily activities.

    6. Android platform has been chosen for receiving and monitoring ECG data inreal-time. Efficient coding techniques could be employed to improve the

    performance of the application. Moreover, research could be carried over other

    such Operating Systems to enhance the effectiveness of the application.

    7. Cloud storage technology could be incorporated into this system to providespeedier treatment to the patient under abnormal conditions i.e. in addition to

    storing data in the phones external memory, data could be synced online with

    the patients medical account (whenever abnormal conditions occur) to which

    his/her physician has free access. Once an abnormality is conveyed to the

    physician, a virtual appointment could be fixed with the patient and recent

    ECG data could be analysed by the physician even before the patient arrives to

    the clinic/hospital. This would greatly improve the efficiency of time

    management in providing immediate treatment.

    6.2 CONCLUSIONCardiac diseases have become common even among youngsters today. So, for

    minor risk patients, it is infeasible to be admitted in the hospital for continuous

    monitoring. Thus, a system is required to continuously monitor such patients and

    provide virtual communication between the physician and the patient.

    The work described in this project is an attempt towards developing such a

    system. As a proof of concept, simple communication modules have been employed

    which need to be replaced with sophisticated ones for commercial implementation.

    Assuming that ECG extraction system is available for mobile conditions of the

    patient, a system has been shown to be working satisfactorily by transmitting sampled

    version of the continuous ECG signals to the patients Android phone via Bluetooth

    Serial Port Profile communication. The modified ECG monitoring algorithm has been

    proven to produce 93.75% accuracy under worst case testing condition using 10

    second samples from the standardized MIT-BIH Arrhythmia database.