You are on page 1of 122

-

e-mail: acd@mol.gov.sa Tel 012-2759819


Spring Semester 1434-1435 H


















) (

.
.
Introduction to Electronics (Integrated Circuits)

Dr. Nema Salem


1


ECG Signal Extraction and Software Implementation of
an Electrocardiogram System Using MatLab

Alaa Abu Al-Soud, Ashwaq Hameed, Asmaa Al-Andijani, Bayan Molah, Doaa Bashoah,
Lamiya Ali, Sara Afify, Sara Al-Ghamdi, Sara Ba-Abdullah, Shahad Bahareth, Shorog
Fatani, Zeineb Elsheikh



Course project:
ECE 210L: Introduction to Electronics (Integrated Circuits)


Supervisor
Dr. Nema Salem


May, 2013





2

Acknowledgment
We would like to thank our supervisor Dr. Nema Salem for the valuable guidance and
advices. She inspired us greatly to work on this project.
We also would like to thank all the doctors in king Phahad hospital and King
Abdulaziz University. We would like to thank Doctor Abeer Khojah for providing us
with the needed medical information.
In addition, we would like to thank Dr. Muhammed A.U. Khan for providing us with
a Signal Extraction circuit and a good advising to complete this project.
Last but not least, we would like to thank Mr. Charles Rajesh Kumar who participated
in answering our questions for this project.










3

Contents:
Acknowledgment ..... 3
Abstract .. 4
Introduction ..................... 5
Background .................... 7
Project Stages ......... 13
Stage I: ECG Signal Extraction .... 13
Stage II: Interfacing ............... 17
Stage III: Noise Reduction Filters ........ 20
Stage IV: Peak Detecting .................... 47
Stage IIV: Displaying the ECG Signal .................. 48
Conclusion and Future Work ................ 54
References 55




4

Abstract
Electrocardiography, ECG, signals are used very widely as a clinical
tool to determine the rate and regularity of heartbeats as well as the size
and the position of the chambers, the presence of any damage to the heart,
and the effects of the drugs or devices used to regulate the heart.
Routinely recorded ECG is corrupted by noises. These noises causing
problems for analysis and interpretation of ECG signal. For this purpose
the ECG should be made free of noises.
Our project started by building a circuit based instrumentation amplifier to
extract the weak ECG signal, 1.5 mV, from the human body. Three
leads are used to extract this signal. The extracted ECG signal has been
feed to the MATLAB software via the PC-sound card. The phase of
processing been started. The main modules are the pre-amplification,
noise removal (filtration), amplification and displaying. Peak detection
algorithm is followed by a heart rate calculation. The heart rhythm is
heard via the PC- sound card as well.
Implementing our project using MATLAB Package is still in progress.
After finishing, it will be tested on a group of people. As a future work,
wireless should be taken into consideration.






5

Introduction
The electrocardiogram (ECG) provides a physician with a view of the hearts activity
through electrical signals generated during the cardiac cycle, and measured with external
electrodes. Its clinical importance in cardiology is well established, being used for
example to determine heart rate, investigate abnormal heart rhythms, and causes of chest
pain.
The most important ECG signal features in a single cardiac cycle are:
P wave - due to depolarization of the atria
Q wave - due to activation of the anterioseptal region of the ventricular myocardium
R wave - due to depolarization of the ventricular myocardium
S wave - due to activation of the posteriobasal portion of the ventricles
T wave - due to rapid ventricular repolarization
Figure 1 is an ideal ECG signal from a healthy subject (time duration equivalent to one
heartbeat).
Key features, including the QRS complex, are identified. Because the QRS complex is
the major feature of an ECG, a great deal of clinical information can be derived from its
features. Identification of this feature in an ECG is known in the literature as QRS


6

detection, and it is a vital task in automated ECG analysis and portable arrhythmia
monitoring.
The range in quality of real-world ECG signals obtained from a variety of subjects under
different measurement conditions makes this task much more difficult.
QRS detection in ECG signals has been the focus of a wide body of research for the last
few decades. One finds in the literature a diverse collection of techniques drawn from
many fields (an excellent review of which is given in [X]), including:
Methods based on discrete derivatives,
Methods based on digital filtering,
Methods based on a wavelet representation of the ECG signal,
Methods based on neural networks,
Methods based on adaptive filtering,
Methods based on genetic algorithms,
Methods based on maximum posteriori (MAP) estimation.










7

Background
The Electrocardiography machine (ECG or EKG) is used to measure the electrical
activity of the heart over a certain period of time depending on the purpose of taking the
reading. It can be used to either monitor over longer periods of time or diagnostic
purposes to analyze the status of the heart at a certain time.
The ECG machine uses a set of electrodes that are attached to the surface of the skin
and the numbers of electrodes that are used vary depending on the use of the ECG. The
number of electrodes varies from the number of leads in some cases like the 12-lead ECG
that actually uses 10 electrodes (wires). The number of leads indicates the different
angular views of the heart and not the number of wires (which is depending on the
number of physical electrodes). Although in majority of hospitals, priority is given to the
12-lead ECG because cardiologists consider it a more detailed view of the heart from
different angles, we have decided to use 3 electrodes (3 leads) for our research.
The output of the ECG is a graph called the PQRST graph/waves. It is divided into
the P wave, QRS complex and the ST wave and each represents the contraction of the
auricles, contraction of the ventricles and the expansion of the ventricles respectively.


8

Information can be obtained from these graphs using the time difference between each of
the sections and the wave patterns. The information that can be deduced from the ECG
readings includes the rate and regularity of heartbeats and size and position of the
chambers



Specifications about the Electrode used to extract the signals :
ECG electrodes are designed to detect electric signals from patients body and
transfer them to the ECG device. The adhesive side of the electrode is protected with a
foil, which is removed directly before application. The electrode is placed on the patients
skin at the precise spot from which the signal is to be read. The outer side of the electro-
de is provided with a snap for connecting the lead wires.
ECG electrodes are designed to detect electric signals from patients body and
transfer them to the ECG device. The adhesive side of the electrode is protected with a
foil that is removed directly before application. The electrode is placed on the patients


9

skin at the precise spot from which the signal is to be read. The outer side of the electro-
de is provided with a snap for connecting the lead wires.
In order to record the ECG, we need a transducer capable of converting the ionic
potentials generated within the body into electronic potentials, which can be measured by
conventional electronic instrumentation. Such a transducer consists of a pair of
electrodes, which measure the ionic potential difference between their respective points
of application on the body surface. Electrodes may be classified either as polarisable, in
which case they behave as capacitors, or nonpolarisable, in which case they behave as
resistors. Common electrodes have characteristics that lie between these extremes; the
silversilver chloride electrode discussed below approximates more closely to a
nonpolarisable electrode.
- Electrode placement
The most obvious way to record the ECG is between the Right Arm (RA) and the
Left Arm (LA) although another two combinations using the Left Leg (LL) are also used
clinically (RALL and LALL). Another electrode is also used to connect the patient to
the common ground of the instrumentation. Usually, this ground electrode is attached to
the right leg.

- General characteristics about the electrode :
Different types of gel, backing and sensors allow optimizing the electrodes selection
depending on patients anatomic condition, practitioners preferen- ces and the
examination performed.
A wide range of shapes and sizes - allows optimal placement, application and removal
of the electrode.

Perfect adhesiveness - a strong, skin friendly adhesive is a guarantee of stable and
comfortable electrode placement. The use of hypoallergenic adhesive protects skin from


10

being irritated

Gel - high quality liquid gel ensures reliable flow of signal and the solid gel increases
the electrodes adhesive area to 100%.

Backing - flexible PE foam is water resistant and watertight while the soft cloth enables
skin breathing.

Sensor - silver chloride (Ag/AgCl) covered sensor ensures perfect conductivity and
exact signal transfer from the patients body to the ECG device, as well as precise
examination reading. For X-ray examination, electrodes with radio-tran- slucent snaps are
also available.

Packing - aluminum pouches with PE foil layer (inside) protect the electrodes gel and
adhesive from drying out.


- Types of the electrode :

Diagnostic resting
electrodes

Electrodes for diagnostics and monitoring. High
quality liquid or solid gel in connection with
Ag/AgCl sensor ensures perfect examination
reading. The electrodes are available in many
shapes and sizes depending on our customers
and end users needs.



11

Holter electrodes

Electrodes for 24 hours holter examination. The
rectangular shape and the highly adhesive PE
foam ensure electrodes reliability. Additional
in-cut allows stable wire connection and
reduction of motion artifacts.

For young patients

Electrodes designed for resting, short termecg
examination of children. The application of
smaller size electrodes provides more comfort
for this group of patients.

For newborns and
premature infants

Prewired (60cm) electrodes designed for both
short and long-term monitoring of tiniest
patients. Made of the highest quality cloth which
enables skin breathing. All surface covered
with hypoallergenic solid gel. Radiotranslucent
version available.

For stress test and long-
term examination

Electrode for stress test and long-term
examinations. The microporouscloth backing
makes skin breathing easy and prevents skin
rash. Also suitable for holter examination.



12

X-ray examination

Diagnostic and monitoring electrode for adults
and youth. The carbon snap makes the electrode
radiotranslucent during X-ray examination.



Project Stages :
To Extract and Implement (ECG/EKG), there are five phases:
I. Stage one: Signal Extraction
II. Stage two: Interfacing via soundcard
III. Stage three: Amplifying & smoothing the signal from the noise
IV. Stage four: Peak Detection
V. Stage five: Displaying the Signal & hearing heart rhythm.

Stage I: ECG Signal Extraction :
Data acquisition system of the ECG is built to extract the ECG signal which has a
very small amplitude and a specific range of frequencies . The circuit of the system
consist of three parts:
1) Extract the ECG signal from the heart using the electrodes specifically three
leads.
2) Pre-Amplification to the signal using instrumentation amplifier .


13

3)Input the signal to the PC and interfacing via the sound card.





- Description of the circuit:
The circuit basically amplifies the difference between the right-arm (RA) lead and the
left-arm (LA) lead with the right-leg (RL) lead as the ground or reference node (i.e. the
RA or LA common mode should be about the same as RL). The circuit consists of a
difference amplifier which is essentially a 2- stage instrumentation amplifier (IA)
followed by another amplifier/filter stage followed by a filter stage .
The sharp R wave pulse needs to be detected using a circuit composed of a
comparator and a monoshot (mono-stable multivibrator) that enables an oscillator to
drive a speaker. A distinct beep sound is to be detected. The mono-shot may be required
because the pulse is very narrow with respect to the period of the waveform typically 1
Hz or a heartbeat rate of 60 per minute.

The proposal of using Driven-right-leg circuit to reduce the common-
mode interference:

The common mode input impedance and thus the CMRR of an amplifier can be
greatly increased by guarding the input circuit. The common mode signal can be obtained


14

by two averaging resistors connected between the outputs of the two input op-amps of an
instrumentation amplifier. The buffered common-mode signal at the output of op-amp 4
can be used as guard voltage to reduce the effects of cable capacitance and leakage. In
many modern biopotential amplifiers, the reference electrode is not grounded. Instead, it
is connected to the output of an amplifier for the common mode voltage, op-amp 3,
which works as an inverting amplifier. The inverted common mode voltage is fed back to
the reference electrode. This negative feedback reduces the common-mode voltage to a
low value [Webster, 1992]. Electrocardiographs based on this principle are called driven-
right-leg systems replacing
the right leg ground electrode
of ordinary
electrocardiographs by an
actively driven electrode.
The gain of INA118:
G= 1+


G= 1 +



G= 26
The inner circuit of the INA118

These are the components we used to build our circuit :
Component

Details
Medical leads




15


Electrical Specifications:
1. Total Gain= 1000 to 3000
2. Signal lower cutoff freq.= 0.05 Hz
3. Upper cutoff freq. = 150 Hz
4. CMRR= Should be high (say 1000)
5. R-wave pulse height = 1 mV

Medical Specifications :
1. Normal heart rate of adults : 60 - 100 beats per minute.
2. Amplitude of the ECG signal : 5 mV peak to peak
3. Bandwidth of the ECG signal : 0.05 100 Hz


Shielded wires


OP-AMP

2 INA118

2 OP07


Resistors

2 390K
1 10K,
4 1K
1 2K

Diodes


8 1N4007


16

Stage II : Interfacing Via Sound Card :
A sound card (also known as an audio card) is an internal computer expansion
card that facilitates the input and output of audio signals to and from a computer
under control of computer programs. The term sound card is also applied to external
audio interfaces that use software to generate sound, as opposed to using hardware
inside the PC. Typical uses of sound cards include providing the audio component for
multimedia applications such as music composition, editing video or audio,
presentation, education and entertainment (games) and video projection. As we all
know, sounds are analog they are made of waves that travel through matter. In the
other hand, computers communicate digitally, using electrical impulses that represent
0s and 1s. Sound card translates between a computer's digital information and the
outside world's analog information.

Acquiring ECG signal using MatLab Data Acquisition ToolBox:
Data acquisition toolbox allows the software MATLAB to acquire data from
sensors and to send out electrical signals that can be used to control or drive external
devices. This toolbox interface with two different pieces of hardware. One is the
sound card built into the computer, and the second is data acquisition card. Data
acquisition card allow the computer to acquire data from many different types of
sensors. We will be acquiring continuous, analog, electrical signal for a defined
duration of time.





17


Implementation:

















if (~isempty(daqfind))
stop(daqfind)
end
duration = 10;
ai = analoginput('winsound');
addchannel(ai, 1);
ai
sampleRate = get(ai, 'SampleRate')
get(ai, 'SamplesPerTrigger')
requiredSamples = floor(sampleRate * duration);
set(ai, 'SamplesPerTrigger', requiredSamples);
waitTime = duration * 1.1 + 0.5
start(ai)
tic
wait(ai, waitTime);
toc
[data, time] = getdata(ai);
figure;
plot(time,data);
xlabel('Time (s)'); % Setting up the xlabel
ylabel('Signal (Volts)'); % Setting up the ylabel
title('Data Acquired using Microphone for 10 seconds'); % Setting up the title
grid on;



18

The Output : Data Acquired using Microphone for 10 seconds


Stage III : Noise Reduction Filters :
Bioelectrical signal including valuable clinical information, but frequently the
valuable clinical information is corrupted by various kinds of noise. We used several
techniques to study their effect and efficiency in the filtering process. To deal with
these different kinds of noises, we tested nine types of filters in order to experience
the efficiency, advantages and disadvantages of each type.
Literature Review :


19

In signal processing, a filter is a device or process that removes from
a signal some unwanted component or feature. Filtering is a class of signal
processing, the defining feature of filters being the complete or partial suppression of
some aspect of the signal. Most often, this means removing some frequencies and not
others in order to suppress interfering signals and reduce background noise. However,
filters do not exclusively act in the frequency domain; especially in the field of image
processing many other targets for filtering exist. In this report, types of noise have
been divided into two categories: external and internal noise. Also, eight types of
filters are described, in addition to the advantages, disadvantages and applications of
each filter.
Classifications of the Noise :
Noise may be put into following two categories.
First: External noises, i.e. noise whose sources are external.
External noise may be classified into the following three types:
1. Atmospheric noises
2. Extraterrestrial noises
3. Man-made noises or industrial noises.
Second: Internal noise in communication, i.e. noises which get, generated within the
receiver or communication system.
Internal noise may be put into the following four categories.
1. Thermal noise or white noise or Johnson noise
2. Shot noise.
3. Transit time noise


20

4. Miscellaneous internal noise.
External noise cannot be reduced except by changing the location of the receiver
or the entire system. Internal noise on the other hand can be easily evaluated
mathematically and can be reduced to a great extent by proper design. As already said,
because of the fact that internal noise can be reduced to a great extent, study of noise
characteristics is a very important part of the communication engineering.
Signal-to-noise (S/N) is much more useful figure of merit than noise alone for
describing the quality of an analytical method. The magnitude of the noise is defined as
the standard deviation s of numerous measurements and signal is given by the mean x of
the measurements. S/N is the reciprocal of the relative standard deviation. S/N < 2 or 3
impossible to detect a signal.
The electrocardiogram (ECG) records the electrical activity of the heart, which is
a noninvasively recording produced by an electrocardiographic device and collected by
skin electrodes placed at designated locations on the body. The ECG signal is categorized
by six peaks and valleys, which are traditionally labeled P, Q, R, S, T, and U .
It has been used extensively for detection of heart disease. ECG is non-stationary
bioelectrical signal including valuable clinical information, but frequently the valuable
clinical information is corrupted by various kinds of noise.
The main sources of noise are:
1. power-line interference from 5060 Hz pickup and harmonics from the power mains
baseline wanders caused by variable contact between the electrode and the skin and
respiration; muscle contraction form electromyogram (EMG) mixed with the ECG
signals.
Electromagnetic interference from other electronic devices and noise coupled
from other electronic devices, usually at high frequencies. The noise degrades the
accuracy and precision of an analysis. Obtaining true ECG signal from noisy


21

observations can be formulated as the problem of signal estimation or signal denoising.
So denoising is the method of estimating the unknown signal from available noisy data.
Generally, excellent ECG denoising algorithms should have the following properties:
Ameliorate signal-to-noise ratio (SNR) for obtaining clean and readily observable
signals; Preserve the original characteristic waveform and especially the sharp Q, R, and
S peaks, without distorting the P and T waves.

Type of Filter used to detect noise :
1) Kalman Filter :
The Kalman filter, also known as linear quadratic estimation (LQE), is
an algorithm that uses a series of measurements observed over time,
containing noise (random variations) and other inaccuracies, and produces estimates of
unknown variables that tend to be more precise than those based on a single measurement
alone. More formally, the Kalman filter operates recursively on streams of noisy input
data to produce a statistically optimal estimate of the underlying system state. The filter is
named for Rudolf (Rudy) E. Klmn, one of the primary developers of its theory. It is an
optimal recursive data processing algorithm.
- Optimal depends on the criteria chosen to evaluate the performance
- Recursive since it does not require storage of all previous data. It also does not
require the previous data to be reprocessed

- Zk is the measured value of the system and it relates to the calculated value Xk.
- In a perfect world, Zk = Xk and B is an identity matrix.
- But in real life applications there is always a noise factor called the Gaussian
noise (vk and w


22

- Kalman filter has two phases:
1) PREDICT
Predicts the state estimate of the current time using the state estimate of the previous
time. The current measured values are not considered.
2) UPDATE
Update phase combines the current time state estimate with the current measured values
and updates the current state estimate.
- Advantages:
Copes with variable A, C, Q and R matrices
Copes with the large uncertainty of the initialization phase
Copes with missing data Provides a convenient measure of estimation accuracy
(via the covariance matrix P)
Fuses information from multiple-sensor .
- Disadvantages:
Computationally complex (especially for large numbers of sensor channels r)
Requires conditional independence of the measurement errors, sample-to-sample
Requires linear models for state dynamics and observation processes (A and C)
Getting a suitable value for Q (a.k.a. tuning) can be something of a black art
2) SGOLAY Filter :


23

The SavitzkyGolay smoothing filter is a filter that essentially performs a
local polynomial regression (of degree k) on a series of values (of at least k+1 points
which are treated as being equally spaced in the series) to determine the smoothed value
for each point.






Algorithm applied on a gaussian peak with random noise, with a degree 3 and a width of 9 points. Smoothing
(top), first derivation (middle), second derivation (bottom).
- Advantages:
The main advantage of this approach is that it tends to preserve features of the
distribution such as relative maxima, minima and width, which are usually 'flattened' by
other adjacent averaging techniques (like moving averages, for example).
3) Smooth Filter :
In statistics and image processing, to smooth a data set is to create an
approximating function that attempts to capture important patterns in the data, while
leaving out noise or other fine-scale structures/rapid phenomena. In smoothing, the data
points of a signal are modified so individual points (presumably because of noise) are
reduced, and points that are lower than the adjacent points are increased leading to a


24

smoother signal. Smoothing may be used in two important ways that can aid in data
analysis by:
1. being able to extract more information from the data as long as the assumption of
smoothing is reasonable
2. By being able to provide analyses that is both flexible and robust.
Many different algorithms are used in smoothing. Data smoothing is typically done
through the simplest of all density estimators, the histogram.
Smoothing may be distinguished from the related and partially overlapping concept
of curve fitting in the following ways:
curve fitting often involves the use of an explicit function form for the result, whereas
the immediate results from smoothing are the "smoothed" values with no later use
made of a functional form if there is one;
The aim of smoothing is to give a general idea of relatively slow changes of value
with little attention paid to the close matching of data values, while curve fitting
concentrates on achieving as close a match as possible.
Smoothing methods often have an associated tuning parameter which is used to
control the extent of smoothing.


25


One of the most common algorithms is the "moving average", often used to try to
capture important trends in repeated statistical surveys. In image
processing and computer vision, smoothing ideas are used in scale space representations.
The simplest smoothing algorithm is the "rectangular" or "unweighted sliding-average
smooth". This method replaces each point in the signal with the average of "m" adjacent
points, where "m" is a positive integer called the "smooth width". Usually m is an odd
number. The triangular smooth is like the rectangular smooth except that it implements a
weighted smoothing function.
- Advantages:
1. First, the filter involves both the smoothing operation and differentation
operation.
- it can be regarded as a low-pass differention filter (digital differentiator).
-it is well known that the common differentiation operation amplifies the high-frequency
noises. therefore, the smoothded differentiation filter would be valuable in experimental
(noisy) data processing.
2. Secondly, the filter coefficients are all convenient integers (simple units) except
for an integer scaling factor,as may be especially significant in some applications
such as those in some single-chip microcomputers, or digital signal processors.

4) Moving Average Filter :
The Moving Average Filter implements a low pass moving average filter. The Moving
Average Filter is part of the Preprocessing Modules.

- Advantages:


26

The Moving Average Filter is good for removing a small amount of high frequency
noise from an N dimensional signal.

- Disadvantages:
The main disadvantage of the Moving Average Filter is that in order to filter out
significantly high frequency noise, the window size of the filter needs to be large. The
problem with having a large filter window is that this will induce a large latency in any
signal passing through the filter, which may not be advantageous for real-time
applications. If you find that you need a large filter window to filter out high frequency
noise and the latency induced by this window size is not suitable for your real-time
application, then you might want to try either a Double Moving Average Filter or Low
Pass Filter instead.

5) Meadian Filter:
In signal processing, it is often desirable to be able to perform some kind of noise
reduction on an image or signal. The median filter is a nonlinear digital
filtering technique, often used to remove noise. Such noise reduction is a typical pre-
processing step to improve the results of later processing (for example, edge on an
image). Median filtering is very widely used in digital image processing because, under
certain conditions, it preserves edges while removing noise.
The median filter is normally used to reduce noise in an image, somewhat like
the mean filter. However, it often does a better job than the mean filter of preserving
useful detail in the image.
- Advantages:
1. Its simple to understand


27

2. The median filter preserves brightness differences resulting in minimal blurring of
regional boundaries
-3. Preserves the positions of boundaries in an image, making this method useful for
visual examination and measurement
-3. Median computer algorithm can be customized You can repeat the median filter on
the image until there are no further changes. In this way the median filter works like a
maximum expectation restoration, or a nearly uniform regions that are effectively
classified for segmentation.
- Disadvantages:
1-Less effective in removing Gaussian or random-intensity noise . The median
filter can remove noise only if the noisy pixels occupy less than one half of the
neighborhood area
2 -Repeating will remove noise but at the expense of detail (posterization occurs ) where
pixel brightness values are leveled across regions "group of pixels having similar
brightness values "
3- High computational cost (for sorting N pixels, the temporal complexity is O(Nlog N),
When the median filter must be carried out in real time, the software implementation in
general-purpose processors does not usually give good results and FPGAs are a good
alternative (Field Programmable Gate Array hardware.
4- Some median algorithms are not good for real time processing

6) BUTTERWORTH Filter :


28

The Butterworth filter is a type of signal processing filter designed to have as flat
a frequency response as possible in the pass band. It is also referred to as a maximally flat
magnitude filter. It was first described in 1930 by the British engineer Stephen
Butterworth in his paper entitled "On the Theory of Filter Amplifiers".
The main characteristic of Butterworth filter is that the pass band is maximally flat.
There are no variations (ripples) in the pass band. The magnitude response of LP
Butterworth filter is given by -
Where
c =cut off frequency
|H()|
2
=magnitude of LPF
N= order of filter that means the no. of stages used in the design of analog filter.
Butterworth filters have the following characteristics:
Smooth response at all frequencies
Monotonic decrease from the specified cut-off frequencies
Maximal flatness, with the ideal response of unity in the passband and zero in the
stopband
Half-power frequency, or 3 dB down frequency, that corresponds to the specified
cut-off frequencies
- Advantages :
The Advantages of Butterworth filters is their smooth, monotonically decreasing
frequency response. The following figure shows the frequency response of a lowpass
Butterworth filter.


29



As shown in the previous figure, after you specify the cut-off frequency of a
Butterworth filter, the steepness of the transition is proportional to the filter order. Higher
order Butterworth filters approach the ideal lowpass filter response.
Butterworth filters do not always provide a good approximation of the ideal filter
response because of the slow roll-off between the passband and the stopband.
- Comparison with other linear filters
Here is an image showing the gain of a discrete-time Butterworth filter next to other
common filter types. All of these filters are fifth-order.


30


The Butterworth filter rolls off more slowly around the cutoff frequency than
the Chebyshev filter or the Elliptic filter, but without ripple.
Applications:
Especially it is very much useful in high quality AUDIO applications because of its flat
response in both pass band and stop band where as chebyshev will be useful in signal
monitoring applications where the phase is not important criteria .
7) Weighted Average Filter :
A weighted average is any average that has multiplying factors to give
different weights to data at different positions in the sample window.
Mathematically, the moving average is the convolution of the datum points
with a fixed weighting function. One application is
removing pixelisation from a digital graphical image.


31

In technical analysis of financial data, a weighted moving
average (WMA) has the specific meaning of weights that decrease in
arithmetical progression.
[2]
In an n-day WMA the latest day has weight n, the
second latest n 1, etc., down to one.

The denominator is a triangle number equal to in the more
general case the denominator will always be the sum of the individual
weights.

8) GUASSI AN FI LTER:
A filter with the transmission characteristic described by the Gaussian curve is the
most common filter used in surface metrology to separate roughness, waviness, and form.
The most natural way to implement the Gaussian filter is to convolve the registered
profile with the filter impulse response. An important drawback of this approach,
however, is that it is difficult to correctly determine the mean line for the profile end
parts, this being referred to as the edge effect. Since a registered profile is frequently too
short, it is undesirable to reject any of its fragments. In the paper, we propose a method
for determining the mean line for a whole profile. This requires extrapolating the profile


32

at both its ends by fragments being some polynomial functions of the spatial variable.
The coefficients of the polynomials are selected so that the mean square difference
between the profile and the mean line reaches a minimum. Experimental results show that
the proposed method eliminates the edge effect even if the amplitude of the form
component significantly exceeds the roughness component.
In electronics and signal processing, a Gaussian filter is a filter whose impulse
response is a Gaussian function. Gaussian filters have the properties of having no
overshoot to a step function input while minimizing the rise and fall time. This behavior
is closely connected to the fact that the Gaussian filter has the minimum possible group
delay. Mathematically, a Gaussian filter modifies the input signal by convolution with a
Gaussian function; this transformation is also known as the Weierstrass transform.
Syntax
b = firgauss(k,n)
[b,n] = firgauss(k,'minorder',v)

- Advantages of Gaussian Filtering :
Gaussian smoothingis very effective for removing Gaussian noise
The weightsgive higher significance to pixels near the edge (reduces edge blurring)
They are linearlow pass filters
Computationally efficient(large filters are implemented using small 1D filters)
Rotationally symmetric(perform the same in all directions)
The degree of smoothingis controlled by (larger for more intensive smoothing)


33

So in general, you have many possibilities : try Gaussian filter, and compare it with other
algorithms such as Wiener filter, Median filter( circular, rectangular, diagonal,...), Gabor
Filter, Kalman filter ,...
- Disadvantages of Gaussian Filter:
tTakes time, reduces details

9) FI R Filter :
In signal processing, a finite impulse response (FIR) filter is a filter whose impulse
response (or response to any finite length input) is of finite duration, because it settles to
zero in finite time. This is in contrast to infinite impulse response (IIR) filters, which may
have internal feedback and may continue to respond indefinitely (usually decaying). FIR
filters are one of two primary types of digital filters used in Digital Signal Processing
(DSP) applications, the other type being IIR.
The impulse response of an Nth-order discrete-time FIR filter (i.e., with a Kronecker
delta impulse input) lasts for N + 1 samples, and then settles to zero.
FIR filters can be discrete-time or continuous-time, and digital or analog.
An FIR filter has a number of useful properties which sometimes make it preferable to an
infinite impulse response (IIR) filter. FIR filters:
Require no feedback. This means that any rounding errors are not compounded by
summed iterations. The same relative error occurs in each calculation. This also
makes implementation simpler.


34

Are inherently stable. This is due to the fact that, because there is no required
feedback, all the poles are located at the origin and thus are located within the unit
circle .
They can easily be designed to be linear phase by making the coefficient sequence
symmetric; linear phase, or phase change proportional to frequency, corresponds
to equal delay at all frequencies. This property is sometimes desired for phase-
sensitive applications, for example data communications, crossover filters, and
mastering.
Windowing Method:
Consider the ideal, or "brick wall," digital lowpass filter with a cutoff frequency of
0

rad/s. This filter has magnitude 1 at all frequencies with magnitude less than
0
, and
magnitude 0 at frequencies with magnitude between
0
and . Its impulse response
sequence h(n) is

This filter is not implementable since its impulse response is infinite and noncausal. To
create a finite-duration impulse response, truncate it by applying a window. By retaining
the central section of impulse response in this truncation, you obtain a linear phase FIR
filter. For example, a length 51 filter with a lowpass cutoff frequency
0
of 0.4 rad/s is
b = 0.4*sinc(0.4*(-25:25));
The window applied here is a simple rectangular window. By
Parseval's theorem, this is the length 51 filter that best
approximates the ideal lowpass filter, in the integrated least
squares sense. The following command displays the filter's
frequency response in FVTool:


35

fvtool(b,1)
fvtool(b,1)

Note that the y-axis shown in the figure is in Magnitude Squared. You can set this by
right-clicking on the axis label and selecting Magnitude Squared from the menu
Ringing and ripples occur in the response, especially near the band edge. This "Gibbs effect" does not vanish as
the filter length increases, but a nonrectangular window reduces its magnitude. Multiplication by a window in the time
domain causes a convolution or smoothing in the frequency domain. Apply a length 51 Hamming window to the filter
and display the result using FVTool:
b = 0.4*sinc(0.4*(-25:25));
b = b.*hamming(51)';
fvtool(b,1)
Note that the y-axis shown in the figure below is in Magnitude Squared. You can set this by right-clicking on the axis
label and selecting Magnitude Squared from the menu.


36


Using a Hamming window greatly reduces the ringing. This improvement is at the
expense of transition width (the windowed version takes longer to ramp from passband to
stopband) and optimality (the windowed version does not minimize the integrated
squared error).
The functions fir1 and fir2 are based on this windowing process. Given a filter order and
description of an ideal desired filter, these functions return a windowed inverse Fourier
transform of that ideal filter. Both use a Hamming window by default, but they accept
any window function. See Windows for an overview of windows and their properties.
Standard Band FIR Filter Design: fir1
fir1 implements the classical method of windowed linear phase FIR digital filter design.
It resembles the IIR filter design functions in that it is formulated to design filters in
standard band configurations: lowpass, bandpass, highpass, and bandstop.
The statements
n = 50;


37

Wn = 0.4;
b = fir1(n,Wn);
create row vector b containing the coefficients of the order n Hamming-windowed filter.
This is a lowpass, linear phase FIR filter with cutoff frequency Wn. Wn is a number
between 0 and 1, where 1 corresponds to the Nyquist frequency, half the sampling
frequency. (Unlike other methods, here Wn corresponds to the 6 dB point.) For a
highpass filter, simply append the string 'high' to the function's parameter list. For a
bandpass or bandstop filter, specify Wn as a two-element vector containing the passband
edge frequencies; append the string 'stop' for the bandstop configuration.
b = fir1(n,Wn,window) uses the window specified in column vector window for the
design. The vector window must be n+1 elements long. If you do not specify a window,
fir1 applies a Hamming window.
Kaiser Window Order Estimation. The kaiserord function estimates the filter order, cutoff
frequency, and Kaiser window beta parameter needed to meet a given set of
specifications. Given a vector of frequency band edges and a corresponding vector of
magnitudes, as well as maximum allowable ripple, kaiserord returns appropriate input
parameters for the fir1 function.

- Advantages:
Compared to IIR filters, FIR filters offer the following advantages:
They can easily be designed to be "linear phase" (and usually are). Put simply,
linear-phase filters delay the input signal but dont distort its phase.
They are simple to implement. On most DSP microprocessors, the FIR calculation
can be done by looping a single instruction.


38

They are suited to multi-rate applications. By multi-rate, we mean either
"decimation" (reducing the sampling rate), "interpolation" (increasing the
sampling rate), or both. Whether decimating or interpolating, the use of FIR filters
allows some of the calculations to be omitted, thus providing an important
computational efficiency. In contrast, if IIR filters are used, each output must be
individually calculated, even if it that output will discarded (so the feedback will
be incorporated into the filter).
They have desirable numeric properties. In practice, all DSP filters must be
implemented using finite-precision arithmetic, that is, a limited number of bits.
The use of finite-precision arithmetic in IIR filters can cause significant problems
due to the use of feedback, but FIR filters without feedback can usually be
implemented using fewer bits, and the designer has fewer practical problems to
solve related to non-ideal arithmetic.
They can be implemented using fractional arithmetic. Unlike IIR filters, it is
always possible to implement a FIR filter using coefficients with magnitude of
less than 1.0. (The overall gain of the FIR filter can be adjusted at its output, if
desired.) This is an important consideration when using fixed-point DSP's,
because it makes the implementation much simpler.
- Disadvantages:
Compared to IIR filters, FIR filters sometimes have the disadvantage that they require
more memory and/or calculation to achieve a given filter response characteristic. Also,
certain responses are not practical to implement with FIR filters.
Applications:
In digital signal processing "filtering" is a common term that is applied to various
applications. Any operation performed to extract wanted information from a digital signal
is termed as filtering in general. A signal/data stored in memory contains lots of
information both wanted and unwanted. Wanted information may be "specific
information at a specific frequency" and unwanted info may be "the noise present in the


39

signal".

Filters have two uses: signal separation and signal restoration. Signal separation is needed
when a signal has been contaminated with interference, noise, or other signals. For
example, imagine a device for measuring the electrical activity of a baby's heart (ECG
signal) while still in the womb. The raw signal will likely be corrupted by the breathing
and heartbeat of the mother. A filter might be used to separate these signals so that they
can be individually analyzed.

In DSP, the digital filters are classified under many categories. One of the categories
classifies the filter into FIR filters (Finite Impulse Response) and IIR (Infinite Impulse
Response) filters. FIR and IIR filters are just two ways of implementing a filtering
method with difference in their design and some trade-offs.







40

Code and I mplementation :














function [QRS_wave]=QRSpulse(qrswidth,bpm,fs,amp)
%QRSpulse(qrswidth,bpm,fs,amp) artifical QRS pulse generator
% [QRS_wave]=QRSPULSE(fs,bpm,amp,qrswidth) returns a waveform vector.
% fs is the sample frequency, 100 to 500 Hz typical.
% bpm is the number of beats per minute.
% amp is the amplitude of the QRS in micro volts, 500 to 5000 uV.
% qrswidth in seconds, the time period between QRS.

%creates an artifical ECG signal

if (exist('fs') ~= 1) fs= 400;
end %default value, Hz
if (exist('bpm') ~= 1) bpm = 72;
end %default value, beats per minute
if (exist('amp') ~= 1) amp = 4000;
end %default value, micro volts
if (exist('qrswidth') ~= 1)
d = 0.120; %.07 to .120 seconds, QRS width
else
d=.08; %.07 to .120 seconds, QRS width
end %default value, micro volts
%things that can change
%d=0.070; %.07 to .120 seconds, QRS width
at=.0005; %amplitude of t-wave, 400 to 1200 uv

RR=(60/bpm); %RR interval
d1=0.4375*d;
d2=0.5*d;
d3=d-(d1+d2);
dt=0.180; %seconds
qt=0.35;
t_line1=0:1/fs:RR+1; QRS_wave=zeros( size(t_line1) );
deadspace=RR-qt;
if deadspace < 0
err_msg=['Bpm must be less than ' int2str(60/qt) '. '];
error(err_msg);
end

%Segment 1 bottom-top (Q-R)
t1=0; t2=t1+d1;
i_t1=time2index(t1,t_line1); i_t2=time2index(t2,t_line1);
bottom=0; top=0.875*amp;
QRS1=bottom:(top-bottom)/(i_t2-i_t1):top;
QRS_wave(i_t1:i_t2)=QRS1;
%Segment 2 top-bottom (R-?)
t1=t2; t2=t1+d2;
i_t1=time2index(t1,t_line1); i_t2=time2index(t2,t_line1);
bottom=-.125*amp;
QRS1=top:(bottom-top)/(i_t2-i_t1):bottom;
QRS_wave(i_t1:i_t2)=QRS1;
%Segment 3 bottom_top (?-S)
t1=t2; t2=t1+d3;
i_t1=time2index(t1,t_line1); i_t2=time2index(t2,t_line1);
top=0;
if (i_t2-i_t1 >0)
QRS1=bottom:(top-bottom)/(i_t2-i_t1):top;
QRS_wave(i_t1:i_t2)=QRS1;


41

Scream Shot of our outcome :




42







43








44


Stage IV: Peak Detection
This link to download the ECG processing demo: http://www.librow.com/cases/case-2
The demo package includes 5 files two MatLab scripts, two data samples and
description:
ecgdemo.m main MatLab script,
ecgdemowinmax.m window peak filter script,
ecgdemodata1.mat first sample ECG data file,
ecgdemodata2.mat second sample ECG data file,
readme.txt description.
I placed the .m and .mat files into the MATLAB workspace folder in order to run them. I
then typed ecgdemo in the command window to get the following:

0 2 4 6
x 10
4
0
0.5
1
1. Original ECG
0 2 4 6
x 10
4
0
0.5
1
2. FFT Filtered ECG
0 2 4 6
x 10
4
0
0.5
1
3. Filtered ECG - 1
st
Pass
0 2 4 6
x 10
4
0
0.5
1
4. Detected Peaks
0 2 4 6
x 10
4
0
0.5
1
5. Filtered ECG - 2
d
Pass
0 2 4 6
x 10
4
0
0.5
1
6. Detected Peaks - Finally


45




0 0.5 1 1.5 2 2.5 3 3.5 4 4.5
x 10
4
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
Comparative ECG R-Peak Detection Plot
0 0.5 1 1.5 2
x 10
4
0
0.5
1
1. Original ECG
0 0.5 1 1.5 2
x 10
4
0
0.5
1
2. FFT Filtered ECG
0 0.5 1 1.5 2
x 10
4
0
0.5
1
3. Filtered ECG - 1
st
Pass
0 0.5 1 1.5 2
x 10
4
0
0.5
1
4. Detected Peaks
0 0.5 1 1.5 2
x 10
4
0
0.5
1
5. Filtered ECG - 2
d
Pass
0 0.5 1 1.5 2
x 10
4
0
0.5
1
6. Detected Peaks - Finally


46


Codes:
ECGDEMO
% ECGDEMO ECG PROCESSING DEMONSTRATION - R-PEAKS DETECTION
%
% This file is a part of a package that contains 5 files:
%
% 1. ecgdemo.m - (this file) main script file;
% 2. ecgdemowinmax.m - window filter script file;
% 3. ecgdemodata1.mat - first ecg data sample;
% 4. ecgdemodata2.mat - second ecg data sample;
% 5. readme.txt - description.
%
% The package downloaded from http://www.librow.com
% To contact the author of the sample write to Sergey
Chernenko:
% S.Chernenko@librow.com
%
% To run the demo put
%
% ecgdemo.m;
% ecgdemowinmax.m;
% ecgdemodata1.mat;
% ecgdemodata2.mat
%
% in MatLab's "work" directory, run MatLab and type in
%
% >> ecgdemo
0 2000 4000 6000 8000 10000 12000 14000 16000 18000
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
Comparative ECG R-Peak Detection Plot


47

%
% The code is property of LIBROW
% You can use it on your own
% When utilizing credit LIBROW site

% We are processing two data samples to demonstrate two different
situations
for demo = 1:2:3
% Clear our variables
clear ecg samplingrate corrected filtered1 peaks1 filtered2 peaks2
fresult
% Load data sample
switch(demo)
case 1,
plotname = 'Sample 1';
load ecgdemodata1;
case 3,
plotname = 'Sample 2';
load ecgdemodata2;
end
% Remove lower frequencies
fresult=fft(ecg);
fresult(1 : round(length(fresult)*5/samplingrate))=0;
fresult(end - round(length(fresult)*5/samplingrate) : end)=0;
corrected=real(ifft(fresult));
% Filter - first pass
WinSize = floor(samplingrate * 571 / 1000);
if rem(WinSize,2)==0
WinSize = WinSize+1;
end
filtered1=ecgdemowinmax(corrected, WinSize);
% Scale ecg
peaks1=filtered1/(max(filtered1)/7);
% Filter by threshold filter
for data = 1:1:length(peaks1)
if peaks1(data) < 4
peaks1(data) = 0;
else
peaks1(data)=1;
end
end
positions=find(peaks1);
distance=positions(2)-positions(1);
for data=1:1:length(positions)-1
if positions(data+1)-positions(data)<distance
distance=positions(data+1)-positions(data);
end
end
% Optimize filter window size
QRdistance=floor(0.04*samplingrate);
if rem(QRdistance,2)==0
QRdistance=QRdistance+1;
end


48

WinSize=2*distance-QRdistance;
% Filter - second pass
filtered2=ecgdemowinmax(corrected, WinSize);
peaks2=filtered2;
for data=1:1:length(peaks2)
if peaks2(data)<4
peaks2(data)=0;
else
peaks2(data)=1;
end
end
% Create figure - stages of processing
figure(demo); set(demo, 'Name', strcat(plotname, ' - Processing
Stages'));
% Original input ECG data
subplot(3, 2, 1); plot((ecg-min(ecg))/(max(ecg)-min(ecg)));
title('\bf1. Original ECG'); ylim([-0.2 1.2]);
% ECG with removed low-frequency component
subplot(3, 2, 2); plot((corrected-min(corrected))/(max(corrected)-
min(corrected)));
title('\bf2. FFT Filtered ECG'); ylim([-0.2 1.2]);
% Filtered ECG (1-st pass) - filter has default window size
subplot(3, 2, 3); stem((filtered1-min(filtered1))/(max(filtered1)-
min(filtered1)));
title('\bf3. Filtered ECG - 1^{st} Pass'); ylim([0 1.4]);
% Detected peaks in filtered ECG
subplot(3, 2, 4); stem(peaks1);
title('\bf4. Detected Peaks'); ylim([0 1.4]);
% Filtered ECG (2-d pass) - now filter has optimized window size
subplot(3, 2, 5); stem((filtered2-min(filtered2))/(max(filtered2)-
min(filtered2)));
title('\bf5. Filtered ECG - 2^d Pass'); ylim([0 1.4]);
% Detected peaks - final result
subplot(3, 2, 6); stem(peaks2);
title('\bf6. Detected Peaks - Finally'); ylim([0 1.4]);
% Create figure - result
figure(demo+1); set(demo+1, 'Name', strcat(plotname, ' - Result'));
% Plotting ECG in green
plot((ecg-min(ecg))/(max(ecg)-min(ecg)), '-g'); title('\bf
Comparative ECG R-Peak Detection Plot');
% Show peaks in the same picture
hold on
% Stemming peaks in dashed black
stem(peaks2'.*((ecg-min(ecg))/(max(ecg)-min(ecg)))', ':k');
% Hold off the figure
hold off
end





49

% ECGDEMO ECG PROCESSING DEMONSTRATION - R-PEAKS DETECTION
%
% This file is a part of a package that contains 5 files:
%
% 1. ecgdemo.m - main script file;
% 2. ecgdemowinmax.m - (this file) window filter
script file;
% 3. ecgdemodata1.mat - first ecg data sample;
% 4. ecgdemodata2.mat - second ecg data sample;
% 5. readme.txt - description.
%
% The package downloaded from http://www.librow.com
% To contact the author of the sample write to Sergey
Chernenko:
% S.Chernenko@librow.com
%
% To run the demo put
%
% ecgdemo.m;
% ecgdemowinmax.m;
% ecgdemodata1.mat;
% ecgdemodata2.mat;
%
% in MatLab's "work" directory, run MatLab and type in
%
% >> ecgdemo
%
% The code is property of LIBROW
% You can use it on your own
% When utilizing credit LIBROW site

function Filtered=ecgdemowinmax(Original, WinSize)

WinHalfSize = floor(WinSize/2);
WinHalfSizePlus = WinHalfSize+1;
WinSizeSpec = WinSize-1;
FrontIterator = 1;
WinPos = WinHalfSize;
WinMaxPos = WinHalfSize;
WinMax = Original(1);
OutputIterator = 0;
for LengthCounter = 0:1:WinHalfSize-1
if Original(FrontIterator+1) > WinMax
WinMax = Original(FrontIterator+1);
WinMaxPos = WinHalfSizePlus + LengthCounter;
end
FrontIterator=FrontIterator+1;
end
if WinMaxPos == WinHalfSize
Filtered(OutputIterator+1)=WinMax;
else
Filtered(OutputIterator+1)=0;
end


50

OutputIterator = OutputIterator+1;
for LengthCounter = 0:1:WinHalfSize-1
if Original(FrontIterator+1)>WinMax
WinMax=Original(FrontIterator+1);
WinMaxPos=WinSizeSpec;
else
WinMaxPos=WinMaxPos-1;
end
if WinMaxPos == WinHalfSize
Filtered(OutputIterator+1)=WinMax;
else
Filtered(OutputIterator+1)=0;
end
FrontIterator = FrontIterator+1;
OutputIterator = OutputIterator+1;
end
for FrontIterator=FrontIterator:1:length(Original)-1
if Original(FrontIterator+1)>WinMax
WinMax=Original(FrontIterator+1);
WinMaxPos=WinSizeSpec;
else
WinMaxPos=WinMaxPos-1;
if WinMaxPos < 0
WinIterator = FrontIterator-WinSizeSpec;
WinMax = Original(WinIterator+1);
WinMaxPos = 0;
WinPos=0;
for WinIterator = WinIterator:1:FrontIterator
if Original(WinIterator+1)>WinMax
WinMax = Original(WinIterator+1);
WinMaxPos = WinPos;
end
WinPos=WinPos+1;
end
end
end
if WinMaxPos==WinHalfSize
Filtered(OutputIterator+1)=WinMax;
else
Filtered(OutputIterator+1)=0;
end
OutputIterator=OutputIterator+1;
end
WinIterator = WinIterator-1;
WinMaxPos = WinMaxPos-1;
for LengthCounter=1:1:WinHalfSizePlus-1
if WinMaxPos<0
WinIterator=length(Original)-WinSize+LengthCounter;
WinMax=Original(WinIterator+1);
WinMaxPos=0;
WinPos=1;
for WinIterator=WinIterator+1:1:length(Original)-1
if Original(WinIterator+1)>WinMax


51

WinMax=Original(WinIterator+1);
WinMaxPos=WinPos;
end
WinPos=WinPos+1;
end
end
if WinMaxPos==WinHalfSize
Filtered(OutputIterator+1)=WinMax;
else
Filtered(OutputIterator+1)=0;
end
FrontIterator=FrontIterator-1;
WinMaxPos=WinMaxPos-1;
OutputIterator=OutputIterator+1;
end

Stage IIV: Displaying the ECG Signal:
Literature Review:
According to T. Luk and O. Ondrek paper, a model for processing ECG signal,
for analyzing respiratory sinus arrhythmia (RSA) and heart rate variability (HRV) was
described. The model was implemented using Simulink and it had to work as real-time
application for biofeedback purposes. ECG signal processing in Simulink results also in
heart rate (HR) signal. Another study shows how to Display an ECG signal using matlab
by uploading the ECG text file and then plot it. ((n.d.).Retrieved from
http://www.youtube.com/watch?v=3tdumuwHgxc).








>>sig = load('ecg.txt');
>>plot(sig)
>>xlabel('samples');
>>ylabel('electric activity');
>>title('ECG signal sample');


52








This demo shows how to set up Acquiring Data with a Sound Card
Description:
The MATLAB code is set to read analog signal like ECG coming from the sound card,
using a microphone which work as a sensor, to display the data in real time or when the
acquisition is finished. The real- time visualization is better for monitoring.
A typical data acquisition consists of four phases:


53

1. Initialization: Creating a device object.
2. Configuration: Adding channels and controlling acquisition behavior with
properties.
3. Execution: Starting the device object and acquiring or sending data.
4. Termination: Deleting the device object.
MATLAB code:



54


Output:


55


Description for SIMULINK module:
Analog Input block is used to acquire the live signal from a data acquisition device into
Simulink. In this model, the sound card is selected as the input device in the Analog Input
block. The Simulink model implements a spectral analysis as shown below:






Simulink model


56

Output:
Getting the sound of a signal:
Record Audio
To record data from an audio input device (such as a microphone connected to the
system) for processing in MATLAB
:

1. Create an audiorecorder object.
2. Call the record or recordblocking method.
3. Create a numeric array corresponding to the signal data using
the getaudiodata method .





57

Code:









Play Audio :
For simple playback using a single function call, use sound or soundsc. For example,
load a sample MAT-file that contains signal and sample rate data, and listen to the audio:







recObj = audiorecorder;
disp('Start speaking.')
recordblocking(recObj, 5);
disp('End of Recording.');
% Play back the recording.
play(recObj);
% Store data in double-precision array.
myRecording = getaudiodata(recObj);
% Plot the samples.
plot(myRecording);

loadchirp.mat;
sound(y, Fs);



58

Project conclusion:
In conclusion, this project examines ECG Extraction technique & Matlab
implementation Design. After finishing all the process phases, it will be
tested on a group of people. As a future work, wireless should be taken
into consideration.
Project Closing:
Successful demonstration and Implimentation of working project
Date: 15
th
, May, 2013

Project Bibliography:
- Luk, T., &Ondrek, Q. (n.d.). Using simulink and matlab for real-time ecg
signal processing. Retrieved from
http://www2.humusoft.cz/www/papers/matlab12/050_Lukac.pdf
- (n.d.). Retrieved from http://www.youtube.com/watch?v=3tdumuwHgxc
- (n.d.). Retrieved from
https://www.mathworks.com/products/daq/supported/sound-cards.html
- (n.d.). Retrieved from
http://www.mathworks.se/matlabcentral/fileexchange/25898-real-time-daq-and-
sound-card-visualization/content/daq_sound_card.m
- (n.d.). Retrieved from
http://www.mathworks.com/matlabcentral/fileexchange/12524 \
- http://www.nickgillian.com/
- http://www2.it.lut.fi/kurssit/07-08/CT20A6100/seminars/Median_Filtering.pdf


59

- http://www.slideshare.net/SaraGh1/savedfiles?s_title=butterworth-filter-
design&user_login=SushantShankar
- http://www.mathworks.com/matlabcentral/fileexchange/6170-smooth-
differentiation/content/smooth_diff.m
- http://en.wikipedia.org/wiki/Moving_average#Weighted_moving_average
- http://www.digitalmetrology.com/SurfaceFinishIn3Steps.htm
- http://help.scilab.org/docs/5.4.0/fr_FR/DesignEllipticFilter.html
- http://www.scienceprog.com/tag/fir-filter/
- http://cdn.intechopen.com/pdfs/16116/InTech-
Adaptive_noise_removal_of_ecg_signal_based_on_ensemble_empirical_mode_d
ecomposition.pdf
- http://en.wikipedia.org/wiki/Driven_right_leg_circuit
-

Spring 2013, ECE210L

1



Saving Lives: Design and Implementation of ECG
System
Dr. Nema Salem et al.
1


Goals and Objectives
Imagine a patient in a bed, forced to lie still due to the medical equipment
monitoring him/her. Also, thinking about the nurse's frustration when a sensor gets
pulled off of the patient by a wire getting snagged as the patient tries to find a more
comfortable position. Not only this is frustrating, but also the time required for the
nurse to come and reattach the sensor while running between a patient and
another. The inconvenience of sensors wired directly to bedside monitoring
equipment has been apparent since electronic monitoring of patients was developed,
see figure 1.
Figure 1: Traditional ECG System 1
For this reason, wireless sensors have become an exciting research area for
Electronic Engineers. Although partial wireless solutions have already been
proposed, none offer a complete wireless solution which indicates a huge potential
market for such a system.


Our ultimate goal is to build a Wireless Patient Monitoring ECG System. Designing and
building a completely wireless ECG sensor system will provide an efficient means for
medical staff to monitor larger number of patients without requiring more staff. It
also provides a more comfortable means for patients to be monitored. This project

1
19 students of class ECE210L, 2
nd
level of electronics, participated in this project; Spring 2013

Spring 2013, ECE210L

2

also has future development as providing a solution to in-home monitoring of patients
and allowing doctors to monitor patients from their offices.
There are many phases of design and implementation to achieve this goal which
can't be done in one semester. During the spring 2013 semester, the students of
ECE210L course "second level of electronics, titled: Introduction to electronics
(Integrated circuits)" started the first phase of the project.

Community Service
Some of the physiological signals are
Electrocardiogram ECG which can be used
to monitoring heart activity, an
Electromyogram EMG for monitoring the
muscle activity and an
Electroencephalogram EEG for monitoring
brain electrical activity. Among these
physiological signal ECG and heart rate are
the most important to be measured and are
used very widely as a clinical tool to
determine the rate and regularity of
heartbeats as well as the size and the
position of the chambers, the presence of any damage to the heart, and the effects of
the drugs or devices used to regulate the heart.
World Health Organization, WHO, estimated revealed that each year more than 16
million people around the world died of cardiovascular disease where this figure
represents 30% of the global death toll.
We consider this project is a contribution to community as monitoring the heart
condition especially for people with health problems is vital. If such people faced a
problem, the device will automatically communicate with the patient's doctor or to a
local hospital or to the ambulance center. As femto seconds affect a lot in people's
life, we believe this device under construction can help in saving lives.

From another point of view, training Electrical Engineering Students in such a
project is great in preparing excellent Engineer who can enrich and provide the
industry by experts, and inventors at the same time.


Industrial Partner(s)
As this project depends on medical information, some of my students communicate
with the following partners:
1. Two doctors working at King Fahad Hospital (KFH)
2. Students at the Medical School of King Abdulaziz University (KAU):
a. Dr. Ibrahim Al-Andijani (finished his B.Sc. from the medical school)
b. Dr. Abeer Khoja (shes graduated from the medical school but she is
doing her training).
Spring 2013, ECE210L

3

3. Medical Student at Alexandria University: D. Sherine Fathi Al Najar

Organization of Team Work
All the 19 class students participated in this first phase of the project. They have
been divided into two teams and each team has been divided into groups. Each
group has a leader which is selected by the students' members themselves and is
responsible of one task. The groups' leaders communicate with the course instructor
and reporting to her. To achieve efficient communication, there is a weekly meeting.
The meeting minutes are recorded and are sent out to the group via email/Black
Board. In the meetings, they discuss, present the achievements and the instructor
guides them to solve problems. Assigning tasks are based on individual strengths
and ability. Since all students are in the learning experience phase of their lives,
everyone shared in all tasks but focused more on one.
The implementation of the ECG system has been done by two ways: software and
hardware. Each method includes many modules to be built. Each team focused on a
method. Due to the interdependency of each module, teams communicated to
exchange information.

First Group Task: ECG Acquisition
The first group is focused in building an electronic circuit based instrumentation
amplifier to extract the weak ECG signal 1.5 mV from the human body. Three
leads are used to extract this signal as in the following figure at the left. They built
the circuit and tested it by a simulator MULTISIM, shown in the following figure at
the right. Then, they ordered the components from the U.S.A and proceeded in
building the circuit. They captured ECG from individuals.


Spring 2013, ECE210L

4

Second Group Task: Interfacing with PC via Sound Card
The second group of students focused on writing an algorithm using MATLAB
commands to interface the acquired ECG signal into the Personal Computer so
signal processing can start. The same group also focused on how to display ECG
signal before and after processing and to hear the heart rhythm.
Duties of the Software Team:
Recorded ECG is corrupted by different types of noise causing problems for analysis
and interpretation of ECG signal. The ECG signal which carries very important
information is also weak in amplitude, see figure. For this purpose the ECG should
be made free of noises and should be amplified at different levels of processing.

This team started the phase of processing the captured noisy and weak ECG signal
by using the MATLAB. The main modules are the pre-amplification, noise removal
(filtration), amplification; peak detection algorithm is followed by a heart rate
calculation, and displaying. The heart rhythm is heard via the PC- sound card as
well. The students tried several noise removal algorithms as shown in the following
figure.
Spring 2013, ECE210L

5


Spring 2013, ECE210L

6

0 2000 4000 6000 8000 10000 12000 14000 16000 18000
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
Comparative ECG R-Peak Detection Plot
The students wrote a MATLAB algorithm detecting the R-R peaks in the ECG signal
as a pre step of calculating the heart pulse beating rate. Their result is shown in the
following figure.
The last step of calculating the beating pulse rate; displaying and hearing also been
accomplished.
Duties of the Hardware Team:
This team focused on finding the efficient design and implementation of a complete
ECG system starting from the signal acquisition from the human body till displaying
both of the ECG signal and the rate of heart beats as well. Also, hearing the heart's
rhythm is a goal.
The initial phase is the signal extraction using electrodes and transmitted via wires
to a patient protection system. A multiplexer is then used to select one of the 3 leads
to process and display. The initial extracted signal is feeble (in the range of
milliVolts) and contains a lot of noise in comparison. The signal is passed through a
high pass filter (cut off frequency 40 Hz) and then an instrumentation amplifier
and finally a low pass filter (cut off frequency 500 mHz). Any noise in the signal
from the body and external sources is filtered (using the two filters) and the signal is
amplified using the instrumentation amplifier and prior to the second filter another
operation amplifier is used for further amplification. The amplifiers (instrumentation
amplifier and operation amplifier) are selected based on availability.
This filtered and amplified signal is then passed to two separate independent output
systems: a peak detector circuit and an oscilloscope. The peak detector is designed
to only detect the peaks, by using a comparator, whereby a reference voltage is set.
The comparator compares the input signal voltage with the reference voltage. If the
input signal voltage is greater than or equal to the reference voltage, the circuit gives
a high voltage (logic 1) forming a square wave. This square wave is given as input to
a counter that counts the number of peaks for a specific period of time, and then
inputs this value to a multiplier which multiplies the value by a factor to get the
number of heart pulses in one minute giving us the pulse rate in beats per minute.
The pulse rate is displayed on a set of seven-segment displays and the ECG wave is
displayed on the oscilloscope.
Spring 2013, ECE210L

7

The block diagram of the overall system is shown in the following figure.









Before building any of these modules, they simulated the circuits first by MULTISIM.
Parts of their results are shown in the following figures.
Simulation of the instrumentation amplifier and Screen Shot of their Bread Board are:

Simulation of the Operational Amplifier Circuit and result are:

Amplification
System
Noise Filter
Sytem
Displays and
Outputs
Signal Extraction
Spring 2013, ECE210L

8


Filter circuit and simulation results:
Spring 2013, ECE210L

9


Simulation Result obtained after filtration is:





Simulation of Peak Detector Circuit and Screen Shot of Bread Board are:
Spring 2013, ECE210L

11

The display stage also been accomplished successfully.
Problems and Obstacles:
The unavailability of the required components in KSA to implement the system is
one of the main problems the students faced. The students had to order from abroad
which wasted time and cost a lot as well.
The available simulator, MULTISIM, was not adequate as there's a lack of its
libraries.
The students registered in many courses, more than 15 CR, affect their progress in
the project.
Recommendations:
Purchasing a more advanced software package for simulation as LabView;
Purchasing components and devices needed before starting the project
especially in the coming phases as more advanced and complicated
components are essential
Achievements:
At the end of the semester the students did the following:
1. Document their work in two reports and submitted to the instructor.
2. Finalize their project in a professional way.
Spring 2013, ECE210L

11

3. Do two posters and a brochure.
4. Present their achievements, discuss the problems they faced and recommend
future work, power points.
5. Write at least one paper to be published in a conference (not yet)
6. Share in undergraduate competitions and awarded certificate and money:
a. Undergraduate Research at Effat University and they got the best
poster.
b. Project Fair of the College of Engineering at Effat University and they
won the 3
rd
place.

Students' Evaluations:
Students' performance and project's output are be evaluated as follows:
1. Team Work (10%):
Based on peer evaluation, observations of group meetings and presentations,
fulfillment of responsibilities and Team morale and cohesiveness
2. Implementation (50%):
Either software or hardware and which is the core of the project.
3. Presentation (15%):
Based on the visual aids, oral presentation, and body language
4. Written Report (15%):
It should be well organized and clearly written. Words are chosen that precisely
express the intended meaning and support reader comprehension. Diagrams
are used to enhance and clarify ideas. Sentences are grammatical and free from
spelling errors.
5. Poster (10%):
Generally, it should be attractive and have creativity. It should include:
i. Title, course title and code, students' names, advisor's
name and semester.
ii. Introduction
iii. Materials and methods
iv. Literature cites
v. Figures
vi. Results
vii. Conclusion
viii. Acknowledgment
ix. Future work

The Possibility of Obtaining a Patent for This Project in the Long Term:
The project's core is not new. Many researchers started working in this idea many
years ago and still in progress. The work in this idea is still in run to develop a
Spring 2013, ECE210L

12

reliable, cheap, simple, light weight, wireless device, which everyone can have and
easily can use.
I hope to have a good idea of implementing such a device to help people and save
lives. By this, the project might be patent.
Attachments:
1. CV of the instructor Dr. Nema Salem
2. Syllabus of the course ECE210L
3. Students List with Their tasks in this project
4. Report of the first team; software task
5. Report of the second team; hardware task
6. Brochure done by the hardware team
7. Power point slides of the two teams
8. Posters of the two teams
9. Copies of the certificates the students awarded from the RCI and the project
fair at Effat University.
References
[1] National Heart, Lung and Blood Institute. (2012): Understanding the Hearts Electrical System and
EKG Results. Retrieved from http://www.nhlbi.nih.gov/health/health-
topics/topics/hb/understanding.html
[2] STMicroelectronics. (2001): General Purpose Single Operational Amplifier Datasheet. Retrieved
from http://www.datasheetcatalog.org/datasheet/stmicroelectronics/5304.pdf
[3] LG Semicon Co. Ltd. (2013): Dual 4-line to 1-line Data Selectors/Multiplexers. Retrieved from
http://www.datasheetarchive.com/GD74LS153-datasheet.html
[4] Texas Instruments. (2011): ADS1258 24 Bit, Fast Channel Cycling Delta-Sigma ADC. Retrieved
from http://www.ti.com/product/ads1258

[5] Nursecom Educational Technologies. (2004): An ECG Primer.
[6] Donald, N. (2010). Microelectronics: Circuit Analysis and Design (4th Ed.). New York:
McGraw-Hill.
[7] Paulus, D., Meier, T. (2009): ECG Amplifier. Retrieved from http://www.mayr.informatik.tu-
uenchen.de/konferenzen/MB-Jass09/courses/1/Paulus.pdf

[8] Texas Instruments Incorporated. (2005): Getting The Most out of Your Instrumentation Amplifier
Design. Retrieved from http://www.ti.com/lit/an/slyt226/slyt226.pdf
Spring 2013, ECE210L

13

[9] Texas Instruments (1998): LM741 Operational Amplifier. Retrieved from
http://www.ti.com/lit/ds/symlink/lm741.pdf

[10] Townsend, N. (2001): Medical Electronics. Retrieved from
www.robots.ox.ac.uk/~neil/teaching/med_elecwww.robots.ox.ac.uk/~neil/teaching/med_eleca

[11] Clayton, G., & Winder, S. (2003): Operational Amplifiers (5th Ed.). England: Newens.
[12] Priemer, R. (1991): Introductory Signal Processing; World Scientific.
[13] Roy, C. D., & Jain, S. (2003): Comparators and Waveforms Generators. In Linear integrated
circuits. New Delhi: New Age International.
[14] Educational Publishing for Design & Technology. (2013): 4511 BCD to 7-segment Decoder.
Doctronics. Retrieved from http://www.doctronics.co.uk/4511.htm
[15] Computer-Related Circuit. (2013): 8-bit Binary to 3-digit Decimal Display Decoder For 8-bit
Microprocessor Systems With 256 by 4 PROM three 7-segment Decoder Drivers With 9374 Input
Latches and Two Gates. Retrieved from http://www.seekic.com/circuit_diagram/Computer-
Related_Circuit/8_bit_binary_to_3_digit_decimal_display_decoder_for_8_bit_microprocessor_system
s_with_256_by_4_PROM_three_7_segment_decoder_drivers_with_9374_input_latches_and_two_gate
s.html
[16] Tech. Philips Semiconductors; (1995): BCD to 7-segment Latch/decoder/driver. Retrieved from
http://www.uib.es/depart/dfs/GTE/staff/jfont/InstrETT/hef4511b.pdf
[17] Vishay Semiconductors. (2013): Standard 7-Segment Display 13 Mm Tech. no. 83126.
Retrieved from http://www.vishay.com/docs/83126/83126.pdf

18. Luk, T., &Ondrek, Q. (n.d.). Using simulink and matlab for real-time ecg signal processing.
Retrieved from http://www2.humusoft.cz/www/papers/matlab12/050_Lukac.pdf
19. (n.d.). Retrieved from http://www.youtube.com/watch?v=3tdumuwHgxc
20. (n.d.). Retrieved from https://www.mathworks.com/products/daq/supported/sound-cards.html
21. (n.d.). Retrieved from http://www.mathworks.se/matlabcentral/fileexchange/25898-real-time-daq-
and-sound-card-visualization/content/daq_sound_card.m
22. (n.d.). Retrieved from http://www.mathworks.com/matlabcentral/fileexchange/12524 \
23. http://www.nickgillian.com/
24. http://www2.it.lut.fi/kurssit/07-08/CT20A6100/seminars/Median_Filtering.pdf
25. http://www.slideshare.net/SaraGh1/savedfiles?s_title=butterworth-filter-
design&user_login=SushantShankar
26. http://www.mathworks.com/matlabcentral/fileexchange/6170-smooth-
differentiation/content/smooth_diff.m
27. http://en.wikipedia.org/wiki/Moving_average#Weighted_moving_average
Spring 2013, ECE210L

14

28. http://www.digitalmetrology.com/SurfaceFinishIn3Steps.htm
29. http://help.scilab.org/docs/5.4.0/fr_FR/DesignEllipticFilter.html
30. http://www.scienceprog.com/tag/fir-filter/
31. http://cdn.intechopen.com/pdfs/16116/InTech-
Adaptive_noise_removal_of_ecg_signal_based_on_ensemble_empirical_mode_decomposition.pdf
32. http://en.wikipedia.org/wiki/Driven_right_leg_circuit


Hardware Design and
Implementation of an
Electrocardiogram
System
Karima Khandaker, Israa Al -Qassas, Reemaz Hetaimish, Haneen
Mohammed, Danah Nour, Lina Babsail, Sarah Al -Harthey

Course: Introduction to Electronic
(Integrated Circuits) - ECE210L
Supervisor: Dr. Nema Salem
Department: Electrical and Computer Engineering
Date of Submission: 15
th
May 2013


Page | I




Abstract
According to the Encyclopaedia of the 20th Century Technology, "the
electrocardiogram (ECG or EKG) is a graphic measurement of the electrical activity of
the heart produced by an electrocardiograph, or ECG machine." The ECG is used to
monitor the electrical activity of the heart which is extracted from the human body in
the form of analog signals.
This project aims to represent efficient design and implementation of a
complete ECG system starting from the signal acquisition from the human body till
displaying both of the ECG signals and the rate of heart beats as well.
The initial phase is the signal extraction using electrodes and transmitted via
wires to a patient protection system. A multiplexer is then used to select one of the 3
leads to process and display. The initial extracted signal is feeble (in the range of
millivolts) and contains a lot of noise in comparison to the part of the signal we need.
The signal is passed through a band pass filter and then an instrumentation amplifier.
Since the extracted signal from the human body is very weak to be fed to the
components of the circuit, it has to be amplified further. ECG signal levels are very
small, so it is necessary to use filtering to remove a wide range of noise. A filter works
by removing or reducing frequencies where noise occurs, while allowing the signal
frequency through. The amplifiers (instrumentation amplifier and operation amplifier)
are selected based on availability. Although the instrumentation amplifier has been
constructed using operation amplifiers at this stage, it is expected to be replaced by
the INA118.
Page | II

This filtered and amplified signal is then fed to a peak detector circuit. The peak
detector is designed to only detect the peaks, by using a comparator, whereby a
reference voltage is set. The comparator compares the input signal voltage with the
reference voltage. If the input signal voltage is greater than or equal to the reference
voltage, the circuit gives a high voltage (logic 1) forming a square wave. This square
wave is given as input to a counter that counts the number of peaks for a specific
period of time, and then inputs this value to a multiplier which multiplies the value by
a factor to get the number of heart pulses in one minute giving us the pulse rate in
beats per minute.
The display segment of the project consists of two important outputs which will
help the physician to get a clear view of the heart beat status and will help him/her to
indicate any problems occurring with the patient's heart. The first output is the ECG
wave displayed on the oscilloscope and the second output is the heartbeat count on
seven-segment displays.


Page | III




Table of Contents
1.0 List of Figures ........................................................................................................................ 1
2.0 Introduction .......................................................................................................................... 2
2.1 Medical Background ................................................................................................................. 5
3.0 Simulation Results ............................................................................................................... 8
3.1 Amplifier Circuit Simulations ................................................................................................ 8
3.2 Filter Circuit Simulations ...................................................................................................... 10
3.3 Peak Detector Circuit Simulations..................................................................................... 13
4.0 Hardware Description ...................................................................................................... 14
4.1 Signal Extraction ...................................................................................................................... 15
4.2 Amplification System ............................................................................................................. 16
4.3 Noise Filter System.................................................................................................................. 21
4.4 Peak Detector System ............................................................................................................ 24
4.5 Displays and Outputs .............................................................................................................. 28
5.0 Discussion ............................................................................................................................ 33
6.0 Conclusion ............................................................................................................................ 35
7.0 References............................................................................................................................ 36
Page | 1




1.0 List of Figures
2.0 Standard Setup of ECG System Used for Monitoring ......................................................... 2
2.1 PQRST Wave ...................................................................................................................................... 6
3.0 Theoretical Measurements of the Instrumentation Amplifier Using Multisim ....... 8
3.1 Operational Amplifier Simulation Circuit .............................................................................. 9
3.2 Operational Amplifier Simulation Results ............................................................................. 9
3.3 Circuit Design of the Filters ....................................................................................................... 10
3.4 Simulation Results Obtained After Filtration at Output at 0.5Hz ............................... 11
3.5 Simulation Results Obtained After Filtration at Output at 175Hz .............................. 11
3.6 Simulation Results Obtained After Filtration at Output at 291Hz .............................. 12
3.7 Simulation Results Obtained After Filtration at Maximum Output ............................ 12
3.8 Complete Circuit Design for Peak Detector Using Multisim ......................................... 13
4.0 Overall ECG System Block Diagram ........................................................................................ 14
4.10 Position of 3 leads Forming Einthovens Triangle ......................................................... 15
4.11 GD74LS153 Multiplexer Pin Diagram ................................................................................. 16
4.20 Instrumentation Amplifier ...................................................................................................... 17
4.21 Instrumentation Amplifier ...................................................................................................... 18
4.22 Pinout Diagram of LM741 ........................................................................................................ 19
4.23 Hardware Design of Instrumentation Amplifier ............................................................. 19
4.24 UA741 Operational Amplifier Pin Connections ............................................................... 20
4.40 QRS Wave to Count Peaks ........................................................................................................ 25
4.41 Implemented Peak Detector Circuit .................................................................................... 28
4.50 HeartRate ....................................................................................................................................... 29
4.52 4511: BCD to 7-Segment Decoder Driver .......................................................................... 29
4.53 7-Segment Display ...................................................................................................................... 29
4.54 Three 7-segment Displays Connected in a Circuit ......................................................... 30





Page | 2




2.0 Introduction
The Electrocardiogram (ECG or EKG) is used to measure the electrical activity of
the heart over a certain period of time depending on the purpose of taking the reading.
It can be used to either monitor over longer periods of time or diagnostic purposes to
analyze the status of the heart at a certain time.

Fig. 2.0 Standard Setup of ECG System Used for Monitoring
The ECG machine uses a set of electrodes that are attached to the surface of the
skin and the numbers of electrodes that are used vary depending on the use of the ECG.
The number of electrodes varies from the number of leads in some cases like the 12-
lead ECG that actually uses 10 electrodes (wires). The number of leads indicates the
Page | 3

different angular views of the heart and not the number of wires (which is depending on
the number of physical electrodes). Although in majority of hospitals, priority is given to
the 12-lead ECG because cardiologists consider it a more detailed view of the heart
from different angles, we have decided to use 3 electrodes (3 leads) for our research.
In addition, safety should be maintained as well by using the driven rightleg
circuitry to prevent any leaked current from travelling back into the body via the
electrodes. For further safety measures all the parts can be covered by rubber to
prevent any effect of the electromagnetic field.
The extracted signal from the human body is very weak to be fed to the
components of the circuit. For this reason, the signal will need to be amplified before it
can be processed further. This can be achieved by using a special type of amplifiers
called an instrumentation amplifier. An instrumentation amplifier will not only amplify
the signal but also reject some of the noise that the extracted signal contains.
Once amplified, the signal is fed to the ECG noise filters. Ideally, a filter should
remove noise without affecting the signal we are interested in. Unfortunately, this is
rarely possible because the signal and noise may share the same frequencies. This noise
may come from an unstable dc offset from electrode/body interface, muscle noise,
mains hum (50/60Hz), electrical noise from equipment in the environment, and from
within the ECG equipment itself, such as from internal ac/dc converters. In most ECGs, a
low-pass filter and a high-pass filter are used, but for this research we have
implemented a band-pass filtee instead, that ranges from 0.5 to 150 Hz. Since a low-
pass and a high-pass filter connected in series forms a band-pass filter, the two filters
can easily be replaced by a single band-pass filter.
Page | 4

General attributes of any signal include the frequency, time period and
amplitude. Frequency is the number of cycles a periodic signal repeats itself in 1 second.
Time period is the time taken for a periodic signal to complete one complete cycle.
Amplitude is the change of the voltage of signal with respect to time. Peak-to-peak
amplitude is difference between the highest amplitude value and the lowest amplitude
value. Peak amplitude is half the peak-to-peak value. "A signal as referred to
in communication systems, signal processing, and electrical engineering is a function
that conveys information about the behavior or attributes of some phenomenon."
Priemer (1991).
Peak detection is the process of identifying and counting the number of peaks in
a signal. These peaks can either be of positive or negative values. According to Web's
definition, it is "an acquisition mode for digital oscilloscopes that lets you see the
extremes of a signal." The phenomenon that will be discussed in this project is related
to the signals coming out of the human body which represent human heart beat.
The objectives of the peak detection was to design and create a module that will
take the amplified, filtered signals and calculate the heart rate from a count of the
number of beats over a period of time. These beats are represented by the peaks of the
signal.
When considering the output of ECG systems, there will be two different types
of displays: the analog ECG signal displayed on the oscilloscope to allow the doctor to
do a preliminary diagnosis or monitor the status of the patients heart using the
heartbeat rate displayed on the output of the peak detector circuit on seven-segment
displays.
Page | 5

Each of the two outputs acquire two circuits; the sound output is extracted using
audio amplifier and the number of heart beats are counted and displayed using 3 digits
7 segment display, traditionally , the wave of the heart beat is shown but since a
hardware system is constructed in this project, no communication nor programming is
used.

2.1 Medical Background
To better understand the signal extraction it is important to know how the signal
is generated in the heart as well as the meaning and importance of the displayed PQRST
wave on the ECG. The PQRST wave consists of the P wave, the QRS complex and the T
wave and represents one complete heartbeat displayed on the ECG.
With each heartbeat, an electrical signal is generated in a group of cells in the
upper right chamber or right atrium of the heart. This signal passes through the two
upper chambers (right and left atria) causing them to contract which in turn causes the
blood to move in the lower chambers of the heart called ventricles. This electrical signal
passing through the atria is shown as the P Wave on the ECG. As the signal passes from
the atria to the ventricles it slows down to allow the ventricles to fill up with blood and
this is shown as the flat region between the P and Q waves.
The signal then distributes across the ventricles instigating them to contract and
pump blood to the various parts of the body. This section causes the QRS waves on the
ECG. Once the ventricles return to their normal state after this, it can be seen on the
ECG as the T wave in Fig 2.1.
Page | 6


Fig. 2.1 PQRST Wave
The ECG allows the medical staff to deduce different conditions based on the
deflection from the general expected ECG waveform. It may be based on the amplitude,
shape, interval lengths or even the absence of expected waves. Table 2.0 shows some
examples of comparisons between normal (expected) data and abnormal data and the
conclusions that can be drawn in each case.
Page | 7


Table 2.0 Comparison and Deductions Based on ECG





Page | 8




3.0 Simulation Results
3.1 Amplifier Circuit Simulations
Beginning with the amplifier circuits, the figures below show the simulation
procedures and results and following them are discussions regarding the simulations
and any assumptions made.









Fig. 3.0 Theoretical Measurements of the Instrumentation Amplifier Using Multisim

Selecting the supply voltage to be 5V and assuming the input (the voltage of the
extracted signal) is 0.5 mV (0.3535 mV rms) and the frequency is 60 Hz, the output
voltage was increased to 979.381 mV.

Page | 9




Fig. 3.1 Operational Amplifier Simulation Circuit




Fig. 3.2 Operational Amplifier Simulation Results
Page | 10

The gain was confirmed and tested using the simulation (Multisim) and the
resistances selected. R
1
(R
f
, feedback resistance) and R
2
were selected as 90 k and 10
k respectively. The input voltage was calculated as 0.177 V
rms
since the V
p-p
is expected
to be 0.5V. The output voltage is then V
p-p
= 1.25 V. This is the amplitude of the final
output voltage as well since there is no further amplification in the system.
The following shows how the resistances were chosen:


The following shows how the gain was calculated from the simulation results:



3.2 Filter Circuit Simulations


Fig. 3.3 Circuit Design of the Filters
Page | 11




Fig. 3.4 Simulation Results Obtained After filtration at Output at 0.5Hz


Fig. 3.5 Simulation Results Obtained After Filtration at Output at 175Hz

Page | 12


Fig. 3.6 Simulation Results Obtained After Filtration At Output At 291Hz


Fig. 3.7 Simulation Results Obtained After Filtration at Maximum Output




Page | 13


3.3 Peak Detector Circuit Simulations
Fig. 3.8: The complete circuit design for the peak detector using Multisim










Page | 14




4.0 Hardware Description



Fig. 4.0 Overall ECG System Block Diagram
The overall system of the ECG can be divided into the above shown 5 subsystems:
Signal Extraction
o Electrodes
o Patient Protection
o Multiplexer
Noise Filter
Signal Extraction
Amplification
System
Noise Filter
Sytem
Displays and
Outputs
Page | 15

Amplification
o Instrumentation Amplifier
o Further Amplification
Peak Detector
o To calculate heart rate
Output and Displays
o From Peak Detector Circuit Seven Segment Displays
o ECG display Oscilloscope

4.1 Signal Extraction
The 3 lead wire ECG System have three colored wires that connect to three
electrodes forming the Einthovens triangle as shown in Fig. 4.10. This system provides
three views of the heart.

Fig. 4.10 Position Of 3 Leads Forming Einthovens Triangle

Page | 16

The multiplexer that is used to select the lead to be processed is a Dual 4-Line To
1-Line Data Selector/Multiplexer, GD74LS153. There are three leads and one needs to
be selected using pin 2. The output from each of the leads is input to pins 3, 4, 5 and 6.
The output of the multiplexer is taken from pin 7. The pin diagram is shown below.

Fig. 4.11 GD74LS153 Multiplexer Pin Diagram

4.2 Amplification System
This section will discuss the amplification stages that must be done on the
extracted signal in order to allow it to be processed and displayed. The theoretical
aspect of amplification and a description of the hardware used in this section is as
follows.
The extracted signal from the human body cannot be fed to the circuit because it
is very weak (around 0.5 mV). For this reason an amplifier should be used to increase
the amplitude of the signal. The extracted signal is not only weak but also comes with a
Page | 17

lot of noise that need to be filtered or rejected. Therefore, a special type of amplifiers
called an instrumentation amplifier is used.
An instrumentation amplifier is basically composed of three operational
amplifiers. The first two are arranged so that they work as a buffer amplifier, and the
third is a differential amplifier to produce the output (See Figure 4.20).
One of the advantages of using an instrumentation amplifier is the ability of
changing the gain by changing only a single resistance. The gain can be determined by
multiplying the gain of the two stages as shown in Figure 4.21.
A good amplifier is known for having a high common mode rejection ration
(CMRR). CMRR is basically the ability of the amplifier to reject the voltage common
between the two inputs. In a mathematical perspective, it is expressed as the
magnitude of the ratio of differential gain to common-mode gain and it measured in
decibels. Typical CMRR values are in the range of 80-100 db.






Fig. 4.20 Instrumentation Amplifier

Page | 18











For this project, an instrumentation amplifier was built using three operational
amplifiers (LM741). LM741 has a minimum supply voltage of -22V and maximum of 22V.
It has a typical CMRR of 90 db (For the complete electrical characteristics table refer to
LM741 operational amplifier in the references section). The desired gain for the pre-
amplification stage was chosen to be 100 and the values of the resistances were chosen
accordingly.
The formula of the voltage gain is expressed as follows:
V
out
/V
in
= (1 + 2R
F
/R
G
) X (R
2
/R
1
)
RF was selected to be 44.2 k, R
G
= 9.1 k, R
1
= 10 k and R
2
= 100 k
When these values are substituted in the formula the voltage gain will be equal
to:
Fig. 4.21 Instrumentation Amplifier

Page | 19

[1 + 2(44.2)/9.1] X (100/10) 100
The supply voltage was selected to be 5V.
The LM741 operational amplifier is available in an 8-pin chip. Figure 4.22 shows
the pinout diagram of a single LM741 operational amplifier.






Component List:
3 LM741
2 44.2 k
2 10 k
2 100 k
1 9.1 k








Fig. 4.23 Hardware Design of the Instrumentation Amplifier
Fig. 4.22 Pinout diagram of LM741
Page | 20

For further amplification the opamp selected is a general purpose single
operational amplifier, UA741. The connections are made according to the simulation
diagram (Fig. 3.1). The following figure shows the pin connections:

Fig. 4.24 UA741 Operational Amplifier Pin Connections

The components used for the operational amplifier circuit are as shown in Table 4.20.
Component Specifications
Operational Amplifier UA741
Resistors
10k (3), 90k (1)
Batteries 18V (2),
Table 4.20 Components List for Opamp Circuit



Page | 21


4.3 Noise Filter System
A hardware description of noise filter part of the system is as follows.
Component List
Breadboard
Op-amps 071
Jumpers
Wires
Capacitors
Resistors
Oscillator
Function Generator

The hardware of the ECG filters was designed to give a clear output in a signal
form. The band pass filters were selected to cancel the noise that surrounds that signal
and any value that is close to zero, which will be considered a DC signal. Furthermore,
the filter will select a specific range in a signal, which starts from 0.5Hz up to a
maximum value of 175 Hz (the maximum range value was approximately 175 Hz to
avoid any errors). The filter circuit has been designed based on specific values of
bandwidths as shown below.


Page | 22


f1 0.5 w1 3.141592654
f2 175 w2 1099.557429
f3 0.3 w3 1.884955592
f4 291.6666667 w4 1832.595715
wp 1 ws 1.669723018
qc 0.053605407



Also, it was assumed the values of a maximum and A minimum, which are the amount
of allowed attenuation in the pass-bands and stop-bands.
Input Data
Amin 2.00E+01
Amax 1.00E+00

Based on Butterworth rules, Butterworth filter has a flat magnitude response in
both pass and stop bands, which is an advantage in retaining the wanted signal;
however, it has a long transition frequency range. The circuit has been designed
according to the Butterworth concept and equations. The following shows one of the
equations that show how to calculate N, which is the number of stages the design
needs:
Page | 23


Butterworth
n 5.799517352
6
e 0.50884714
wo 1.119185591

The values of capacitors and resistors has been calculated based on the poles that has
been implemented, the results were based on these equations:

Poles One
R1C R2C R3C C R1 R2 R3
0.000209607 0.003155859 0.003155859 1.00E-
07
2.10E+03 3.16E+04 3.16E+04
Page | 24

0.00057492 0.001155135 0.001155135 1.00E-
07
5.75E+03 1.16E+04 1.16E+04
0.000788489 0.000845625 0.000845625 1.00E-
07
7.88E+03 8.46E+03 8.46E+03

Poles Two
R1C R2C R3C C R1 R2 R3
0.091730679 0.105782468 1.381104925 4.70E-
05
1.95E+03 2.94E+04 2.94E+04
0.250610613 54.67752946 0.503529116 4.70E-
05
5.33E+03 1.07E+04 1.07E+04
0.34233733 -0.395826942 0.367144127 4.70E-
05
7.28E+03 7.81E+03 7.81E+03


The above equations were used to calculate the gain. The circuit was simulated (shown
in the simulation section) and furthermore, to prevent each stage from reaching the
saturation mode, an operational amplifier has to be implemented.

4.4 Peak Detector System
The signals extracted from the human body have a certain pattern, as can be
seen in the figure below. There are three main points to this pattern and they are
Page | 25

labelled using the letters Q,R,S. Each of these points represents a certain characteristic
of the human heart that can be used to study the behavior of the human heart.
However, this electrocardiogram has been designed using the counting of the R peaks,
because it is the most significant peak and therefore the easiest to measure, as can be
seen in figure 4.40 below.






Fig. 4.40 QRS Wave To Count Peaks

To measure these R peaks, a comparator with the IC name of LM741 is used. "A
comparator is a circuit which compares a signal voltage applied at one input of an op-
amp with a known reference voltage at the other input." (Choudhury & Shail, 1991) A
reference voltage is set; for the ECG application, this voltage would be set to the R
value, and the comparator compares the input signal voltage with the reference
voltage. If and only if the 2 values are equal the circuit forms a square wave form.
Now that the square signal has been formed it must be limited with reference to
time with the purpose of performing tasks simultaneously and therefore make our ECG
Page | 26

more time efficient. To do so, the square waveform is to be one of the 2 inputs of an
AND gate, with the IC value of 7411, with the other input being 1 square pulse with a
time period of 10 seconds, and an amplitude identical to that of the square waveform.
This square pulse was generated the 555 timer. This will give only one limited portion of
the square waveform.
The next step would be to count the number of square pulses by giving the
square waveform as an input to the 4-bit synchronous counter with an IC value of
74163, that will count step by step the number of square pulses in binary by binaurally
increasing each of the 4 bits, until the counter has counted all the square waves. A 4-bit
synchronous counter was used because the normal heart rate for a human ranges from
60 to 100 beats/minute. This number will be obtained in a further stage of the process,
namely after the output number obtained from the counter is passed through a
multiplier. Because it is passed to a multiplier, that will display this 3 digit number, only
2 digits in decimal are needed in this stage meaning 4 binary digits.
The output from the 4-bit synchronous counter which represented the number
of heart pulses in 10 seconds is given as one of the inputs to an 4bit by 4bit multiplier,
with the IC value of SN54284. The other input is a binary number 0110 which is 6 in
decimal. The processing that happens on the 2 inputs is multiplication of the value of
the number of square waveforms there are by 6. The mathematical process is as
follows:



Page | 27

Pulses: Time
output value from counter : 10 seconds
? : 60 seconds
Cross multiplication implies that the output value from the counter is to always
be multiplied by 6. The number of pulses in 60 seconds is what is needed because the
unit of heart rate is beats/minute.
The theoretical description above was used to design the peak detection of the
circuit belonging to the electrocardiogram system. However, during implementation
due to the lack of some components certain changes in the peak detection circuit had to
be made. Firstly, the 4bit by 4bit multiplier was not used and instead the counter
counted the number of square waveforms in 60 seconds complete. Secondly, because
the 4-bit synchronous counter was not found, 4 ICs with the value of 74107N were used
to count. This IC represents the JK flip flop. The connections between them were made
in such a way that together they acted as a 4-bit synchronous counter. The actual
implementation for the peak detector circuit is shown in figure 4.41 below.





Page | 28







Fig. 4.41 Implemented Peak Detector Circuit

There are then several ways to display the heart rate value. This can be done the
conventional way; on an oscilloscope. Other methods include a 7-segment display, an
LCD or a loud speaker that gives a sound every time there is a pulse and the number of
pulses is noted down manually. Below is a description of how the output is displayed on
7 segment displays.

4.5 Displays and Outputs
The following figures describe the output of an ECG system.
Page | 29







Fig. 4.50 HeartRate






Fig. 4.51 4511: BCD to 7-segment Decoder Driver





Fig. 4.52 7-Segment Display
Page | 30



Fig. 4.53 Three 7-Segment Displays Connected in a Circuit

A hardware description of the output display of an ECG system is as follows.
Firstly, the counter output. This output consists of 3 digits of 7 segment display where
it's known that the maximum heart rate might exceed 200 which is a 3 digits numbers,
figure 4.50. The circuit mainly consist of BCD to 7-segment decoder driver connected to
resistor not to burn the 7- Segment LED display connected with a control circuit involve
NAND and NOR gate with resistors and capacitors. See figure 4.50.
Page | 31

BCD to 7-segment decoder driver (chip (4511) has 16 pin. see figure 4.53. DA to
DD address (data) inputs, EL latch enable input (active LOW), BI ripple blanking input
(active LOW), LT lamp test input (active LOW), Oa to Og segment outputs. The main
function is to convert the logic states at the outputs of a BCD counter into signals, which
will drive a 7-segment display.
For the 7- Segment LED display there are two important types. Common cathode
and common anode where in a common cathode display, the cathodes of all the LEDs
are joined together and the individual segments are illuminated by HIGH voltages on
the contrary in the common anode the individual segments are illuminated by
connecting to a LOW voltage. For the output here the common anode was chosen
because of the LOW voltage input to enlighten the LED. The pining of the common
anode is simple (figure 4.54), where there are 10 pins from (e , d , c , b , a ,g) that
represent each segment of the 7 segments and
When EL the enable / store input pin is LOW, the state of the segment outputs
(Oa toOg) is determined by the data on DA to DD which are the inputs. When EL goes
HIGH, the last data present on DA to
DD are stored in the latches and the segment outputs remain stable. When LT is
LOW, all the segment outputs are HIGH independent of all other input conditions. With
LT HIGH, a LOW on BI forces all segment outputs LOW. The inputs LT and BI do not
affect the latch circuit. BI mean Blanking Input and LT means Lamp Test and LE means
Latch Enable. It is noticeable that Lamp Test (LT) and Blanking Input (BI) input labels are
written with Boolean complementation bars over the abbreviations. Bar symbols label
these inputs as active-low, meaning that it must make each one "low" in order to invoke
Page | 32

its particular function. Making an active-low input "high" places that particular input
into a "passive" state where its function will not be invoked. Equally, the Latch Enable
(LE) input has no complementation bar written over its abbreviation, and
correspondingly it is shown connected to ground ("low"). The Latch Enable input is
an active-high input, which means it must be made "high" (connected to V
dd
) in order to
invoke its function.
Three seven segment drivers are connected to three seven segment displays,
where the output of Oa to Og as e , d , c , b , a ,g is connected to the seven segment
displays inputs e , d , c , b , a ,g and all the 3 VDD +V
e
connected to a power supply of
range between ( 5 15) and all the 3 V
ss
0 V are grounded where the ripple blanking and
the lamp test input connected to high and enable connected to low. The inputs for the
driver A, B, C, and D, are extracted from the 4 outputs coming from the peak detector
circuit. Since three seven segment drivers are used and three seven segment displays a
control circuit was constructed to ensure a 3 digits of 7 segment display.
The control circuit is a combination of NAND, NOR gates connected with 100-
ohm resistor and .001 F, which will help to display the value in 2 or 3 digits depending
on the value detected (refer to fig. 4.53).





Page | 33






5.0 Discussion
Initially there was an option of having three separate (but identical) circuits for
each lead and installing a multiplexer at the end, right before the output or using the
multiplexer right after the data is acquired to that only one signal is processed at a time.
The reason the latter was selected was to reduce costs and complexity of the circuit.
This also results in a smaller overall ECG circuit. Ideally, it would be preferred to use the
multiplexer at the end so that all the data is processed and available at the multiplexer
to choose which is to be displayed on the oscilloscope.
Also in the beginning of the phase of design, it was decided to use a high
accuracy instrumentation amplifier (INA118) that is applicable in medical
instrumentation. This instrumentation amplifier is available in an 8-pin single chip and
has a high CMRR. Due to the unavailability of this chip in the local market and the time
it would take to reach if ordered online, it was not an option. Another option was to
build an instrumentation amplifier using three Precision CMOS Single Operational
Amplifiers, but it was also not available.
For the filter circuits, reaching a gain value of 10 V was a challenge, because
having too many stages can suddenly drop the amplitude. Another difficulty faced in the
filters circuit was choosing resistors values for the filters circuit after the third stage
after a drop happened in the amplitude, and making sure it doesn't reach to a
saturation mode. Adding another stage was required, as to avoid having a really small
Page | 34

value, for instance, having the amplitude or the output in (10
-6
).

For the output process, there was difficulty to simulate the circuit in multisim
due to the unavailability of the some of the components in the program. There was
also difficulty to build the sound output circuit according to the initial concept due to
the unavailability of the audio amplifier component in the market.





















Page | 35





6.0 Conclusion
To further enhance accuracy this system can easily be modified to build a 12-
lead ECG, depending on the availability of the required components (specifically the
electrodes and wires).
Advancements in technology now require us to convert the signals to digital in
order to allow them to be processed for further information. Several parts of the circuit
(including the multiplexers, filters and analog-to-digital convertor) can be replaced by a
single IC (e.g. the ADS1258 - 16-channel (multiplexed), low-noise, 24-bit, delta-sigma (
) analogue-to-digital converter). Its important to have digital data in order to be able
to transmit it via wireless or Bluetooth technology as well or process it in order to
display it on a computer screen. Also for future improvements, the designed
instrumentation amplifier used in this project will be replaced with a single chip INA118.
For future recommendations in the peak detector circuit, it may be simpler to
count the number of square waveforms that represent the peaks, by programming a
microcontroller to do so.
The 3 digits 7 segment display helped in collecting important data about the
heart rate which will help in easing the diagnosis process. Its recommended for higher
efficiency to have one driver and 3 attached 7 segment display where there is no need
for control circuit. Also according to initial blueprints for the audio, the sound of the
Page | 36

heartbeat was supposed to be output to a loudspeaker. This can be implemented for
future improvements where in the components need to be ordered in advance.



7.0 References
[1] National Heart, Lung and Blood Institute. (2012): Understanding the Hearts
Electrical System and EKG Results. Retrieved from
http://www.nhlbi.nih.gov/health/health-topics/topics/hb/understanding.html
[2] STMicroelectronics. (2001): General Purpose Single Operational Amplifier
Datasheet. Retrieved from
http://www.datasheetcatalog.org/datasheet/stmicroelectronics/5304.pdf
[3] LG Semicon Co. Ltd. (2013): Dual 4-line to 1-line Data Selectors/Multiplexers.
Retrieved from http://www.datasheetarchive.com/GD74LS153-datasheet.html
[4] Texas Instruments. (2011): ADS1258 24 Bit, Fast Channel Cycling Delta-Sigma
ADC. Retrieved from http://www.ti.com/product/ads1258

[5] Nursecom Educational Technologies. (2004): An ECG Primer.
[6] Donald, N. (2010). Microelectronics: Circuit Analysis and Design (4th Ed.). New
York: McGraw-Hill.
[7] Paulus, D., Meier, T. (2009): ECG Amplifier. Retrieved from
http://www.mayr.informatik.tu-uenchen.de/konferenzen/MB-Jass09/courses/1/Paulus.pdf

[8] Texas Instruments Incorporated. (2005): Getting The Most out of Your
Instrumentation Amplifier Design. Retrieved from
http://www.ti.com/lit/an/slyt226/slyt226.pdf
[9] Texas Instruments (1998): LM741 Operational Amplifier. Retrieved from
http://www.ti.com/lit/ds/symlink/lm741.pdf

[10] Townsend, N. (2001): Medical Electronics. Retrieved from
www.robots.ox.ac.uk/~neil/teaching/med_elecwww.robots.ox.ac.uk/~neil/teaching/med_
eleca

[11] Clayton, G., & Winder, S. (2003): Operational Amplifiers (5th Ed.). England:
Newens.
Page | 37

[12] Priemer, R. (1991): Introductory Signal Processing; World Scientific.
[13] Roy, C. D., & Jain, S. (2003): Comparators and Waveforms Generators. In Linear
integrated circuits. New Delhi: New Age International.
[14] Educational Publishing for Design & Technology. (2013): 4511 BCD to 7-
segment Decoder. Doctronics. Retrieved from http://www.doctronics.co.uk/4511.htm
[15] Computer-Related Circuit. (2013): 8-bit Binary to 3-digit Decimal Display Decoder
For 8-bit Microprocessor Systems With 256 by 4 PROM three 7-segment Decoder
Drivers With 9374 Input Latches and Two Gates. Retrieved from
http://www.seekic.com/circuit_diagram/Computer-
Related_Circuit/8_bit_binary_to_3_digit_decimal_display_decoder_for_8_bit_microproc
essor_systems_with_256_by_4_PROM_three_7_segment_decoder_drivers_with_9374_i
nput_latches_and_two_gates.html
[16] Tech. Philips Semiconductors; (1995): BCD to 7-segment
Latch/decoder/driver. Retrieved from
http://www.uib.es/depart/dfs/GTE/staff/jfont/InstrETT/hef4511b.pdf
[17] Vishay Semiconductors. (2013): Standard 7-Segment Display 13 Mm
Tech. no. 83126. Retrieved from http://www.vishay.com/docs/83126/83126.pdf

By: Karima Khandaker, Israa Al-Qassas,
Reemaz Hetaimish, Haneen Mohammed,
Danah Nour, Lina Babsail, Sarah Al-
Harthey
Course:
Introduction to Electronic
(Integrated Circuits) - ECE210L
Supervisor:
Dr. Nema Salem
Department:
Electrical and Computer Engineering


HARDWARE DESIGN
AND
I MPLEMENTATI ON
OF AN
ELECTROCARDIOGR
AM
SYSTEM
What is an ECG system ?
According to the Encyclopaedia of the 20th Century Technology, "the
electrocardiogram (ECG or EKG) is a graphic measurement of the
electrical activity of the heart produced by an electrocardiograph, or
ECG machine." The ECG is used to monitor the electrical activity of
the heart which is extracted from the human body in the form of
analog signals.
Why to build an ECG system ?
to represent efficient design and implementation of a complete ECG
system starting from the signal acquisition from the human body till
displaying both of the ECG signals and the rate of heart beats as
well.
What does the ECG do ?
The Electrocardiogram (ECG or EKG) is used to measure the
electrical activity of the heart over a certain period of time
depending on the purpose of taking the reading. It can be
used to either monitor over longer periods of time or
diagnostic purposes to analyze the status of the heart at a
certain time.

ELECTROCARDIOGRAM
ECG
Fig. 1.0 Standard Setup of ECG System Used for Monitoring

With each heartbeat, an electrical signal is generated in a
group of cells in the upper right chamber or right atrium of
the heart. This signal passes through the two upper
chambers (right and left atria) causing them to contract
which in turn causes the blood to move in the lower
chambers of the heart called ventricles. This electrical
signal passing through the atria is shown as the P Wave on
the ECG. As the signal passes from the atria to the
ventricles it slows down to allow the ventricles to fill up with
blood and this is shown as the flat region between the P
and Q waves. The signal then distributes across the
ventricles instigating them to contract and pump blood to
the various parts of the body. This section causes the QRS
waves on the ECG. Once the ventricles return to their
normal state after this, it can be seen on the ECG as the T
wave in Fig 2.0. The ECG allows the medical staff to
deduce different conditions based on the deflection from
the general expected ECG waveform. It may be based on
the amplitude, shape, interval lengths or even the
absence of expected waves. Table 2.0 shows some
examples of comparisons between normal (expected)
data and abnormal data and the conclusions that can be
drawn in each case.
3 lead wire ECG System have three colored wires that
connect to three electrodes forming the Einthovens
triangle as shown in Fig. 3.0. This system provides three
views of the heart.
HEART BEATS : PQRST WAVE
ON THE ECG
Fig. 2.0 PQRST Wave


Fig. 3.0 Position Of 3 Leads Forming Einthovens Triangle


HARDWAR IMPLEMENTATION
Signal
Extraction
Amplification
System
Noise Filter
System
Peak Detector
System
Displays and
Outputs
The overall system of the ECG can be divided into the shown 5
subsystems:

Signal Extraction
Electrodes
Patient Protection
Multiplexer
Further Amplification




Noise Filter
Amplification
Instrumentation Amplifier


Peak Detector
To calculate heart rate
Output and Displays
From Peak Detector Circuit
- Seven Segment Displays
ECG display Oscilloscope
Fig. 2.0 Overall ECG System Block Diagram

Signal
Extraction
Amplification
System
Noise Filter
System
Peak Detector
System
Displays and
Outputs

Signals are extracted from lead wire and connected to
the multiplexer that is used to select the lead to be
processed is a Dual 4-Line To 1-Line Data Selector/
Multiplexer.



The extracted signal from the human body cannot be
fed to the circuit because it is very weak (around 0.5 mV).
For this reason an amplifier should be used to increase
the amplitude of the signal


Filter the noise from the amplified signal , the band pass
filters were selected to cancel the noise that surrounds
that signal and any value that is close to zero, which will
be considered a DC signal. Furthermore, the filter will
select a specific range in a signal, which starts from 0.5Hz
up to a maximum value of 175 Hz . The filter circuit has
been designed based on specific values of bandwidths
as shown below.
Count the most significant peak using a comparator
which compares a signal voltage applied at one input of
an op-amp with a known reference voltage at the other
input . The next step would be to count the number of
square pulses by giving the square waveform as an input
to the 4-bit synchronous counter . The output from the 4-
bit synchronous counter which represented the number
of heart pulses in 10 seconds

The output viewed through oscilloscope and 3 digits of 7
segment display where it's known that the maximum
heart rate might exceed 200 which is 3 digits numbers .


[1] National Heart, Lung and Blood Institute. (2012). Understanding the Hearts Electrical System and EKG Results. Retrieved from
http://www.nhlbi.nih.gov/health/health-topics/topics/hb/understanding.html
[2] STMicroelectronics. (2001). General Purpose Single Operational Amplifier Datasheet. Retrieved from http://www.datasheetcatalog.org/datasheet/stmicroelectronics/5304.pdf
[3] LG Semicon Co. Ltd. (2013). Dual 4-line to 1-line Data Selectors/Multiplexers. Retrieved from
http://www.datasheetarchive.com/GD74LS153-datasheet.html
[4] Texas Instruments. (2011). ADS1258 24 Bit, Fast Channel Cycling Delta-Sigma ADC. Retrieved from
http://www.ti.com/product/ads1258
[5] Nursecom Educational Technologies. (2004). An ECG Primer.
[6] Donald, N. (2010). Microelectronics: Circuit Analysis and Design (4th ed.). New York: McGraw-Hill.
[7] Paulus, D., Meier, T. (2009). ECG Amplifier. Retrieved from
http://www.mayr.informatik.tu-uenchen.de/konferenzen/MB-Jass09/courses/1/Paulus.pdf
[8] Texas Instruments Incorporated. (2005). Getting The Most out of Your Instrumentation Amplifier Design. Retrieved from http://www.ti.com/lit/an/slyt226/slyt226.pdf
[9] Texas Instruments (1998). LM741 Operational Amplifier. Retrieved from
http://www.ti.com/lit/ds/symlink/lm741.pdf
[10] Townsend, N. (2001). Medical Electronics. Retrieved from
www.robots.ox.ac.uk/~neil/teaching/med_elecwww.robots.ox.ac.uk/~neil/teaching/med_eleca
[11] Clayton, G., & Winder, S. (2003). Operational Amplifiers. (5th ed.). England: Newens.
[12] Priemer, R. (1991). Introductory Signal Processing. World Scientific.
[13] Roy, C. D., & Jain, S. (2003). Comparators and Waveforms Generators. In Linear integrated circuits. New Delhi: New Age International.
[14] Educational Publishing for Design & Technology. (2013). 4511 BCD to 7-segment Decoder. Doctronics. Retrieved from http://www.doctronics.co.uk/4511.htm
[15] Computer-Related Circuit. (2013). 8-bit Binary to 3-digit Decimal Display Decoder For 8-bit Microprocessor Systems With 256 by 4 PROM three 7-segment Decoder Drivers With 9374 Input
Latches and Two Gates. Retrieved from
http://www.seekic.com/circuit_diagram/Computer-Related_Circuit/
8_bit_binary_to_3_digit_decimal_display_decoder_for_8_bit_microprocessor_systems_with_256_by_4_PROM_three_7_segment_decoder_drivers_with_9374_input_latches_and_two_gates.html
[16] Tech. Philips Semiconductors. (1995). BCD to 7-segment Latch/decoder/driver. Retrieved from
http://www.uib.es/depart/dfs/GTE/staff/jfont/InstrETT/hef4511b.pdf
[17] Vishay Semiconductors. (2013). Standard 7-Segment Display 13 Mm. Tech. no. 83126. Retrieved from http://www.vishay.com/docs/83126/83126.pdf


REFERENCES

You might also like