Sie sind auf Seite 1von 89

COMPUTING

ENG499
CAPSTONE ICT PROJECT







Final Report
On An Electronic Stethoscope

SIM University
ENG499 Capstone Project


11 May 2009

By

Mr She Renyou Roston,
Student No: H06047

Abstract

The Stethoscope is an acoustic medical device for listening to internal sounds in human
body which is known, in medical terms, as auscultation. One problem with acoustic
stethoscopes is that the sound level is extremely low. Electronic stethoscopes are able to
offer signal amplification and other benefits over traditional stethoscopes.

This project is an attempt to build an electronic stethoscope that amplifies body sound
signals for clear auscultation. An electret condenser microphone senses the heart sounds
converting them into electrical signal. The signal is amplified and filtered in desired
frequency band. This signal is then fed to a personal computer which will be digitized by
the sound card.

The signal will be presented in a format that makes it easy for a user to visualize and
analyze them. Through a graphical user interface (GUI) using Matlab, the signal can be
recorded and stored in a personal computer for further analysis.












i

Acknowledgement

First, I would like to thank my project supervisor, Dr. Yuan Zhongxuan for patiently
guiding me over the past nine months. This project could not have been accomplished
without his guidance. My sincere gratitude for his indispensable advices and valuable
time spent on the project.

I would also like to extend my gratitude to Singapore Institute of Management and
Singapore Polytechnic for the opportunity to take part in this project.

Last but not least, I would also like to thank my office-mate, David Goh and supervisor,
Mr Thomas Tan for their expert help and advice.

















ii

Table of Contents



Page
Abstract i

Acknowledgement ii

List of Figures vi

List of Tables viii

1. Project Definition 1
1.1 Project Objective.................... 1
1.2 Overall Objective................... 2
1.3 Proposed Approach and Methodology............... 2
1.3.1 Signal Acquisition and Pre-Processing. 3
1.3.2 Heart Sound Analysis.... 3

2. Investigation of Project Background 4
2.1 Background to the Project ......................... 4
2.2 Existing Work Related to the Project..... 5
2.3 History of Stethoscopes...... 6
2.4 Types of Stethoscopes............ 7
2.4.1. Acoustic Stethoscopes.. 7
2.4.2. Electronic Stethoscopes 8
2.5 Physiology of Hearts...... 8
2.6 Heart Sounds.......... 9
2.7 Heart Murmurs. ..... 10
iii

2.8 Acquisition of Heart Sound Signal. 11
2.8.1 Sensors... 12
2.8.2 Filters..... 13
2.8.2.1 Analogue Filter.. .. 13
2.8.2.2 Digital Filter.. ... 13
2.8.2.3 Flexibility.. 14
2.9 Analysis of Heart Sound Signal. 14
2.9.1 Time and Frequency Domain.... 14
2.9.2 Time-Frequency Domain...... 14

3. Project Plan
3.1 Scope of the Project............ 16
3.1.1 Project Tasks ............ 17
3.1.2 Projection Management..... 17

4. Project Approach: Design and Analysis 19
4.1 Architecture of the Stethoscope System........ 19
4.2 Hardware Design.................... 20
4.2.1 Power Supply ............ 20
4.2.2 Sensor ............... 22
4.2.3 Preamplifier. ..... 25
4.2.4 Low-Pass Filter.......... 26
4.2.5 Power Preamplifier ....................... 30
4.2.6 Combination of Individual Circuits................... 31
4.3 Software Design ....................... 32
4.3.1 Graphical User Interface....................... 32
4.3.2 Time Analysis........................ 33
4.3.3 Frequency Analysis....................... 34
4.3.4 Time-Frequency Analysis......................... 34
4.3.4.1 Spectrogram...................... 35
iv

4.3.5 Digital Filter.......................................... 35
4.3.6 Heart Rate Calcualtion.......................................... 36
4.3.7 Quality of Audio Recordings......................................... 36

5. Result and Analysis 39
5.1 Performance of Power Supply............ 39
5.2 Performance of Low-Pass Filter......... 40
5.3 Results of Heart Beat Calculation...................... 41
5.4 Digital Filtering of Heart Signals........................... 42
5.5 Problem Encountered............................. 42
5.6 Shortcoming of the Project............................ 43


6. Conclusion and Recommendation 44
6.1 Conclusion.............. 44
6.2 Recommendation for Future Work................. 45
6.3 Critical Review and Reflection...... 47

References


Appendices
51 - Appendix A Overall Circuit Schematic and Bill of Material (BOM)
54 - Appendix B Flow-chart of Heart Rate Calculation
55 - Appendix C Typical electret condenser microphone properties
56 - Appendix D Matlab Code (Main GUI)
72 - Appendix E Matlab Code (Sub GUI for Filter Setting)
77 - Appendix F Matlab Code (Sub GUI for Recording Option)


v

List of Figures



Page
1.1 Block Diagram of the Stethoscope System 3

2.1 Relationship between the range of sounds produced in the heart and the
human threshold of audibility
5
2.2 Early monaural stethoscope (1860), Camman's binaural stethoscope
(1870), a modern binaural stethoscope and a modern electronic
stethoscope
7
2.3 Basic anatomy of the human heart 9
2.4 Heart sound of a normal person 10
2.5 Heart sound with both systolic and diastolic murmurs 10
2.6 Electret condenser microphone (left) and piezoelectric accelerometer
(right)
12

4.1 Overview of the stethoscope system 19
4.2 Schematic Diagram of a Single Supply Power Circuit 20
4.3 Voltage noise with and without bypass capacitor 22
4.4 Schematic Diagram of Sensor 24
4.5 Schematic Diagram of Preamplifier 26
4.6 Schematic Diagram of Low-Pass Filter 28
4.7 Schematic Diagram of Power Amplifier 30
4.8 User Interface 33
4.9 Normal heart sound showing S1 and S2 33
4.10 Power spectrum of normal heart sound 34
4.11 Spectrogram of normal heart sound 35
4.12 GUI of Filter Setting 36
vi

4.13 GUI of Recording Option 37

5.1 Oscilloscope view of DC Power Supply pin on non-inverting amplifier 39
5.2 Output of non-inverting amplifier 40
5.3 Sallen-Key Low-Pass Filter at 100Hz cut-off 40
5.4 Sallen-Key Low-Pass Filter at 1000Hz cut-off 41
5.5 Time Domain Analysis - signal before filtering 42
5.6 Time Domain Analysis - signal after filtering 42

6.1 4 Pole Low-Pass Filter

46














vii

List of Tables



Page
2.1 Gradations of Murmurs 11

3.1 Project Tasks List 17
3.2 Gantt chart showing the project development schedule 18

4.1 Comparison between Dynamic And Condenser Microphone 23
4.2 Comparison of Operational Amplifiers 25
4.3 Comparison of Various Filter Responses 29

5.1 Accuracy of the Heart Beat Calculation 41










viii
CHAPTER 1

PROJECT DEFINITION



1.1 Project Objective

The project objective is to design and construct an electronic stethoscope to convert
acoustic sound waves to electrical signals which can then be amplified and processed for
analysis.

The specific objectives of this project include, but are not limited to:

- Conversion of acoustic sound waves to electrical signals

- Pre-processing of auscultation signals, involving removal of interference noise
and separation of respiratory noises, and amplification of the signals

- Transmitting the heart sounds signal to a personal computer using a graphical user
interface for analysis and to build-up the data-base for replay, demonstration or
consultation purposes

- Calculation and display of heart beat rate





1

1.2 Overall Objective

Recognition of heart disease is an important goal in medicine. The majority of
stethoscopes currently on the market are acoustic devices that use purely passive
mechanical parts to isolate and focus sound generated by the body. Unfortunately, though
these methods have been used for years, the simplicity of such devices is overshadowed
by poor sound quality. These devices are also difficult to interface with modern
technologies such as computers to record and analyze body sounds. The goal of this
project is to design and construct an electronic stethoscope that is comparable in cost, has
better acoustic response, and can interface with modern technologies better than the
current acoustic stethoscope.


1.3 Proposed Approach and Methodology

In order to extract reliable diagnostic features from heart sound it is important to first
suppress noise. During heart sound acquisition many external body noises such as
ambient noise, as well as internal body noises such as heavy breathing, speech and etc.,
may be captured. These noises are mixed with heart sound.

The approach to this project is to keep things as simple as possible. The stethoscope
system detecting heart sounds has two main blocks: Signal Acquisition and Pre-
processing (Signal Conditioner), and Analysis of heart sound. It consists of two parts:
Hardware and software. The hardware component consists of a power supply, sensor,
preamplifier, low pass filter and power amplifier. The software component consists of a
segmentation and analysis algorithm. The block diagram below (Figure 1.1) shows the
key parts required in this project.
2

Signal from
Microphone
Signal
Conditioner
(Hardware)
Audio
Output
A/D
Converter
Display
the Signal
Analysis
(Software)
Headphone

Figure 1.1: Block Diagram of the Stethoscope System.

1.3.1. Signal Acquisition and Pre-Processing (Signal Conditioner)

The circuit will be operating on its own portable power source. The power source and
circuitry will provide adequate voltage for the electronic components to function properly.
There will be a sensor to convert the acoustic signal from the stethoscope into electrical
signal. The signal will be pre-amplified using op-amps. A low pass filter will be designed
to remove interference noise. Finally, the filtered signal will then be amplified again
using power amplifiers.


1.3.2. Heart Sound Analysis

The signal is processed through analysis algorithm before a final diagnosis can be made.
The analysis algorithm is based on the analysis of heart sounds and separates the heart
sound into individual cycles with each cycle containing First Heart Sound (S1), Systolic
Period, Second Heart Sound (S2) and Diastolic. The main idea is that first the location of
S1 and S2 will be computed and then based on that information the location of systolic
and diastolic periods will be calculated. This allows further analysis on heart sounds and
murmurs. The algorithms will be designed and implemented in Matlab.

3

CHAPTER 2

INVESTIGATION OF PROJECT BACKGROUND



The term Auscultation means, literally, to listen is the act of listening to the sounds
made by internal organs, is a valuable medical diagnostic tool. Auscultation methods
provide the information about a vast variety of internal body sounds originated from the
heart, lungs, bowel and vascular disorders. The ability to detect heart sounds may be
influenced by a number of factors, including the presence of ambient noise or other
sensory stimuli [1]. Therefore, only the skilled physician who is proficient in the skill of
auscultation is likely to make accurate diagnoses upon cardiac auscultation. This may
result in inaccurate or insufficient information due to the inability of the user to discern
certain complex, low-level, short duration or rarely encountered abnormal sounds [1]. It
is, thus, desirable to enhance the diagnostic ability by processing the auscultation signals
electronically and providing a visual display and automatic analysis to the physician for a
better comparative study [14].


2.1 Background to the Project

Stethoscopes are medical instruments that help doctors detect sounds produced within the
body, in particular heart and lungs, for monitoring the physiological condition of a patient.
They typically include diaphragm detectors for picking-up sounds of lower frequency,
and bell-shaped detectors for picking-up sounds of higher frequency.

Typically, heart sounds and murmurs are of relatively low intensity and are band limited
to about 101000 Hz. Meanwhile, Speech signal is perceptible to the human hearing.
4

Therefore, auscultation with an acoustic stethoscope is quite difficult. Only a small
proportion of cardiovascular sound energy is audible by the human ear, see Figure 2.1 [1],
[2].

The problem with acoustic stethoscopes is that the sound level is low, making
diagnosis more difficult. By amplifying body sounds, electronic stethoscopes overcome
the low sound levels. Modern electronic stethoscopes include electrical transducers for
converting the sounds to electrical signals and amplification of the signals.


Figure 2.1: Relationship between the range of sounds produced in the heart and the
human threshold of audibility


2.2 Existing Work Related to the Project

There are several commercially available electronic stethoscopes on the market. One of
them is the Littmann Electronic Stethoscope Model 3000 manufactured by 3M [3]. This
stethoscope is designed with a high level of amplification of up to 18 times greater than
the best non-electronic stethoscopes. It features an ergonomic design and simple push
button control to change modes without interrupting auscultation. Its' new Ambient Noise
Reduction technology reduces distracting room noise by an average of 75% without
5

eliminating critical body sounds.

2.3 History of Stethoscopes

The development of the stethoscope can be traced back to the beginning of the nineteenth
century when a French physician by the name of Rene Laennec first invented the
stethoscope in 1816. During Laennec's time, auscultation when undertaken, placed the
physician's ear directly upon the patient's chest.
4
For the sake of convenience and
propriety, Dr. Rene Laennec simply rolled three pieces of paper and created a cylinder,
placing one end on the patient's chest and keeping the other end over his ear. This
primitive stethoscope that he had invented would become "the first noninvasive
diagnostic instrument in medical history" [4], [5]. The invention of the stethoscope
resulted in, without precedent, the most widely spread diagnostic instrument in the
history of biomedical engineering. The stethoscope has evolved over the years, but the
underlying technology remains the same.

Throughout the twentieth century the stethoscope became an integral part of medicine.
The beginning of this century was marked by the introduction of the electronic
stethoscope which could be used to make records of heart sounds and murmurs and also
for teaching purposes [7]. There continued to be modifications of pre-existing designs as
well as introductions of new designs, some of which were considered impractical while
others proving to be useful. However, the invention of the binaural stethoscope in the
1850's has left its mark in history, as this ingenious invention is more or less the modern
day form that is used today [6]. Technology developments show no sign of ending.
Current and recent developments of the stethoscope are focused on obtaining the best
acoustic properties of this binaural form. A selection of stethoscopes from different eras
is shown in Figure 2.2.
6



Figure 2.2: Early monaural stethoscope (1860), Camman's binaural stethoscope (1870), a
modern binaural stethoscope and a modern electronic stethoscope (from left to right)


2.4 Types of Stethoscopes

There are several basic types of medical diagnostic equipment. The stethoscope is most
often used to listen to heart sounds and breathing. There are two basic types of
stethoscopes for respiration system diagnostics of the human body.


2.4.1 Acoustic Stethoscope

Acoustic stethoscopes are familiar to most people, and operate on the transmission of
sound captured by a chest piece, via two air-filled hollow tubes, to the listener's ears [8].
The chest piece usually consists of a bell (hollow cup) and a diaphragm (plastic disc) that
can be placed against the patient for sensing sound. The bell is used with light skin
contact to hear low frequency sounds and the diaphragm is used with firm skin contact to
hear high frequency sounds. The disadvantage is that the sound level is very low, making
these stethoscopes less practical in noisy environments. However, acoustic stethoscopes
are the most commonly used.

7


2.4.2 Electronic Stethoscope

Electronic stethoscopes function in a similar way as acoustic stethoscopes, but the sound
is converted to electrical signals which can then be amplified and processed for optimal
listening.
8
Because the sounds are transmitted electronically, an electronic stethoscope
can be a wireless device, can be a recording device, and can provide noise reduction,
signal enhancement, and both visual and audio output.


2.5 Physiology of the Heart

The human heart is composed of four chambers, see Figure 2.3. The upper chambers are
called atria and the lower chambers are called ventricles. The heart muscle squeezes
blood from chamber to chamber. At each squeeze, the heart valves open when each
chamber contracts to let blood through to the next chamber and close to prevent backflow
of blood when the contraction is completed [15]. In this way, the valves keep blood
moving as efficiently as possible through the heart and out to the body.


8


Figure 2.3: Basic anatomy of the human heart


2.6 Heart Sounds

The sound heard during auscultation are called the first (S1) and the second (S2) heart
sounds respectively, shown in Figure 2.4. The first 2 heart sounds (S1 and S2) are
normal heart sounds that should be detectable in most patients. The S1 sound
represents the near-simultaneous closure of the mitral and tricuspid valves, after blood
has returned from the body and lungs [9]. This is the start of systole. The S2 sound
represents the near-simultaneous closure of the aortic and pulmonary valves as blood
exits the heart to the body and lungs [9]. This is the end of systole and the beginning of
diastole.


9



Figure 2.4: Heart sound of a normal person



Figure 2.5: Heart sound with both systolic and diastolic murmurs


2.7 Heart Murmurs

A heart murmur is an abnormal sound of the heart that is usually caused by valvular
dysfunctions which occurs when a valve does not work the way it should.10 Murmurs
can occur in either systole or diastole, as seen in Figure 2.5. Systolic murmurs occur
between the first and second heart sound (S1 and S2), and diastolic murmurs occur
between the second and first heart sounds (S2 and S1). The severity of systolic murmurs
10

is determined by grades, with grade 1 being the lowest in amplitude and 6 being the
highest, see table 2.1. Murmurs with higher amplitudes can sometimes be heard without a
stethoscope. Most murmurs are not serious, and many childhood murmurs disappear with
time.


Table 2.1: Gradations of Murmurs


2.8 Acquisition of Heart Sound Signal

The audio recording involves a sequence of transformations of the signal: a sensor to
convert sound into electrical signal, a preamplifier to amplify the signal, a low pass filter
to remove background noise, a power amplifier to amplify the filtered signal and an
analogue to digital converter to convert the signal into digital form.





11

2.8.1 Sensors

There are multiple types of sensors that can be used in the chest piece of an electronic
stethoscope to convert body sounds into an electronic signal. Microphones and
accelerometers are the common choice of sensor for sound recording. These sensors have
a high-frequency response that is quite adequate for body sounds. Rather, it is the low-
frequency region that might cause problems [11]. The microphone is an air coupled
sensor that measure pressure waves induced by chest-wall movements while
accelerometers are contact sensors which directly measures chest-wall movements [12].
For recording of body sounds, both kinds can be used. More precisely, condenser
microphones and piezoelectric accelerometers have been recommended, see Figure 2.6
[13].

Both transducers are popular in sound recording. However, accelerometers are typically
more expensive than microphones, are often fragile, and may exhibit internal resonances.
Thus, this concludes that the microphone is prefect for the application.



Figure 2.6: Electret condenser microphone (left) and piezoelectric accelerometer (right)




12

2.8.2 Filters
The sensors used in electronic stethoscopes often pick up background noise, therefore it
is important to filter that signal and only reproduce the sounds of interest. There are two
kinds of filter, analog and digital, that can be used in an electronic stethoscope to reduce
the ambient noise and increase the intensity of the desired signal.


2.8.2.1 Analogue Filter

An analog filter uses analog electronic circuits made up from components such as op-
amps, capacitors, and resistors to produce the required filtering effect. The disadvantage
of the analog filter is that large number of components may be needed to implement a
filter that has sufficient roll-off at the desired cutoff frequency. Also, the multiple analog
components required can add noise to the signal.


2.8.2.2 Digital Filter

Digital filters, however, can be implemented without added noise. The two digital filter
types, finite impulse response (FIR) and infinite impulse response (IIR) can be
implemented using software. Digital filters with FIR filters have both advantages and
disadvantages compared to IIR filters. FIR filters are always stable, while IIR filters may
be unstable. However, the primary advantage of IIR filters over FIR filters is that they
typically meet a given set of specifications with a much lower filter order than a
corresponding FIR filter. Although IIR filters have nonlinear phase, data processing
within Matlab software is commonly performed "offline," that is, the entire data sequence
is available prior to filtering. This allows for a non-causal, zero-phase filtering approach,
which eliminates the nonlinear phase distortion of an IIR filter.


13

2.8.2.3 Flexibility

Analogue filters commonly require more effort to change than digital filters. For example,
changing the cutoff frequency of an analog filter will often require a component change.
A digital filter is extremely flexible, allowing changes to any aspect of the filter.
However, this does not mean that analogue filtering will not be used in the stethoscope.


2.9 Analysis of Heart Sound Signal

2.9.1 Time and Frequency Analysis

The traditional method to analyze the signal is to view them in time-domain
representation by showing parameter variation such as amplitude versus time. The other
representation is the frequency analysis; also know as spectral analysis, which shows the
frequencies existed for total duration of time. There are several researchers using time
and frequency analysis to examine the heart sounds.

In general, time and frequency analysis provide fundamental information to the signal
analysis. However, time and frequency analysis do not fully describe the whole
interpretation of the signals of interest such as heart sounds. For instance, the classical
spectral analysis needs to be enhanced to analyze the signals. Thus, another type of
representation should be considered for signal analysis such as time-frequency analysis.


2.9.2 Time- Frequency Analysis

Time-frequency analysis proves to be a powerful method due to its ability to determine
which frequencies existed at a particular of time compared to frequency analysis that can
only show the range of frequency component of the signals. The time or frequency
14

analysis alone is unable to represent the multi-component signals in logical way. Time-
frequency analysis reveals the multi-component nature of the signals by concentrating the
signal energy in time-frequency plane around the instantaneous frequency law component.




























15

CHAPTER 3

PROJECT PLAN



This stage is critical to successful resourcing and execution of the project activities and it
includes the development of the overall project structure, the activities and
workplan/timeline that will form the basis of the project management process throughout
the project lifecycle.

The electronic stethoscope must be carefully evaluated and implemented. The hardware
and software that are most cost effective must be identified and implemented. Through a
careful and thorough planning, an electronic stethoscope can be designed and constructed
in time.

An action plan and milestones must be prepared. These identify the many actions
required to implement an electronic stethoscope. Although the schedule is important,
several other elements should be addressed, including the types of resources required to
complete the action, funding sources for the implementation, and the access to equipment
and facilities. The milestones identified for the project are the significant steps along the
path to implementation.


3.1 Scope of Project
The primary focus of this project is to develop and construct an electronic stethoscope
that will make it easier to detect heart sounds. Standard stethoscopes provide no
amplification which limits their use. This stethoscope will be designed with a certain
level of amplification and includes a low pass filter to remove ambient noise.
16


Signals from stethoscope will be transferred to the microphone, filtered and amplified.
Then signals will be fed into an A/D converter and convert them into digital signals to be
displayed on the computer using Matlab program for analysis.


3.1.1 Project Tasks
The table below shows the list of key tasks required in this project.

Task 1 Background study and literature review on stethoscope
Task 2 Design a power circuit
Task 3 Design a preamplifier circuit
Task 4 Design a low-pass filter
Task 5 Design a power amplifier circuit
Task 6 Overall schematic generation
Task 7 Implementation of the circuit
Task 8 Writing the software algorithm
Task 9 Testing and Debugging

Table 3.1: Project Tasks List


3.1.2 Project Management Plan
A good project management is one of the keys to a successful project outcome. The
project work was distributed in the Gantt chart shown below.
17



Table 3.2: Gantt chart showing the project development schedule











18

CHAPTER 4

PROJECT APPROACH: DESIGN AND ANALYSIS



The hardware for the stethoscope composes of 2 parts: sensor and signal conditioner. The
signal conditioner is further divided into 3 stages: preamplifier, low-pass filter and power
amplifier.


4.1 Architecture of the Stethoscope System

An overview of the stethoscope is shown below.


Figure 4.1: Overview of the stethoscope system

4.2 Hardware Design
19


The hardware design of this project is composed of the following major parts: power
supply, sensor, preamplifier, low-pass filter and power amplifier. In the sections that
follow, the specifications of each part will be described.

4.2.1 Power Supply

Most portable systems have one battery, thus, the popularity of portable equipment
results in increased single supply applications. Although it is advantageous to implement
op amp circuits with balanced dual supplies, there are many practical applications where,
for energy conservation or other reasons, single-supply operation is necessary or
desirable. But single-supply operation has its drawbacks: It requires additional passive
components in each stage and, improper execution of the design can lead to serious
instability problems.


Figure 4.2: Schematic Diagram of a Single Supply Power Circuit

The circuit in Figure 4.2 shows a single-supply biasing method. 9V is chosen since it is
compatible with the microphone, op amp and power amplifier. This non-inverting, op-
amp circuit uses a resistor divider with two biasing resistors, R5 and R6, to set the
20

voltage on the non-inverting input equal to Vcc/2. R5 and R6 are equal values, selected
with power consumption versus allowable noise in mind

The values of R5 and R6 are chosen to be as low as feasible; the 47 k values chosen
here are intended to conserve supply current. Attempts to use small resistor values in the
voltage divider will increase power-supply current consumption, may overheat the
resistors, and certainly is not a good design approach.

To avoid substantial feedback through the power supply at low signal frequencies, a
larger capacitor is needed to effectively bypass the voltage divider at all frequencies
within the circuits passband. Therefore the capacitance value of 1F for C3 is chosen.

With a 47k/47k voltage divider for R5 and R6 and a 1F capacitance value for C3,
the 3dB bandwidth of this networks impedance, set by the parallel combination of R5,
R6, and C3, is equal to z
F
k
C
RA
H ~
|
.
|

\
| O
=
|
.
|

\
|
7
1
2
47
2
1
3
2
2
1
t t


The common-mode rejection drops below 7Hz. Instability will not occur as the electret
condenser microphone only picks up signal above 20Hz.

In figure 4.3, it shows a noisy voltage with a bypass capacitor installed. Random
electrical noise causes the voltage to fluctuate. This is often called 'noise' or 'ripple'. The
blue line, represents the voltage of a circuit that doesn't have a bypass. The pink line is a
circuit that has a bypass. Ripple voltages are present in almost any DC circuit. Even with
the bypass, the voltage does fluctuate, even though it is to a smaller degree. The key
function of the bypass capacitor is to reduce the amount of ripple in a circuit. Too much
ripple is bad, and can lead to failure of the circuit. Ripple is often random, but sometimes
other components in the circuit can cause this noise to occur. By installing bypass
capacitors, the DC circuit will not be as susceptible to ripple currents and voltages.

21


Figure 4.3: Voltage noise with and without bypass capacitor

C12 is a bypass capacitor which on top of preventing the supply voltage from fluctuating,
also supplies positive supply current when the battery runs down and its internal
resistance rises.


4.2.2 Sensor

The quality of an acoustic stethoscope is greatly affected by the quality of its chest piece.
Due to the lack of expertise necessary to design the mechanical aspects of a chest piece,
modification is done on an existing chest piece. The microphone is placed within it to
maximize the benefits of mechanical filtering that are already present.

As mentioned in Part 2, microphone was chosen for this project. The next step is to
choose which specific microphone to use. In this decision there are several criteria that
must be examined. One of the criteria is the microphones frequency response. It must be
able to pick up sounds in the range of 20Hz to 2kHz. Another criterion is its sensitivity;
22

the microphone must be able to reproduce the correct intensity of body sounds that it
receives.


Dynamic Microphone Condenser Microphone
Do not have flat frequency response Have a flat frequency response
Operate with the principle of
Electromagnetism as it does not require
voltage supply.
Employs the principle of electrostatics
and consequently, require voltage supply
across the capacitor for it to work.
It is suitable for handling high volume
level, such as musical instruments.
It is not ideal for high volume work as its
sensitivity makes it prone to distortion.
The signal produced are strong therefore
making them sensitive
The resulting audio signal is stronger
than that from a dynamic. It also tends to
be more sensitive and responsive than
dynamic.
Table 4.1 Comparison between Dynamic And Condenser Microphone

Table 4.1 shows the comparison between the dynamic and condenser microphone.
Condenser microphones generally have flatter frequency responses than dynamic, and
therefore mean that a condenser microphone is more desirable if accurate sound is a
prime consideration as required in this design.

There are two types of condenser microphones; standard condenser and electret
condenser. A standard condenser microphone consists of a small diaphragm that vibrates
in response to acoustic pressure. Standard condenser microphones have very high output
impedance, so they are not suitable for transferring signals over even a very small
distance. An electret condenser microphone combines a condenser microphone with a
Field Effect Transistor (FET), which amplifies the signal and transforms the impedance
23

to a more useful level. This characteristic of electret condenser microphones makes them
very sensitive to small sounds. Its properties can be found in Appendix C.

The electret condenser microphone requires a supply voltage in order to bias the FET
inside the microphone. Most electret condenser microphones have only two prongs, so
the common way of providing the bias current to the microphone is known as Phantom
Power. The basic procedure is to use a resistor between the voltage source and ground to
limit the current into the FET, and a capacitor to block the DC offset of the supply
voltage from the amplifier circuitry.

R1 is to provide bias current for the electret microphones internal FET The bias voltage
of around 1-10V is needed to supply the build-in FET buffer. The load resistor defines
the impedance and can be matched to the low noise amplifier intended. Therefore, the
suitable resistance values are typically in the range of 1-10 k. The lower limit is defined
by amplifier voltage noise and the upper limit by interference pickup (and amplifier
current noise). R2 and C1 is a supply filter circuit to keep supply voltage fluctuations
away from the circuit's sensitive input.

Figure 4.4: Schematic Diagram of Sensor



24

4.2.3 Preamplifier

An operational amplifier, which is often called an op-amp, is a DC-coupled high-gain
electronic voltage amplifier with differential inputs and, usually, a single output.
Typically the output of the op-amp is controlled either by negative feedback, which
largely determines the magnitude of its output voltage gain, or by positive feedback,
which facilitates regenerative gain and oscillation. High input impedance at the input
terminals (ideally infinite) and low output impedance (ideally zero) are important typical
characteristics. The op-amp exhibits high input impedance and thus when placed in
parallel with the bodys relatively low impedance is assumed to allow the following
section to amplify the voltage with minimal current consumption.

A couple of different operational amplifiers have been specified for the
preamplifier. Table 4.2 shows a comparison of the suggested op-amps.


Power
Supply
Gain-BW
Product
(MHz)
Bias
current
(nA)
Slew
Rate
(V/us)
THD
(%)
Noise
(nV/\Hz)
NE5532 6V - 22V 10 20 8 0.0004 8
OPA2134 2.5V - 18V 8 0.005 20 0.002 8
TL072 7V - 18V 3 0.02 13 0.003 18
Table 4.2: Comparison of Operational Amplifiers

The OPA2134 has the most excellent performance among the 3 op-amps. However, it is
naturally more expensive and is not available in local shops. Therefore, NE5532 is
chosen because of its availability and has lower noise as compared to TL072. However, it
is power hungry since it has high input bias currents.
25


The NE5532 is an internally compensated dual low noise OP-AMP. The high small
signal and power bandwidth provides superior performance. It is also a low-power device
that can be operated from a single voltage supply, therefore appropriate for battery-
operated circuits.

The gain is only a function of the feedback and gain resistors, so the feedback has
accomplished its function of making the gain independent of the op amp parameters.

Gain = 21
2 . 2
47
3
4
~
O
O
=
k
k
R
R


The impedance level does not set the gain; the ratio of R4/R3 does. The circuit input
impedance is set by R3 because the inverting input is held at a virtual ground.


Figure 4.5: Schematic Diagram of Preamplifier


4.2.4 Low Pass Filter

In this project, it is desired to filter out the high-frequency sounds picked up by the
microphone which make it difficult to listen to (low-frequency) bodily sounds (e.g., a
heart beating). As such, the frequency response specifications do not need to be
26

extremely accurate since we are dealing with audible frequencies and the human ear
cannot discern frequencies that are close together [16]. Filters that use op-amps as the
active element provide several advantages over passive filters (R, L, and C elements
only). The op-amp provides gain, so that the signal is not attenuated as it passes through
the filter. The high input impedance of the op-amp prevents excessive loading of the
driving source, and the low output impedance of the op-amp prevents the filter from
being affected by the load that it is driving. Active filters are also easy to adjust over a
wide frequency range without altering the desired response.

The Sallen-Key filter is used since it is a popular filter due to its versatility and ease of
design. The Sallen-Key is one of the most common configurations for a second-order
(two-pole) filter.

Letting R R R = = 2 1 , and C C C = = 2 1 , results in:
RC
fc
t 2
1
= and
K
Q

=
3
1
. Now
and Q are independent of one another, and design is greatly simplified although limited.
The gain of the circuit now determines Q. RC sets - the capacitor chosen and the
resistor calculated. One minor drawback is that since the gain controls the Q of the
circuit, further gain or attenuation may be necessary to achieve the desired signal gain in
the pass band.
fc
fc

In Figure 4.6, it shows a precision 2-pole Sallen-Key Butterworth low-pass filter that
cuts-off frequencies above 100Hz and 1000Hz. Heartbeat and respiration sounds are
passed and background sounds are reduced. A frequency switch for heart sounds
(20~100Hz) and respiration sounds (20~1000Hz) will be incorporated which allows the
listener to concentrate on a particular sound.




27


Figure 4.6: Schematic Diagram of Low-Pass Filter

For heart sounds (20~100Hz),
Since and O = = k R R 33 2 1 nF C C 47 2 1 = = ,
z
nF k RC
fc H ~
O
= = 100
) 47 )( 33 ( 2
1
2
1
t t


For respiration sounds (20~1000Hz),
Since and O = = k R R 33 2 1 nF C C 7 . 4 2 1 = = ,
z
nF k RC
fc H ~
O
= = 1000
) 7 . 4 )( 33 ( 2
1
2
1
t t


The op-amp in the second-order Sallen-Key filter acts as a non-inverting amplifier with
the negative feedback provided by the R9/R10 network. The damping factor is set by the
values of R9 and R10, thus making the filter response Butterworth, Chebyshev, or Bessel.
Table 4.3 shows a comparison of the filter responses. The R9/R10 ratio must be 0.586 to
produce the damping factor of 1.414 required for a second-order Butterworth response.

For a Butterworth response,
28

586 . 0 10 / 9 = R R
By choosing R10 = 56k,
O ~ O = = k k R R 33 ) 56 ( 586 . 0 ) 10 ( 586 . 0 9

The overall gain is set by the ratio of R9 and R10. The gain is 6 . 1
10
9
1 ~ +
R
R



Advantages Disadvantages
Butterworth Response
It provides maximally flat
magnitude response in the
pass-band. It has good all-
around performance. Its
pulse response is better than
Chebyshev. Its rate of
attenuation is better than
that of Bessel.
Some overshoot and ringing
is exhibited in step
response.
Chebyshev Response
It provides better
attenuation beyond the
pass-band than Butterworth.
Ripple in pass-band may be
objectionable. There is
considerable ringing in step
response.
Bessel Response
It provides best step
response: very little
overshoot or ringing.
It exhibits slower rate of
attenuation beyond the
pass-band than Butterworth.

Table 4.3: Comparison of Various Filter Responses




29

4.2.5 Power Amplifier

There are two primary factors that control the frequency response of an amplifier circuit;
these are the choice of active components (such as transistors and ICs), and the design of
input and output coupling networks.

The LM386 circuit is an audio amplifier designed for use in low voltage consumer
applications which provides both voltage and current gain for signals. The inputs are
ground referenced while the output automatically biases to one-half the supply voltage.
The quiescent power drain is only 24 milliwatts when operating from a 6 volt supply,
making the LM386 ideal for battery operation.

This chip has been a popular choice for low-power audio applications for many years.
There are many other audio amp ICs on the market, but the LM386 is sufficient for the
purposes. Another benefit about the LM386 is that the gain-frequency curve can be
shaped with some external feedback components, so it is a very flexible device.


Figure 4.7: Schematic Diagram of Power Amplifier


30

The gain is internally set to 20 to keep external part count low, but the addition of an
external resistor and capacitor between pins 1 and 8 can increase the gain to any value
from 20 to 200.

All the capacitors and resistors were non-critical except for the 1000uF output coupling
capacitor, C11, which couples the audio but blocks the half-supply DC voltage at the
output of the LM386 from going to the earphones. The other values are only required for
the Zobel network which neutralizes the effect of the voice coil's inductance. The diodes,
D1 and D2 clamp the input voltage on pin 3 at +/- 0.7V, to ensure that excessive voltage
is never applied to this pin, which could damage the circuit. The 1K value for R13 fully-
charges C11 in 1 second.


4.2.6 Combination of Individual Circuits

Combining all the individual parts to complete the circuit often leads to unavoidable
interactions between filter response characteristics, noise, and other circuit characteristics.
It should always begin by prototyping separate gain, offset, and filter stages, and then
combine them if possible after each individual circuit function has been verified. The
overall schematic of the circuit can be found in Appendix A.

Gain from preamplifier circuit = 21
Gain from Sally-Key low-pass filter = 1.6
Gain from power amplifier = 20

Overall gain = 336
2
20 6 . 1 21
=


The reason why the overall gain was divided by half was due to the voltage divider that
cut the gain to half.


31

4.3 Software Design

The software for this project is completely designed in Matlab.


4.3.1 Graphical User Interface

In order to meet the objectives stated in Chapter 1, a Graphical User Interface (GUI) was
developed. Figure 4.8 shows the user interface.

The full program codes can be summarized into the following main modules;

1) Recording of heart beat and respiration signals from the hardware prototype
2) Displaying the signals in different waveforms
3) Displaying of heart beat rate
4) Stores the data in the computer
5) Replaying of the data stored
6) Filtering the signal
7) Enable user to choose the recording quality

This GUI is divided into one main GUI and two sub GUIs. The main GUI will include all
of the above main modules except 6 and 7. One of the sub GUIs is to allow the user to
choose the recording quality. The other sub GUI allows the user to choose the filtering
parameters. The Matlab code can be found in Appendix D to F.



32


Figure 4.8: User Interface


4.3.2 Time Analysis

A signal is generally a function of many variables. Signal in a function of time is the most
fundamental analysis as it displays the signal amplitude varying in time. Time-domain
signal allows other properties to be determined such as energy and power of the signal.
Figure 4.9 shows a normal heart sound in time-domain representation.


S1 S2
Figure 4.9: Normal heart sound showing S1 and S2

33

4.3.3 Frequency Analysis

Spectrum analysis is one of the basic methods to analyze signal that is also referred to as
the frequency analysis. The signal is decomposed and represented in terms of its
frequency components. The spectrum analysis of heart sound is shown in Figure 4.10.


Figure 4.10: Power spectrum of normal heart sound

Based on Figure 4.10, the power spectrum of heart sound is able to show frequency
content of the signal. However, this method is unable to localize the frequency content
prior to time-varying characteristic in the time-domain representation and failed to
determine the frequency at a particular time. Thus, an alternative method will be required
to display and differentiate various types of heart sounds.


4.3.4 Time-Frequency Analysis

Time-frequency analysis is chosen to analyze time-varying and non-stationary signals
such as heart sounds. It has been used successfully in applications such as speech analysis,
communication and biomedicine signals.


4.3.4.1 Spectrogram
34


One of the best-known time-frequency distributions is the spectrogram, defined as the
squared magnitude of the short-time Fourier transform. The spectrogram of heart sound is
shown in Figure 4.11.


Figure 4.11: Spectrogram of normal heart sound


4.3.5 Digital Filter

A low-pass digital filter is designed using various analog prototypes: Butterworth,
Chebyshev and Elliptic. The optimum filter type is chosen on the basis of implementation
complexity, magnitude response and phase response. In terms of passband ripple, the
Butterworth filter gives the optimum response. The frequency response of the
Butterworth filter is maximally flat (has no ripples) in the passband, and rolls off towards
zero in the stopband. The elliptic and Chebyshev filters both have much more ripple in
the passband. So, there is a tradeoff between these three different types of filters.
Butterworth filter is most likely the optimum choice since it have a more linear phase
response in the passband than the Chebyshev and elliptic filters. Figure 4.12 shows one of
the sub GUIs, which allows the user to choose the parameters for filtering.
35


Figure 4.12: GUI of Filter Setting


4.3.6 Heart Rate Calculation

Heart rate is calculated using simple threshold and peak finding. The flow chart of the
heart rate calculation can be found in Appendix B.


4.3.6 Quality of Audio Recordings

The dynamic range of the heart and lungs is 20Hz to 1kHz. In order to preserve sound
quality during recording, sampling should be done at a rate that is at least twice the
highest frequency of interest (1kHz in the case of the heart and lungs). This is known as
the Nyquist sampling rate, the rate at which no aliasing occurs. Of course it is better to
sample at a rate higher than 2kHz, for improved sound quality. Figure 4.13 shows the
user interface of the recording option. The recording option is one of the sub GUIs, which
is called from the main GUI in Figure 4.8. It allows the user to change the sampling
frequency and bit resolution.

36


Figure 4.13: GUI of Recording Option














37

CHAPTER 5

RESULTS AND ANALYSIS



The hardware design which composes of the following major parts: power supply, sensor,
preamplifier, low-pass filter and power amplifier were individually simulated and/or
tested before the hardware prototype was completely assembled as shown in Figure 5.1.


Figure 5.1: The assembly of the electronic stethoscope prototype

The overall circuit was first constructed on a breadboard, shown in Figure 5.2, to debug
and demonstrate that it works properly. The idea of using a breadboard to test the circuit
first is a good practice in general, since it allows debugging of the circuit design more
easily and allows to experiment with different component values.
38


Figure 5.2: Breadboarding of the circuit


5.1 Performance of Power Supply

As one can see, there is a lot of high frequency noise displacing the DC level
(approximately 10mVP-P). Then, far more pronounced, there are regular spikes in excess
of 50mV. Since power supplies are assumed to be stable, any perturbations will couple
directly into the circuit and might cause instability.


Figure 5.1: Oscilloscope view of DC Power Supply pin on non-inverting amplifier
39



The effect of the bypass capacitor on the stability of the output of the non-inverting
amplifier can be seen in Figure 5.2.




Figure 5.2: Output of non-inverting amplifier


5.2 Performance of Low-Pass Filter

In Figure 5.3, a simulation was done using PSpice. It shows a cut-off frequency at 100Hz.

Figure 5.3: Sallen-Key Low-Pass Filter at 100Hz cut-off

40



In Figure 5.4, the same simulation was done with a cut-off frequency at 1000Hz.

Figure 5.4: Sallen-Key Low-Pass Filter at 1000Hz cut-off


5.3 Results of Heart Beat Calculation

The recordings were made in a normal room (some background noise is present in some
recordings). The patients were instructed to breathe normally. Each recording was 10
seconds long, recorded in 16 bits resolution and sampled with 8000 samples per second.
Recordings from 5 subjects were included. The recordings were low-pass filtered with a
2nd order Butterworth filter using a cut-off frequency at 200Hz. The records are shown in
Table 5.1.


Measured Heart
Beat Rate
Actual Heart Beat
Rate
Accuracy (%)
Patient 1 74 85 87.0
Patient 2 72 81 88.0
Patient 3 69 78 88.5
Patient 4 80 87 92.0
Patient 5 90 100 90.0
Table 5.1: Accuracy of the Heart Beat Calculation
41

5.4 Digital Filtering of Heart Signals


Signal contains
S2
S1
noise frequency
Figure 5.5: Time Domain Analysis - signal before filtering

S2 S1
Noise frequencies reduced
Figure 5.6: Time Domain Analysis - signal after filtering


5.5 Problems Encountered

Below is a list of problems encountered during the development of the hardware
prototype.

1 Earthing Problem
During the testing of the hardware prototype, there was a loud buzz coming out from the
output. The buzz is present with or without an input signal. Voltage check was done
across the circuit and found that it was not giving any problem. The op-amp and power
amplifier were replaced but to no available. Finally, the soldering of the components was
42

checked and found that the log potentiometer was not grounded properly.


2 Bad Layout and Soldering of Circuit

After building the hardware prototype on an actual PCB, no output signal was detected.
Voltage check across the circuit was done and found that the op-amp was not powered
correctly and a few components were not grounded properly. The output signal was
detected after the problems were fixed. However, the signal had a lot of noise. Therefore,
another prototype was remade as shown in Figure 5.1.


Figure 5.5: The first prototype assembled



5.6 Shortcoming of the Project

Owning to time constraints and partly the lack of maintaining self discipline and
commitment, some of the individual circuit parts were not tested. More details will be
defined in the next chapter under critical review and reflection.


43

CHAPTER 6

CONCLUSION AND RECOMMENDATION

6.1 Conclusion

Single-supply op amp design is more complicated than split-supply op amp design, but
with a logical design approach excellent results are achieved. Single-supply design was
considered technically limiting because the older op amps had limited capability. Single-
supply op amp design usually involves some form of biasing, and this requires more
thought. Therefore, designing a single supply op amp circuit design that considers input
bias current errors as well as power supply rejection, gain, input and output circuit
bandwidth, etc., can become quite involved. So, single-supply op amp design needs
discipline and a procedure. More attention must be paid to the details to achieve a
successful single supply design.

The signal-to-noise ratio has several components that have to be analyzed. The signal
comes to the op amp with a noise burden caused by the transducer, cabling, and
connections. Making the op amp a filter/amplifier combination eliminates some of this
noise. There is always system noise, and a portion of this noise propagates through the op
amp into the signal. The system noise is minimized by extensive use of decoupling
capacitors.

The heart beat rate calculation using simple threshold and peak finding is not as accurate
as expected.

Overall, this project was a really enriching experience. The process of this project has
certainly equipped me with the necessary skills by research information, selecting
44

components, design circuit, calculation, testing and troubleshooting of the circuits. The
issues that arise had certainly provided me with the platform for a problem based learning
experiences.

Cardiac auscultation remains an important diagnostic tool, when performed skillfully, can
provide clinicians with a wealth of information regarding patients cardiac health.
However, the standard acoustic stethoscope which has been useful for

more than a
century, cannot process, store, and play back sounds

or provide visual display, and
teaching is hindered because

there is no means to distribute the same sounds
simultaneously

to more than one listener. Modern portable and inexpensive tools

are now
available to provide, through digital electronic means,

better sound quality with visual
display and the ability to

replay sounds of interest at either full or half speed with

no loss
of frequency representation or sound quality. Visual

display is possible in both standard
waveform and spectral formats.

Heart sounds are easily archived and retrieved, in
addition, would allow physicians to keep an archive of retrievable auscultatory
examinations that would allow physicians to track the progression of cardiovascular
disease in patients based on auscultatory findings. Permanent auscultatory records could
be included as part of a patients medical record and may be used to support referrals for
more costly and specialized diagnostic procedures.




6.2 Future Work

No project is ever complete for there is always room for improvement. Throughout the
different stages of the progress, some of the areas that could benefit from improvements
were noted down.

The obvious deficiencies with this project are:

1) It is monophonic (not stereo): For a true stereo output, a separate amplifier is needed
45


2) It is not very efficient in terms of battery life: It would be better to use OPA2134 as it
consumes a lot less power than NE5532.

3) Low roll-off rate from the low-pass filter: To achieve higher roll-off rate, it can be
done by cascading two two-pole low-pass filters as shown in Figure 6.1. The reason
for only using a 2 pole filter is also to reduce the size of the circuit board.

4) Heart beat rate calculation not near prefect: By using a more complex algorithm such
as autocorrelation, the heart beat rate calculation can be more accurate.



Figure 6.1: 4 Pole Low-Pass Filter

Advances in technology with the introduction of electronic stethoscopes mean that early
detection of heart disease is fast becoming a reality in primary care settings. Evaluating
the acoustic properties of the heart using auscultation methods with a traditional
stethoscope has long been the trusted method of assessment. However, the continually
evolving technology over the past ten years of microchip development means that
electronic stethoscopes have the facility to analyze and measure heart sounds in a more
objective manner. Now practitioners can rely less on their subjective judgement and own
hearing ability to gain an accurate representation of sounds using the electronic version.
46

Software versions allow downloads to computer after digitally recording heart sounds for
data analysis. Noise reduction technology reduces noise by 75% on average but still
allows critical body sounds to be heard. Researchers now use this facility to provide
valuable new insight into the diagnostic value of the heart sounds and the analysis
techniques adopted using PC downloaded recordings include wavelet transform and
neural network. It is anticipated that with further technical advances in the field of the
development of electronic models, the possible detection of heart disease early in a
patients examination is likely to be a scenario seen far more predominantly in a
physicians office.


6.3 Critical Review and Reflections

To review upon the project and how it has progressed, I have to summarize by admitting
the level of design, prototyping and user involvement was considered low. I would admit
that the concept has gradually become more and more dilute due to time constraints and
lack of self discipline and commitment. However, I do feel that this project is useful, and
would be extremely well picked up on if it was applied correctly.

The skills which I need improvement were project planning, understanding of Matlab and
PSpice, and report writing. In order to tackle these weaknesses, I did some read up online.
Even though I did some reading, but still, I failed to tackle weaknesses in report writing
and project planning. In general, I am not very pleased with the lack of user involvement
and prototype testing.

To reflect on myself briefly, I have not applied myself or committed myself 100% to this
project, mainly due to other commitments. I feel I am not committed enough to stick to
my Gantt chart and follow the schedule; therefore, there are lapses in my work.



47

Reference



[1] Luisada AA. The auditory system of man. In: Green WH, ed. The Sounds of the
Normal Heart. St Louis, Mo: Warren H. Green, Inc.;1972:23-25

[2] Butterworth JS, Chassin MR, McGrath R. Cardiac Auscultation.New York, NY:
Grune & Stratton; 1955

[3] http://solutions.3m.com/wps/portal/3M/en_WW/globallittmann/home/stethoscope
/model-3000/

[4] Salinsky, M. 1990. Early Chapters in the Stethoscope's Evolution. JAMA.
264(21):2817

[5] Abdulla, Ri. 2001. The History of the Stethoscope. Pediatric Cardiology.Sept-Oct;
22(5):371-2

[6] Bishop, P.J. 1980. Evolution of the Stethoscope. Journal of the Royal Society of
Medicine.73:448-456

[7] Sheldon, P.B. 1935. The Development of the Stethoscope. Bulletin of the New
York Academy ofMedicine. 11:608-626

[8] http://en.wikipedia.org/wiki/Stethoscope

[9] Epstein EJ. Heart sounds. In: Cardiac Auscultation. Oxford, England:
Butterworth-Heinemann Ltd.; 1991:24-44

48

[10] A. G. Tilkian and M. B. Conover, Understanding heart sounds and murmurs: with
an introduction to lung sounds, 4. ed. Philadelphia: Saunders, 2001

[11] R. B. Northrop, Noninvasive instrumentation and measurement in medical
diagnosis. Boca Raton, Fla., London: CRC; Chapman & Hall, 2002

[12] H. Nygaard, "Evaluation of Heart Sounds and Murmurs - a Review with Special
Reference to Aortic Valve Stenosis," Department of Electrical Engineering,
College of Engineering, Aarhus, Denmark 1996

[13] L. Vannuccini, J. E. Earis, P. Helist, B. M. G. Cheetham, M. Rossi, A. R. A.
Sovijrvi, and J. Vanderschoot, "Capturing and preprocessing of respiratory
sounds," Eur Respir Rev, vol. 10, pp. 616-620, 2000

[14] 3rd Kuala Lumpur International Conference on Biomedical Engineering 2006
Biomed 2006, 11 14 December 2006 Kuala Lumpur, Malaysia

[15] Michael, T.A.D., Auscultation of the Heart. 1997. McGraw-Hill, New York.

[16] Jason D. Lohn and Silvano P. Colombano, Automated analog circuit synthesis
using a linear representation, Volume 1478/1998 of Evolvable Systems: From
Biology to Hardware

[17] Ricardo A. Losada, Digital Filters with MATLAB

[18] B.P. Marchant, Time-frequency Analysis for Biosystems Engineering,
Biosystems Engineering 85(3), pp. 261-281, 2003



49

Appendix A Overall Circuit Schematic and Bill of
Material (BOM)

50

RefDes Part Description Value Quantity Tolerance Rating
R1 1/4W Resistor 10k 1 5% 1/4W
R3 1/4W Resistor 2.2k 1 5% 1/4W
R4, R5,
R6
1/4W Resistor 47k 3 5% 1/4W
R7, R8,
R9
1/4W resistor 33k 3 5% 1/4W
R8 1/4W resistor 56k 1 5% 1/4W
R2, R13 1/4W resistor 1k 2 5% 1/4W
R12 1/4W resistor 3.9 1 5% 1/4W
R11 Log Potentiometer 10k 1
C1 Electrolytic Capacitor 470uF 1 20% 16V
C2 Electrolytic Capacitor 10uF 2 20% 25V
C3, C8 Electrolytic Capacitor 1uF 2 20% 50V
C10 Electrolytic Capacitor 4.7uF 1 20% 25V
C4, C6
Metalized Plastic-film
Capacitor
0.047uF 2 5% 63V
C5, C7
Metalized Plastic-film
Capacitor
0.0047uF 2 5% 100V
C11,
C12
Electrolytic Capacitor 1000uF 2 20% 16V
C9 Ceramic Capacitor 0.1uF 1 50V
D1, D2 1N4142 Diode 2
D3 Green LED 1
U1
NE5532 Dual low noise
OP-AMP
1
U2
LM386 Low Voltage Audio
Power
1
51

Amplifier
MIC
Two-wire Electret
Microphone
1
J1
1/8" Stereo Headphones
Jack
1
















52

Appendix B Flow-chart of Heart Rate Calculation














53

Appendix C Typical electret condenser microphone
properties

Property Unit Value Comment
Supply Voltage V 1.5 - 3 2V typical
Supply Current A
200 -
300
Set by
Phantom
biasing
Resistor
Interface Resistor k 2
Maximum Sound
Pressure (SPL)
dB 108
For THD <
0.5%
ECM
sensitivity
dBV -44
Without JFET
gain
Signal to
Noise (SNR)
dB 55
With typical
JFET
Frequency Response Hz
20 -
20000


Property Unit Value Comment















54

Appendix D Matlab Code (Main GUI)

function varargout = gui(varargin)
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gui_OpeningFcn, ...
'gui_OutputFcn', @gui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin & isstr(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end

% End initialization code - DO NOT EDIT

% --- Executes just before gui is made visible.
function gui_OpeningFcn(hObject, eventdata, handles, varargin)
global axes_signal axes_spec cb_undock cb_undock2 Fs nbits Fs2 nbits2
statustext1 statustext2 statustext3 statustext4
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui (see VARARGIN)
% Choose default command line output for gui
handles.output = hObject;
axes_signal = handles.axes_signal;
axes_spec = handles.axes_spec;
cb_undock = handles.cb_undock;
cb_undock2 = handles.cb_undock2;
Fs = get(handles.tx_fs,'String');Fs = str2num(Fs);
nbits = get(handles.tx_nbits,'String');nbits = str2num(nbits);

Fs2 = get(handles.tx_fs2,'String');Fs2 = str2num(Fs2);
nbits2 = get(handles.tx_nbits2,'String');nbits2 = str2num(nbits2);

statustext1 = handles.tx_status1;
statustext2 = handles.tx_status2;
statustext3 = handles.tx_status3;
statustext4 = handles.tx_status4;
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes gui wait for user response (see UIRESUME)
55

% uiwait(handles.figure1);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%


% --- Outputs from this function are returned to the command line.
function varargout = gui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

%set(handles.bt_zoom_in,'Enable','off');
%set(handles.bt_zoom_out,'Enable','off');
set(handles.bt_play,'Enable','off');
set(handles.bt_playstop,'Enable','off');
set(handles.bt_save,'Enable','off');
set(handles.bt_recordstop,'Visible','off');
set(handles.bt_recordstop,'Enable','off');
set(handles.bt_option,'Enable','on');
set(handles.bt_filter,'Enable','off');
set(handles.bt_playoutput,'Visible','off');
%set(handles.bt_playoutput,'Enable','off');
set(handles.bt_stopoutput,'Visible','off');
%set(handles.bt_stopoutput,'Enable','on');
set(handles.pop_menu,'Visible','off');
set(handles.cb_undock,'Visible','off');
set(handles.pop_menu2,'Visible','off');
set(handles.cb_undock2,'Visible','off');





% --- Executes on button press in bt_record.
function bt_record_Callback(hObject, eventdata, handles)

global micrecorder Fs nbits

%Fs = get(handles.tx_fs2,'String');Fs = str2num(Fs);
%nbits = get(handles.tx_nbits2,'String');nbits = str2num(nbits);

set(handles.bt_recordstop,'Visible','on');
set(handles.bt_recordstop,'Enable','on');
set(handles.bt_record,'Visible','off');
set(handles.bt_record,'Enable','off ; ')
text=['Recording..'];addtext(text);
56



micrecorder = audiorecorder(Fs,nbits,1); %initialize recorder
record(micrecorder); %recording data


%set(handles.bt_zoom_in,'Enable','off');
%set(handles.bt_zoom_out,'Enable','off');
set(handles.bt_play,'Enable','off');
set(handles.bt_playstop,'Enable','off');
set(handles.bt_save,'Enable','off');
set(handles.bt_load,'Enable','off');
set(handles.bt_option,'Enable','off');
set(handles.bt_filter,'Enable','off');
set(handles.bt_playoutput,'Visible','off');
set(handles.bt_stopoutput,'Visible','off');


%clears the string in the edit box
set(handles.tx_heartrate,'stri','')
set(handles.tx_fs2,'stri','')
set(handles.tx_nbits2,'stri','')
set(handles.tx_time,'stri','')

cla(handles.axes_signal)
cla(handles.axes_spec)
guidata(hObject, handles);



% --- Executes on button press in bt_save.
function bt_save_Callback(hObject, eventdata, handles)
global Fs2 data

[filename, pathname] = uiputfile('*.wav', 'Save Data to Wave File');
if filename ~= 0
wavwrite(data,Fs2,[pathname filename])
end


% --- Executes on button press in bt_load.
function bt_load_Callback(hObject, eventdata, handles)

global data axes_signal

[filename, pathname] = uigetfile('*.wav','select a wave file to load');

set(handles.tx_load_file,'String',[pathname filename]); % check file is
selected

if filename== 0

57

return;

end

cla(handles.axes_signal)
cla(handles.axes_spec)

[data,Fs,nbits] = wavread([pathname filename]); %Get data and
sampling rate
assignin('base','data',data);
assignin('base','Fs',Fs);


datalen=length(data);
startsampl=1;
endsampl=max(datalen);

%Set data fields
set(handles.tx_fs2,'String',num2str(Fs));
set(handles.tx_nbits2,'String',num2str(nbits));
set(handles.tx_time,'String',[num2str(length(data)/Fs)]);


%Make buttons available
set(handles.bt_play,'Enable','on');
set(handles.bt_playstop,'Enable','on');
set(handles.bt_recordstop,'Enable','on');
set(handles.bt_option,'Enable','on');
set(handles.bt_filter,'Enable','on' );
set(handles.bt_save,'Enable','on');
set(handles.pop_menu,'Visible','on');
set(handles.cb_undock,'Visible','on');


%set region sliders
set(handles.slider_start,'Max',max(datalen));
set(handles.slider_start,'Min',1);
set(handles.slider_start,'Value',1);
set(handles.slider_end,'Max',max(datalen));
set(handles.slider_end,'Min',1);
set(handles.slider_end,'Value',max(datalen));



undock = 0;
undock = get(handles.cb_undock,'Value');
timedata(axes_signal,data,Fs,undock);% displays the time graph of the
signal



for i=1;
58


AmpSig(1:2*Fs(1,i),i)=1000*abs(data(1:2*Fs(1,i),i).^2);

[SigMax(i,1),SigInd(i,1)]=max(AmpSig(1:2*Fs(1,i),i));
thresh_1(i,1)=round(0.85*SigMax(i,1));


q=0;
while (AmpSig(q+1,i)<=thresh_1(i,1))&& (q < 2*Fs(1,i))%% Search for
first peak
q=q+1;
end
Peak1Loc(i,1)=q; %% Store peak location
PeakMask(i,1)=Peak1Loc(i,1)+ 8000;%% create a mask of 8000 pts away
from first peak
r=PeakMask(i,1);
while (AmpSig(r,i)<=thresh_1(i,1))&&(q < 2*Fs(1,i)) %% Search for
second peak
r=r+1;
end
Peak2Loc(i,1)=r; %% Store second peak location
p2p(i,1)=Peak2Loc(i,1)-Peak1Loc(i,1);%% number of samples between 1
beat
% Heart rate Calculations
samp_sec(i,1)=Fs(1,i); %% calculate samples per second
beat_samp(i,1)=1/p2p(i,1); %% calculate beats per sample
RateSec(i,1)=samp_sec(i,1).*beat_samp(i,1); %% calculate heart rate per
sec
RateMin(i,1)=RateSec(i,1)*60; %% beats per min
% Heart rate segment done
HBeat=num2str(RateMin(i,1));
K=cat(2,HBeat);
set(handles.tx_heartrate,'String',num2str(K));
end




% --- playing entire file
function bt_play_Callback(hObject, eventdata, handles)

global player data

startsampl =
get(handles.slider_start,'Value');startsampl=round(startsampl); %get
slider positions
endsampl =
get(handles.slider_end,'Value');endsampl=round(endsampl);

text=['Playing..'];addtext(text);


Fs = get(handles.tx_fs2,'String');Fs = str2num(Fs);
59

nbits = get(handles.tx_nbits2,'String');nbits = str2num(nbits);


%data = getaudiodata(micrecorder);
player = audioplayer(data,Fs,nbits); %initialize player
play(player,[startsampl endsampl]);%playback
pause((endsampl-startsampl)/Fs);




% --- playing entire file
function bt_recordstop_Callback(hObject, eventdata, handles)
global micrecorder data axes_signal Fs nbits

stop(micrecorder);
data = getaudiodata(micrecorder);%get the recorded data
assignin('base','data',data);
assignin('base','Fs',Fs);

datalen=length(data);

%Make buttons available
set(handles.bt_recordstop,'Visible','off');
set(handles.bt_recordstop,'Enable','off');
set(handles.bt_record,'Visible','on');
set(handles.bt_record,'Enable','on');
%set(handles.bt_zoom_in,'Enable','on');
%set(handles.bt_zoom_out,'Enable','on');
set(handles.bt_play,'Enable','on');
set(handles.bt_playstop,'Enable','on');
set(handles.bt_save,'Enable','on');
set(handles.bt_load,'Enable','on');
set(handles.bt_option,'Enable','on');
set(handles.bt_filter,'Enable','on');
set(handles.pop_menu,'Visible','on');
set(handles.cb_undock,'Visible','on');

%Set data fields
set(handles.tx_fs2,'String',num2str(Fs));
set(handles.tx_nbits2,'String',num2str(nbits));
set(handles.tx_time,'String',[num2str(length(data)/Fs)]);

text=['Recording stopped.'];addtext(text);

%set region sliders
set(handles.slider_start,'Max',max(datalen));
set(handles.slider_start,'Min',1);
set(handles.slider_start,'Value',1);
set(handles.slider_end,'Max',max(datalen));
set(handles.slider_end,'Min',1);
set(handles.slider_end,'Value',max(datalen));

60




undock = 0;
undock = get(handles.cb_undock,'Value');
timedata(axes_signal,data,Fs,undock);% displays the time graph of the
signal

for i=1;

AmpSig(1:2*Fs(1,i),i)=1000*abs(data(1:2*Fs(1,i),i).^2);
[SigMax(i,1),SigInd(i,1)]=max(AmpSig(1:2*Fs(1,i),i));
thresh_1(i,1)=round(0.85*SigMax(i,1));
q=0;
while (AmpSig(q+1,i)<=thresh_1(i,1))&& (q < 2*Fs(1,i))%% Search for
first peak
q=q+1;
end
Peak1Loc(i,1)=q; %% Store peak location
PeakMask(i,1)=Peak1Loc(i,1)+ 8000;%% create a mask of 8000 pts away
from first peak
r=PeakMask(i,1);
while (AmpSig(r,i)<=thresh_1(i,1))&&(q < 2*Fs(1,i)) %% Search for
second peak
r=r+1;
end
Peak2Loc(i,1)=r; %% Store second peak location
p2p(i,1)=Peak2Loc(i,1)-Peak1Loc(i,1);%% number of samples between 1
beat
% Heart rate Calculations
samp_sec(i,1)=Fs(1,i); %% calculate samples per second
beat_samp(i,1)=1/p2p(i,1); %% calculate beats per sample
RateSec(i,1)=samp_sec(i,1).*beat_samp(i,1); %% calculate heart rate per
sec
RateMin(i,1)=RateSec(i,1)*60; %% beats per min
% Heart rate segment done
HBeat=num2str(RateMin(i,1));
K=cat(2,HBeat);
set(handles.tx_heartrate,'String',num2str(K));
%msgbox(K)
end



% --- Executes on button press in bt_playstop.
function bt_playstop_Callback(hObject, eventdata, handles)
% hObject handle to bt_playstop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global player

stop(player);

text=['Playing stopped.'];addtext(text);
61





% --- Executes on button press in bt_close.
function bt_close_Callback(hObject, eventdata, handles)

close;














% --- Executes on slider movement.
function slider_start_Callback(hObject, eventdata, handles)

global data


Fs = get(handles.tx_fs2,'String');Fs = str2num(Fs);
startsampl =
get(handles.slider_start,'Value');startsampl=round(startsampl);
line_handle = findobj(gca,'LineStyle',':','Color','r');
if exist('line_handle')== 1
delete(line_handle);
end
line_handle1 =
line([startsampl/Fs,startsampl/Fs],[min(min(data)),max(max(data))],'Col
or',[1 0 0],'LineStyle',':','LineWidth',1.5);







% --- Executes on slider movement.
function slider_end_Callback(hObject, eventdata, handles)

global data

62


Fs = get(handles.tx_fs2,'String');Fs = str2num(Fs);
endsampl = get(handles.slider_end,'Value');endsampl=round(endsampl);
line_handle = findobj(gca,'LineStyle',':','Color','m');
if exist('line_handle')== 1
delete(line_handle);
end
line_handle2 =
line([endsampl/Fs,endsampl/Fs],[min(min(data)),max(max(data))],'Color',
[1 0 1],'LineStyle',':','LineWidth',1.5);


% --- Executes on selection change in pop_menu.
function pop_menu_Callback(hObject, eventdata, handles)
global axes_signal data

undock = 0;
undock = get(handles.cb_undock,'Value');
Fs = get(handles.tx_fs2,'String');Fs = str2num(Fs);

switch get(handles.pop_menu,'Value')

case 1
timedata(axes_signal,data,Fs,undock);
case 2
psddata(axes_signal,data,Fs,undock);
case 3
spectdata(axes_signal,data,Fs,undock);
case 4
fftdata(axes_signal,data,Fs,undock);

end



% --- Executes on button press in cb_undock.
function cb_undock_Callback(hObject, eventdata, handles)
%


% --- Executes on button press in bt_option.
function bt_option_Callback(hObject, eventdata, handles)

%call the gui_option
option();


% --- Executes on button press in bt_filter.
function bt_filter_Callback(hObject, eventdata, handles)
%filterfile(handles);
filter();

63




% --- Executes on button press in bt_playoutput.
function bt_playoutput_Callback(hObject, eventdata, handles)
global player

text=['Playing Output..'];addtext(text);
Fs = get(handles.tx_fs2,'String');Fs = str2num(Fs);
nbits = get(handles.tx_nbits2,'String');nbits = str2num(nbits);
f_data = evalin('base','f_data');
player = audioplayer(f_data,Fs,nbits);
play(player);




% --- Executes on button press in bt_stopoutput.
function bt_stopoutput_Callback(hObject, eventdata, handles)
global player

text=['Playing stopped.'];addtext(text);
stop(player);


% --- Executes on selection change in pop_menu2.
function pop_menu2_Callback(hObject, eventdata, handles)
global axes_spec

undock = 0;
undock = get(handles.cb_undock2,'Value');
Fs = get(handles.tx_fs2,'String');Fs = str2num(Fs);
f_data = evalin('base','f_data');

switch get(handles.pop_menu2,'Value')

case 1
timedata2(axes_spec,f_data,Fs,undock);
case 2
psddata2(axes_spec,f_data,Fs,undock);
case 3
spectdata2(axes_spec,f_data,Fs,undock);
case 4
fftdata2(axes_spec,f_data,Fs,undock);

end

% --- Executes on button press in bt_help.
function bt_help_Callback(hObject, eventdata, handles)
%


64


%--------------------------------------------------------
% SUBFUNCTION
function s = push(s,new_item)
% Function 'push' adds 'new_item' to stack 's'
if ~isempty(s)
height = length(s);
s{height+1} = new_item;
else
s{1} = new_item;
end


function H = timedata(Fig,data,Fs,undock)
global cb_undock axes_signal

datlen = length(data)/Fs;
delta_t = 1/Fs;
t = 0:delta_t:(datlen-delta_t);
undock = get(cb_undock,'Value');
if undock == 0
% figure(fig);
H = subplot(axes_signal);
else
figure()
end
plot(t,data(:,1)), xlabel('Time [sec]'), ylabel('Amplitude');
axis([0 datlen min(min(data))-0.01
max(max(data))+0.01]);set(gca,'YGrid','on');
hold on;

hold off;

function H = psddata(Fig,data,Fs,undock)
global cb_undock axes_signal

undock = get(cb_undock,'Value');
if undock == 0

H = subplot(axes_signal);

else
figure()
end

psd(data(:,1))
hold on;


hold off;
set(gca,'XTickLabel',{'0';num2str(0.1*Fs/2);num2str(0.2*Fs/2);num2str(0
.3*Fs/2);num2str(0.4*Fs/2);num2str(0.5*Fs/2); ...
65


num2str(0.6*Fs/2);num2str(0.7*Fs/2);num2str(0.8*Fs/2);num2str(0.9*Fs/2)
;num2str(Fs/2)});
ylabel('Power Spectrum Magnitude [dB]');xlabel('Frequency
[Hz]');title(''); grid on;


function H = fftdata(Fig,data,Fs,undock)
global cb_undock axes_signal

winlen = 2048;
fftlen = 2*winlen;
len = length(data);
w = hamming(winlen)';
a = ceil(length(data)/winlen)*winlen;
data = [data;zeros(a-length(data),1)];%zero-padding
len = length(data);
n = 1;
pos=1;
while (pos+winlen <= len)
frame = data((pos:pos+winlen-1),1).*w'; %windowing
pos = pos + winlen/2; %50% overlap
Y(n,:) = fft(frame,fftlen);
n = n+1;
end
Y = sum(Y)/n;
Y(Y == 0) = 1e-17;
fftdata=20*log10(abs(Y(1:fftlen/2))+eps);

f = (0:fftlen/2-1)*Fs/fftlen;


mini = min(min(fftdata));
if mini < -120
mini = -120;
end

undock = get(cb_undock,'Value');

if undock == 0

H = subplot(axes_signal);

else
figure()
end
plot(f,fftdata);
axis([10 Fs/2 mini max(max(fftdata))+1]);ylabel('Magnitude
[dB]');xlabel('Frequency [Hz]'); grid on;hold on;



hold off;
66


function H = spectdata(Fig,data,Fs,undock)
global cb_undock axes_signal

if length(data) <= Fs
winlen=128;
olap=64;
end
if length(data)>Fs && length(data)<=3*Fs
winlen=256;
olap=128;
end
if length(data)>3*Fs
winlen=512;
olap=256;
end
fftlen = 2*winlen;

undock = get(cb_undock,'Value');

if undock == 0
H = subplot(axes_signal);
specgram(data,fftlen,Fs,hamming(winlen),olap);xlabel('Time [sec]'),
ylabel('Frequency [*10kHz]');
set(gca,'YDir','normal');%colormap('hsv');

else
figure()
specgram(data,2048,Fs,hamming(winlen),olap);xlabel('Time [sec]'),
ylabel('Frequency [kHz]');
set(gca,'YDir','normal');
colorbar; %colormap('hsv');
end

function H = timedata2(Fig,f_data,Fs,undock)
global cb_undock2 axes_spec

datlen = length(f_data)/Fs;
delta_t = 1/Fs;
t = 0:delta_t:(datlen-delta_t);
undock = get(cb_undock2,'Value');
if undock == 0
% figure(fig);
H = subplot(axes_spec);
else
figure()
end
plot(t,f_data(:,1)), xlabel('Time [sec]'), ylabel('Amplitude');
axis([0 datlen min(min(f_data))-0.01
max(max(f_data))+0.01]);set(gca,'YGrid','on');
hold on;

hold off;

67

function H = psddata2(Fig,f_data,Fs,undock)
global cb_undock2 axes_spec

undock = get(cb_undock2,'Value');
if undock == 0

H = subplot(axes_spec);

else
figure()
end

psd(f_data(:,1))
hold on;


hold off;
set(gca,'XTickLabel',{'0';num2str(0.1*Fs/2);num2str(0.2*Fs/2);num2str(0
.3*Fs/2);num2str(0.4*Fs/2);num2str(0.5*Fs/2); ...

num2str(0.6*Fs/2);num2str(0.7*Fs/2);num2str(0.8*Fs/2);num2str(0.9*Fs/2)
;num2str(Fs/2)});
ylabel('Power Spectrum Magnitude [dB]');xlabel('Frequency
[Hz]');title(''); grid on;


function H = fftdata2(Fig,f_data,Fs,undock)
global cb_undock2 axes_spec
winlen = 2048;
fftlen = 2*winlen;
len = length(f_data);
w = hamming(winlen)';
a = ceil(length(f_data)/winlen)*winlen;
f_data = [f_data;zeros(a-length(f_data),1)];%zero-padding
len = length(f_data);
n = 1;
pos=1;
while (pos+winlen <= len)
frame = f_data((pos:pos+winlen-1),1).*w'; %windowing
pos = pos + winlen/2; %50% overlap
Y(n,:) = fft(frame,fftlen);
n = n+1;
end
Y = sum(Y)/n;
Y(Y == 0) = 1e-17;
fftdata2=20*log10(abs(Y(1:fftlen/2))+eps);

f = (0:fftlen/2-1)*Fs/fftlen;


mini = min(min(fftdata2));
if mini < -120
mini = -120;
end
68


undock = get(cb_undock2,'Value');

if undock == 0

H = subplot(axes_spec);

else
figure()
end
plot(f,fftdata2);
axis([10 Fs/2 mini max(max(fftdata2))+1]);ylabel('Magnitude
[dB]');xlabel('Frequency [Hz]'); grid on;hold on;



hold off;

function H = spectdata2(Fig,f_data,Fs,undock)
global cb_undock2 axes_spec

if length(f_data) <= Fs
winlen=128;
olap=64;
end
if length(f_data)>Fs && length(f_data)<=3*Fs
winlen=256;
olap=128;
end
if length(f_data)>3*Fs
winlen=512;
olap=256;
end
fftlen = 2*winlen;

undock = get(cb_undock2,'Value');

if undock == 0
H = subplot(axes_spec);
specgram(f_data,fftlen,Fs,hamming(winlen),olap);xlabel('Time
[sec]'), ylabel('Frequency [*10kHz]');
set(gca,'YDir','normal');%colormap('hsv');

else
figure()
specgram(f_data,2048,Fs,hamming(winlen),olap);xlabel('Time [sec]'),
ylabel('Frequency [kHz]');
set(gca,'YDir','normal');
colorbar; %colormap('hsv');
end


function text = addtext(text)
69

global statustext1 statustext2 statustext3 statustext4
%displays textmessages
text1=get(statustext1,'String');
text2=get(statustext2,'String');
text3=get(statustext3,'String');
text4=get(statustext4,'String');

text1=text2;
text2=text3;
text3=text4 ;
text4=text;

set(statustext1,'String',text1);
set(statustext2,'String',text2);
set(statustext3,'String',text3);
set(statustext4,'String',text4);























70

Appendix E Matlab Code (Sub GUI for Filter Setting)

function varargout = Filter(varargin)
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @Filter_OpeningFcn, ...
'gui_OutputFcn', @Filter_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback []); ',
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Filter is made visible.
function Filter_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to Filter (see VARARGIN)

% Choose default command line output for Filter
handles.output = hObject;
mainFigureHandle = gui; %stores the figure handle of Quan's GUI here
mainGUIdata = guidata(mainFigureHandle);
mainGUIposition = get(mainGUIdata.figure1,'Position');
subGUIposition = get(handles.figure1,'Position');
subGUIposition =
[mainGUIposition(2)+mainGUIposition(1),subGUIposition(2),subGUIposition
(3),subGUIposition(4)];
set(handles.figure1,'Position',subGUIposition);


set(mainGUIdata.bt_play,'Enable','on');
set(mainGUIdata.bt_playstop,'Enable','on');
set(mainGUIdata.bt_save,'Enable','on');
set(mainGUIdata.bt_load,'Enable','on');
set(mainGUIdata.bt_option,'Enable','on');
set(mainGUIdata.bt_filter,'Enable','on');
set(mainGUIdata.pop_menu,'Visible','on');
set(mainGUIdata.cb_undock,'Visible','on');
set(mainGUIdata.pop_menu2,'Visible','on');
71

set(mainGUIdata.cb_undock2,'Visible','on');
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Filter wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Filter_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;



set(handles.tx_lowpass,'Enable','off');
set(handles.tx_highpass,'Enable','off');



% --- Executes on selection change in pop_filter.
function pop_filter_Callback(hObject, eventdata, handles)

switch get(handles.pop_filter,'Value')
case(1)
%
case(2)
set(handles.tx_lowpass,'Enable','on');
set(handles.tx_highpass,'Enable','off');
case(3)
set(handles.tx_lowpass,'Enable','off');
set(handles.tx_highpass,'Enable','on');
otherwise

end





% --- Executes on button press in bt_ok.
function bt_ok_Callback(hObject, eventdata, handles)
global axes_spec

s = get(handles.pop_type,'Value');
s1 = get(handles.pop_filter,'Value' );
n = get(handles.pop_order,'Value');
72


final=(s*10) + s1;
Fs = evalin('base', 'Fs');
switch(final )
case(12)
fpass = str2num(get(handles.tx_lowpass,'String'));
wn = fpass*2/Fs;
[b,a] = butter(n,wn,'low');



case(13)
fpass = str2num(get(handles.tx_highpass,'String'));
wn = fpass*2/Fs;
[b,a] = butter(n,wn,'high');


end

data = evalin('base','data');
f_data = filter(b,a,data);
assignin('base','f_data',f_data);
assignin('base','b',b);
assignin('base','a',a);

% get the main gui handle (access to the gui)
mainGUIhandle = gui;
% get the data from the gui (all handles inside gui_main)
mainGUIdata = guidata(mainGUIhandle);

% plot to main gui
axes_spec = mainGUIdata.axes_spec;

timedata(axes_spec,f_data,Fs);% displays time graph


% save changed data back into main gui
guidata(gui, mainGUIdata);

close(filter);

set(mainGUIdata.bt_playoutput,'Visible','on');
set(mainGUIdata.bt_stopoutput,'Visible','on');
set(mainGUIdata.pop_menu2,'Visible','on');
set(mainGUIdata.cb_undock2,'Visible','on');




% --- Executes on selection change in pop_type.
function pop_type_Callback(hObject, eventdata, handles)

73


%guidata(hObject, handles);



% --- Executes on button press in bt_set.
function bt_set_Callback(hObject, eventdata, handles)

s = get(handles.pop_type,'Value');
s1 = get(handles.pop_filter,'Value' );
n = get(handles.pop_order,'Value');

final=(s*10) + s1;
Fs = evalin('base', 'Fs');

switch(final)
case(12)
fpass = str2num(get(handles.tx_lowpass,'String'));

wn = fpass*2/Fs;
[b,a] = butter(n,wn,'low');


case(13)
fpass = str2num(get(handles.tx_highpass,'String'));
wn = fpass*2/Fs;
[b,a] = butter(n,wn,'high');


end

[H,w]=freqz(b,a,512,1);
axes(handles.axes_filter);
plot(w,20*log10(abs(H)));
grid on;
title ('Frequency Response of Digital Filter');
xlabel('Frequency (Hz)');
ylabel('Magnuitude (dB)')







% --- Executes on button press in bt_cancel.
function bt_cancel_Callback(hObject, eventdata, handles)

close(filter);


74




%--------------------------------------------------------
% SUBFUNCTION

function H = timedata(Fig,f_data,Fs)
global axes_spec

datlen = length(f_data)/Fs;
delta_t = 1/Fs;
t = 0:delta_t:(datlen-delta_t);

H = subplot(axes_spec);

plot(t,f_data), xlabel('Time [sec]'), ylabel('Amplitude');
axis([0 datlen min(min(f_data))-0.01
max(max(f_data))+0.01]);set(gca,'YGrid','on');
hold on;

hold off;


















75

Appendix F Matlab Code (Sub GUI for Recording
Option)

function varargout = option(varargin)
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @option_OpeningFcn, ...
'gui_OutputFcn', @option_OutputFcn, ...
'gui_LayoutFcn', [], ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before option is made visible.
function option_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin unrecognized PropertyName/PropertyValue pairs from the
% command line (see VARARGIN)



% Choose default command line output for option
handles.output = hObject;
mainFigureHandle = gui; %stores the figure handle of Quan's GUI here
mainGUIdata = guidata(mainFigureHandle);
mainGUIposition = get(mainGUIdata.figure1,'Position');
subGUIposition = get(handles.figure1,'Position');
subGUIposition =
[mainGUIposition(2)+mainGUIposition(1),subGUIposition(2),subGUIposition
(3),subGUIposition(4)];
set(handles.figure1,'Position',subGUIposition);


set(mainGUIdata.bt_play,'Enable','on');
set(mainGUIdata.bt_playstop,'Enable','on');
set(mainGUIdata.bt_save,'Enable','on');
set(mainGUIdata.bt_load,'Enable','on');
76

set(mainGUIdata.bt_option,'Enable','on');
set(mainGUIdata.bt_filter,'Enable','on');
set(mainGUIdata.pop_menu,'Visible','on');
set(mainGUIdata.cb_undock,'Visible','on');
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes option wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = option_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;
set(handles.tx_nbits,'Visible','off');
set(handles.tx_fs,'enable','off');


% --- Executes on button press in bt_ok.
function bt_ok_Callback(hObject, eventdata, handles)

% get the main_gui handle (access to the gui)
mainGUIhandle = gui;
% get the data from the gui (all handles inside gui_main)
mainGUIdata = guidata(mainGUIhandle);

% change gui strings
set(mainGUIdata.tx_fs, 'String', get(handles.tx_fs, 'String'));
set(mainGUIdata.tx_nbits, 'String', get(handles.tx_nbits, 'String'));




% save changed data back into main_gui
guidata(gui, mainGUIdata);

% close this gui
close(option);


% --- Executes on button press in bt_cancel.
function bt_cancel_Callback(hObject, eventdata, handles)

% close this gui
close(option);

77


% --- Executes on selection change in pop_fs.
function pop_fs_Callback(hObject, eventdata, handles)

switch get(handles.pop_fs,'Value')
case 1
set(handles.tx_fs,'string',1000);
case 2
set(handles.tx_fs,'string',2000);
case 3
set(handles.tx_fs,'string',4000);
case 4
set(handles.tx_fs,'string',8000);
case 5
set(handles.tx_fs,'enable','on');
otherwise
end

guidata(hObject, handles);


% --- Executes on selection change in pop_nbits.
function pop_nbits_Callback(hObject, eventdata, handles)

switch get(handles.pop_nbits,'Value')
case 1
set(handles.tx_nbits,'string',8);
case 2
set(handles.tx_nbits,'string',16);
case 3
set(handles.tx_nbits,'string',24);
otherwise
end

guidata(hObject, handles);



function tx_fs_Callback(hObject, eventdata, handles)

input = str2num(get(hObject,'String'));

%checks to see if input is empty. if so, default input1_editText to
zero
if (isempty(input))
set(hObject,'String','1000')
end
guidata(hObject, handles);




function tx_nbits_Callback(hObject, eventdata, handles)
78


79

input = str2num(get(hObject,'String'));

guidata(hObject, handles);

Das könnte Ihnen auch gefallen