You are on page 1of 83

Design and Implementation of a Wireless EKG and Pulse

Oximetry Monitor and Visualization System

Prepared for:
ECE 4600 Group Design Project

Group 13

Prepared by:
Ahmed Bu Aishah
Danielle Rocan
Joshua Halek
Mujtaba Abdul Jalil
Qiu Chan Yu
Ying Pan

Faculty Advisor:
Dr. Jun Cai, PhD, P.Eng., SIEEE
Associate Professor

External Support:
Michael G. Zhang
Seven Oaks General Hospital

March 17th, 2017


Abstract

Abstract

The goal of this project was to design and implement a wearable and wireless EKG and
Pulse Oximetry Monitor and Visualization system. The device created for this project obtains a
user’s EKG data and measures their heart rate and blood oxygen saturation level (SpO2). The
device then sends the information over Low Energy Bluetooth (BLE) to an Android based
application for visualization. The designed EKG monitoring system utilizes an Analog Front End
Amplifier (AFE) that features low noise, low power, small size, high performance and adaptive
filtering. The SpO2 level and heart rate are measured by using a photo sensor and integrated
LEDs. The measured data is acquired by the MCU through implementation of SPI and I2C
communication interfaces. The Android application graphs the EKG and displays the values for
heart rate and blood oxygen saturation level.
The report details the four major components of this project which are data acquisition,
data communication, data visualization and cloud storage. The data acquisition sections provide a
comprehensive overview of how the system is designed to obtain good EKG and SpO2 signals. It
also discusses critical design based considerations for patient safety and equipment techniques for
filtering out noise. An implementation of Low Energy Bluetooth protocol is covered in the data
communication section, whereas the data visualization section looks at signal plotting and a
technique of data parsing on Android application. The cloud storage section covers the
implementation of a real-time database to store user information and acquired data for future
reference.

i
Acknowledgements

Acknowledgements

A big thanks to our advisor Dr. Jun Cai for supporting us throughout the project and providing
valuable guidance

We would like to thank Dr. Derek Oliver for being there for us through thick and thin.

A huge thank Aidan Topping, as she was integral to the completion of all our documents and
answered our endless questions.

We would like to thank Mr. Daniel Card, for his invaluable advice, and help in forming the
group.

Thank you to Dr. Ahmad Byagowi, for his continued encouragement, and support throughout the
designing process.

We would like to thank Sinisa Janjic, Ken Biegun, and Mount-First Ng, for handling all our
orders and providing us with extra components, and a big thanks Zoran Trajkoski for soldering
our components.

A big thanks Mr. Ramin Soltanzadeh, for his advice with early development and guidance
through the early stages of the project.

A special thanks to Jasper Arthur for providing us with the means to 3-D print the carrying case.

ii
Table of Content

Table of Content

ABSTRACT .............................................................................................................................. I
ACKNOWLEDGEMENTS .................................................................................................... II
TABLE OF CONTENT ......................................................................................................... III
CONTRIBUTIONS ................................................................................................................ V
LIST OF FIGURES ............................................................................................................... VI
LIST OF TABLES .............................................................................................................. VIII
NOMENCLATURE............................................................................................................... IX
CHAPTER 1 - INTRODUCTION ........................................................................................... 1
1.1 MOTIVATION ............................................................................................................ 1
1.2 MONITORING METHODS........................................................................................... 1
Electrocardiogram ................................................................................................ 1
Pulse Oximeter ..................................................................................................... 3
CHAPTER 2 - PROJECT DETAILS ....................................................................................... 4
2.1 OVERVIEW................................................................................................................ 4
2.2 SCOPE ....................................................................................................................... 4
2.3 PARAMETERS FOR SUCCESS ..................................................................................... 4
CHAPTER 3 - DATA ACQUISITION .................................................................................... 6
3.1 ELECTROCARDIOGRAM OVERVIEW ......................................................................... 6
3.2 ELECTROCARDIOGRAM SPECIFICATIONS ................................................................. 6
3.3 ELECTROCARDIOGRAM HARDWARE ........................................................................ 7
Right Leg Drive (RLD) ........................................................................................ 8
Voltage Regulator ................................................................................................ 8
Defibrillator Protection ........................................................................................ 9
Decoupling Strategy........................................................................................... 10
Clock/Oscillator ................................................................................................. 11
Serial Interface Hardware .................................................................................. 11
3.4 ELECTROCARDIOGRAM SOFTWARE IMPLEMENTATION ......................................... 12
SPI Communication ........................................................................................... 12
System Initialization and Data Acquisition ....................................................... 14
3.5 PULSE OXIMETER OVERVIEW ................................................................................ 18
3.6 PULSE OXIMETER SPECIFICATION .......................................................................... 19
3.7 PULSE OXIMETER HARDWARE ............................................................................... 20
3.8 PULSE OXIMETER SOFTWARE IMPLEMENTATION .................................................. 21
I2C Communication............................................................................................ 21
System Initialization and Data Streaming .......................................................... 22
CHAPTER 4 - DATA COMMUNICATION ......................................................................... 24
4.1 BLUETOOTH LOW ENERGY PROTOCOL AND OPERATION ...................................... 24
4.2 MCU AND ANDROID SMARTPHONE GATT COMMUNICATION .............................. 25
iii
Table of Content

CHAPTER 5 - DATA VISUALIZATION AND STORAGE ................................................ 27


5.1 OVERVIEW.............................................................................................................. 27
5.2 ANDROID GRAPHICAL USER INTERFACE ............................................................... 27
5.3 REAL-TIME DATABASE AND CLOUD STORAGE ..................................................... 32
CHAPTER 6 - SYSTEM INTEGRATION ............................................................................ 35
6.1 PCB FABRICATION ................................................................................................. 35
Design Considerations and Component Integration .......................................... 35
6.2 CARRYING CASE ..................................................................................................... 36
CHAPTER 7 - CONCLUSION .............................................................................................. 38
7.1 FUTURE WORK ....................................................................................................... 38
BIBLIOGRAPHY .................................................................................................................. 40
APPENDIX A: BUDGET ...................................................................................................... 42
APPENDIX B: APPLICATION USER MANUAL .............................................................. 44
APPENDIX C: TESTING RESULTS ................................................................................... 46
APPENDIX D: SOFTWARE RESOURCES ........................................................................ 50
SOFTWARE FLOWCHARTS .................................................................................................. 51
SOFTWARE ALGORITHMS AND LIBRARIES ......................................................................... 58

iv
Contributions

Contributions

The project was broken down into 4 separate sections: Data Acquisition, Communications,
Data Visualization, and Data Storage. Where each member contributed to the completion of each
section

Ahmed Bu Aishah

Danielle Rocan

Joshua Halek

Mujtaba Jalil

Qiuchan Yu

Ying Pan
Literature Review ○ ○ ○ ○ ○ ○
Hardware Design ○ ○ ●
Data Acquisition
Data Processing ○ ○ ○ ● ● ○
BLE ○ ●
Communications MCU
● ○
Communication
Data GUI ○ ○ ●
Visualization Data and Parsing ○ ●
Database ○ ●
Data Storage
Cloud Storage ○ ○ ●
Final Report ○ ○ ● ○ ○ ○

Legend: ● Section Lead ○ Contributor

v
List of Figures

List of Figures

Figure 1-1: QRS Complex [21]........................................................................................................ 2

Figure 1-2: Placement of Limb Leads Electrodes [5] ..................................................................... 3

Figure 3-1: Placement of electrodes [4]. .......................................................................................... 6

Figure 3-2: Electrode and Lead Configurations, Analog Lead Mode [7] ........................................ 7

Figure 3-3: Right Leg Drive Configuration [7] ............................................................................... 8

Figure 3-4: 9V to 3.3V Voltage Regulator AZ1117C [8] ................................................................ 9

Figure 3-5: Defibrillator Protection Circuit [7]................................................................................ 9

Figure 3-6: EKG Signal without Right Leg Drive ......................................................................... 10

Figure 3-7: EKG Signal with Right Leg Drive .............................................................................. 10

Figure 3-8: Locations of Decoupling Capacitors, indicated by C1, C2 ......................................... 11

Figure 3-9: External Crystal Clock of 8.192 MHz......................................................................... 11

Figure 3-10: Serial Interface .......................................................................................................... 12

Figure 3-11: SPI modes of communication based on the clock cycle [12]. ................................... 13

Figure 3-12: Flow diagram for ADAS1000-4 data streaming process .......................................... 18

Figure 3-13 Extinction coefficient VS light wavelength plot ........................................................ 19

Figure 3-14 SpO2 System schematic diagram. ............................................................................... 21

Figure 3-15: Left hand side: I2C clock cycle and data start (S), repeat (Sr) and stop (P) sequences.
Right hand side: one byte transaction completion with acknowledge clock pulse [6].
.................................................................................................................................... 22

vi
List of Figures

Figure 3-16: Flow charts for SpO2 and heart rate data retrieval. ................................................... 23

Figure 4-1: GAP Arcitecture depicting server and client............................................................... 24

Figure 4-2: Demonstration of advertisement data [16] .................................................................. 25

Figure 5-1: Signin screen. .............................................................................................................. 28

Figure 5-2: (a) Information screen. (b) FileList screen. ................................................................. 29

Figure 5-3: (a) Main screen before hardware connection. (b) Main screen after connection
streaming data. ........................................................................................................... 30

Figure 5-4: Flow diagram for parse algorithm. .............................................................................. 31

Figure 5-5: Firebase authentication console .................................................................................. 33

Figure 5-6: Real-time data base populated with test user information. ......................................... 34

Figure 6-1: (a) and (b) represent the front and back of the central PCB. Image (c) and (d)
represent the pulse oximeter PCB. ............................................................................. 35

Figure 6-2: Copper fill on PCB depicted by large blue patches. ................................................... 36

Figure 6-3 3-D Render of Enclosure Case ..................................................................................... 37

Figure C-1 Qiuchan Yu’s EKG signal result ................................................................................. 46

Figure C-2 Danielle Rocan’s EKG signal result ............................................................................ 47

Figure C-3 Ying Pan's EKG signal result ...................................................................................... 47

Figure C-4 Joshua Halek’s EKG signal result ............................................................................... 48

Figure C-5 Standard EKG signal[21]............................................................................................. 48

vii
List of Tables

List of Tables

Table 3-1: Frame Rates vs. Clock Frequency ........................................................................ 14

Table 3-2: Register names and hexadecimal commands writeen to power up the system..... 15

Table 3-3: Default 2kHz frame word format. ........................................................................ 16

Table 3-4: Customized data format for the application.......................................................... 16

Table 3-5 SpO2 specification metric ...................................................................................... 20

Table 3-6: Summary of key specifications for the voltage regulator [6]. .............................. 20

Table 4-1: Custom UUIDs service parameters ...................................................................... 26

Table C-1 The SpO2 result of all team members ................................................................... 49

viii
Nomenclature

Nomenclature

ADC Analog-to-Digital Converter LA Left Arm


AFE Analog frontend Amplifier LL Left Leg
ATT Attribute Protocol LSB Least Significant Bit
BLE Bluetooth Low Energy MCU Microcontroller Unit
CMR Common-Mode Rejection MSB Most Significant Bit
CPHA Clock Phase RAM Random Access Memory
CPOL Clock Polarity RA Right Arm
EKG Electrocardiogram RL Right Leg
ESD Electrostatic Discharge RLD Right Leg Drive
FIFO First In, First Out SCL Serial Clock Line
FTDI Future Technology Devices SDA Serial Data Line
International
GAP Generic Access Profile SPI Serial Peripheral Interface Bus

GATT Generic Attribute Profile SpO2 Peripheral Capillary Oxygen


Saturation
IC Integrated Circuit UART Peripheral Capillary Oxygen
Saturation
I2C Inter-Integrated Circuit UID Unique Identifier
IDE Integrated Development UUID Universally Unique Identifiers
Environment
IR Infrared Radiation WPAN Wireless Personal Area
Network

ix
Introduction

Chapter 1 - Introduction

1.1 Motivation

Heart disease has been on the rise in recent years and is currently the leading cause of death
in Canada [1]. An effective method to reduce the rate of mortality from cardiovascular disease is
for doctors to monitor their patient’s heart condition. The electrocardiogram (EKG) is a vital
signal that reflects the heart’s electrical activity and presents critical information about the heart’s
functioning. As such it would be beneficial to develop a portable and widely available device that
can monitor a patient’s EKG when they are not in a doctor’s office. Monitoring heart activity
with blood oxygen saturation (SpO2) level is common in patients who suffer from chronic heart
failure and congenial heart disease. Congenital heart disease is the most common birth defect in
the world and there are 257,000 Canadians living with the condition [2]. Early detection is
instrumental in treating underlying heart conditions, and to easily communicate a patient’s EKG
and SpO2 reading to their doctor will help reduce the mortality rate.

1.2 Monitoring Methods

Two common practices of measuring the health of a heart and a patient are the
Electrocardiogram (EKG), and the Pulse Oximeter. An EKG is widely used as a representation of
heart health, and is used to help diagnose heart disease. The Pulse Oximeter provides a reading of
the saturation of oxygen in the bloodstream that is commonly used for monitoring patient health
after surgery.

Electrocardiogram

An EKG is the measurement of the heart’s electrical activity during the contraction and
relaxation process. The sinoatrial node in the right atrium of the heart generates an action
potential which initiates contraction. During the contraction of the heart muscle, the cells undergo
an electric potential shift, the potential goes from resting -70mV, to 0mV relative to the fluid
outside the cell. This is called depolarization and is the due to the influx of positively charged

1
Introduction

sodium ions. Positively charged potassium ions then flow out of the cell to repolarize it to the
resting potential in preparation for the next contraction [3].

When an EKG signal is measured, the depolarization and repolarizations of the heart muscle
result in Figure 1-1 [21]. As shown in the Figure there are separate sections, each represents a
different area of the heart undergoing depolarization or repolarization. The P component
represents the atrial depolarization, the QRS interval represents ventricular depolarization, and
the T component represents the ventricular repolarization. The U component is atrial
repolarization but is often invisible in EKGs due to such a small impulse [21].

Figure 1-1: QRS Complex [21]

The EKG signal is measured by placing four electrodes on the patient’s body as shown in
Figure 1-2. The word ‘Lead’ in this figure refers to the potential between the two electrodes. The
three leads form a triangle known as Einthoven’s Triangle. Einthoven’s Law states that any wave
complex in Lead II is equal to the sum of complexes from Lead I and Lead III [4]. An EKG
reading can be these leads plotted separately, but for this project the EKG is the average of these
three Leads. The fourth electrode labeled as RL is used as a reference.

2
Introduction

Figure 1-2: Placement of Limb Leads Electrodes [5]

Pulse Oximeter

A pulse oximeter is a device to measure the percentage of hemoglobin in blood that is


saturated with oxygen. Generally, the pulse oximeter is placed either on the earlobe or the tip of
the finger. These positions are chosen because they have the best access to capillary beds with
little interference from fat, cartilage or bone. In this project, the pulse oximeter is designed to be
placed on the tip of a finger. The pulse oximeter consists of a photo detector, red LED and
infrared LED. The device is pressed against the finger so that the light from the LEDs shines
through the skin. The photo detector then measures the amount of red and infrared light not
absorbed. Oxygenated hemoglobin and deoxygenated hemoglobin absorb red and infrared light
at different rates which allows the pulse oximeter to calculate the percentage of hemoglobin that
is oxygenated [6].

3
Project Details

Chapter 2 - Project Details

2.1 Overview

The Wireless EKG and Pulse Oximetry Monitoring and Visualization System is a system
that monitors a patient’s EKG, heart rate and SpO2 level. The system is described in four separate
areas: data acquisition, data communication, data visualization, and cloud storage. The system
obtains a patient’s EKG, heart rate and SpO2 information to a microcontroller unit which
communicates the data over BLE to an Android application. The application continuously
visualizes the EKG signal and updates the heart rate and SpO2 readings. The data can be saved
onto a cloud based storage system and later downloaded to be viewed again on the application. In
keeping with the nature of the health care field, the system keeps patient information and data
confidential through user authentication.

2.2 Scope

The motivation for this project was to design a useful device to monitor patient health that
could be used in a clinical or at home setting. Therefore, the focus of this project was to develop
an accurate and wearable EKG, SpO2, and heart rate monitoring system that uses an application
to visualize the data and can save it to a cloud based storage system for later analysis. Since the
project is dealing with patient information, techniques for keeping their data separated and private
are also considered.

2.3 Parameters for Success

1. For this project to be considered a success, the following parameters should be met:
2. Accurate: to give health care professional’s information they can reliably use.
3. Portable and lightweight: the device needs to be wearable and can be easily transported
throughout a clinic or to a patient’s home.

4
Project Details

4. Wireless: data acquired from the hardware design must be communicated to a custom
Android application.
5. Visualize measured data in the application: applications are available to everyone and the
devices they are used on are small and portable.
6. Stored on a cloud storage service: if a patient is at home when the EKG readings are
taken a doctor can later view those readings by downloading them back onto the
application.
7. User friendly: With the focus, primarily on patient use it is important the hardware device
and application are easy to use.

5
Data Acquisition

Chapter 3 - Data Acquisition

3.1 Electrocardiogram Overview

The EKG measurement system includes hardware and software designs. The EKG signal is
measured using silver chloride electrodes that are connected to the patient in the shape of a square
over their torso as demonstrated by RA, LA, RL and LL in Figure 3-1. RA represents right arm
electrode, LA left arm, RL right leg, and LL left leg. The four electrodes connect to a 4-wired
EKG cable which is connected to the hardware device. The first component the hardware device
is the defibrillator protection circuit which shields the device from damage and protects the
patient from shocks. The signal acquired by the hardware is in the magnitude of 0.5-5 mV. The
hardware device amplifies and filters the signal before transmitting the data to the application for
visualization.

Figure 3-1: Placement of electrodes [4].

3.2 Electrocardiogram Specifications

The hardware design for the EKG monitor requires differential pre-amplifiers, analog-to-
digital (ADC) converters and noise filters. The ADAS1000-4 from Analog Device is an Analog
Front End Amplifier (AFE) that measures 3-channel electro cardiac signals. To implement a
wearable system, the ADAS1000-4 integrated chip was used in the designed EKG measurement
system. This chip contains three pre-amplifiers that work in parallel and are capable of measuring
three lead EKG signals at the same time. There is an ADC converter following each pre-amplifier

6
Data Acquisition

for digitization of the signals. The functions and sampling rate are configured through software
communication to the ADAS1000-4. The three signals outputted from the ADCs are transferred
to the microcontroller (MCU) using a serial peripheral interface bus for further analysis and
communication to the Android application.

3.3 Electrocardiogram Hardware

The main stages of the ADAS1000-4 circuit are EKG signal capture and digitization. Figure
3-2 shows the circuit of how the analog EKG signals are captured and digitized. The lead ports
are configured as analog lead mode (CHCONFIG = 1) with a gain of 1.4, which is a low noise
mode and generates the leads in the analog domain. The signal from the three electrodes LA, LL
and RA are input to differential amplifiers which provide the values of the Leads; Lead I (LA-
RA), Lead II (LL-LA) and Lead III (LL-RA). These values are then digitized by the ADCs at a
sampling frequency of 2 kHz.

Figure 3-2: Electrode and Lead Configurations, Analog Lead Mode [7]

7
Data Acquisition

Right Leg Drive (RLD)

To improve common-mode rejection (CMR) and noise cancellation in the EKG design, a
closed-loop RLD system was introduced, which works as the reference drive. This RLD circuit
was designed based on the recommendations in the ADAS datasheet and is shown in figure 4.
The right leg drive amplifier is used as part of a feedback loop to force the patient’s common-
mode voltage close to the internal 1.3 V reference level (VCM_REF) [7]. The RLD effectively
centers the electrode input voltages relative to the input span, providing maximum input dynamic
range. Figure 3-3 shows the measured ECG signal without the RLD and Figure 3-6 shows the
measured ECG signal with the designed RLD. As shown in the Figures 3-6 and 3-7, introducing
the RLD outputs a clearer ECG signal because it cancels out the noise that is sensed by the
electrodes.

Figure 3-3: Right Leg Drive Configuration [7]

Voltage Regulator

Since a 9V battery is used as the power supply for the whole systems, and the ADAS1000-4
requires a 3.3V power, the voltage regulator AZ1117C that converts 9V to 3.3V is introduced in
the SpO2 design because of its low current dropout. Figure 3-4 shows the detail connections of
the voltage regulator.

8
Data Acquisition

Figure 3-4: 9V to 3.3V Voltage Regulator AZ1117C [8]

Defibrillator Protection

High voltages between electrodes may occur during the application which presents a risk to
the Analog Front End Amplifier. A defibrillator protection circuit is needed protect the device
against serious damage. The defibrillator protection circuit is used for electrostatic discharge
(ESD) protection and patient safety, as defective input stages could apply dangerous currents to
the patient. In this project, the defibrillator protection circuit was designed and modified per the
recommendations in the ADAS1000-4 datasheet [7]. Figure 6 shows the defibrillation protection
circuit that was used in the EKG hardware design. The data acquired from the electrodes is
passed through a protection circuit as show in Figure 3-5 before being transmitted to the AFE
chip.

Figure 3-5: Defibrillator Protection Circuit [7]

The protection circuit is based on the TVS Diode Arrays SP724, which provides protection
up to 8kV against ESD and other transient overvoltage events [9]. The diode array protects the
input signal lines between the patient and the ECG circuit by establishing electrostatic protective

9
Data Acquisition

areas free of static. The protection circuit also uses resistors to limit the current that is emitted
from a patient’s body, which is picked up by the electrodes.

EKG without RLD


25610000

25600000

25590000

25580000

25570000

25560000
0 500 1000 1500 2000 2500 3000 3500

Figure 3-6: EKG Signal without Right Leg Drive

EKG with RLD


25600000
25595000
25590000
25585000
25580000
25575000
25570000
0 50 100 150 200 250 300 350

Figure 3-7: EKG Signal with Right Leg Drive

Decoupling Strategy

For the ADAS1000-4, all power supply pins labeled AVDD or IOVDD are decoupled by a
0.01 μF and a 4.7μF capacitor. The unused power supply pins labeled ADCVDD and DVDD
need decoupling by a 0.01μF and a 2.2μF capacitor. Finally, the pins REFOUT and REFIN are
decoupled with a 0.1μF and a 10μF capacitor. As showed in the Figure 3-8, the ideal location for
each capacitor should be located as close to the device pin as possible. The locations of the
decoupling capacitors are showed in Figure 3-8.

10
Data Acquisition

Figure 3-8: Locations of Decoupling Capacitors, indicated by C1, C2

Clock/Oscillator

An external crystal clock of 8.192 MHz is used to operate the AFE, and the configuration is
showed in Figure 3-9 below. The external clock input is provided for ‘gang mode’ use so
conversions between the MCU and AFE are synchronized. The CLK_IO pin (pin 29) on the chip
is disabled to reduce power consumption.

Figure 3-9: External Crystal Clock of 8.192 MHz

Serial Interface Hardware

The ADAS1000-4 is controlled by a development board from Adafruit called Feather M0


BLE via a Serial Peripheral Interface (SPI). The MCU configures registers in the AFE and reads
the measured EKG data. Figure 3-10 demonstrates connections for the SPI bus between the MCU
and AFE.

11
Data Acquisition

Figure 3-10: Serial Interface

3.4 Electrocardiogram Software Implementation

At the Feather M0's heart is an ATSAMD21G18 ARM Cortex M0 processor, clocked at 48


MHz and at 3.3Vlogic. This MCU supports 256KB of flash memory and 32KB of random access
memory (RAM). The MCU can be programmed without the need for an extra FTDI based
debugger which allows it to be smaller in size as well as encourages debug operations using the
Arduino Integrated Development Environment. The board houses a Low Energy Bluetooth (BLE)
module that establishes a link between the data acquisition system and the Android based device.

Communication was established between the microcontroller and the ADAS1000-4 chip
using Serial Peripheral Interface (SPI). “SPI devices communicate in full duplex mode using a
master-slave architecture with a single master. The master device originates the frame for reading
and writing. Multiple slave devices are supported through selection with individual slave select
(SS) lines” [10].

SPI Communication

To explain the read and write operations for this project, it is imperative to understand the
SPI protocol. Figure 3-10 represents a simple block diagram of a physical connection between a
slave and master device.

SPI is a 4-wire interface with two unidirectional direction data lines, a clock signal for
synchronizing the communication and a slave select to identify which device is selected in case
multiple devices are operating on the same bus. The clock signal is provided by the master to
provide synchronization. “The clock signal controls when data can change and when it is valid for
reading [or writing]” [11]. Variation in the frequency of clock signal does not disrupt the data;

12
Data Acquisition

rather it causes the data exchange rate to change with it. Clock signal improves flexibility towards
controlling the connected slave device by ensuring no transaction occurs if the clock is removed.
Under no circumstance does the slave take control of the clock signal. The communication
protocol has four operating modes. These modes exploit the phase and polarity of the clock signal
to initiate a transaction and their usage is dependent on manufacturer’s specifications. Figure 3-1
looks at the clock polarity (CPOL) and clock phase (CPHA) to identify the differences between
each mode.

Figure 3-11: SPI modes of communication based on the clock cycle [12].

In the above diagram, toggling edge represents the initiation of a transaction and the sample
edge represents when the data transfer begins. The frequency of the clock is determined based on
the capability of the connected peripheral. For this application, the calculated minimum clock
frequency is based on equation below:

𝑆𝐶𝐿𝐾𝑓𝑚𝑖𝑛 = 𝐹𝑟𝑎𝑚𝑒 𝑟𝑎𝑡𝑒 × 𝑊𝑜𝑟𝑑𝑠 𝑃𝑒𝑟 𝐹𝑟𝑎𝑚𝑒 × 𝐵𝑖𝑡𝑠 𝑃𝑒𝑟 𝑊𝑜𝑟𝑑 (1)

Another key component of this protocol is the bit order, for this system the most significant
bit (MSB) is required first from the peripheral device which is the AFE. Read and write
operations need to be programmed accordingly depending on the architecture of the master and
slave. Transactions can vary in size from 1 to 4 bytes per word and if using an 8-bit architecture
MCU to handle 32-bit architecture peripheral it is important to send and receive words in proper
sequence and use appropriate bit shifting techniques to combine data. Losing track of sequencing
can result in data loss or improper data retrieval. This system’s relevant modes of operation are
discussed in the following section. However, all of the details of relative functions are provided in
Appendix D which contains the flowcharts and code used for the project.

13
Data Acquisition

System Initialization and Data Acquisition

Peripheral integrated chips hold the ability to be programmed as slave devices while a
microcontroller or a microcomputer acts as the master. However, the ADAS1000-4 holds the
capability to act as a master if a 12-lead implementation of EKG is required; the product’s
datasheet refers to this as ‘Gang Mode’. This system does not use ‘Gang Mode’ to keep the
implementation simple and within the provided guidelines of the project. For this design, the
MCU acts as the master and the ADAS1000-4 as the slave.

EKG monitoring is initialized by instantiating the ADAS1000-4 class. After creating the
instance, the microcontroller initializes pin #A4 as the data ready indicator and pin #A5 as slave
select. Once the pins are initialized the device resets the BLE module and starts advertising. The
algorithm is designed to wait for a Bluetooth connection to be established before enabling power
to the ADAS1000-4 and Pulse Oximeter chip. The device is set into advertisement mode so it can
communicate its presence to nearby devices. A detailed discussion of Bluetooth communication
protocols is discussed in Chapter 5 of this document. Upon establishing a connection, a sequence
of commands is written to the AFE to power up and begin acquiring EKG data. All commands
written and read between the MCU and AFE are 4 byte words. Since the Arduino IDE only
allows 1 byte operations, a separate algorithm was written to allow read and write operations.

3.4.2.1 Read and Write Operation

The AFE offers multiple data exchange rate options. Each option offers different data bit
resolution and types of data available to be read.

Table 3-1: Frame Rates vs. Clock Frequency

Maximum Words Minimum SCLK


Frame Rate Word Size
per Frames frequency

128 kHz 16 bits 13 words 26.62 MHz

16 kHz 32 bits 10 words 5.12 MHz

2 kHz 32 bits 10 words 640 kHz

A frame rate of 2 kHz was selected because of the MCU capabilities. It provides a good
balance between the processing power required and best resolution of the acquired data. Although

14
Data Acquisition

a minimum clock frequency of 640 kHz is required, the clock is programmed at 5.12 MHz to
allow system flexibility for future work. The system is programmed to communicate under mode
3 as outlined in Chapter 3.4.1 SPI communication and transmit most significant bit first as
instructed by the manufacturer. A single read or write transaction comprises of a minimum of 4
bytes. Each transfer is one byte long and multiple transfers can be completed in a continuous
sequence. For a transaction to occur the MCU pulls the chip select pin to low logic voltage and
sends configuration parameters to the SPI bus. On configuration, it transfers the number of bytes
specified by the user and ends transaction after the last byte is transferred releasing the chip select
pin.

Since each write command is 4 bytes long, the data is broken down into an array of single
bytes. One key aspect of the write transaction is asserting a 1 as the MSB of the write data word.
After the assertion, the data is then passed on as a parameter to the SPI_Write() function. A read
command requires putting transferred data into an array and consolidating the information using
bit shifting and a logical bitwise OR operation.

3.4.2.2 Software Power-up Sequence

A combination of internal registers is configured as a power-up ritual to start the data


acquisition process. The data sheet provides which bits to select and clear for the configuration
command of this application.. Once the command is built it is passed to the SetRegisterValue()
function along with the pre-defined address of the respective register to configure. This function
is responsible for asserting a 1 on the MSB and breaking the command down into an array of 4
bytes. It then calls the SPI_Write() function to complete the configuration process. Table 3-2
represents the commands in hexadecimal format and respective registers that are written as the
power up configuration.

Table 3-2: Register names and hexadecimal commands writeen to power up the system.

Register Name Hexadecimal Command

ADAS1000_EKGCTL 0x81E007AE

ADAS1000_CMREFCTL 0x85E0000A

ADAS1000_FILTCTL 0x8B000020

ADAS1000_FRMCTL 0x8A1FCE00

15
Data Acquisition

The ECGCTL register is responsible for enabling and disabling all the internal blocks of the
AFE. It controls which mode of operation the chip is functioning in (Analog, Electrode or
Digital), enables system power and permits the leads to stream EKG data. For this system the
AFE is configured to operate in Analog mode. CMREFCTL sets the mode for common mode
reference for use on the RLD, the detailed function of RLD was covered in the EKG hardware
section. FILTCTL enables the filters required for the application whereas FRMCTL is
responsible for formatting the data frame that is read by the MCU while streaming EKG data. The
order of configuring these registers can be changed except for ECGCTL register since none of the
internal blocks can be configured without enabling power.

3.4.2.3 Data Streaming

After complete system configuration, an infinitely repeating loop to reads the real-time data
stream and latches it to the BLE module. The function ReadData() is called to read the data
stream within the loop. A detailed flow of ReadData() function is provided in Appendix D. This
function accepts a pointer to an empty buffer, number of frames to be read and control bits as
input parameters and returns a filled data buffer. It is crucial to understand that the function itself
is not designed to return any parameters, it completes the return operation by pointing to a
memory location in the MCU memory to an empty buffer waiting to be filled. The SPI_Read()
function is then called to fill the memory in the form of single bytes. The default format of a data
read is provided in Table 3-3. Table 3-4 displays the configuration of the frame control register
for this project. Only the lead data is required, and hence the FRMCTL register was configured to
disable all other parameters.

Table 3-3: Default 2kHz frame word format.

Register Header Lead Lead Lead PACE RESPM RESPPH LOFF GPIO CRC
I/LA II/LL III/RA
Address 0x40 0x11 0x12 0x13 0x1A 0x1B 0x1C 0x1D 0x06 0x41

Table 3-4: Customized data format for the application.

Register Header Lead I Lead II Lead III


Address 0x40 0x11 0x12 0x13

16
Data Acquisition

ReadData() uses two control bits to hold control over data transactions, the function waits for the
data ready bit to be set before enabling the reading process. On completion of the read process it
looks for the stop bit and returns from the process. After the data buffer is filled, the printData()
function is called which is responsible for combining individual lead data. Once each lead data is
combined into 4-byte words, the mean of all leads were calculated to produce a single EKG
signal. The data is then latched onto the BLE module to be sent to the Android application. The
flow chart in Figure 3-12 below provides a comprehensive look at the sequencing of commands
to send the data stream form MCU to the Android application.

17
Data Acquisition

Figure 3-12: Flow diagram for ADAS1000-4 data streaming process

3.5 Pulse Oximeter Overview


The pulse oximetry (SpO₂) monitor utilizes the fluctuation in the absorption of light incident
to arterial blood. A red and an infrared LED are used to shine light on the index finger and a
photo sensor detects the unabsorbed light. The incoming light is used to estimate the hemoglobin
oxygen saturation level of arterial blood [6]. The oxyhemoglobin (HbO2) absorbs visible and
infrared light differently than deoxyhemoglobin (Hb). Due to the pulsatile nature of blood flow,

18
Data Acquisition

the absorption in arterial blood can be represented by a periodically alternating signal with a DC
offset. The DC offset is generated due to absorption in other substances such as pigmentation in
tissue, venous blood and bone. The calculation for heart rate is done by counting the pulses.

Figure 3-13 Extinction coefficient VS light wavelength plot

Figure 3-13 represents the relation between the measure of light absorption (extinction
coefficient) and wavelength. When blood is exposed to a photon having a wavelength of 650nm
the deoxygenated hemoglobin absorbs more light than the oxygenated hemoglobin. When a
photon with a wavelength of 1000nm enters the blood the opposite would be true. A pulse
oximeter displays the percentage of hemoglobin that is oxygenated. A normal SpO₂ reading can
range between 95 and 100% [13].

3.6 Pulse Oximeter Specification

The hardware design for the pulse oximetry sensor requires two LEDs and a photo detector.
To keep the footprint of hardware as small as possible, MAX30100 integrated chip (IC) from
Maxim Integrated Products was used in this project. This IC possesses the capability of acquiring
the pulse oximetry and heart rate signals, and digitizing those signals with the use of a low-noise
analog to digital converter (ADC). All internal components of the chip are configurable by
software and the digitized data generated by the ADC is stored in on-chip 16-deep FIFO [6]. The
on-chip sigma-delta ADC has a maximum resolution of 16 bits and a minimum of 13 bits. It
offers a nominal sampling rate of 50 Hz; however, the rate can be increased to 1000 Hz at the cost

19
Data Acquisition

of resolution and additional noise. A metric of hardware specification is provided in Table 3-5.
The specification of the selected device fall within the proposed range.

Table 3-5 SpO2 specification metric

Description Value
SpO2 system voltage 1.8 V
SpO2 overall system current (includes
40.6 mA
LED and photo sensor)
SpO2 communication protocol I2C

3.7 Pulse Oximeter Hardware

The circuitry for SpO2 required three major components, a voltage regulator, I2C pullup
network and the MAX30100 IC. The purpose of the voltage regulator is to convert the voltage
level from 3.3V to 1.8V since the LEDs integrated inside the IC work at a different voltage level
as compared to the photodetector component. The voltage regulator can deliver up to 250mA. A
summary of key specifications for the voltage regulator are provided in Table 3-6. A similar
decoupling strategy to the AFE, as mentioned in section 3.3.5, was implemented and 10 µF
capacitor was connected at the input of the voltage regulator while a 1 µF was used at output.

Table 3-6: Summary of key specifications for the voltage regulator [6].

Description Value or Range


Input Voltage range 2.3V to 6V
Output voltage 1.2 V to 5V
Output current for >=2.5V 250mA
Output current for < 2.5V 200mA

The I2C interface works at 3.3 V logic level hence, the pull-up network was pulled using 4.7
kΩ resistors connected to 3.3 V supply line. A detailed discussion on the I2C is covered in section
3.8.1, the section also discusses the software implementation for the SpO2. The final component
of the design was the IC. The schematic for the final design is illustrated in figure 3-14.

20
Data Acquisition

Figure 3-14 SpO2 System schematic diagram.

The component labeled as P1 in figure 3-14 is the interface used to provide power and I2C
data lines to the design. The wires are directly connected to P1 which are used as medium
between the SpO2 system and the development board.

3.8 Pulse Oximeter Software Implementation

As discussed in Section 3.4 the development board used in this project is the Feather M0.
Unlike the communication to the ADAS1000-4 chip, the MAX301000 uses Inter-Integrated
Circuit (I²C) commutation protocol. This project uses both modes of the MAX301000 chip which
are SpO2 and heart rate.

I2C Communication

I2C uses two bidirectional lines, Serial Data Line (SDA) and Serial Clock Line (SCL). SDA
is for data transfer and the SCL is used to synchronize the data transfers over the I2C bus. The
MCU was configured as the master and the MAX30100 was configured as the slave. The master
generates the clock on the SCL and initiates data transfers on the bus. Both the master and slave
can send data on the SDA, but the master must initiate the transfer. Communication between the
master and slave begins with the start sequence on the I2C bus. The start sequence is one of the
two special cases where the SDA changes when the SCL is high. [14]. The other case is the stop

21
Data Acquisition

sequence, Figure 3-15 depicts the start, repeat and stop sequence for I2C. For the master to read
data from the slave, the master transmits the proper slave address with a ‘1’ asserted at the least
significant bit (LSB), followed by nine SCL pulses [6]. The MAX30100 then transmits data on
the SDA in sync with the low pulses of the SCL. The MCU acknowledges it has received the data
and issues the stop sequence. To write to the MAX30100 the start sequence is sent followed by
the proper address of the device. After the device is selected, the address of the register is issued
on the SDA line followed by the command. Data transmitted to the MAX30100 is 8-bits long and
is followed by an acknowledge clock pulse. [6].

Figure 3-15: Left hand side: I2C clock cycle and data start (S), repeat (Sr) and stop (P) sequences.
Right hand side: one byte transaction completion with acknowledge clock pulse [6].

System Initialization and Data Streaming

The MCU initializes the MAX30100 to have a sampling frequency of 100Hz, and sets the
LEDs to get a current of 20mA for 1.6ms. This is done by writing to the LED current control and
LED pulse width control registers in the MAX30100. The MAX30100 is configured to operate in
heart rate and SpO2 modes by writing to mode control register. The MCU gets the data from the
MAX30100 in the pox.update() function. Within pox.update(), readFIFO() is called and this
function retrieves the data from the FIFO memory in the MAX30100. This FIFO memory buffers
the SpO₂ and heart rate data in the memory location MAX30100_REG_FIFO_DATA. The
function burstRead() takes the data from the FIFO and sends it to the MCU. Figure 3-16
illustrates the programming flow of configuring the MAX30100 and reading SpO2 and heart rate
data.

22
Data Acquisition

Figure 3-16: Flow charts for SpO2 and heart rate data retrieval.

The data is then labeled by inserting a letter ‘H’ before the heart rate reading and an ‘S’
before SpO₂ data. The MCU then transmits this data over BLE to the Android application. BLE
communication is discussed in chapter 4.

23
Data Communication

Chapter 4 - Data Communication

4.1 Bluetooth Low Energy Protocol and Operation

Bluetooth low energy (BLE) is a wireless, open source, and low power technology which is
suitable for short range communication. Due to recent technological advances, BLE offers
compact size and a robust protocol for data transmission. “It is a wireless personal area network
(WPAN) technology aimed at novel applications in the healthcare, fitness, beacons, security and
home entertainment industries” [15].

Bluetooth utilizes Generic Access Profile (GAP) which controls the connection and
advertising of a device. The role of a device is setup based on the GAP protocol. Under the GAP
protocol, devices function in a server client architecture. A role is assigned to each device,
peripheral or server devices are the ones with power constraints and less computational resources
whereas central or client devices are generally smartphones or other devices that have abundant
computational resources and higher power availability [16]. Figure 4-1 presents a simple
visualization of system structure of BLE.

Server/Peripheral

Client/Central

Figure 4-1: GAP Arcitecture depicting server and client.

24
Data Communication

The peripheral device advertises its presence to all the nearby devices capable of
receiving BLE information at regular intervals as programmed. Any nearby client device can read
the advertised data and ask the peripheral to send a scan packet to get additional information.
When the scan packet is received, the central device can request a connection with the peripheral.
Figure 4-2 illustrates a conversation between the peripheral and a client device.

Figure 4-2: Demonstration of advertisement data [16]

Once a connection is established between the peripheral and the central device the GAP
advertising stops. At this point no surrounding central devices can detect the presence of the
peripheral. The dual mode communication used in the project is called Generic Attribute Profile
(GATT) which utilizes Attribute Protocol (ATT). It is used to store services, characteristics and
relation data in a simple lookup table using 16-bit Universally Unique Identifiers (UUID).

4.2 MCU and Android Smartphone GATT Communication

For this system, the MCU board was assigned the role of Server and the Android smartphone
was configured as a client. Once the connection is established between the BLE module on the
MCU board and the smartphone the server establishes parameters for the connection. All
transactions are initiated by the MCU and a response is requested from the smartphone every time
a transaction is completed. A timeout of the response is set by the server after which the client
looks for an initiation of a new transaction. Along with the response timeout, it also configures
the length of connection interval to preserve energy. The connection interval restricts the time the
central device looks for reconnection if no data has been received. After setting the parameters,
the MCU configures the profile to be used that contains single or multiple characteristics. Each
characteristic has a descriptor and all this information is saved as a constructor hierarchy. For this
application, a universal asynchronous receiver/transmitter (UART) profile was used since it is

25
Data Communication

one of the most commonly used profiles for streaming data and behaves like a wired serial
connection. It offers a full duplex communication mode under which data can be sent and
received between both connected devices. As mentioned in the previous section, UUIDs are 16-
bits long; Bluetooth also allows users to setup custom characteristics that are 128-bit long. UART
transmitter (TX) and receiver (RX) characteristics are custom defined based on the limitations of
the BLE module being used. For the communication to work between the MCU and the
smartphone, the programmed UUIDs must match between the two devices. In case of a mismatch
the connection is terminated without any data transaction. Table 4-1 denotes the programmed
UUIDs.

Table 4-1: Custom UUIDs service parameters

Type 128-bit UUID

UART Service 6E400001-B5A3-F393-E0A9-E50E24DCCA9E

TX Characteristic 6E400002-B5A3-F393-E0A9-E50E24DCCA9E

RX Characteristic 6E400003-B5A3-F393-E0A9-E50E24DCCA9E

Due to FIFO memory restrictions, the RX data is limited to 20 bytes in size. If longer
information is sent, it is broken down into packets of 20 bytes. The smartphone follows the same
standard and receives data as an array of bytes with a maximum of 20 bytes in a single packet. On
the smartphone, the BLE is handled as a service. A service runs in the background of the
application. Upon establishing a connection to a peripheral device, the service requests the UART
characteristic. If the received UART characteristic does not match the UUID given in Table 4-1,
it notifies the user that the UART service is not available. Depending on the characteristic
received after a successful connection, the service updates the respective parameter which enables
the application to process data. The TX data is then passed to the main activity of the Android
application which parses the data for visualization. The parsing process is discussed in Chapter 5.

26
Data Visualization and Storage

Chapter 5 - Data Visualization and Storage

5.1 Overview

A custom Android application was developed to record and visualize the information
gathered by the data acquisition system. The application for the project is called “G13 Wireless
EKG”. Devices that support applications are small and easily portable which is important to the
overall design goal of the project. The application receives information over BLE and plots the
real-time EKG data to a graph and updates the SpO2 and heart rate readings every second.

The application was created in Android Studio, an integrated development environment for
creating Android applications. Projects are written in Java programming language and the
different functions of an application are separated into different activities.

5.2 Android Graphical User Interface

When the application is opened the login screen is displayed, this in the Signin Activity. To
register for the application, a user enters their email address and creates a password the presses
the NEXT button. This information is saved to the applications database account which holds all
user’s authentication information. More on the database is in the next section. A returning user
logs in by entering their email and password then pressing the SIGN IN button. An image of the
login screen is shown in Figure 5-1. The application requires a patient to sign in to keep their
information separate from other users.

27
Data Visualization and Storage

Figure 5-1: Signin screen.

Once a patient has logged into their account the application enters the Information Activity.
This screen is Figure 5-2 (a), it has boxes for the patient to enter their name, height, weight, birth
date, and gender. The purpose of this page is to be a failsafe for doctors to make sure they are
looking at the correct user account. A new user must fill in all the boxes before pressing the
NEXT button. If the user presses NEXT without filling in valid information the application
notifies them. Clicking the NEXT button saves the information as separate strings, each with an
identifier, into a newly created object for the user within the real-time database. Returning user’s
information is recalled from Firebase and populated into the boxes by the FileList Activity. An
image of this screen is shown as Figure 5-2 (b). This FileList Activity is entered automatically
when a returning user signs in and gives the user the option to edit the information or continue. If
the EDIT button is selected the appplication goes back to the Information Activity and clears the
boxes to be re-entered. If the CONFIRM button is pressed the application enters the Main
Activity.

28
Data Visualization and Storage

(a) (b)

Figure 5-2: (a) Information screen. (b) FileList screen.

The Main Activity of the application is where the patient’s EKG, SpO₂ reading, and heart
rate is displayed as shown in Figure 5-3. The main page initially has three buttons, CONNECT,
SAVE and LOAD. Pressing the CONNECT button will allow the user to connect to the hardware
device. If a user presses this button and the Bluetooth capability of their device is not turned on,
the application will request to user to turn on Bluetooth. This project utilizes BLE and not all
devices that have Bluetooth support BLE. The application checks the capabilities of the device
and will display a message if BLE is not supported. Once Bluetooth is turned on the DeviceList
Activity can be entered. DeviceList looks for the presence of GAP signals for a short period and
displays the list of devices in the area. The GAP signal is discussed in section 4.2. The user must
select the hardware device from that list.

29
Data Visualization and Storage

(a) (b)

Figure 5-3: (a) Main screen before hardware connection. (b) Main screen after connection
streaming data.

When the device is selected, the application establishes parameters for the connection in the
UartService Activity. Please see section 4.2 for UART service parameters. When all the
connections in UartService are successful, data becomes available to the application and the Main
Activity can begin parsing it.

When a data packet is coming into the application UARTService action


ACTION_DATA_AVAILABLE becomes true and an IF statement in the BroadcastReceiver
function of the Main Activity is entered. As discussed in Section 4.1, BLE communicates
information in the form of packets. Data streaming to the application from the MCU is EKG,
SpO₂ and heart rate information. The data from an incoming packet is stored as a String in a
variable called ‘packet’. ‘Packet’ is split into an array called ‘data’; it is split by the presence of
‘\n’ which is a new line in ‘packet’. In the case of EKG data, the value of a complete EKG
reading may be split up into different packets that came into the application at separate times. A
complete data set ends with ‘\n’. If the first value in the ‘data’ array ends with ‘\n’ the data may
belong with a data set from the previous packet, so the value is added to a variable called

30
Data Visualization and Storage

‘unusedData’. The ‘unusedData’ value will contain data if the last value in the ‘data’ array from
the previous packet did not end with a ‘\n’, otherwise ‘unusedData’ will be empty. Data that is
not in the first or last position of the ‘data’ array is considered complete. Once the IF statement
has confirmed a complete data set, a function within the IF statement called ‘parse’ is used to
separate the data as EKG, SpO₂ or heart rate information. When all the values in the ‘data’ array
are sent to be parsed the IF statement is finished.

Within the Main Activity the ‘parse’ function is used to differentiate what type of
information is in a certain position of ‘data’ array. The function starts by looking at the first
character of the incoming string and checks if it is an ‘H’ or an ‘S’. In these cases, the ‘parse’
function saves the text as either ‘heart’ or ‘SpO2’ while also removing the ‘H’ and ‘S’ characters.
If the first character of the string is not an ‘H’ or an ‘S’, the data must be an EKG reading. Figure
5-4 represents a flowchart for the parsing algorithm.

Figure 5-4: Flow diagram for parse algorithm.

31
Data Visualization and Storage

The string of EKG data must be converted to a double to be displayed on the graph. The
double is paired with the next value of time and saved to the end of a continually growing
variable ‘series’. This variable ‘series’ is what is being plotted on the graph. Values of heart rate
and SpO₂ are updated on the main screen when the MCU sends their data, which takes place
every one second.

A DICSCONNET button appears in the place of the CONNECT button when the hardware
device is connected. Pressing the DISCONNECT button disconnects the application from the
hardware device and changes the button to CONNECT. The user now has the option to reconnect,
save the data that is there, or load previously saved readings.

Once the application has received some data the user can now save their reading by pressing
the SAVE button on the main screen. If there is data available to be saved the fileWrite function
prepares the data to be saved by naming it with the patient’s user name and a time stamp. The
uploadFile function uploads the file to the user’s folder in the database by accessing its URL. To
ensure the application can generate a list of files for the user to download, the name of the file is
saved to the real-time database.

If the LOAD button is pressed, the LoadFiles Activity is entered and a list of files available
from the user’s folder is displayed. When the user selects a file, it is downloaded to the
application and displayed on the screen. Further discussion on the database storage is in the next
section.

5.3 Real-Time Database and Cloud Storage

The database used in the application is Google’s Firebase platform. Firebase is an


application platform with specific features for application development. The application uses the
authentication, database, and storage features in Firebase.

To sign up for the application a user must enter their email address and create a password.
Firebase authentication assigns the user a unique identifier (UID) and saves their information to
the Firebase console. The Firebase console for the application can be viewed online by the creator
of the application. In the authentication part of the console, a list of user email addresses can be
seen but not their password. An image of the authentication console is displayed in Figure 5-5.

32
Data Visualization and Storage

The UID created here is used throughout the application to access a user’s information in the
Database and Storage sections of the console.

Figure 5-5: Firebase authentication console

The next step in the application is to gather personal information about the patient. This
information is stored to the database part of the console. Each user has their own object within the
database named with the user’s UID. The information the patient has filled out is stored in an
information object within their UID object. The next time a user logs in their information is
recalled from this object and populates the boxes. If a user choses to edit their information the
previous values are overwritten. Figure 5-6 is an image from the real-time database console.

33
Data Visualization and Storage

Figure 5-6: Real-time data base populated with test user information.

On the main page of the application a user can save and load data. When a patient presses
the SAVE button their data is saved to the storage section of the Firebase console. The data is
saved as a text file. Like the database section, each user has separate folders within the storage
section. Files inside the storage section are accessed using URLs. The URLs contain the users
UID and a file name. The application names a file with the username and a time stamp before it
uploads it to their folder in the storage section. The name of the file is also stored in the user’s
database in an object called Files. A list of a test user’s files is shown in Figure 5-6. If the LOAD
button is pressed, the application lists the contents in the files object. The user must select a file to
download. After a file is chosen the application generates the complete URL to download it from
storage.

34
System Integration

Chapter 6 - System Integration

6.1 PCB Fabrication

To integrate the hardware components covered in data acquisition section, two PCBs were
fabricated for the project. First PCB featured the EKG analog frontend amplifier, voltage
regulator and connection terminal blocks. The second PCB was designed for the pulse oximetry
monitor which features a voltage regulator, an integrated chip for SpO2 and an I2C pull-up
network. To achieve the goal of making the system compact, light and portable, PCB footprints
were kept as small as possible. The PCB with EKG acts as a central hub between the pulse
oximeter PCB and the development board.

Design Considerations and Component Integration

One major challenge was to accommodate the decoupling strategy discussed in section 3.4.
The goal was to maintain the same form factor as the development board and place the capacitors
in an orderly fashion around the AFE. Altium Designer was used to design the complete system
schematic. Depicted in Figure 6-1 are the final PCB designs.

(c)

(a) (b) (d)

Figure 6-1: (a) and (b) represent the front and back of the central PCB. Image (c) and (d)
represent the pulse oximeter PCB.

35
System Integration

The second major challenge and consideration involved in the PCB design was the noise
reduction. Since the central PCB houses the AFE and an external clock that operates at 8.192
MHz, a copper fill connected to the ground plane was added to the design. The ground plane
absorbs the high frequency noise. Figure 6-2 (a) illustrates the use of copper fills for the noise
reduction.

(a) (b)

Figure 6-2: Copper fill on PCB depicted by large blue patches.

To ensure proper heat dissipation in the system a copper fill was added to the output of the
voltage regulator as shown in Figure 6-2 (b).

6.2 Carrying case

One of the main goals throughout this project was to have the device be lightweight, and
portable, such that it could be used on the go. With that in mind, the team designed a portable and
lightweight 3-D printed case that can contain the power source and all of the electronics except
for the MAX30100.

36
System Integration

As demonstrated in Figure 6-1 below, the carrying case was designed as a three piece-unit,
which allows for the quick access of the electronics and power supply. The case allows for an On-
Off slide switch to control the power, and a series of lights to show the current state of function of
the device.

Figure 6-3 3-D Render of Enclosure Case

Aesthetically, it was decided to go with a light color, and to have the parts that are
removable set to a different color than the main case as to allow for distinction between the solid
body and the access panels.

37
Conclusion

Chapter 7 - Conclusion

In conclusion, the Design and Implementation of a Wireless EKG and Pulse Oximetry
Monitor and Visualization System as defined by our standards in section 2.3, was nothing but an
unparalleled success. All the proposed design specifications have been met. To reiterate these
specifications, the design has managed to:

 Gather accurate data that could potentially be used by health care professionals
 Acquire data wirelessly through Bluetooth communication
 Visualize the received data on a custom Android application
 Have the data stored on Google’s Firebase, where it is accessible by the patient and
their doctor
 Create a user-friendly experience where the learning curve is low

The entire project has come in under budget at $431.36 CAD, of the total available $600.00
CAD. The large allotted budget allowed for more freedom with the design choices, and allowed
for a much more compact and accurate device. The full detailed information regarding the
budget can be found in Appendix A.

7.1 Future Work

The device can undergo various developments and improvements. Analyzing the detected
EKG signal on the application is one possible improvement. This feature can be used as a
reference for doctors to track if a patient has had any odd heart activity. An example of this odd
activity would be the atrial fibrillation. A second improvement to the device would be adding a
Google platform which is a website could be built for doctors to view their registered patient’s
data. A third feature could be creating an application based on IOS to allow for more users to
benefit from the content of this project. The fourth feature can be adding a pacing artifact
detection function. Since this function can be run in parallel with the EKG channels, the MCU
can process and detect the potential pacing artifacts and measures the width and amplitude of
valid pulses. A fifth improvement could be adding the respiration measurement function.

38
Conclusion

Respiration measurement is another feature supported by ADAS1000-4. The respiration


measurement is based on the signals that are measured from RA, LA and LL electrodes. These
collected signals can go through an external path via pins EXT_RESP_RA, EXT_RESP_LA and
EXT_RESP_LL. After that, the MCU can process this data and generate the respiration level.
Since the hardware setup of the current EKG design already has the required RA, LA and LL lead
connections for the respiration measurement traced on the PCB, it would be easy to implement
the respiration and pace detection functions.

39
Bibliography

Bibliography

1. "Heart and Stroke", Health Canada. [Online]. Available: http://://www.hc-sc.gc.ca/hc-ps.


[Accessed: 16- Mar- 2017].
2. "Facts and issues", Canadian Congenital Heart Alliance, 2017. [Online]. Available:
http://www.cchaforlife.org/facts-issues. [Accessed: 16- Mar- 2017].
3. "McMaster Pathophysiology Review | MPR | pathophys.org | beta", Pathophys.org. [Online].
Available: http://www.pathophys.org. [Accessed: 10- Mar- 2017].
4. "The ECG Leads, Polarity and Einthoven’s Triangle", The Student Physiologist, 2017.
[Online]. Available: https://thephysiologist.org/study-materials/the-ecg-leads-polarity-and-
einthovens-triangle/. [Accessed: 10- Mar- 2017].
5. E. Wong and S. Chaudhry, "Physiology of cardiac conduction and contractility", McMaster
Pathophysiology Review, 2017. [Online]. Available:
http://www.analog.com/media/en/technical-documentation/data-sheets/ADAS1000-3_1000-
4.pdf. [Accessed: 05- Mar- 2017].
6. "Pulse Oximeter and Heart-Rate Sensor IC for Wearable Health", 2014. [Online]. Available:
http://pdf.datasheetcatalog.com/datasheets/maxim/MAX30100.pdf. [Accessed: 09- Mar-
2017].
7. "Datasheet ADAS1000-3/ADAS1000-4", /www.analog.com, 2015. [Online]. Available:
http://www.analog.com/media/en/technical-documentation/data-sheets/ADAS1000-3_1000-
4.pdf. [Accessed: 16- Feb- 2017].
8. "Low Dropout Linear Regulator", Diodes, 2017. [Online]. Available:
https://www.diodes.com/assets/Datasheets/AZ1117C.pdf. [Accessed: 08- Mar- 2017].
9. "Circuit Protection, Fuses, Thyristors, Automotive Circuit Protection, Protection Relays and
Controls - Littelfuse", Littelfuse.com, 2013. [Online]. Available: http://www.littelfuse.com.
[Accessed: 05- Feb- 2017].
10. "Serial Peripheral Interface Bus", En.wikipedia.org, 2017. [Online]. Available:
https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus. [Accessed: 11- Mar- 2017].
11. "Overview and Use of the PICmicro Serial Peripheral Interface", Microchip, 2017. [Online].
Available: http://ww1.microchip.com/downloads/en/devicedoc/spi.pdf. [Accessed: 01- Jan-
2017].

40
Bibliography

12. "Byte Paradigm – Speed up embedded system verification – PC Instruments for Test and
Debug", Byteparadigm.com, 2017. [Online]. Available: http://www.byteparadigm.com.
[Accessed: 22- Feb- 2017].
13. "Hypoxemia (low blood oxygen) - Mayo Clinic", Mayo Clinic, 2015. [Online]. Available:
http://www.mayoclinic.org/symptoms/hypoxemia/basics/definition/sym-20050930.
[Accessed: 10- Mar- 2017].
14. "Using the I2C Bus", Robot-electronics.co.uk. [Online]. Available: http://www.robot-
electronics.co.uk/i2c-tutorial [Accessed: 16- Mar- 2017].
15. "Bluetooth low energy", En.wikipedia.org, 2017. [Online]. Available:
https://en.wikipedia.org/wiki/Bluetooth_low_energy. [Accessed: 16- Mar- 2017].
16. "GAP | Introduction to Bluetooth Low Energy | Adafruit Learning System",
Learn.adafruit.com, 2014. [Online]. Available: https://learn.adafruit.com/introduction-to-
bluetooth-low-energy/gap. [Accessed: 04- Jan- 2017].
17. "Advanced Life Support Assist Skills (Appendix C)", Find.galegroup.com. [Online].
Available: http://find.galegroup.com/nrcx/Toolbox/1401879330-00050.htm. [Accessed: 16-
Mar- 2017].
18. "NordicSemiconductor/Android-nRF-Toolbox", GitHub, 2017. [Online]. Available:
https://github.com/NordicSemiconductor/Android-nRF-Toolbox. [Accessed: 11- Mar- 2017].
19. "adafruit/Bluefruit_LE_Connect_Android", GitHub, 2017. [Online]. Available:
https://github.com/adafruit/Bluefruit_LE_Connect_Android. [Accessed: 11- Mar- 2017].
20. "firebase/quickstart-android", GitHub. [Online]. Available:
https://github.com/firebase/quickstart-android/tree/master/database. [Accessed: 11- Mar-
2017].
21. S. Chakrabarti and A. Stuart, "Understanding cardiac arrhythmias", adc.bmj.com, 2017.
[Online]. Available: http://adc.bmj.com/content/90/10/1086. [Accessed: 06- Mar- 2017].

41
Appendix A: Budget

Appendix A: Budget

The maximum budget for this project was set at $600.00. The proposed budget was
$352.97, which left $247.03 for later additions. Throughout the design process the proposed
design was updated and many components changed. The final cost of this project is $431.36 and
is broken down in the table below.

Table 1: Budget

Item Part # Supplier Qty Unit Subtotal


Cost
Microcontroller FEATHER M0 Digikey.ca 1 $42.52 $42.52
BLUEFRUIT LE
USB Cable N/A Team 1 free free
menber
Analog Front End ADAS1000-4BSTZ Digikey.ca 1 $33.26 $33.26
Amplifier
IC Sensor MAX30100EFD+-ND Digikey.ca 1 $5.02 $5.02
Oximeter/Heartrate
9v Energizer Battery N/A Techshop 1 free free
9V Battery Straps 36-232-ND Digikey.ca 1 $0.92 $0.92
232-234 Drawing
Output 3.3V and 1.8V N/A Digikey.ca 2 $0.62 $1.24
Voltage regulators
4 Conductors 3.5mm 839-1036-ND Digikey.ca 2 $6.28 $15.56
Cable
3 EKG Leads Cable SHIELD-EKG- Digikey.ca 1 $17.97 $17.97
EMG-PA
1 EKG Lead Cable N/A Techshop 1 free free
Ag/AgCl Electrodes N/A Techshop 50 free free
11 Pin Female Header S7009-ND Digikey.ca 1 $1.26 $1.26
15 Pin Female Header S7013-ND Digikey.ca 1 $1.73 $1.73
Slide Switch CKN10666-ND Digikey.ca 1 $7.87 $7.87
TVS Diodes SP724 F2863CT-ND Digikey.ca 1 $ 2.57 $ 2.57
4 pole Audio Female CP-43514SJCT-ND Digikey.ca 2 $1.65 $ 3.30
8.192MHz 535-9865-1-ND Digikey.ca 1 $0.7 $0.70
Crystal Oscillator
510 ohms SMD 311-510ERCT-ND Digikey.ca 4 $0.15 $0.60
Resistor
4.5k ohm SMD 311-4.53KFRCT- Digikey.ca 4 $0.15 $0.60
Resistor ND
4.7k ohm SMD 311-4.7KERCT-ND Digikey.ca 2 $0.15 $0.30

42
Appendix A: Budget

Resistor
40.2k ohm SMD A110697CT-ND Digikey.ca 1 $0.92 $0.92
Resistor
100k ohm SMD 311-100KFRCT-ND Digikey.ca 1 $0.15 $0.15
Resistor
4.02M ohms SMD 311-4.02MFRCT- Digikey.ca 1 $0.15 $0.15
Resistor ND
18pF ceramic 490-6203-1-ND Digikey.ca 2 $0.14 $0.28
capacitor
2nF ceramic capacitor 1276-1983-1-ND Digikey.ca 1 $0.14 $0.14
0.01uF Ceramic 490-4516-1-ND Digikey.ca 10 $0.14 $1.40
Capacitor
0.1uF Ceramic 490-6328-1-ND Digikey.ca 1 $0.14 $0.14
Capacitor
1uF Ceramic 587-1308-1-ND Digikey.ca 1 $0.14 $0.14
Capacitor
2.2uF Ceramic 490-10451-1-ND Digikey.ca 3 $0.14 $0.42
Capacitor
4.7uF Ceramic 1276-2087-1-ND Digikey.ca 7 $0.14 $0.98
Capacitor
10uF Ceramic 490-3340-1-ND Digikey.ca 3 $0.18 $0.54
Capacitor
22uF Ceramic 490-1824-1-ND Digikey.ca 1 $0.51 $0.51
Capacitor
Tax $18.36
Shipping $8.00
PCB Printing $57.48
DIP Conversion Prototype Cost $206.33
Fabrication Cost $225.03
Proposed Cost $352.97
Total Cost $431.36

43
Appendix B: Application User Manual

Appendix B: Application User Manual

Part A: Hardware device

1. Place electrodes on your body in the shape of a square as shown in the figure below.

[17]

2. There are 4 wires that attach to these electrodes and they are labeled as LA, RA, LL and
RL. The wire labeled LA is for the left arm and goes to the black circle electrode. RA is
right arm for the white, LL is left leg for the red and RL is right leg for the blue.
3. Place index finger in the SpO₂ sensor.
4. Turn on device by flipping the switch to the ON position.

Part B: Application

1. To use this application, you must have an Android device with Low Energy Bluetooth
capabilities.
2. Download G13 from the application store onto your Android device.
3. Turn on the Bluetooth capability of your device.
4. When you open the application the sign in screen will appear, to use the app you must
first create an account. To register enter your email address and create a password, then
press the SIGNUP button.
5. Returning users will enter their email address and password then press the SIGNIN
button.

44
Appendix B: Application User Manual

6. Once logged in a personal information page is shown. If you are a first-time user, enter
your information into the boxes and press the NEXT button.
7. Returning users personal information will already be filled in. You can update this
information by pressing the EDIT button, entering the correct information and then
pressing the CONFIRM button.
8. The next screen is the main page of the application. To begin reading your EKG, SpO₂
percentage and heart rate, press the CONNECT button.
9. If your device does not have its Bluetooth turned on or does not support BLE a message
will appear.
10. If your device is ready to connect a list of devices that are transmitting BLE signals in the
area will pop up. Select the hardware device from this list. If you do not see the hardware
device, ensure that the switch is in the ON position.
11. The graph will begin showing your EKG and the SpO₂ and heart rate fields will be filled
with your readings. The CONNECT button will now read DISCONNECT and when
pressed will disconnect your device from the hardware.
12. You will now be able to save your EKG by pressing the SAVE button. You can save
while you are still connected to the hardware device or you can press the DISCONNECT
button and save your information then.
13. To view EKG reading you have saved, disconnect from the hardware and press the
LOAD button.
14. A list of files you have saved will pop up. You can differentiate these files by the time
they were saved at.
15. Select the file you want to view and it will be shown on the graph.
16. When you are finished, press the back button to logout.

45
Appendix C: Testing Results

Appendix C: Testing Results

The result of EKG signal and SpO2 of every team member is shown in below figures and
table. Comparing with the standard EKG signal as shown in Figure 0-5, the result from the
designed device is correct and clear. The table shows that the result of measurement from the
designed device is right because it is similar to the one measured from social device.

Figure C-1 Qiuchan Yu’s EKG signal result

46
Appendix C: Testing Results

Figure C-2 Danielle Rocan’s EKG signal result

Figure C-3 Ying Pan's EKG signal result

47
Appendix C: Testing Results

Figure C-4 Joshua Halek’s EKG signal result

Figure C-5 Standard EKG signal[21]

48
Appendix C: Testing Results

Table C-1 The SpO2 result of all team members

users Testing using designed SpO2 Testing using a commercial


monitor product

Heart rate (bpm) SpO2 level (%) Heart rate (bpm) SpO2 level (%)

Qiuchan Yu 67 98 67 100

Ying Pan 75 96 74 100

Joshua Halek 73 97 75 98

49
Appendix D: Software Resources

Appendix D: Software Resources

This page is intentionally left blank.

50
Appendix D: Software Resources

Software Flowcharts

Main function for MCU

51
Appendix D: Software Resources

Error and Beat Functions


Error and Beat Functions for MCU

ReadData Function for MCU

52
Appendix D: Software Resources

PrintData Function for MCU


53
Appendix D: Software Resources

54
Appendix D: Software Resources

Packet Function for Application

55
Appendix D: Software Resources

Parse Function for Application

56
Appendix D: Software Resources

Complete flowchart for


G13 Wireless EKG

57
Appendix D: Software Resources

Software Algorithms and Libraries

#include <ADAS1000.h>
#include <SPI.h>
#include <Arduino.h>
#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined
(_VARIANT_ARDUINO_ZERO_)
#include <SoftwareSerial.h>
#endif
#include <Adafruit_BLE.h>
#include <Adafruit_BluefruitLE_SPI.h>
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"

#define REPORTING_PERIOD_MS 1000


#define CS A5
#define DRDY A4
#define BUFSIZE 128 // Size of the read buffer
for incoming data
#define VERBOSE_MODE true // If set to 'true'
enables debug output
#define BLUEFRUIT_SPI_CS 8
#define BLUEFRUIT_SPI_IRQ 7
#define BLUEFRUIT_SPI_RST 4 // Optional but
recommended, set to -1 if unused

PulseOximeter pox;

uint32_t tsLastReport = 0;

// Callback (registered below) fired when a pulse is detected


void onBeatDetected()
{
Serial.println("Beat!");
}

unsigned char Lead[24000]={0,};


unsigned long old_sum =0;

Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ,


BLUEFRUIT_SPI_RST);
ADAS1000 ADAS1000;
void printData(unsigned char* data, unsigned int bytes, unsigned long*
old_sum)
{
unsigned long Lead1_cur = 0;

58
Appendix D: Software Resources

unsigned long Lead2_cur = 0;


unsigned long Lead3_cur = 0;
unsigned long sum = 0;

for (unsigned long u = 4; u < bytes; u = u + 24)


{
if (data[u] == 17)
{
Lead1_cur = ((unsigned long)data[u + 1] << 16) +
((unsigned long)data[u + 2] << 8) +
((unsigned long)data[u + 3] << 0);
Lead2_cur = ((unsigned long)data[u + 5] << 16) +
((unsigned long)data[u + 6] << 8) +
((unsigned long)data[u + 7] << 0);
Lead3_cur = ((unsigned long)data[u + 9] << 16) +
((unsigned long)data[u + 10] << 8) +
((unsigned long)data[u + 11] << 0);
sum = (Lead1_cur + Lead3_cur +Lead2_cur)/3;

*old_sum= sum;
ble.println(*old_sum);

Serial.println(sum);
}
}

void error(const __FlashStringHelper*err)


{
Serial.println(err);
}

void setup(void)
{
delay(500);
Serial.begin(115200);
pinMode(CS, OUTPUT);
pinMode(DRDY,INPUT_PULLUP);
digitalWrite(CS, HIGH);

// Initialise the module


Serial.print(F("Initialising the Bluefruit LE module: "));

if ( !ble.begin(VERBOSE_MODE) )
{
error(F("Couldn't find Bluefruit, make sure it's in CoMmanD mode &
check wiring?"));

59
Appendix D: Software Resources

}
Serial.println( F("OK!") );

// Perform a factory reset to make sure everything is in a known


state
Serial.println(F("Performing a factory reset: "));
if (! ble.factoryReset() ){
error(F("Couldn't factory reset"));
}

// Disable command echo from Bluefruit


ble.echo(false);

Serial.println("Requesting Bluefruit info:");


// Print Bluefruit information
ble.info();
Serial.println(F("Setting device name to 'Bluefruit HRM': "));

if (! ble.sendCommandCheckOK(F("AT+GAPDEVNAME=G13 Wireless EKG")) ) {


error(F("Could not set device name?"));
}

ble.verbose(false); // debug info is a little annoying after this


point!

Serial.println("Waiting for a BLE connection to continue ...");

// Wait for connection to finish


while (! ble.isConnected()) {
delay(5000);
}

//Set to data mode


ble.setMode(BLUEFRUIT_MODE_DATA);
Serial.println(F("CONNECTED!"));

ADAS1000.Init(ADAS1000_2KHZ_FRAME_RATE);
ADAS1000.SetRegisterValue(ADAS1000_ECGCTL, 0x81E007AE);
ADAS1000.SetRegisterValue(ADAS1000_CMREFCTL, 0x85E0000A);
ADAS1000.SetRegisterValue(ADAS1000_FILTCTL, 0x8B000020);
ADAS1000.SetRegisterValue(ADAS1000_FRMCTL,0x8A1FCE00);

pox.begin();
pox.setOnBeatDetectedCallback(onBeatDetected);
}

void loop(void)
{

60
Appendix D: Software Resources

pox.update();

if (millis() - tsLastReport > REPORTING_PERIOD_MS) {

Serial.print(pox.getHeartRate());
ble.print("H");
ble.println(pox.getHeartRate());
Serial.print("bpm / SpO2:");
Serial.print(pox.getSpO2());
Serial.println("%");
ble.print("S");
ble.println(pox.getSpO2());

tsLastReport = millis();
}
ADAS1000.ReadData(Lead,1,1,1,1,0);
printData(Lead,24,&old_sum);

ADAS1000-4 Librabry
/**********************************************************************
*****//**
* @file ADAS1000.cpp
* @brief Implementation of ADAS1000 Driver.
* @author ACozma (andrei.cozma@analog.com)
* @adaptation Mujtaba Jalil
***********************************************************************
*********
* Copyright 2012(c) Analog Devices, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* - Neither the name of Analog Devices, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* - The use of this software may or may not infringe the patent
rights
* of one or more patent holders. This license does not release you

61
Appendix D: Software Resources

* from the requirement that you obtain separate licenses from these
* patent holders to use this software.
* - Use of the software either in source or binary form, must be run
* on or directly connected to an Analog Devices Inc. component.
*
* THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES "AS IS" AND ANY EXPRESS
OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, NON-INFRINGEMENT,
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL ANALOG DEVICES BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT
* LIMITED TO, INTELLECTUAL PROPERTY RIGHTS, PROCUREMENT OF SUBSTITUTE
GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***********************************************************************
*********
* SVN Revision: 570
***********************************************************************
********/

/**********************************************************************
*******/
/***************************** Include Files
*********************************/
/**********************************************************************
*******/
#include "ADAS1000.h"
//#include <SPI.h>
#include <SPI.h>
#include <Arduino.h>
#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined
(_VARIANT_ARDUINO_ZERO_)
#include <SoftwareSerial.h>
#endif

/**********************************************************************
*******/
/************************ Variables Definitions
******************************/

62
Appendix D: Software Resources

/**********************************************************************
*******/
static unsigned long frameSize = 0; //ADAS1000 frame size
in bytes
static unsigned long frameRate = 0; //ADAS1000 frame rate
static unsigned long inactiveWordsNo = 0; //number of inactive words in
a frame

/**********************************************************************
*****//**
* @brief Initializes the SPI communication with ADAS1000 and checks if
the
* device is present by reading its ID. If the ID read is ok
the ADAS1000
* is configured with the spefified frame rate and all the
words in a
* frame are activated.
*
* @param rate - ADAS1000 frame rate.
*
* @return status - Result of the initialization procedure.
* Example: 1 - if initialization was successful;
* 0 - if initialization was unsuccessful.
***********************************************************************
********/
ADAS1000::ADAS1000()
{
}

unsigned char ADAS1000::Init(unsigned long rate)


{
unsigned long minSpiFreq = 0;
unsigned long revId = 0;

//store the selected frame rate


frameRate = rate;
//SPI.begin(); //SPI init command
// Compute the SPI clock frequency.
switch(frameRate)
{
case ADAS1000_16KHZ_FRAME_RATE:
minSpiFreq = ADAS1000_16KHZ_FRAME_RATE *
ADAS1000_16KHZ_WORD_SIZE *
ADAS1000_16KHZ_FRAME_SIZE;
break;
case ADAS1000_128KHZ_FRAME_RATE:
minSpiFreq = ADAS1000_128KHZ_FRAME_RATE *
ADAS1000_128KHZ_WORD_SIZE *

63
Appendix D: Software Resources

ADAS1000_128KHZ_FRAME_SIZE;
break;
case ADAS1000_31_25HZ_FRAME_RATE:
minSpiFreq = (ADAS1000_31_25HZ_FRAME_RATE *
ADAS1000_31_25HZ_WORD_SIZE *
ADAS1000_31_25HZ_FRAME_SIZE) /
100;
break;
default: // ADAS1000_2KHZ__FRAME_RATE
minSpiFreq = ADAS1000_2KHZ_FRAME_RATE *
ADAS1000_2KHZ_WORD_SIZE *
ADAS1000_2KHZ_FRAME_SIZE;
break;
}

// Initialize the SPI controller.


// The SPI frequency must be greater or equal to minSpiFreq.
/* if(!SPI_Init(0, minSpiFreq, 1, 1))
{
return 0;
} */

// Reset the ADAS1000.


SoftwareReset();

// Activate all the channels


inactiveWordsNo = 0;
SetInactiveFrameWords(0);

//Set the frame rate


SetFrameRate(frameRate);

return 1;
}

/**********************************************************************
*****//**
* @brief Reads the value of the selected register
*
* @param regAddress - The address of the register to read.
* @param regVal - Pointer to a variable where to store the read data.
*
* @return None.
***********************************************************************
********/
void ADAS1000::GetRegisterValue(unsigned char regAddress, unsigned
long* regVal)
{

64
Appendix D: Software Resources

unsigned char readCmd[4] = {0, 0, 0, 0};


unsigned char readData[4] = {0, 0, 0, 0};
unsigned long reg = 0;
// Select the register (For register reads, data is shifted out
// during the next word).
readCmd[0] = regAddress; // Register address.
SPI_Write(readCmd, 4);

// Read the data from the device.


SPI_Read(readData, 4);
*regVal = ((unsigned long)readData[1] << 16) +
((unsigned long)readData[2] << 8) +
((unsigned long)readData[3] << 0);
reg = *regVal;
//Serial.println(reg);
//delay(5000);
return;
}

/**********************************************************************
*****//**
* @brief Writes a value to the selected register
*
* @param regAddress - The address of the register to write to.
* @param regValue - The value to write to the register.
*
* @return None.
***********************************************************************
********/
void ADAS1000::SetRegisterValue(unsigned char regAddress,
unsigned long regVal)
{
unsigned char writeCmd[4] = {0, 0, 0, 0};

writeCmd[0] = 0x80 + regAddress; // Write bit and register


address.
writeCmd[1] = (unsigned char)((regVal & 0xFF0000) >> 16);
writeCmd[2] = (unsigned char)((regVal & 0x00FF00) >> 8);
writeCmd[3] = (unsigned char)((regVal & 0x0000FF) >> 0);
SPI_Write(writeCmd, 4);
}

/**********************************************************************
*****//**
* @brief Resets the ADAS1000 part.
*
* @return None.

65
Appendix D: Software Resources

***********************************************************************
********/
void ADAS1000::SoftwareReset(void)
{

unsigned long hell = 0;


// Clear all registers to their reset value.
//Serial.println(ADAS1000_ECGCTL_SWRST); // Just for debug
purpose
SetRegisterValue(ADAS1000_ECGCTL, ADAS1000_ECGCTL_SWRST);
//GetRegisterValue(ADAS1000_ECGCTL, regVal);
//Serial.println(hell); // Debug purpose

// The software reset requires a NOP command to complete the


reset.
SetRegisterValue(ADAS1000_NOP, 0);
}

/**********************************************************************
*****//**
* @brief Selects which words are not included in a data frame.
*
* @param channelsMask - Specifies the words to be excluded from the
data
* frame using a bitwise or of the
corresponding bits
* from the Frame Control Register.
*
* @return None.
***********************************************************************
********/
void ADAS1000::SetInactiveFrameWords(unsigned long wordsMask)
{
unsigned long frmCtrlRegVal = 0;
unsigned char i = 0;

// Read the current value of the Frame Control Register


GetRegisterValue(ADAS1000_FRMCTL, &frmCtrlRegVal);
//Serial.println(frmCtrlRegVal);
//set the inactive channles
frmCtrlRegVal &= ~ADAS1000_FRMCTL_WORD_MASK;
frmCtrlRegVal |= wordsMask;

// Write the new value to the Frame Coontrol register.


SetRegisterValue(ADAS1000_FRMCTL, frmCtrlRegVal);

//compute the number of inactive words


inactiveWordsNo = 0;

66
Appendix D: Software Resources

for(i = 0; i < 32; i++)


{
if(wordsMask & 0x00000001ul)
{
inactiveWordsNo++;
}
wordsMask >>= 1;
}

//compute the new frame size


switch(frameRate)
{
case ADAS1000_16KHZ_FRAME_RATE:
frameSize = (ADAS1000_16KHZ_WORD_SIZE / 8) *
(ADAS1000_16KHZ_FRAME_SIZE -
inactiveWordsNo);
break;
case ADAS1000_128KHZ_FRAME_RATE:
frameSize = (ADAS1000_128KHZ_WORD_SIZE / 8) *
(ADAS1000_128KHZ_FRAME_SIZE -
inactiveWordsNo);
break;
case ADAS1000_31_25HZ_FRAME_RATE:
frameSize = ((ADAS1000_31_25HZ_WORD_SIZE / 8) *
(ADAS1000_31_25HZ_FRAME_SIZE -
inactiveWordsNo)) / 100;
break;
default: // ADAS1000_2KHZ__FRAME_RATE
frameSize = (ADAS1000_2KHZ_WORD_SIZE / 8) *
(ADAS1000_2KHZ_FRAME_SIZE -
inactiveWordsNo);
break;
}
}

/**********************************************************************
*****//**
* @brief Sets the frame rate.
*
* @param rate - ADAS1000 frame rate.
*
* @return None.
***********************************************************************
********/
void ADAS1000::SetFrameRate(unsigned long rate)
{
unsigned long frmCtrlRegVal = 0;

67
Appendix D: Software Resources

// Store the selected frame rate


frameRate = rate;

// Read the current value of the Frame Control Register


GetRegisterValue(ADAS1000_FRMCTL,&frmCtrlRegVal);
frmCtrlRegVal &= ~ADAS1000_FRMCTL_FRMRATE_MASK;

// Compute the new frame size and update the Frame Control
Register value
switch(frameRate)
{
case ADAS1000_16KHZ_FRAME_RATE:
frameSize = (ADAS1000_16KHZ_WORD_SIZE / 8) *
(ADAS1000_16KHZ_FRAME_SIZE -
inactiveWordsNo);
frmCtrlRegVal |= ADAS1000_FRMCTL_FRMRATE_16KHZ;
break;
case ADAS1000_128KHZ_FRAME_RATE:
frameSize = (ADAS1000_128KHZ_WORD_SIZE / 8) *
(ADAS1000_128KHZ_FRAME_SIZE -
inactiveWordsNo);
frmCtrlRegVal |= ADAS1000_FRMCTL_FRMRATE_128KHZ;
break;
case ADAS1000_31_25HZ_FRAME_RATE:
frameSize = ((ADAS1000_31_25HZ_WORD_SIZE / 8) *
(ADAS1000_31_25HZ_FRAME_SIZE -
inactiveWordsNo)) / 100;
frmCtrlRegVal |= ADAS1000_FRMCTL_FRMRATE_31_25HZ;
break;
default: // ADAS1000_2KHZ__FRAME_RATE
frameSize = (ADAS1000_2KHZ_WORD_SIZE / 8) *
(ADAS1000_2KHZ_FRAME_SIZE -
inactiveWordsNo);
frmCtrlRegVal |= ADAS1000_FRMCTL_FRMRATE_2KHZ;
break;
}

// Write the new Frame control Register value


SetRegisterValue(ADAS1000_FRMCTL, frmCtrlRegVal);
}

/**********************************************************************
*****//**
* @brief Reads the specified number of frames.
*
* @param pDataBuffer - Buffer to store the read data.
* @param frameCnt - Number of frames to read.

68
Appendix D: Software Resources

* @param startRead - Set to 1 if a the frames read sequence must be


started.
* @param stopRead - Set to 1 if a the frames read sequence must be
sopped
* when exiting the function.
* @param waitForReady - Set to 1 if the function must wait for the
READY bit
* to be set in the header.
* @param readyRepeat - Set to 1 if the device was configured to repeat
the
* header until the READY bit is set.
*
* @return None.
***********************************************************************
********/
void ADAS1000::ReadData(unsigned char* pDataBuffer, unsigned long
frameCnt,
unsigned char startRead, unsigned char
stopRead,
unsigned char waitForReady, unsigned
char readyRepeat)
{
unsigned char readCmd[4] = {0, 0, 0, 0};
unsigned long ready = 0;

// If the read sequence must be started send a FRAMES command.


if(startRead)
{
readCmd[0] = ADAS1000_FRAMES; // Register address.
SPI_Write(readCmd, 4);
}

// Read the number of requested frames.


while(frameCnt)
{
// If waiting for the READY bit to be set read the header
until the bit is set, otherwise just read the entire frame.
if(waitForReady)
{
ready = 1;
while(ready == 1)
{
//if the header is repeated until the READY bit
is set read only the header, otherwise read the entire frame
if(readyRepeat)
{
SPI_Read(pDataBuffer, 4);
ready = *pDataBuffer & 0x40;

69
Appendix D: Software Resources

//Serial.print(pDataBuffer[5]);//for
debug
if(ready == 0)
{
SPI_Read(pDataBuffer + 4, frameSize
- 4);
pDataBuffer += frameSize;
frameCnt--;

//Serial.print(pDataBuffer[5]);//for debug
}
}
else
{
SPI_Read(pDataBuffer, frameSize);
ready = *pDataBuffer & 0x40;
if(ready == 0)
{
pDataBuffer += frameSize;

frameCnt--;

//Serial.print(pDataBuffer[5]);//for debug
}
}
}
}
else
{
SPI_Read(pDataBuffer, frameSize);
pDataBuffer += frameSize;
frameCnt--;
}
}

// If the frames read sequence must be stopped read a register to


stop the frames read.
if(stopRead)
{
GetRegisterValue(ADAS1000_FRMCTL,&ready);
//Serial.print(pDataBuffer[5]);//for debug
}
}

/**********************************************************************
*****//**
* @brief Computes the CRC for a frame.
*

70
Appendix D: Software Resources

* @param pBuf - Buffer holding the frame data.


*
* @return Returns the CRC value for the given frame.
***********************************************************************
********/
unsigned long ADAS1000::ComputeFrameCrc(unsigned char *pBuf)
{
unsigned char i = 0;
unsigned long crc = 0xFFFFFFFFul;
unsigned long poly = 0;
unsigned char bitCnt = 0;
unsigned long frmSize = 0;

// Select the CRC poly and word size based on the frame rate.
if(frameRate == ADAS1000_128KHZ_FRAME_RATE)
{
poly = CRC_POLY_128KHZ;
bitCnt = 16;
}
else
{
poly = CRC_POLY_2KHZ_16KHZ;
bitCnt = 24;
}

frmSize = frameSize;

// Compute the CRC.


while(frmSize--)
{
crc ^= (((unsigned long)*pBuf++) << (bitCnt - 8));
for(i = 0; i < 8; i++)
{
if(crc & (1ul << (bitCnt - 1)))
crc = (crc << 1) ^ poly;
else
crc <<= 1;
}
}

return crc;
}

/**********************************************************************
*****//**
* @brief Writes data to SPI.
*
* @param data - data represents the write buffer.

71
Appendix D: Software Resources

* @param bytesNumber - Number of bytes to write.


*
* @return Number of written bytes.
***********************************************************************
********/
/**********************************************************************
*********
* Make sure to use A5 as the chip select
*
*
*
*
***********************************************************************
*********/

unsigned char ADAS1000::SPI_Write(unsigned char* data,


unsigned char bytesNumber)
{

unsigned int i = 0;
digitalWrite(A4,LOW); //A4 is a GPIO pin that is active low
SPI.beginTransaction(SPISettings(5120000,MSBFIRST,SPI_MODE3));
for (int i = 0; i < bytesNumber; i++)
{
SPI.transfer(data[i]);
}
digitalWrite(A4,HIGH);
SPI.endTransaction();
return bytesNumber;
}

/**********************************************************************
*****//**
* @brief Reads data from SPI.
*
* @param data - Data represents the read buffer.
* @param bytesNumber - Number of bytes to read.
*
* @return Number of read bytes.
***********************************************************************
********/
unsigned char ADAS1000::SPI_Read(unsigned char* data,
unsigned char bytesNumber)
{
unsigned int i = 0;
digitalWrite(A4,LOW);
SPI.beginTransaction(SPISettings(5120000,MSBFIRST,SPI_MODE3));

72
Appendix D: Software Resources

for (int i = 0; i < bytesNumber; i++)


{
data[i] = SPI.transfer(0);
}
digitalWrite(A4,HIGH);
SPI.endTransaction();
return bytesNumber;
}

73

You might also like