wireless ecg monitoring - nyit logo (new york...

46
Wireless ECG Monitoring Jimmy Marsanico, Kubra Kuzu, Anthony Brown, Rahul Jain 5/18/2012 New York Institute of Technology Old Westbury, NY Department of Electrical and Computer Engineering EENG 491

Upload: lamnguyet

Post on 21-Mar-2018

219 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

Wireless ECG MonitoringJimmy Marsanico, Kubra Kuzu, Anthony Brown, Rahul Jain

5/18/2012

New York Institute of TechnologyOld Westbury, NYDepartment of Electrical and Computer EngineeringEENG 491

Faculty Advisor : Dr. Delgosha

Page 2: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

Abstract

Technological advancements in the 21st Century are booming. It is believed that medical

applications of technology are the future. When a patient dies at home or in a nursing home because of

unknown heart conditions, it is asked, what else can be done? By focusing on medical monitoring

solutions, not only will family members and loved ones of patients be at ease when away from a loved

one in need of care, but the doctors will be able to monitor patients’ conditions from remote locations.

Medical alarming systems will allow the monitoring of a patient and react knowing when a patient is in

need of medical attention – often times, long before the patient knows he or she is in need of help. By

developing a small, wireless monitoring system that is adaptable for any person to use, it is possible to

create systems of communication for multiple patients and their doctors. These devices will be able to

communicate wirelessly to nearby cell phones or computers in order to share the data in a way that makes

it easy to access for both the patient and their doctor. The ideal system will have in place methods that

will help to eliminate errors and expand efficiency of data transmission. Relaying this data back to a cell

phone or base computer will allow for further processing of data, data storage, and the ability for data

mining. Most importantly, the ability to deliver this data to a doctor’s smartphone for remote monitoring

is a key component. When the data contains “life or death” information, speed and efficiency cannot be

taken for granted. This technology is generalized enough have multiple applications. The monitoring of

patients is useful for patients at home, patients in nursing home, and those in rehabilitation centers. The

patient does not require full attention, as in an ICU, but is not stable enough to go completely unattended.

This technology will change the medical field. The same way that Facebook took over social interaction

in the 21st Century, medical wireless monitoring will change the way patients are cared for. The road to

the preservation of human life in a world full of technology begins here. This paper will explain the steps

on how we researched and applied this technology.

1

Page 3: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

I. Determining Project Path: What is the Problem?

ECG (Electrocardiogram) is a signal that is used by medical professionals to determine what is wrong

with the heart and the body. Based on medical usage of ECG, we found that the ECG is an extremely

important vital signal that needs to be monitored for heart patients. Heart failure is common, but

unrecognized and often misdiagnosed. It affects nearly 5 million Americans [7]. In 2008, over 616,000

Americans died of heart disease; almost 1 in every 4 deaths that year was due to heart disease [6]. We

decided that if any vital signal was worth monitoring, ECG is a great start for this technology.

II. Background Information

ECG is a diagnostic precedure that measures electrical activity of the heart muscle over time. The

electrical waves can be measured at selectively placed electrodes (electrical contacts) on the skin.

Electrodes on different sides of the heart measure the activity of different parts of the heart muscle. An

ECG displays the voltage between pairs of these electrodes, and the muscle activity that they measure,

from different directions.

The ECG is recorded by placing an array of electrodes at specific locations on the body. Three

types of ECG leads are recorded by the electrodes:

Standard limb leads,

Augmented limb leads

Chest leads.

These electrode leads are then connected to a device that measures the potential differences between

chosen electrodes and plots the characteristic tracings.

Lead I: Positive electrode is on the left arm and negative electrode is on the right. It measures the

potential difference across the chest between two arms.

Lead II: Positive electrode is on the left leg, while the negative one is on the right arm.

Lead III: Positive electrode is on the left leg and the negative one is on the left arm.

2

Page 4: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

III. Proposed Process

For the application of ECG monitoring, we decided to use the Arduino board for comparison

algorithms and for sending this information to a smart phone. The flow of logic for this project has been

as such:

1. Take in an ECG signal from the body.

2. Pass the ECG signal through an amplification circuit.

3. Read amplified signal into Arduino board.

4. Run comparisons for max peak and frequency measurement.

5. Transmit data via Bluetooth to a smartphone.

6. Modify the application on the smartphone for optimization and expansion.

Each of these steps in the project has many sub-steps in them, including hardware, software, and

communication capability.

3

Page 5: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

IV. ECG Signal Acquisition

ECG signals consist of low amplitude voltages that are susceptible to a high level of noise. To acquire

proper ECG signal, noise has to be suppressed and amplitude has to be enlarged. Suppression of noise can

be made by using filters, while amplitude of signal can be enlarged by operational amplifiers. Heart signal

frequency is generally bounded to a certain band that is between 0.05Hz and 2Hz, approximately 1 beat

per second. Based on the Arduino hardware, the signal will require an offset as well to input an entirely

positive signal for proper evaluation in software.

ECG Signal Analysis

Figure 1, above, shows a signal has five points of interest namely P,Q,R,S,T. These points are needed for

ECG analysis and the analysis is as follows:

4

Figure 1: Typical ECG signal [10]

Page 6: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

In Figure 1(Above): 

-P is the open ventricle for atrium 

-Q is the close action of the ventricle 

-R is the push of blood by heart by the tricuspid valve 

-S is the close of the valve 

-T is the push of blood from the lungs to the heat i.e., blue blood 

So the main question is: What causes irregular heartbeats and how do they look? 

- Spike at R. 

- Depletion of P and Q which also leads to S spiking upward. 

- S spikes downward, high blood pressure. 

- Frequency is faster, tachycardia.

- Frequency is slower, bradycardia.

-Frequency is skipping, arrhythmia.

For other information the window of information needed is dependent on the situation 

- ICU - need every second, constant stream of information 

- Rehabilitation, every 5 minutes the patient is checked, i.e., a 5 minute window. 

For emergency, must know by first irregularity, do something by second.

The above information will be used for programming to evaluate the maximum as well as for

determining the frequency and how often we should determine the frequency of the signal. In a real

world application of a commercial product using the technology, the period in which the signal is tested

and recorded will be programmable as per the doctor’s requests. There will also be certain security

procedures that a doctor can set in order to allow patients different levels of control of the device; such as

ability to change the period of testing, etc.

5

Page 7: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

V. Amplifier

The major addition from last semester was to incorporate a frequency counter that would be able

to tell the frequency of the signal read into the Arduino board. After some deliberation, we tested out a

hypothesis of having two different inputs in the Arduino, one analog, one digital. The analog input was

for the signal to give a maximum value, while the digital input was to enable us to use the frequency

counter method [8] to run a frequency counter.

We then proceeded to run the frequency counter method [8] and try to understand how it works.

After running several tests on the method, we came to the conclusion that the digital pin would need at

least 5 Volts as a digital input in order to be able to accurately measure frequency. We also experimented

with the analog section and concluded that we needed at least 1 Volt as an analog input to accurately

measure maximum height of the ECG signal.

The ECG signal in itself has a voltage of 1 ~ 4 mV, thus amplification on the ECG signal will be

needed to get the minimal voltage requirements of the digital and analog inputs. The amplifier and band

pass filter we started working with was the one shown below in Figure2 (a):

6

Page 8: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

We have to include an opto-coupler, to ensure that the patient does not have any current return to

back to the electrodes on the skin, and a band-pass filter, so that we can remove the noise from our

amplified signal.

After running multiple tests with an ECG generator, connected to the circuit in Figure 2(b), we

were getting an amplification of approx. 700 times ~ 700 mV, however that is not enough for the required

Arduino inputs, and we had to add an additional amplifier to get a higher amplification.

After some research we decided to add an amplifier to ensure that we were getting at least 5V into

the digital pin of the Arduino. The amplifier that was added was the INA128 (Figure 3), after this

amplification we had to shift the amplified ECG signal so that the smart phone would display the whole

signal peak to peak and not a half signal. The amplification of our final amplifier design is in a range from

5000 times to 8000 times ~ 5V to 8V, giving us ample voltage of the digital signal required for the

Arduino. The amplification range can be adjusted as desired by adjusting the variable resistor attached to

the INA128.

7

Figure 2: (a) Schematic for amplifier and band pass filter; (b) Actual amplifier circuit

Page 9: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

VDD

= 9V

VSS

= -9

VVS

S =

-9V

VDD

= 9V

Adju

sted

Res

R =

200k

6

2 3

7 4uA

741

VSS

= -9

VVDD

= 9V

1 4

23NE4

37

R =

3.5k

+ +

- -

VDD

= 9V

VSS

= -9

V1 2 3 11 13 12 16

8 710 69

+ In

put

- Inp

ut

AD62

4C

= 1µ

F

R =

150

R =

10k

R =

4MC

= 0.

1µF

VSS

= -9

V

VDD

= 9V

C =

100µ

F

IN40

01

18 27 36 45

R

RG

RG

INA1

28

V ou

t

8

Figure 3: Schematic of final ECG amplifier, band pass filter and shifter.

Page 10: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

Figure 5: Arduino UNO

VI. Reading the Signal into the Arduino Board

The Arduino development board is an open source kit that is used for many types of projects that

include both analog and digital signal processing. Its popularity in the electronics field has provided

much support for the hardware and its peripherals as well as for the software libraries. 99% of all

Arduino support one may require can be found on the Arduino website, <www.arduino.cc>. Figure 5, on

the left, shows the Arduino UNO, which is the most basic

development board available. It is easy to use and fast to

learn.

The UNO has a series of digital pins and analog pins

on board. As explained later, in Section VII, the software will

require a digital input for one section of the monitoring

algorithm, but an analog input of the same signal for another

segment of the algorithm. What we will be able to do is split the output from the amplifier circuit,

9

Figure 4: Printed Circuit Board Layout.

Page 11: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

ensuring there is enough current entering the board, and have one lead enter a digital pin and the other

enter an analog pin. The UNO is capable of the A-D conversion, so having the analog signal from the

amplifier enter the digital pin onboard will not be a problem. We will just keep in mind that we will use

separate grounds for digital and analog pins [9].

VII. Logical Analysis and Software

The Arduino software will be in charge of analyzing the heartbeat signal. We will have three main

software functions occurring on the Arduino: measuring the frequency of the heartbeat, monitoring the

‘R’ value of the ECG signal (which is the maximum amplitude of the signal, determined by the push of

blood by the heart through the tricuspid valve), and finally recreating the patient’s signal on the

smartphone.

The FreqMeasure.h library [8] will allow the Arduino to take in any signal into a digital pin and

measure the frequency of a repetitious signal. We have the choice of taking a large average of values or

grabbing an instantaneous frequency. As of now, we found that it is best to grab the most instantaneous

value possible. Below in Figure 6, there is the method that we built from the FreqMeasure.h library.

This method will be put into one file combined with the ‘R’-level monitoring algorithm, which

checks how healthy the functionality of the tricuspid valve is. Now this algorithm requires the

10

Figure 6: Frequency measurement method from the FreqMeasure.h library (sample code).

Full code available in Appendix I.

Page 12: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

analogRead() method, which returns an analog value. This value is what we will map backwards to a

certain voltage level, which will be determined as healthy or unhealthy based on a general average, or

programmed to a specific patient condition. The output of this algorithm [Good] or [Bad] can be directly

printed to the patient’s phone as a signal with an alarm and it can also be sent via email or text message to

a doctor’s device, once it is transmitted to the patient’s device.

VIII. Bluetooth and Transmission

Bluetooth technology gives us a way to connect one device to another device wirelessly, in close

proximity. For our purposes on transmitting data by the use of a smartphone, Bluetooth works extremely

well and is adaptable to those in any situation. It is no secret that the average American is likely to have a

smartphone with Bluetooth capability in the 21st century. Utilizing a tool that most people carry with

them every single day is what makes this technology scalable to the American market.

The Bluetooth Special Interest Group is the interest group that oversees the development of

Bluetooth standards and all Bluetooth ™ technologies. They are a unification of telecommunications,

computing, networking, industrial automation and automotive industries, and were founded in September

of 1998. This Special Interest Group (SIG) includes companies such as Microsoft, IBM, Intel, Motorola,

etc. The Bluetooth wireless technology is able to simplify and combine multiple forms of wireless

communication into one single, complete, secure, low powered, low-cost, globally available radio

frequency [4].

Bluetooth has worked on perfecting this technology by dealing with its faults: costs, transfer

rates, and battery usage. Bluetooth is a short range wireless communication technology invented to easily

allow users to create a personal area network, or in Bluetooth terminology, a pico-net. On the security

aspect of Bluetooth technology, people have concern for security. This concern was made minimal

because this technology will not automatically connect to Bluetooth enabled devices. If a user wants to

pair with their device, they need a pairing key. If they do not want anyone to see the device, they can

11

Page 13: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

prevent their device from being visible to other Bluetooth devices by just switching the device to

invisible. This ability and ease of use is marketed to allow anyone to be able to use this technology, but

this push of functionality and usability can have detrimental effects on security [2].

a. Bluetooth Shield Properties

Amarino works well with BlueSmirf Gold and Bluetooth Mate. BlueSmirf Gold is the latest

Bluetooth wireless serial cable replacement. These modems work as a serial (RX/TX) pipe. Any serial

stream from 9600 to 115200bps can be passed seamlessly from your computer to your target. The modem

can be control over open air at 350ft (106m). The remote unit can be powered from 3.3V up to 6V for

easy battery attachment.

Setting Up the BlueSmirf Gold:

The Bluetooth modem has 6 labeled pins, TX, RX, Vcc, GND, CTS-I, RTS-O. Those pins need

to be connected to the Arduino board. In order to successfully configure the BlueSmirf module a laptop

with Bluetooth connection is required.

Step 1

Connect the TX pin of Bluetooth modem to the RX pin of Arduino,

Connect the RX pin of Bluetooth modem to the TX pin of Arduino,

Connect the VCC pin of Bluetooth modem to the VCC pin of Arduino,

Connect the GND pin of Bluetooth modem to the GND pin of Arduino,

Make shortcut the CTS-I pin and RTS-O pin of Bluetooth module [5].

Step 2

After connecting the Bluetooth module, red light of BlueSmirf on the board starts blinking. Then

Bluetooth module should be added to computer from Control Panel>Hardware and Sound>Add a Device.

Select the device and click Next.

Then the device pairing screen comes up;

12

Page 14: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

Select second option, Enter the device’s pairing code and enter 1234.

As soon as you enter the pairing code, Windows starts installing the device driver for the module.

Step 3

Open Arduino’s terminal or another terminal program (since Arduino’s terminal supports the

baud rates which we need, we used that one). Select the port which the Bluetooth module is assigned.

In this case Port7:

Then open the Serial Monitor. As soon as you open Serial Monitor, there should be connection

between the BlueSmirf module and Bluetooth of your computer. After connection is established the

yellow LED on module should light up.

Select ‘NO LINE ENDING’ at the bottom right side and set baud rate to 115200 baud, which is

BlueSmirf’s current baud rate. Type $$$ to put Bluetooth module into command mode, CMD

13

Figure 7: Bluetooth pairing screen

Figure 8: Arduino IDE, serial port connection

Page 15: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

immediately will be seen on the display. Then change ‘NO LINE ENDING’ to ‘CARRIAGE

RETURN’ and type D. All information of Bluetooth Module is shown up. [5]

To change the baud rate, type R SU,57 to change the baud rate to 57600; this is done because

Amarino works on 57600 or on 115200. If the baud rate is changed on the module, AOK command will

be seen, otherwise, you will get ERR will be displayed on the screen. [5]

To exit from command mode type ---<cr>

b. Data Transfer from Arduino to Android over Bluetooth

Arduino is an open source electronics prototyping platform designed to be low-cost and easy to

learn. Also it is well documented and there is a great community supporting it.

For the smartphones to control a hardware device, we need an external circuitry that

communicates between the phone and the client device. Also we need a software interface that can bridge

the board and our Android mobile. “Amarino” serves this purpose; it has many pre-defined libraries in it

which can be used to control the board with little knowledge.

IX. Amarino

14

Figure 79 Bluetooth properties displayed on COM port

Page 16: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

Amarino is a toolkit that connects Android- driven mobile devices with Arduino microcontrollers.

Amarino basically consists of three main parts: [1]

Android application called "Amarino".

Arduino library called "MeetAndroid".

Amarino plug-in bundle.

To work with Amarino, it requires at least: [1]

An Android phone (Android 2.x works best, however Android 1.6 is also supported but not all

models will work, e.g. HTC Hero and Samsung Behold II with Android 1.x will not work).

An Arduino board.

A Bluetooth shield for your Arduino.

X. Ethics

Engineers of all types have to be mindful of ethics. Everything we do affects the public and

because of this, we take our jobs seriously. There is an emphasis placed on ethics in engineering exams

and in professional engineering organizations. Organizations such as the National Society of Professional

Engineers push for engineers to understand and live by an engineering code of ethics.

There are fundamental canons that engineers must follow during their daily tasks. According to a short

excerpt The National Society of Professional Engineers,

“Engineers, in the fulfillment of their professional duties shall:

1. Hold paramount the safety, health and welfare of the public.

2. Perform services only in area of their competence.

3. Issue public statements only in an objective and truthful manner.

4. Act for each employer or client as faithful agents or trustees.

5. Avoid deceptive acts.

15

Page 17: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

6. Conduct themselves honorably, responsibly, ethically, and lawfully so as to enhance the honor,

reputation, and usefulness of the profession.” [10]

If engineers choose not to follow these rules, then the safety of the public is compromised. There

are many examples of what kind of catastrophes can happen when engineers do not follow the code of

ethics. One prime example is the Tay Bridge disaster of 1879. The 2 mile bridge collapsed into the River

Tay while a train was passing over it. The collapse killed 75 people. The engineer who designed the

bridge was accused of not taking in to account wind loading. [11]

Safety is paramount for an engineer. So how is our design project safe? We have included an opto

coupler. The opto coupler provides electrical isolation between its input and output. This ensures that

there is no current draining back to the patient and possibly shocking him or her.

Since our project includes the possible and eventual use of a live human being, we took a course from the

Institutional Review Board (IRB) that allows us to use a live human in our experiments. The course

teaches you about the ethics around using a human for experimentation. At the end of each chapter we

had to take a quiz to ensure the material was learned. There are also security issues that we need to take

into consideration. Since we are transmitting data wirelessly that data needs to be encrypted to ensure

that hackers and other threats cannot compromise the data, especially since this data is very important to

the patient and holds vital information.

a. RoHS Compliance

Restriction of Hazardous Substances or RoHS is to restrict dangerous substances commonly used

in electronics and electronic equipment. This was adopted in February 2003 by the European Union and

after July 1, 2006, all electronic products in the European Union must pass RoHS compliance. Lead,

Mercury, Cadmium, Hexavalent Chromium, Polybrominated Bihenyls and Polybrominated Diphenyl

Ethers are restricted by RoHS. RoHS sets maximum levels of each substance that can be used. This

impacts large household appliances, small household appliances, computing and communications

equipment, consumer electronics, lighting, power tools, toys and sports equipment and automatic

dispensers. [12]

16

Page 18: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

Both the Bluesmirf Bluetooth adapter and Arduino UNO board is RoHS compliant. Since Arduino is an

Italian product, it is required to meet RoHS compliance by law.

XI. Future Work

This project has a lot of potential for expansion. Some future work that we would accomplish would be:

1. Building a database for storing the values of maximum heartbeat, frequency, and status of the

patient.

2. Encode an adaptive filter that would filter our random noise generated by the human body.

3. Phone functions such as vibrating, sending texts and uploading values to a database.

4. Wifi Capabilities instead of Bluetooth.

5. Work with a live human specimen (IRB).

XII. Conclusion

The project consists of several levels including signal acquisition, amplification, filtering,

processing, transmission, and management. Acquiring and processing the signal requires some medical

background knowledge, which we acquired via the web and our friends at NYCOM. The signal amplifier

and filter was built from scratch by members of the group in order to be able to read a small signal into

the Arduino processing board. Then, the software was built to encompass all aspects of the desired output

of the signal, including frequency measurement, and signal recreation. Choosing Bluetooth transmission

to a smartphone makes this project adaptable to real world applications by anyone with a smartphone. In

American culture today, smartphones, especially with Bluetooth connectivity, is extremely prevalent.

This makes it so easy to adapt this technology to everyday life. Even in developing nations, the wireless

communication industry is growing rather quickly and can soon be introduced there as well. The

marriage of medical monitoring and wireless communication will make for a huge technological growth

in the 21st century!

17

Page 19: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

XIII. Appendix I

Arduino Code for Heart Monitor

/* Analog input, analog output, serial output Jimmy Marsanico 5/18/2012 ECG Monitoring Program */#include <MeetAndroid.h>#include <FreqMeasure.h>

// These constants won't change. They're used to give names// to the pins used:const int digitalInPin = 8; // Input pin for signal/Frequency Measurementconst int analogInPin = A5; // Analog input pin that the ECG is attached toconst int analogOutPin = 12; // Analog output pin that copies inputPinconst int green = 5; // Green LEDconst int red = 6; // Red LEDconst int yellow = 7; // Yellow LEDconst int stat = 13; // status LED (blue)

//variables that will change throughout the program//for overall programint sensorValue = 0; // value read from the potint outputValue = 0; // value output to the PWM (analog out)//rValue()int count = 0; // check for 'R' max will reset every # countsint resetCount = 500; // how many counts the max value checks before resettingint maxRead = 0; // for monitoring the R-value spikeint maxMM = 0;//measureFreq()double sumF = 0; // use for Freq algorithmint countF = 0; // used to count the Freq loopint countFto = 2; // countF compares to this to know when to restartdouble frequency = 0; // initializes the frequencydouble BPM = 0; // initializes the BPM

int intBPM = int(BPM);

String color = " ";

18

Page 20: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

String toPhone = " "; //fix thischar str[30];

//setting up Android section:MeetAndroid meetAndroid;

void setup() { // initialize serial communications at 9600 bps: Serial.begin(57600); pinMode(analogInPin, INPUT); FreqMeasure.begin();}

void checkStatus(){ solidLED(stat); delay(2000); analogWrite(stat, 0);}

void rValue(){ sensorValue = analogRead(analogInPin); // read the analog in value: outputValue = map(sensorValue, 0, 1023, 0, 255); // map it to the range of the analog out: analogWrite(analogOutPin, outputValue); // change the analog out value to recreate analog input with 8-bit resolution

maxRead = (max(maxRead, sensorValue)); maxMM = maxRead * 4.9; /* if(maxRead > 140 && maxRead < 300) { // yellow LED color = "Low"; //'R' value is too low; heart is not pumping enough blood to the body solidLED(yellow); //Serial.println("Warning Heart isn't providing enough blood to the body."); analogWrite(green, 0); analogWrite(red, 0); } else if(maxRead >= 300 && maxRead < 750) { // green LED color = "Normal"; //'R' value is maxing out in a NORMAL RANGE solidLED(green); //Serial.println("Heart is pumping at a normal amplitude."); analogWrite(red, 0); analogWrite(yellow, 0); }

19

Page 21: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

else if(maxRead >= 750 && maxRead <= 1023) { // red LED color = "High"; //'R' value is too high; heart is pumping too hard to provide blood to body solidLED(red); //Serial.println("Danger! Heart is pumping too hard to provide blood to the body."); analogWrite(green, 0); analogWrite(yellow, 0); } else { //In the case of outputValue = 0, or an error occurs, no light (other than Status) will blink color = "n/a"; analogWrite(green, 0); analogWrite(yellow, 0); analogWrite(red, 0); } */

count = count + 1; if(count >= resetCount){ // number of counts before resetting count = 0; maxRead = 0; frequency = 0; }}

void measureFreq(){ if (FreqMeasure.available()) { analogWrite(stat,255); // average several reading together sumF = sumF + FreqMeasure.read(); countF = countF + 1; if (countF > countFto) { frequency = F_CPU / (sumF / countF); // beats/sec(frequency) * 60sec/min BPM = frequency*60; intBPM = int(BPM); //Serial.print("F: "); //Serial.println(frequency); sumF = 0; countF = 0; } else { analogWrite(stat,0); } if (intBPM < 40 || intBPM >= 150) { color = "Warning"; } else if (intBPM >= 40 && intBPM < 60) { color = "Low";

20

Page 22: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

} else if (intBPM >= 60 && intBPM < 120) { color = "Normal"; } else if (intBPM >=120 && intBPM < 150) { color = "High"; } }}

void blinkLED(int color) { //makes the indicated LED blink analogWrite(color, 255); delay(10); analogWrite(color, 0); delay(10); }

void solidLED(int color) { //keeps the indicated LED a solid color analogWrite(color, 255); }

//need to fixvoid setOutput(){ //static char buffr[30]; //toPhone = String(sensorValue)+","+dtostrf(BPM,1,2,buffr)+","+String(maxRead)+","+color; toPhone = String(sensorValue)+","+String(intBPM)+" BPM,"+String(maxMM)+"mV,"+color; toPhone.toCharArray(str,30);}

void printToSerial() { // print the results to the serial monitor: /*Serial.print("sensor = " ); Serial.print(sensorValue); */Serial.print("\t BPM = "); Serial.print(BPM); Serial.print("\t intBPM = "); Serial.println(intBPM); /*Serial.print("\t output = "); Serial.print(outputValue); Serial.print("\t count = "); Serial.print(count);*/ /* Serial.print("\t max = "); Serial.print(maxRead); Serial.print("\t status = "); Serial.println(color);

21

Page 23: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

*/ //Serial.println(str);

/*Serial.print("\t frequency = "); Serial.println(frequency);*/}

void loop() { //keep this in loop() to receive events from phone meetAndroid.receive(); //call the R-Peak detection algorithm //rValue(); //delay(5); //call the Frequency measurement algorithm measureFreq();

//set the output to be a string of all the values we need //setOutput(); //send data to Android //toPhone.toCharArray(str,30); meetAndroid.send(intBPM); //meetAndroid.send(str); //meetAndroid.send(sensorValue); // send "toPhone" later

//calls a print method to display data on serial monitor // printToSerial();// Serial.flush(); // wait 10 millisecond(s) before the next loop // for the analog-to-digital converter to settle // after the last reading: delay(10);}

22

Page 24: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

XIV. Appendix II

Android Phone Code: Viewer

/**/package edu.mit.media.hlt.sensorgraph;

import android.content.Context;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.View;

public class GraphView extends View {

private Bitmap mBitmap;private Paint mPaint = new Paint();private Paint mPaint2 = new Paint(); //used for grid

private Canvas mCanvas = new Canvas();

private float mSpeed = 1.0f;private float mLastX;

private float mScale; private float mLastValue; private float mYOffset; private int mColor; private float mWidth; private float maxValue = 1024f; public GraphView(Context context) { super(context); init(); } public GraphView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init(){ mColor = Color.argb(192, 64, 128, 64); mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);

23

Page 25: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

} public void addDataPoint(float value){ final Paint paint = mPaint; float newX = mLastX + mSpeed; final float v = mYOffset + value * mScale; paint.setColor(mColor); mCanvas.drawLine(mLastX, mLastValue, newX, v, paint); mLastValue = v; mLastX += mSpeed;

invalidate(); } public void setMaxValue(int max){ maxValue = max; mScale = - (mYOffset * (1.0f / maxValue)); } public void setSpeed(float speed){ mSpeed = speed; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565); mCanvas.setBitmap(mBitmap); mCanvas.drawColor(0xFFFFFFFF); mYOffset = h; mScale = - (mYOffset * (1.0f / maxValue)); mWidth = w; mLastX = mWidth; super.onSizeChanged(w, h, oldw, oldh); }

@Override protected void onDraw(Canvas canvas) { synchronized (this) { if (mBitmap != null) { if (mLastX >= mWidth) { mLastX = 0; final Canvas cavas = mCanvas; cavas.drawColor(0xFFFFFFFF); mPaint.setColor(0xFF777777); cavas.drawLine(0, mYOffset, mWidth, mYOffset, mPaint);

24

Page 26: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

//Grid for Canvas cavas.drawColor(Color.WHITE); mPaint2.setColor(Color.LTGRAY); mPaint2.setStrokeWidth(1); for (int i=0; i<30; i++){ int x = i*20; int y = i*100; int z = y/2; int w = x*2; mCanvas.drawLine(0, x, 2000, x, mPaint2); mCanvas.drawText("SEC", y, 250, mPaint2); mCanvas.drawLine(z, 0 , z, 2000, mPaint2); mCanvas.drawText("VOLT", 20, w, mPaint2); } } canvas.drawBitmap(mBitmap, 0, 0, null); } } }

}

Android: Processing

/**/package edu.mit.media.hlt.sensorgraph;

import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.os.Vibrator;import android.util.Log;import android.widget.TextView;import at.abraxas.amarino.Amarino;import at.abraxas.amarino.AmarinoIntent;

/** * <h3>Application that receives sensor readings from Arduino displaying it graphically.</h3> * * This example demonstrates how to catch data sent from Arduino forwarded by Amarino 2.0. * SensorGraph registers a BroadcastReceiver to catch Intents with action string: <b>AmarinoIntent.ACTION_RECEIVED</b>

25

Page 27: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

* * @author Bonifaz Kaufmann - April 2010 * */public class SensorGraph extends Activity {

public Vibrator vibrator;public boolean isVibrating;

private static final String TAG = "SensorGraph";

// change this to your Bluetooth device address private static final String DEVICE_ADDRESS = "00:06:66:08:5E:EB"; //"00:06:66:03:73:7B";

private GraphView mGraph; private TextView mValueTV;private TextView mValueBPM;private TextView mValueRV;

private ArduinoReceiver arduinoReceiver = new ArduinoReceiver();

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // get handles to Views defined in our layout file //mGraph = (GraphView)findViewById(R.id.graph); mValueTV = (TextView) findViewById(R.id.value); mValueBPM = (TextView) findViewById(R.id.value2); mValueRV = (TextView) findViewById(R.id.value3); //mGraph.setMaxValue(1024); vibrator = ((Vibrator) getSystemService(VIBRATOR_SERVICE)); }

@Overrideprotected void onStart() {

super.onStart();

// in order to receive broadcasted intents we need to register our receiverregisterReceiver(arduinoReceiver, new IntentFilter(AmarinoIntent.ACTION_RECEIVED));

26

Page 28: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

// this is how you tell Amarino to connect to a specific BT device from within your own code

Amarino.connect(this, DEVICE_ADDRESS);}

@Overrideprotected void onStop() {

super.onStop();stopVibrate();// if you connect in onStart() you must not forget to disconnect when your app is closedAmarino.disconnect(this, DEVICE_ADDRESS);

// do never forget to unregister a registered receiverunregisterReceiver(arduinoReceiver);

}

public void startVibrate() {if(vibrator != null && !isVibrating){

isVibrating = true;vibrator.vibrate(new long[]{0,1000,250},0);

}}public void stopVibrate(){

if(vibrator != null && isVibrating){isVibrating = false;vibrator.cancel();

}}

/** * ArduinoReceiver is responsible for catching broadcasted Amarino * events. * * It extracts data from the intent and updates the graph accordingly. */public class ArduinoReceiver extends BroadcastReceiver {

String received = null; //delimited stringString data = null; //current readint BPM = 12345;// = null; //BPMString rValue = null; //max readString status = null; //color/status

@Overridepublic void onReceive(Context context, Intent intent) {

// the device address from which the data was sent, we don't need it here but to demonstrate how you retrieve it

27

Page 29: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

final String address = intent.getStringExtra(AmarinoIntent.EXTRA_DEVICE_ADDRESS);

// the type of data which is added to the intentfinal int dataType = intent.getIntExtra(AmarinoIntent.EXTRA_DATA_TYPE, -1);

// we only expect String data though, but it is better to check if really string was sent

// later Amarino will support differnt data types, so far data comes always as string and

// you have to parse the data to the type you have sent from Arduino, like it is shown below

if (dataType == AmarinoIntent.STRING_EXTRA){//received = intent.getStringExtra(AmarinoIntent.EXTRA_DATA);//delimit(received);data = intent.getStringExtra(AmarinoIntent.EXTRA_DATA); //*CHANGE

THISif (data != null){

//mValueTV.setText(data);try {

// since we know that our string value is an int number we can parse it to an integer

final int sensorReading = Integer.parseInt(data);if (sensorReading >= 200){BPM = 200;}else if (sensorReading <= 0){BPM = 0;}else {BPM = sensorReading;}//mGraph.addDataPoint(sensorReading);Log.d("graph"," "+sensorReading);

} catch (NumberFormatException e) { /* oh data was not an

integer */ }}/*if (data > rValue){

rValue = data;}*/if (BPM != 12345){

mValueBPM.setText(data + "BPM");if (BPM < 60){

rValue = "Low BPM";status = "Warning!";mValueRV.setBackgroundColor(-256);//startVibrate();//stopVibrate();

} else if (BPM >= 60 && BPM < 130){rValue = "Normal BPM";status = "Status okay...";mValueRV.setBackgroundColor(-16711936);

28

Page 30: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

//stopVibrate();} else if (BPM >= 130){

rValue = "High BPM";status = "Warning!";mValueRV.setBackgroundColor(-65536);//startVibrate();//stopVibrate();

}} else {mValueBPM.setText("BPM N/A");}

if (rValue != null){mValueTV.setText(rValue);

} else {mValueTV.setText("BPM Status N/A");}

if (status != null){mValueRV.setText(status);

} else {mValueRV.setText("Status N/A");}}

}

public void delimit(String receive) {String str = receive;String delims = ",";String[] tokens = str.split(delims);data = tokens[0];//BPM = tokens[1];rValue = tokens[2];status = tokens[3];

}

}

}

Graphical Layout

29

Page 31: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

XML Code

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" >

<TableLayout android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" android:stretchColumns="*" > < TableRow >

<TextView android:id="@+id/value" android:layout_width="200dp" android:layout_height="150dp" android:layout_weight="6" android:background="#fff" android:gravity="center" android:text = "BPM Status" android:textSize="40sp" /> </TableRow> </TableLayout>

<TextView android:id="@+id/value2" android:layout_width="fill_parent" android:layout_height="150dp" android:background="#fff" android:gravity="center" android:text = "BPM" android:textSize="40sp" />

30

Page 32: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

<TextView android:id="@+id/value3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#fff" android:gravity="center" android:text = "Status Message" android:textSize="40sp" />

</LinearLayout>

31

Page 33: Wireless ECG Monitoring - NYIT Logo (New York …iris.nyit.edu/.../prj_reports/spring2012/project2.docx · Web viewAndroid application called "Amarino". Arduino library called "MeetAndroid"

References

[1] "Amarino - "Android Meets Arduino" - Documentation." Amarino. 2011. Web. 2 Feb. 2012. <http://www.amarino-toolkit.net/index.php/docs.html>.

[2] Bluetooth Technologies, "Welcome to Bluetooth Technology 101." n. page. Web. 20 Feb. 2011. http://www.bluetooth.com/Pages/Fast-Facts.asp&xgt.

[3] Chen, Chai Hung et al. ECG Measurement System. Columbia University. http://www.cisl.columbia.edu/kinget_group/student_projects/ECG%20Report/E6001%20ECG%20final%20report.htm. Date accessed: March 27, 2012.

[4] "Our History." Document Moved. 2011. Web. 20 Feb. 2012. <http://www.bluetooth.com/Pages/History-of-Bluetooth.aspx>. Date accessed: March 17, 2012.

[5] "Roving Networks Bluetooth™ Product User Manual." Roving Network, 21 Nov. 2009. Web. 14 Mar. 2012. <http://www.sparkfun.com/datasheets/Wireless/Bluetooth/rn-bluetooth-um.pdf>.

[6] “Heart Disease Facts.” Centers for Disease Control and Prevention. March 23, 2012. Web. <http://www.cdc.gov/heartdisease/facts.htm> Date accessed: March 29, 2012.

[7] “Quick Facts & Questions About Heart Failure.” Heart Failure Society of America. 2012. Web. <http://www.hfsa.org/heart_failure_facts.asp> Date accessed: March 29, 2012.

[8] < http://www.pjrc.com/teensy/td_libs_FreqMeasure.html> Date accessed: January 29, 2012.

[9] < http://www.arduino.cc/en/Guide/Board?from=Tutorial.ArduinoBoard> Date accessed: February 2, 2012.

[10] “NSPE Code of Ethics for Engineers” July 2007 <http://www.nspe.org/Ethics/CodeofEthics/index.html>

[11] “Tom Martin’s Tay Bridge Disaster Web Pages” <http://taybridgedisaster.co.uk/>

[12] “RoHS Guide Compliance” < http://www.rohsguide.com/>

32