87
UNIVERSITI TEKNOLOGI MALAYSIA NOTES : * If the thesis is CONFIDENTIAL or RESTRICTED, please attach with the letter from the organisation with period and reasons for confidentiality or restriction. DECLARATION OF THESIS / UNDERGRADUATE PROJECT PAPER AND COPYRIGHT Author’s full name : JOHNNY KONG JAK KAN Date of birth : 14 th AUGUST 1988 Title : FIR DIGITAL FILTER ON FPGA FOR ECG SIGNAL PROCESSING Academic Session : 2011/2012 I declare that this thesis is classified as: CONFIDENTIAL (Contains confidential information under the Official Secret Act 1972)* RESTRICTED (Contains restricted information as specified by the organisation where research was done)* OPEN ACCESS I agree that my thesis to be published as online open access (full text) I acknowledged that Universiti Teknologi Malaysia reserves the right as follows: 1. The thesis is the property of Universiti Teknologi Malaysia. 2. The Library of Universiti Teknologi Malaysia has the right to make copies for the purpose of research only. 3. The Library has the right to make copies of the thesis for academic exchange. Certified by: SIGNATURE SIGNATURE OF SUPERVISOR 880814-52-5905 PROF. DR. MOHAMED KHALIL HANI (NEW IC NO./ PASSPORT NO.) NAME OF SUPERVISOR Date: 28 JUNE 2012 Date: 28 JUNE 2012 PSZ 19:16 (Pind. 1/07)

10_JOHNNYKONGJAKKAN.pdf

Embed Size (px)

Citation preview

UNIVERSITI TEKNOLOGI MALAYSIA

NOTES : * If the thesis is CONFIDENTIAL or RESTRICTED, please attach with the letter from

the organisation with period and reasons for confidentiality or restriction.

DECLARATION OF THESIS / UNDERGRADUATE PROJECT PAPER AND COPYRIGHT

Author’s full name : JOHNNY KONG JAK KAN Date of birth : 14th AUGUST 1988

Title : FIR DIGITAL FILTER ON FPGA FOR ECG SIGNAL PROCESSING

Academic Session : 2011/2012 I declare that this thesis is classified as:

CONFIDENTIAL (Contains confidential information under the

Official Secret Act 1972)*

RESTRICTED (Contains restricted information as specified by the

organisation where research was done)*

OPEN ACCESS I agree that my thesis to be published as online open access (full text)

I acknowledged that Universiti Teknologi Malaysia reserves the right as follows:

1. The thesis is the property of Universiti Teknologi Malaysia. 2. The Library of Universiti Teknologi Malaysia has the right to make copies for the

purpose of research only. 3. The Library has the right to make copies of the thesis for academic exchange.

Certified by:

SIGNATURE SIGNATURE OF SUPERVISOR

880814-52-5905 PROF. DR. MOHAMED KHALIL HANI (NEW IC NO./ PASSPORT NO.) NAME OF SUPERVISOR

Date: 28 JUNE 2012 Date: 28 JUNE 2012

PSZ 19:16 (Pind. 1/07)

“I hereby declare that I have read this thesis and in my opinion this thesis is sufficient in

terms of scope and quality for the award of the degree of

Bachelor of Engineering (Computer).”

Signature :

Name of Supervisor : PROF. DR. MOHAMED KHALIL HANI

Date : 28 JUNE 2012

FIR DIGITAL FILTER ON FPGA FOR ECG SIGNAL PROCESSING

JOHNNY KONG JAK KAN

A thesis submitted in the fulfillment of the

requirements for the award of the degree of

Bachelor of Engineering (Computer)

Faculty of Electrical Engineering

Universiti Teknologi Malaysia

JUNE 2012

ii

I declare that this thesis entitled “FIR Digital Filter on FPGA for ECG Signal Processing”

is the result of my own research except as cited in the references. The thesis has not been

accepted for any degree and is not concurrently submitted in candidature of any other

degree.

Signature :

Name : JOHNNY KONG JAK KAN

Date : 28 JUNE 2012

iii

My genuine dedications to my dearest mother

iv

ACKNOWLEDGEMENTS

“Knowing is not enough; we must apply. Willing is not enough; we must do.”

(Johann Wolfgang von Goethe, 1749-1832).

First and foremost, I would like to convey my deepest gratitude from the bottom

of my heart to my supervisor, Prof. Dr. Mohamed Khalil who has been the most

influential person. His support, guidance and advice throughout the research project are

very much appreciated.

I extend my sincere acknowledgements to all my mentors and friends especially

Mr. Sia, Mr. Lum and Mr. Wong. Thank you so much and I am glad to have you all who

are ready to listen and willing to give a hand when I am needed. They are my own “souls

out of my soul” who keep my spirits up when the muses fail me.

Before I conclude, I would like to dedicate my deep and sincere appreciation to

my beloved family and my fiancée, Miss Hii who always support me, encourage me and

listen to me along my research.

v

ABSTRACT

Electrocardiogram (ECG) signal can be used to count the heart rate beat for

various diagnostic purposes in medicine. There are many research are related to the ECG

signal such as fatigue driver detection using ECG signal. However, most of the captured

ECG signal will be distorted by the noise that cause by the measurement instrument.

Sometimes, the noise will totally mask the ECG signal. The signal is hardly to be

processed for further analysis. Therefore, it is essential that the ECG signal must be

filtered to avoid the failure detection of the signal. FIR Digital filter is used to filter the

noise in ECG signal. There are some advantages that the FIR digital filter is chosen. Due

to all zero structures of FIR filters, it is guaranteed to be stable. Moreover, FIR digital

filter is simple to design and it has linear phase characteristics. This project aims for

implementation option that satisfies the requirement on flexibility and portability such as

speed enhancement and hardware cost. The project has achieved the target to filter the

noise in ECG signal using a low pass filter. The output of ECG signal is compared with

the ECG signal before filtering by plotting the signal in time domain and frequency

domain using MATLAB. FIR serial architecture technique is used for the hardware

design in order to minimize the hardware resource. However, the design tradeoff for this

hardware architecture is that it will result in higher delay due to serial of data

computation. Hence, a future study of FIR linear phase characteristics can be carried out.

vi

ABSTRAK

Isyarat elektrokardiogram (ECG) boleh digunakan untuk pengiraan kadar

denyutan jantung bagi tujuan dalam bidang perubatan. Terdapat pelbagai penyelidikan

tentang isyarat ECG seperti pengesanan keletihan pemandu melalui isyarat ECG. Walau

bagaimanapun, kebanyakan isyarat ECG telah dihingar akibat alat pengukuran. Kadang

kala, isyarat ECG telah diliputi oleh hingar. Isyarat ECG tidak dapat diproses untuk

analisis lanjutan. Oleh itu, isyarat ECG mesti ditapis dahulu untuk mengelakkan

kegagalan pengesanan isyarat ECG. Penapis digit FIR digunakan untuk menapis hingar

dalam isyarat ECG kerana ianya sangat stabil, mudah direka bentuk dan mempunyai

ciri-ciri fasa lelurus. Projek ini berusaha mencari kaedah untuk memenuhi keperluan dari

segi fleksibiliti dan kemudahalihan seperti peningkatan kelajuan dan kos peranti keras.

Dalam projek ini, penapis digit laluan rendah telah direka dan berjaya menapis hingar

dalam isyarat ECG. Output isyarat ECG dan isyarat ECG yang belum ditapis telah

diplotkan dalam domain masa dan domain frekuensi dengan menggunakan MATLAB

untuk tujuan perbandigan kedua-dua isyarat tersebut. Teknik reka bentuk FIR secara siri

telah digunakan dalam projek ini dengan tujuan mengurangkan penggunaan peranti

keras. Namun demikian, teknik ini akan megakibatkan kritikal kelewatan disebabkan

pengiraan data secara siri. Oleh itu, kajian masa depan tentang fasa lelurus FIR boleh

dijalankan.

vii

TABLE OF CONTENTS

CHAPTER TITLE PAGE

DECLARATION ii

DEDICATION iii

ACKNOWLEGEMENTS iv

ABSTRACT v

ABSTRAK vi

TABLE OF CONTENTS vii

LIST OF TABLE x

LIST OF FIGURES xi

LIST OF ABBREVIATION xiii

LIST OF SYMBOLS xiv

1 INTRODUCTION 1

1.1 Background of Study 1

1.2 Problem Statement 3

1.3 Objectives 3

1.4 Scope of Project 4

1.5 Report Outline 4

2 THEORY & LITERATURE REVIEW 5

2.1 Noise in ECG signal 5

2.2 Advantages of FIR Digital Filter 6

viii

2.3 FIR Filter Design 7

2.3.1 Linear Phase FIR Design Using Windows Method 8

2.3.2 Equiripple Linear Phase Filters 11

2.3.2.1 Remex Exchange (Parks-McClellan) 13

2.3.2.2 Alternation Theorem 15

2.4 Quantization 18

2.4.1 Finite Word Length Effects 18

2.5 Structures for Discrete-Time System 19

2.5.1 Direct Form Structures 20

2.5.2 Linear Phase FIR Structures 21

2.6 Hardware Architecture 22

2.6.1 Low Pass Serial FIR Filter Architecture 23

2.6.2 Parallel low pass FIR Filter with Serial Adder Connection 24

2.6.3 Parallel Low Pass FIR filter with Branch Tree Adder Connection 25

2.7 Advantages of Hardware Implementation of FIR Digital Filters on FPGA 26

3 METHODOLOGY 27

3.1 Overall Flowchart 27

3.2 FIR Filter Specifications 29

3.3 Realization on Filter Structures 30

3.4 Conversion of Coefficient to Integer 31

3.5 Hardware Implementation 33

3.6 Project Timeline 35

4 SYSTEM DESIGN AND IMPLEMENTATION 36

4.1 FIR Low Pass Filter Design Using MATLAB 37

4.2 Datapath Unit Design 38

ix

4.3 Control UnitDesign 42

4.4 Interface Design 45

4.5 System on Programmable Chip (SOPC) 47

4.6 Firmware Design 49

5 RESULT AND DISCCUSSION 51

5.1 Input Data 52

5.2 Comparison of ECG Signals 56

5.3 Hardware Limitations 56

6 CONCLUSION AND RECOMMENDATION 58

6.1 Conclusion 58

6.2 Recommendation for Future Works 59

REFERENCES 61

APPENDICES 63

x

LIST OF TABLE

TABLE NO. TITLE PAGE

2.1

Some Common Windows

11

2.2 Frequency response of linear phase filters 13

2.3 Basic block diagram structures and their functionality 19

3.1 Design Specification of FIR Low Pass Filter 30

3.2 Numeric Representation Format in 16-bit 32

3.3 Comparison between partial original coefficients and

modified coefficient

33

4.1 Activated and deactivated control vector signals 43

xi

LIST OF FIGURES

FIGURENO. TITLE PAGE

1.1

Basic block diagram of a basic filter.

2

1.2 Sample of ECG signal. 2

2.1 Filter specifications for a low pass filter. 8

2.2 Convolution process implied by truncation of the ideal impulse

response. The higher the area under side lobe, the larger will be

the ripples in pass band and stop band.

9

2.3 Typical approximation resulting from windowing the ideal

impulse. The width of the transition region between pass band

and stop band in H(w) increases with the width of the main

lobe W(w).

10

2.4 DTFT of a typical window, characterized by the width of main

lobe and peak side lobe. A is the amplitude of W (ejw) at w = 0.

10

2.5 Direct form I structures. 20

2.6 Direct form II structures. 21

2.7 Linear phase FIR structures. 22

2.8 Block diagram for serial FIR filter architecture. 23

2.9 Block diagram for FIR filter architecture with serial adder

connection.

24

2.10 Block diagram for FIR filter with branch tree adder connection 25

3.1 Workflow for designing low pass FIR digital filter. 28

xii

3.2 Magnitude frequency response of a low pass filter with 50

order.

29

3.3 Structure of a FIR filter of order L. 31

3.4 Gantt chart for semester 1. 36

3.5 Gantt chart for semester 2. 36

4.1 ECG signal with noise plotted in time domain and frequency

domain.

38

4.2 Filtered ECG signal using MATLAB. 39

4.3 Functional block diagram for serial FIR filter architecture 40

4.4 The block diagram of datapath unit for FIR low pass filter

synthesized from Quartus.

41

4.5 ASM chart for FIR low pass filter design. 44

4.6 Block diagram of connection between FIR low pass filter with

system interconnect fabric.

46

4.7 Altera SOPC Builder. 48

4.8 Quartus programmer that downloads the FIR filter into FPGA. 48

5.1 Sample 1 of raw ECG. 52

5.2 Filtered ECG signal Altera FPGA DE2 Board. 53

5.3 Filtered ECG signal using MATLAB. 53

5.4 Sample 2 of raw ECG signal. 54

5.5 Filtered ECG signal using Altera FPGA DE2 Board. 54

5.6 Filtered ECG signal using MATLAB. 55

xiii

LIST OF ABBREVIATION

FIR - Finite Impulse Response

IIR - Infinite Impulse Response

MATLAB - Matrix Laboratory

PCB - Printed Circuit Board

ECG - Electrocardiogram

FPGA - Field-Programmable Gate Array

VHDL - Hardware Description Language

DE 2 board - Development and Education 2 board

LCCDE - Linear Constant-Coefficient Difference Equation

FDA tool - Filter Design & Analysis Tool

ASM - Algorithmic State Machine

xiv

LIST OF SYMBOLS

Hz - Hertz

wc - Pass Band Frequency

ws - Stop Band Frequency

훿 - Stop Band Deviation

훿 - Pass Band Deviation

wp - Pass Band Frequency

∆푓 - Transition Width

CHAPTER 1

INTRODUCTION

This chapter presents the background of study, problem statement, objectives,

scope of the project and report organization.

1.1 Background of Study

In signal processing, filters play an important role to remove the unwanted

signals such as noise or extract the important part of the signals that lie within certain

frequency range. Finite impulse response (FIR) filter and infinite impulse response (IIR)

filter are the two primary types of filters. The main difference between these two types

of filters is that FIR filter does not have feedback while IIR filter does have feedback.

Nowadays, digital filters are widely used in the electronic industry as they are easy to

design. MATLAB is the common software tool that enables users to design desired

digital filters. There are many types of filters such as low pass filter, high pass filter,

2

band pass filter and band stop filter. Due to the all zero structures, FIR digital filter is

very stable. Figure 1.1 shows a basic block diagram of a basic filter.

Digital filters are programmable. This feature helps to reduce the design cycle

and minimizes the risk of design. Moreover, digital filters perform noiseless

mathematical operations at each intermediate step in transforming [1]. Digital filters are

extremely stable with respect both to time and temperature and perform low frequency

signals accurately [6].

Figure 1.1: Basic block diagram of a basic filter.

Figure 1.2: Sample of ECG signal.

In Figure 1.2, it shows a sample of electrocardiogram (ECG) signal. The ECG is

an electrical signal that shows the functioning heart of a person [4]. It is the heart rate

3

variability of a person which can be used for diagnostic purpose in medicine. However,

the captured ECG signal is usually contaminated by noise. Therefore, it is important to

filter the noise to prevent any mistakes in further analysis of the signal.

1.2 Problem Statement

ECG signal can be applied in the detection of a fatigue driver whether he is

sleepy. However, the captured ECG signal is distorted by noise caused by measurement

equipment. The presence of noise will lead to failure detection of the ECG signal in

further analysis. Moreover, it is essential to minimize the hardware resources used in

FPGA. Having a lot of multiply units is not area efficient. Therefore, it is essential to

filter the noise that exists in ECG signal and implement an optimized hardware in FPGA.

1.3 Objectives

The objectives of this project are

(1) To design a low pass digital filter to remove noise in the electrocardiogram

(ECG) signal.

(2) To implement the FIR digital filter using VHDL code on Altera FPGA DE2-

50 board.

4

1.4 Scope of Project

The scope of this project is to design a low pass FIR filter that can remove the

noise (above 45Hz) in ECG signal using MATLAB. ECG signal is plotted in frequency

domain to identify the noise. The signals that exist above 45 Hz are treated as noise. The

designed low pass FIR digital filter is implemented on Altera FPGA DE2-50 Board.

Software tools such as Quartus and Nios II are used to design and implement the low

pass FIR digital filter.

1.5 Report Outline

The report consists of 6 chapters. Chapter 1 is the introduction that contains the

background of study, problem statement, objectives, scope of the project and report

outline. The second chapter is about the theory and literature review. In chapter 3, it

discusses about the methodology and overall workflow of this project. In Chapter 4

discusses about the system design and implementation of low pass FIR digital filter.

Chapter 5 is mainly about the result and discussion of this project. Lastly, Chapter 6

summarizes the work that has been completed throughout the project and future works

are proposed.

CHAPTER 2

THEORY & LITERATURE REVIEW

In this chapter, it presents the overview and theories behind noise in ECG signal,

advantages and types of FIR low pass digital filter, filter coefficient calculation and

effect of quantization. Apart from that, related work about FIR digital filter structures

and architectures of hardware design will be discussed.

2.1 Noise in ECG signal

Electrocardiogram (ECG) testing and analysis is an important means to

understand the functionality of a heart, diagnosis of cardiovascular diseases and assess

various treatments. The ECG in body surface has a strong random and background noise

which is non-linear, non-stationary weak signal [2]. Therefore, ECG signals that being

captured is usually distorted by noise. Two main noise that present in ECG signal are

baseline wander noise (caused by breathing, movement and electrode contact of a person)

and power line interface noise (caused by muscle contraction noise and monitoring

6

equipment). The frequency range of baseline wander noise is below 0.5 Hz. 50 Hz or 60

Hz power line interface noise will also distort the ECG signals. Sometimes ECG signal

is totally masked by power line interface noise [3] [4] [5]. Hence, the power line

interface noise must be removed before the signals are applied for future analysis.

2.2 Advantages of FIR Digital Filter

(i) FIR digital filters are simple to design. In realization of FIR filters, direct

form structures can be used as it is easy.

(ii) FIR filters are guaranteed to be stable due to all zero structures and have

linear phase.

(iii) FIR filters also have low sensitivity to filter coefficient quantization errors

which will ease in hardware implementation [6].

(iv) FIR digital filters can transmit all frequencies with the same amount of delay.

Hence, there will be no phase distortion and the input signal will be delayed by a

constant when it is transmitted to the output. A filter with constant group delay is

highly desirable in the transmission of digital signal [7].

7

2.3 FIR Filter Design

The transfer function in z-transform for a FIR system is shown as below MzMbzbzbbzH )(...)2()1()( 21

01

(2.1)

The difference equation of FIR filter

)()(...)1()1()()0(

)()()(0

MnxMbnxbnxb

knxkbnyM

k

(2.2)

The input function )(nx is the unit sample function δ(n), the output )(ny can be

obtained by summing out the unit sample input that convolved with unit sample impulse

response (b(0), b(1), b(2), b(3), …, b(M))denoted by h(n). In equation (2.2), h (n) = b (k),

which means that the unit impulse response h (n) of the discrete-time system described

by the difference equation in equation (2.2) is finite in length. Therefore, the system is

known as finite impulse response [7].

Before designing a filter, the filter specifications must be defined. For example,

to design a low pass filter with a cutoff frequency wc, the frequency response of an ideal

low pass filter with linear phase and a cutoff frequency wcis

0)(

jj e

eh

c

c

(2.3)

which has a unit sample response

)()sin(

)(

n

nnh c

(2.4)

8

Most of the idealized frequency response has discontinuities or abrupt jump at

the boundaries between bands. Hence, the impulse response becomes non-causal and

unstable. To avoid these problems, it is necessary to truncate the ideal impulse response

by allowing some deviation from the ideal response. The deviation includes the pass

band cutoff frequency, wc, stop band cutoff frequency, ws, pass band deviation,훿 and

stop band deviation,훿 [8]. Figure 2.1 shows the filter specification for a low pass filter

whereas Dpass is the pass band deviation,훿 , Dstop is the stop band deviation,훿 , Fpassis

pass band cutoff frequency and Fstop is the stop band frequency.

Figure 2.1: Filter specifications for a low pass filter.

2.3.1 Linear Phase FIR Design Using Windows Method

FIR filters design using Windows method is the simplest form of design. Let

hd(n)be the unit sample response.

0

)(][

nhnh d

otherwiseMn 0

(2.5)

9

Since hd(n) will be infinite in length, it is essential to obtain a FIR approximation

Hd(ejw). Using window design method, the filter is designed by windowing the unit

sample response.

h[n] = hd(n)w(n) (2.6)

where

01

)(nw otherwise

Mn 0

(2.7)

w(n) is a finite-length window.

deWeHeWeHeH wjjd

jwjwd

jw )()(21)(*)(

21)( )(

(2.8)

Figure 2.2: Convolution process implied by truncation of the ideal impulse response.

The higher the area under side lobe, the larger will be the ripples in pass band and stop

band [16].

10

Figure 2.3: Typical approximation resulting from windowing the ideal impulse. The

width of the transition region between pass band and stop band in H(w)increases with

the width of the main lobe W(w)[16].

Figure 2.4: DTFT of a typical window, characterized by the width of main lobe and

peak side lobe. A is the amplitude of W (ejw) at w = 0 [17].

The performance of frequency response of a filter designed with window design

method approximates is determined by the width of the main lobe W (ejw) and peak side

11

lobe amplitude of W (ejw). For an ideal window, the main lobe must be narrow and the

side lobe amplitude must be small. But for a fixed length window, there are several

constrains regarding on main lobe and peak side lobe amplitude. As the frequency band

gets narrower, the length of window will be larger resulting in a decrease in the

transition width between pass band and stop band. The side lobe amplitude is increasing

directly proportional to the increase of window length. Table 2.1 shows some of the

common windows that can be used for FIR digital filter design.

Table 2.1: Some Common Windows [8].

Rectangular

01

)(nwelse

Nn 0

Hanning

0

)2cos(5.05.0)( N

nnw

elseNn 0

Hamming

0

)2cos(46.054.0)( N

nnw

elseNn 0

Blackman

0

)4cos(08.0)2cos(5.042.0)( N

nN

nnw

elseNn 0

2.3.2 Equiripple Linear Phase Filters

Optimum FIR filters have the main goal to achieve the best filter. In another

words, it means smallest error possible. Window design method is a straight forward

method and will result a relatively good performance. But there are two respects where

the windows filters are not optimal. Firstly, the pass band and stop band deviation are

12

approximately equal. The window design method always has the largest error at the

discontinuities. Furthermore, window method does not allow individual control over the

approximation errors in different bands.

With the window design method, it is necessary to overdesign the filter in the

pass band in order to satisfy more strict requirements in the stop band. Secondly, for

most window, the ripple is not uniform neither in the pass band nor in the stop band and

generally it decreases when moving away from the transition band [3]. A typical

description of filter contains the specification of pass band frequency, ωc, stop band

frequency, ωs, ideal gain and allowed deviation (ripple) from the desired transfer

function. A special class of filter that satisfies above said criteria is known as Equiripple

FIR filter [9]. By using algorithmic techniques, better filters can be designed by

minimizing of maximum error. Table 2.2 shows the frequency response of linear phase

filters.

13

Table 2.2: Frequency response of linear phase filters [3].

2.3.2.1 Remex Exchange (Parks-McClellan)

Type I linear phase (Table 2.1 Case 1), is used for the discussion in Parks-

McClellan algorithm. The frequency response of FIR linear phase is written as

H(ejw) = A(ejw)e –jαw (2.9)

A(ejw) is a real valued function of w. For a type I linear phase filter,

h(n)=h(N-n) (2.10)

14

where N is an even integer. The symmetry of h(n) allows the frequency response to be

expressed as

퐴 푒 = 푎(푘)cos(푘푤)

(2.11)

where L = N/2 and

푎(0) = ℎ (2.12)

푎(푘) = ℎ 푘 + 푘 = 1,2, … , (2.13)

The term cos(푘푤) may be expressed as a sum of powers of cos w in the form

cos(푘푤) = 푇 (cos푤) (2.14)

where Tk(x) is a kth-order Chebyshev polynomial, hence,

퐴 푒 = ∑ 훼(푘)(cos푤) (2.15)

A(ejw) is a Lth-order polynomial in cosw. With Ad(ejw) a desired amplitude and W(ejw) a

positive weighting function, let

퐸 푒 = 푊 푒 퐴 푒 − 퐴 푒 (2.16)

15

be a weighted approximation error. The equiripple filter design problem thus involves

finding the coefficients a(k) that minimize the maximum absolute value of E(ejw) over a

set of frequencies, f.

{ |퐸(푒 )|∈ }( ) (2.17)

For example, to design a low pass filter, the set f will be the frequencies in the

passband, [0,wp] and the stop band [ws,π]. The transition band, (wp,ws) is a don’t care

region and it is not considered in the minimization of the weighted error [8].

2.3.2.2 Alternation Theorem

Using alternation theorem, it can give the solution to the optimization of the

problem given in Parks-McClellan. Let f, be a union of closed subsets over the interval

[0, π]. For a positive weighting function W(ejw), a necessary and sufficient condition for

equation 2.11

퐴 푒 = 푎(푘)cos(푘푤)

to be unique function that minimizes the maximum value of the weighted error |E (ejw)|

over the set f is that E (ejw) have at least L+2 alternations or it must be at least L+2

extremal frequencies,

w0< w1< … <wL+1

over the set f such that

)()( 11 kk jwjw eEeE k = 0, 1, …, L (2.18)

and )(max)( 1 jw

fw

jw eEeE k

k= 0, 1, ..., L+1 (2.19)

16

Hence, the alternation theorem states that optimum filter is equiripple. Although

the alternation theorem specifies the minimum number of ripple that the optimum filter

must have, it may have more.

From the alternation theorem, it follows that

kjwjwd

jw eAeAeW k )1()]()()[( k=0, 1, ..., L+1 (2.20)

where )(max jw

fweE

(2.21)

is the maximum absolute weighted error. These equations may be written in matrix form

in terms of the unknowns a (0), ..., a(L) and as follows.

)(

)(

)()(

)(

)1()0(

)(/)1()cos()cos(1)(/)1()cos()cos(1

)(/1)cos()cos(1)(/1)cos()cos(1

1

0

1

1

0

1

11`

11

00

L

L

L

L

jwd

jwd

jwd

jwd

jwLLL

jwLLL

jw

jw

eAeA

eAeA

La

aa

eWLwweWLww

eWLwweWLww

(2.22)

An efficient iterative method, Parks-McClellan algorithm can be used to find the

extremal frequencies (ripple) that involves the following steps.

(1) Guess an initial set of extremal frequencies.

(2) Find by solving equation 2.22. The value of has been shown to be

1

0

1

0

)(/)()1(

)()(L

k

jwk

L

k

jw

k

k

eWkb

eDkb (2.23)

where

1

,1 )cos()cos(1)(

L

kii ik wwkb (2.24)

17

(3) The weighted error functions over the set fis evaluated by interpolating between

the extremal frequencies using the Lagrange interpolation formula.

(4) A new set of extremal frequencies is selected by choosing the L+2 frequencies

for which the interpolated error function is maximum.

(5) If the extremal frequencies have changed, step 2 is repeated.

A design formula below can be used to estimate the filter order of an equiripple filter for

a low pass filter with transition width f , pass band ripple, p and stop band ripple, s

[8].

fN sp

6.14

13)log(10 (2.25)

18

2.4 Quantization

The word length of filter coefficient will determine the accuracy of a filter. The

ideal filter requires infinite word length. However, due to hardware limitation, it is not

practical to implement an ideal filter on hardware [3]. One approach to solve the

problem is rounding off coefficients to a b-bit representation to minimize the hardware

use [11].

2.4.1 Finite Word Length Effects

Since practical digital filter has to be implemented with finite precision and

arithmetic, the filter coefficients, the input and output signals for filters are in discrete

form. Hence, there are four types of finite word length effects. Quantization

(discretization) the filter coefficients will affect the location of poles and zeros of the

filter. Therefore, the actual filter response will have slightly different from the ideal

response. This phenomenon is known as coefficient quantization error. By using the

finite precision arithmetic to quantize the filter coefficients, round off noise will be

created. Round off noise is the error in the filter output that results from rounding the

calculations within filters. Nonlinearity will be caused by quantization of the filter

coefficients. However, for large signals, nonlinearity can be ignored and round off noise

will be the main concern. However, for a recursive filter with a zero or constant input,

this nonlinearity will cause limit cycles. With fixed-point arithmetic, there is a tendency

that the filter calculation to overflow [10].

19

2.5 Structures for Discrete-Time System

The output y[n] of time invariant system is convolution between input signals,

x[n] with impulse response h[n]. The discrete systems can be represented using block

diagrams. Hence, it is easy to transfer the structures to algorithm for programming

purposes. The system is needed to be represented by linear constant-coefficient

difference equations (LCCDE).Table 2.4 shows the function of basic block diagram

structures including addition, multiplication and unit delay.

Table 2.3: Basic block diagram structures and their functionality

Basic Block Diagram Structures Function

Addition of two sequences

Multiplication of a sequence by a

constant

Unit delay

20

2.5.1 Direct Form Structures

If a given transfer function of FIR filter as퐻(푧) = ∑ ℎ(푛)푧 , when N = 4.

Obtain the equivalent algorithm for the output [7]. The first step is to get the linear

constant-coefficient difference equations (LCCDE).

푦(푛) = ℎ(0)푥(푛) + ℎ(1)푥(푛 − 1) + ℎ(2)푥(푛 − 2) + ℎ(3)푥(푛 − 3) + ℎ(4)푥(푛 − 4)

(2.26)

From the LCCDE, we can draw the block diagram as shown in Figure 2.5.

Figure 2.5: Direct form I structures [6].

21

Figure 2.6: Direct form II structures [14].

Both structures require N+1 multiplication, N additions and N delays. Figure 2.6 shows

another type of structures which is similar to direct form I structures.

2.5.2 Linear Phase FIR Structures

The symmetry or anti symmetry property of a linear phase FIR can be exploited

to reduce the number of multipliers into almost half of that in the direct form

implementations. Let consider a length of 7, type 1 FIR transfer function with a

symmetric impulse response.

푦(푛) = ℎ(0)푥(푛) + ℎ(1)푥(푛 − 1) + ℎ(2)푥(푛 − 2) + ℎ(3)푥(푛 − 3) + ℎ(2)푥(푛 −

4) + ℎ(1)푥(푛 − 5) + ℎ(0)푥(푛 − 6) (2.27)

푦(푛) = ℎ(0){푥(푛) + 푥(푛 − 6)} + ℎ(1){푥(푛 − 1) + 푥(푛 − 5)} + ℎ(2){푥(푛 − 2) +

푥(푛 − 4)} + ℎ(3)푥(푛 − 3) (2.28)

22

ℎ(0) = 푓푖푙푡푒푟푐표푒푓푓푖푐푖푒푛푡

푥(푛) = 푖푛푝푢푡푑푎푡푎

푦(푛) = 표푢푡푝푢푡

From the LCCDE above, the realization structures below can be obtained.

Figure 2.7: Linear phase FIR structures [14].

2.6 Hardware Architecture

There are many ways to realize the FIR filter based on the design issues, latency,

filter operation and area-efficiency. From the filter structures shown in Figure 2.5,

Figure 2.6 and Figure 2.7, it is easy to implement hardware of the FIR digital filter.

There are several methods to implement hardware architecture of FIR low pass digital

filter such as serial input serial output and parallel input serial output.

23

2.6.1 Low Pass Serial FIR Filter Architecture

Figure 2.8: Block diagram for serial FIR filter architecture.

The architecture of series FIR filter only requires an adder, a multiplier and a

delay unit. The designed hardware is very slow in term of time taken for data

computation. In another words, this hardware architecture design will result in high

critical delay to obtain the output. However, it is a good choice with respect to hardware

efficiency. It requires less logic elements in the hardware implementation.

24

2.6.2 Parallel Low Pass FIR Filter with Serial Adder Connection

Figure 2.9: Block diagram for FIR filter architecture with serial adder connection [3].

This hardware architecture design can process data in parallel way instead of

processing one by one. But, with respect to hardware efficiency, it is really not cost-

effective. If the designed filter has 50th order filter, it requires approximate 51

multipliers, 51 adders and 51 registers. Hence, in term of hardware use, this design will

require a lot of logic elements. In figure 2.9, it can be observed that all the adders are

connected to the output of previous adder. The output obtained at the output terminal is

the sum of the output of all adders. This will result in high critical delay as well [3].

25

2.6.3 Parallel Low Pass FIR filter with Branch Tree Adder Connection

Figure 2.10: Block diagram for FIR filter with branch tree adder connection [3].

The input data will be passed in parallel form through the registers. Each of the

input data will be multiplied by the filter coefficient and the output data is to sum up all

the output from multiplier. By using the Branch Tree Adder connection, each adder will

compute two outputs from multipliers and gives an output for next adder computation.

The process will end when all the outputs are summed up. This design will really reduce

the critical delay if compared to the serial FIR filter architecture as shown in above.

However the biggest challenge in implementing filters in hardware is to achieve a

specified speed of data processing at minimum hardware cost [3]. In terms of hardware

efficiency, this design is not really good as it requires more resources that will increase

the cost of hardware implementation.

26

2.7 Advantages of Hardware Implementation of FIR Digital Filters on FPGA

Field Programmable Gate Array (FPGA) is a good testing platform for

evaluating and implementing signal processing algorithms due to its programmability,

configurability, low cost, high logic density and high reliability [12] [13]. In designing

FIR digital filters, it requires a lot of multipliers, adders and registers. The multipliers

and adders can be formed using the logical array. Since FPGA is a structured internal

logic array and rich connection resources, it is very suitable for hardware realization on

FIR digital filter.

CHAPTER 3

METHODOLOGY

In this chapter, the details on the methodology to complete this project are

discussed. This project can be divided into two phases. Initially, MATLAB is used to

design the low pass FIR digital filter. Filter coefficients can be generated from

MATLAB. Next, the VHDL programming code is used to implement the low pass FIR

digital filter and the functionality of designed filter is tested.

3.1 Overall Flowchart

Figure 3.1 shows the overall workflow for the methodology. The design of a

digital filter involves five steps. Firstly, the filter specifications is determined which

includes the type of filter (low pass filter, band pass filter, high pass filter), sampling

frequency, word length of the input data, pass band frequency and stop band frequency.

Next will be the filter coefficient calculation. However to ease the flow of the project,

the filter coefficients can be obtained through MATLAB software tools. The third step is

28

to convert the transfer function into a suitable filter structure. The next step is to analysis

the finite word length effect. Due to hardware constraints, the filter coefficients must be

quantized. Hence, the effect of quantizing the filter coefficients and input data using a

fixed word length of the filter performance is analysed. Finally, the last step is to write

VHDL code for the designed filter and its functionality is tested.

Figure 3.1: Workflow for designing low pass FIR digital filter.

29

3.2 FIR Filter Specifications

The design specifications for a FIR digital filter include

(i) Characteristics of the filter (low pass, high pass, bandpass)

(ii) Pass band frequency

(iii) Stop band frequency

(iv) Sampling frequency

(v) Number of order

(vi) How to implement the filter

(vii) Design constraints ( cost, resources limitation)

Figure 3.2: Magnitude frequency response of a low pass filter with 50 order.

The parameters that are interested in filter design specification:

(i) Pass band ripple, 훿

(ii) Stop band ripples,훿

(iii) Stop band frequency, 푤

(iv) Pass band frequency, 푤

(v) Sampling frequency, 푓

30

Table 3.1: Design Specification of FIR Low Pass Filter.

Pass band ripple, 훿 0.06

Stop band ripples,훿 0.0001

Stop band frequency, 푤 45Hz

Pass band frequency, 푤 35Hz

Sampling frequency, 푓 200Hz

Order 50

The magnitude frequency response of low pass filter can be obtained using the

MATLAB fdatool command as shown in Figure 3.2. By asserting the desired value of

stop band frequency, pass band frequency and sampling frequency, MATLAB will

generate the appropriate filter order required. For simplification, the filter coefficients

are generated using the MATLAB FDA tool [3]. Table 3.1 shows the design

specification of FIR low pass filter in this project.

3.3 Realization on Filter Structures

Block diagram can be used to represent the computational algorithm of a FIR

filter. Multipliers, adders and registers are used to represent the basic building block

diagrams. From table 2.4, it shows the functionality of each basic block diagram. These

basic block elements and their equivalent signal flow diagrams are shown in Figure 3.3.

31

Figure 3.3: Structure of a FIR filter of order L.

x [n] is the input data, y [n] is the output data and f [0], f [1], f [2], f [L-2], f [L-1]

are the unit impulse response. Based on the equation (2.1) of a FIR filter, a basic block

diagram can be drawn. This is to simplify in the hardware architecture design.

3.4 Conversion of Coefficient to Integer

To design an ideal filter, it requires an infinite word length of filter coefficients.

However, it is not possible to do so. Hence, an appropriate approach to solve this

problem is to round off the filter coefficients to an X-bit representation [11]. In order to

minimize the hardware used in this project, the filter coefficient will be quantized to 16-

bit data [11]. The filter coefficient has a 16-bit data width whereby the most significant

bit denotes the sign of the data either it is positive or negative. The remained 15-bit is

used for the magnitude of fractions. In table 3.2, it shows the numeric representation

format of 16-bit data width.

32

Table 3.2: Numeric Representation Format in 16-bit.

MSB

(15)

Bit

(14)

Bit

(13)

Bit

(12)

Bit

(11)

Bit

(10)

Bit

(9

Bit

(8)

Sign Fraction Fraction Fraction Fraction Fraction Fraction Fraction

Bit

(7)

Bit

(6)

Bit

(5)

Bit

(4)

Bit

(3)

Bit

(2)

Bit

(1)

LSB

(0)

Fraction Fraction Fraction Fraction Fraction Fraction Fraction Fraction

Since the coefficient number is in floating point format, it has to be converted to

integer. The filter coefficients are converted and rounded off using MATLAB. In this

project design, the filter coefficients are shifted 15 bits to the right and rounded off using

MATLAB to obtain the coefficient in integer form. In table 3.3, it shows the partial of

values comparison between original coefficients and modified coefficients in integer

form. The full comparison of original coefficients and modified coefficients is shown in

Appendix page 70.

33

Table 3.3: Comparison between partial original coefficients and modified coefficient. Tap Original Coefficient in floating point Modified coefficient in integer form

1 0.000335693359375 11

2 0.00018310546875 6

3 -0.00225830078125 -74

4 -0.00811767578125 -266

5 -0.01458740234375 -478

6 -0.01528930664063 -501

7 -0.006378173828125 -209

8 0.006683349609375 219

9 0.01156616210938 379

10 0.002044677734375 67

3.5 Hardware Implementation

FIR filter can be implemented by using an adder, a multiplier and registers. To

optimize the hardware resources used, the number of multipliers is reduced. It is not

area-efficient if using a lot of multipliers. For hardware implementation, if a designed

filter has 50 orders, it requires 51 multipliers for the computation. Implementing 51

multipliers in FPGA board is not an appropriate way as it is not area-efficiency.

Therefore, a circular buffer technique is proposed in this project to implement the

hardware of FIR digital filter.

Pseudo code for the FIR filter program using circular buffering

(1) Update the RAM’s address for the input signal’s circular buffer

(2) Zero the accumulator

(3) Update the ROM’s address for the coefficient’s circular buffer

(4) Multiply the coefficient by the sample

34

(5) Add the product to the accumulator

(6) Repeat step 1 until all the input data is processed.

The above pseudo code step is similar if applied to the hardware design. The

input data and coefficient are stored in RAM and ROM respectively. The addresses of

RAM and ROM will be updated when the arithmetic operation (multiplication and

addition) is done. Then the next input data and coefficient will be computed. The

process will continue until all the input data are processed.

35

3.6 Project Timeline

The workflow for this project is going to be done within two semesters. The

Gantt chart of the project in semester 1 (FYP 1) is shown in Figure 3.5 and semester 2

(FYP 2) is shown in Figure 3.6.

Figure 3.4: Gantt chart for semester 1.

Figure 3.5: Gantt chart for semester 2.

Chapter 4

SYSTEM DESIGN AND IMPLEMENTATION

The final goal of this project is to get the FIR low pass filter running with the

NIOS II processor on the Altera DE2-50 Board. In order to achieve this objective, FIR

low pass filter design is divided into two main parts. Firstly, the filter is initially

designed using MATLAB. The ECG signals are filtered using MATLAB to test the

functionality of the filter. The filter coefficients will be quantized and rounded off

through MATLAB.

To ease the project design, a register-transfer level (RTL) design method is used.

Design of digital systems can be complex. In order to manage the complexity, a modular

hierarchical approach is applied. At the top level of RTL design hierarchy, a digital

system is usually divided into two units that known as control unit and datapath unit.

The hardware design is then followed by interface designs that related to the signal

interaction in between the Avalon Bus Memory Mapped and hardware of the FIR low

pass filter. The designed hardware is tested in Quartus before it is downloaded into

Altera FPGA DE2 Board for further analysis.

37

4.1 FIR Low Pass Filter Design Using MATLAB

In Figure 4.1 the ECG signal is plotted in both time domain and frequency

domain. It is easier to analyse noise region of a signal by plotting it in the frequency

domain. The ECG signal is filtered using the designed low pass FIR digital filter.

Figure 4.1: ECG signal with noise plotted in time domain and frequency domain.

38

Figure 4.2: Filtered ECG signal using MATLAB.

4.2 Datapath Unit Design

The main function of datapath unit is performing the data processing and

computation. The hardware design of FIR filter design can be deduced from the equation

4.1.

푦[푛] = 푎 푥[푛] + 푎 푥[푛 − 1] + 푎 푥[푛 − 2] + ⋯+ 푎 푥[푛 − 49] (4.1)

푦[푛] = 표푢푡푝푢푡

푛 = 푛푢푚푏푒푟표푓푖푛푝푢푡푑푎푡푎

푎 = 푐표푒푓푓푖푐푖푒푛푡, 푖 = 0,1,2, … ,50

39

It is obvious that from equation 4.1, the FIR filter is multiplying and adding all

the time. In order to design the datapath unit, a multiplier, an adder and registers are

used to implement the FIR filter. Figure 4.1, it shows a functional block diagram of the

FIR digital filter. In this project, a ROM is used to store the filter coefficients as the

values are always constant. For the ECG input data, a RAM with 16k word size is used.

The signed adder and signed multiplier in this design are applied from the predefined

module in Altera Quartus software. The size of width size for input data and coefficient

is 16-bit respectively. But the width size for multiplier and adder will be 32-bit. The

ECG signal used to be filtered only contained 10-bit. Hence, the output registers with the

32-bit width is enough to overcome the overflow issue.

In Figure 4.4, it shows the block diagram of datapath unit that was coded using

VHDL programming language and synthesized from Quartus. ROM and RAM are used

to store coefficients and ECG data respectively before any data processing is launched.

The width of input and output for RAM and ROM is 16-bit. In this project design, the

registers, counters, RAM and ROM have a synchronous clock signal. Two registers with

32-bit width are used in the output stage due to the inner register will be cleared when

the computation of input data is done once. At the same time, counter 1 will be cleared

as well. Hence, another register is required to hold the output data. In another words, the

inner register will have asynchronous clear signal that other register and counters. Other

logic elements such as counters, comparators and multiplexer are used for controlling

signals.

40

Figure 4.3: Functional block diagram for serial FIR filter architecture.

41

Figure 4.4: The block diagram of the datapath unit for FIR low pass filter synthesized from Quartus.

Inner register

Outer register

Comparator

Counter 2

Counter 1

Counter 3

ROM

RAM Multiplexer

Multiplier Adder

42

4.3 Control Unit Design

In order to determine the sequence of data processing operation performed by

datapath unit, a control unit is needed. The control unit functions to deliver the control

signals in specified order. For the FIR filter design, a datapath unit requires other logic

elements together to control the sequence of data computation. A multiplexer, three

counters and three comparators are needed. There are other external control signals such

as start signal and load data signal to set up the control unit. Counters are used to count

the total number of input data and point the addresses of ROM and RAM. Comparators

are used to determine in which situation the data processing should begin, stop or

continue. The overall sequence for the FIR filter is illustrated in Figure 4.4. A control

vector table that shows the activated signals at each state is developed.

Initially, the input data will be stored in RAM before any data computation starts.

Counter 3 is a count up counter that used to accumulate the total amount of input data

and determine whether all the input ECG data are computed. Once all the input data are

ready, the start signal will be given to datapath unit to begin the data computation. The

increment and decrement signals are applied to the appropriate counters in order to

update the addresses of RAM and ROM. This is to ensure the data processing for ECG

signals can continue. When one point of output data is completed it will be loaded into

the outer registers and a done one point signal is shown. A done signal will be delivered

if only if all the input data are computed or when the value of counter 3 is less than zero.

43

Table 4.1: Activated and deactivated control vector signals. State Operation Control Vector

done Done_one_

point

clear Rom_

enable

Ram_

enable

Load reg32A Load reg32B sel Wren2 Ld_

counter1

Ld_

counter2

Increment3 Decrement2 Decrement3

S0 mux sel1 0 0 0 0 0 0 0 1 0 0 0 0 0 0

S1 Counter3 +1

RAM2 write1

RAM2 enable1

0 0 0 0 1 0 0 1 1 0 0 1 0 0

S2 Counter3-1

load counter21

clear1

mux sel0

0 0 1 0 0 0 0 0 0 0 1 0 0 1

S3 Done1 1 0 0 0 0 0 0 0 0 0 0 0 0 0

S4 Rom1 enable1

Ram2 enable1

0 0 0 1 1 0 0 0 0 0 0 0 0 0

S5 Rom1 enable1

Ram2 enable1

Load reg32A1

Counter2 -1

Counter1+1

0 0 0 1 1 1 0 0 0 1 0 0 1 0

S6 Load reg32B 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0

S7 Done_one_point1 0 1 0 0 0 0 0 0 0 0 0 0 0 0

44

Figure 4.5: ASM chart for FIR low pass filter design.

45

4.4 Interface Design

In order to read and write interfaces on master and slave components in a

memory-mapped system, Avalon Memory-Mapped interfaces are used. These

components include microprocessors, memories, UART, DMA and timers that

connected with an interconnect fabric. The system Interconnect fabric is a high

bandwidth interconnect structure for connecting components that use the Avalon

Memory-Mapped (Avalon-MM). For the interface design, some signals are fixed and

unchangeable. The signals include the reset signal, clock signal, chipselect signal,

address signal, write signal, writedata signal and readdata signal.

It is the same thing if applied Avalon-MM to the designed FIR low pass filter. In

Figure 4.5, it shows that the connection between FIR filter and system interconnection

fabric. In order to get data from the hardware or input any data to hardware, readdata

and writedata bus will be used respectively. In this project design, the raw ECG data will

be passed through from firmware via writedata bus to the hardware and stored in RAM.

The filtered ECG data will be passed through readdata bus to firmware and stored in a

text file.

46

Figure 4.6: Block diagram of the connection between FIR low pass filter with system interconnect fabric.

47

4.5 System on Programmable Chip (SOPC)

Altera’s Nios II is a soft processor that can be implemented in FPGA devices

using Quartus. In order to implement a useful system or use Nios II processor on the

board, it is necessary to add in other functional units such as memories, input and output

interfaces, and communication interfaces. Therefore, a compatible system on

programmable chip is needed for this task. The SOPC builder system will be varied as it

depends on the requirement of an individual project.

SOPC Builder connects the soft-hardware components by creating a complete

system that runs on FPGA board. The predefined components in SOPC Builder include

SDRAM, on-chip memory, LED, switch, timer, JTAG UART and so on. The

interconnections of these components are connected through the Avalon bus. In Figure

4.6, it shows the Altera SOPC Builder that will be used in this FIR filter design. The

designed FIR filter hardware is treated as a component that will be added in SOPC

Builder. Before generating the SOPC Builder, it is important to auto assign the base

address and IRQs of all the components.

A simple Nios II embedded system is built with some peripherals such as Nios

II/s processor, system ID peripheral, on-chip memory, SDRAM, PLL (clock signal

generation), 18 red LEDs, 8 green LEDs, timers and JTAG UART for data

communication. A system file (.ptf) will be generated when SOPC builder generation is

success. The system file (.ptf) will be downloaded into Altera FPGA DE2-50 board

through Quartus II via USB blaster cable. In Figure 4.7, it shows the download process

of the designed FIR low pass filter into the board. The progress bar shows 100% when

the download is completed.

48

Figure 4.7: Altera SOPC Builder.

Figure 4.8: Quartus programmer that downloads the FIR filter in FPGA.

49

4.6 Firmware Design

Altera Nios II Integrated Development Environment (IDE) is used to design the

desired firmware for FIR filter. In order to access registers in user logic, IORD () and

IOWR () macros are used. IORD reads data out from the hardware while IOWR gives

input data to the hardware. For example, “IOWR

(FILTER_CORE_PROCESSOR_0_BASE, start, 0)”gives start signals from firmware to

hardware. “IORD (FILTER_CORE_PROCESSOR_0_BASE, data_out)” retrieves the

output data from hardware after data processing.

The data of ECG signals are stored in a text file. The preset data length of the

ECG signal is 10000. Therefore, it is impossible for a user to key in the data one by one

into the hardware. One approach to solve this problem is to read the data from text file

and store in array through firmware. The ECG data will be passed from firmware to the

board. After the filtering process is done, the output data should be retrieved back and

stored in text file again for verification. In order to achieve the task, host-based file

system is used. The host-based file system enables programs executing on a target board

to read and write files stored on the host computer. The Nios II IDE transmits file data

over the USB blaster cable. The host-based file system can be accessed using the

standard library I/O functions such as fopen(), fscanf(), fclose() and fprintf(). The host-

based file system is a software component that must be added to the system library.

There are some disadvantages of the host-based file system. Firstly, it only can

operate while debugging a project. It cannot be used for run sessions. The host files data

travels between host and target serially through Altera download cable. Hence, file

access time is quite slow. It takes approximately 10ms per call to the host. Undeniably, it

is compulsory to specific the mount point within the HAL file system to have the file to

be read or written. For instance, in this project the path location is named as

50

“d:/FYP2/software/fir_filter” corresponding to the project directory on the host

computer. A simple code “(d:/FYP2/software/fir_filter/Data1.txt, “r”)” is opening a file

that access to the host system. The full coding for firmware can be obtained in Appendix

page 67.

Therefore, the input data of ECG signal can be easily read from the host and the

output of ECG signal after filtered can be conveniently written back to the host file

system. The filtered ECG data that is stored in a text file can be used to verify the

functionality of FIR low pass filter. MATLAB tool is used to plot the filtered ECG

signal to analysis the signal.

Chapter 5

RESULT AND DISCCUSSION

The captured ECG signals contain the power line interface noise that lies in the

range of 50Hz or 60Hz.This kind of noise normally is caused by the muscle contraction

noise and measurement equipment. The present of noise will lead to failure detection of

the QRS complex. It is essential to remove the unwanted noise before the ECG signals

can be applied for future use like analysis on driver drowsiness detection. Hardware

implementation of FIR filter is to accelerate the filtering process.

In this chapter, unfiltered ECG signals are compared with the filtered ECG

signals using MATLAB. The ECG signals are plotted both in the time domain and

frequency domain. The ECG signals that are filtered through hardware are compared

with the ECG signals filtered through MATLAB.

52

5.1 Input Data

The input data of ECG signal are directly read in from the host-based file system.

The data processing of the signal is done within the board to remove the unwanted noise

in the original signal. All the ECG signal data length is set to 10000.

Figure 5.1: Sample 1 of raw ECG signal.

53

Figure 5.2: Filtered ECG signal using the Altera FPGA DE2 Board.

Figure 5.3: Filtered ECG signal using MATLAB.

54

Figure 5.4: Sample 2 of ECG signal.

Figure 5.5: Filtered ECG signal using the Altera FPGA DE2 Board.

55

Figure 5.6: Filtered ECG signal using MATLAB.

56

5.2 Comparison of ECG Signals

From Figures 5.2 and 5.5 above, it is very obvious that the ECG signals are

filtered successfully. The ECG signals that are filtered using the Altera FPGA DE2

board are plotted both in the time domain and frequency domain using MATLAB. To

ensure the filtered ECG signals from hardware are correct, the same raw ECG signals

are filtered again using MATLAB. Both filtered ECG signal using hardware and

MATLAB are plotted. It can be summarized that the FIR low pass filter is functioning

well. It can filter the noise in the raw ECG signal and gives a similar output if compared

to MATLAB’s output.

If look into the filtered ECG data, there are slight differences between the filtered

ECG signals using Altera FPGA DE2 board and MATLAB. This is due to quantization

of filter coefficient from infinite word length to finite word length. The filter coefficients

are converted and rounded off because of hardware constraints. However, from the

plotting of ECG signals in time domain, it shows that the filter works as expected though

the quantization effect. In this project, the quantization effect is not an impact.

5.3 Hardware Limitations

There are a few hardware limitations in this project design. Firstly, the filter

coefficients obtained from MATLAB are in floating point form. MATLAB can have

very high precision. In order to obtain the same output ECG signal from Altera DE2

Board with MATLAB’s output, it is essential to use the infinite word length for

57

coefficients. However, it is not practical when comes to hardware implementation. To

implement an infinite word length of filter coefficients, it will waste a lot of hardware

resources. Hence, it is necessary to modify and round off the filter coefficient floating

point number into integer form. The modified filter coefficients will have slightly lower

bit precisions if compared to original filter coefficients. This is because filter coefficients

are quantized from infinite word length to finite word length.

Apart from that, Altera Cyclone II DE2-50 Board has very limited memory block.

When designing the FIR filter, a lot of considerations have to be made. In this project

design, RAM is used to store the raw ECG signals. The size of RAM is limited to 16k

word. This is mainly due to the memory block limitation of Altera Cyclone II DE2-50

Board. Therefore, the data length of ECG signal cannot be more than 16k.

CHAPTER 6

CONCLUSION AND RECOMMENDATION

This chapter concludes the work that has been accomplished throughout the

project. It also summarizes the achievements of the project. Areas for future work

towards this project are discussed.

6.1 Conclusion

The project aims to design a low pass digital filter to remove noise in the

electrocardiogram (ECG) signal. The desired low pass digital filter is implemented using

VHDL code on Altera FPGA DE2-50 board. Implementation of FIR filters on FPGA is

essential as FPGA can give enhanced speed. Further analysis like driver drowsiness

detection through ECG signal can use this designed FIR low pass filter to remove the

noise. Before designing the filter, the design specifications such as sampling frequency,

pass band cutoff frequency, stop band cutoff frequency, stop band deviation and pass

59

band deviation must be defined. For simplicity in hardware design, the filter coefficient

can be generated through MATLAB. In designing the digital filter via FPGA the speed

of operation and hardware cost are the main constraints in designing an optimized

hardware. The FIR filter design is depended on the requirement either a low cost

hardware is needed or a fast filter is needed.

In this project, a 50 order low pass filter is implemented in Altera FPGA DE2-50

board. A serial FIR filter architecture approach is applied in this project. This design

method requires less hardware resources but will result in higher delay to obtain the

filtered ECG signal. This is the design tradeoff in order to obtain the optimized hardware.

6.2 Recommendation for Future Works

The FIR low pass digital filter can be improved in future works as it has some

drawbacks. For future works, the recommendations are listed as below.

i. Utilize the characteristics of linear phase FIR filter

The symmetry or anti-symmetry property of a linear phase FIR filter can

reduce the clock cycles for data processing in almost half. A linear phase

FIR filter has the characteristic whereby the first coefficient is the same

as the last; the second coefficient is same as the next to last. However, a

linear phase FIR filter having an odd number of coefficients will have a

60

single coefficient in the centre which has no mate. Refer to equations

2.27 and 2.28, both equations show how the linear phase FIR filter is

fully utilized. Equation 2.27 shows the transfer function of a symmetric

impulse response. It can be reduced into a simpler form in equation 2.28.

In this project, the execution time for ECG data processing is just

satisfactory. By utilizing the linear phase characteristics of the FIR filter,

the data processing time will be greatly reduced.

ii. A real time system of the FIR filter can be implemented

In this project, an offline system of FIR filter is implemented. All the

ECG data must be stored in the RAM before the filtering process begins.

In order to obtain the filtered ECG signal, it takes time for the input data

to be loaded into the board. The system will process the latest ECG data

until the oldest ECG data that are stored in RAM. Apart from that, the

size of RAM used in this project is limited to 16k word size due to the

limitation of memory block usage in Altera FPGA DE2-50 board.

Therefore, a real time system can overcome the aforesaid drawbacks.

61

REFERENCES

[1] Y. S. Wang, "Implementation of digital filter by using FPGA," Bachelor of

Engineering, Curtin University of Technology, 2005.

[2] J. S. Wang, et al., "Research on Denoising Algorithm for ECG Signals," in

Proceedings of the 29th Chinese Control Conference, Beijing, China, July 29-31, 2010,

pp. 2936-2940.

[3] R. Chand, et al., "FPGA Implementation of Fast FIR Low Pass Filter for EMG

Removal from ECG Signal," IEEE, vol. 978-1, 2010.

[4] Z. D. Zhao and Y. Q. Chen, "A NEW METHOD FOR REMOVAL OF

BASELINE WANDER AND POWER LINE INTERFERENCE IN ECG SIGNALS," in

Proceedings of the Fifth International Conference on Machine Learning and Cybernetics

Dalian, August 13-16, 2006, pp. 4342-4347.

[5] A. K. Ziarani and A. Konrad, "A Nonlinear Adaptive Method of Elimination of

Power Line Interference in ECG Signals," IEEE Transactions on Biomedical

Engineering, vol. 49(6), pp. 540-547, 2002.

[6] P. Ranjan, "Implementation of FIR Filters on FPGA," Master Thesis,

Department of Electronics and Communication Engineering, Thapar University, Punjab,

India, 2008.

[7] B. A. Shenoi, Introduction to Digital Signal Processing and Filter Design: John

Wiley & Sons, Inc, 2006.

[8] M. H. Hayes, Schaum's Outlines Digital Signal Processing: The McGraw-Hill

Companies, 1999.

62

[9] U. Meyer-Basese, Digital Signal Processing with Field Programmable Gate

Array. New York: Springer-Verlag Berlin Heidelberg, 2001.

[10] V. K. Madisetti, Digital Signal Processing Fundamentals, Second ed.: Taylor and

Francis Group, LLC, 2010.

[11] G. L. Richard, Understanding Digital Signal Processing: New Jersey Prentice

Hall 2004.

[12] S. Joshi and B. Ainapure, "FPGA Based FIR filter," International Journal of

Engineering Science and Technology, vol. 2(12), pp. 7320-7323, 2010.

[13] S. Shanthala and S. Y. Kulkarni, "High Speed and Low Power FPGA

Implementation of FIR Filter for DSP Applications," European Journal of Scientific

Research, vol. 31 No.1, pp. 19-28, 2009.

[14] http://www.site.uottawa.ca/~mbolic/elg6163/ELG6163_FIR.pdf

[15] http://www.physionet.org/cgi-

bin/atm/ATM?database=mitdb&tool=plot_waveforms

[16] http://www-sigproc.eng.cam.ac.uk/~op205/

[17] http://www.dsprelated.com/dspbooks/sasp/Rectangular_Window.html

APPENDICES

VHDL code for datapath unit library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; use ieee.std_logic_signed.all; entity filter is port ( clock,reset: in std_logic; clear,ram_enable1,ram_enable2,load_32,enable_32,sel : in std_logic; wren2: in std_logic; ld_counter1,ld_counter2,increment3,decrement2,decrement3: in std_logic; zero_out_counter2,zero_out_counter3,test_counter1 : out std_logic; data2: in std_logic_vector (15 downto 0); ram_out2 : out std_logic_vector (15 downto 0); data_out : out std_logic_vector (31 downto 0) ); end filter; architecture behavior of filter is signal q1,q2 : std_logic_vector (15 downto 0); signal multi_out : std_logic_vector (31 downto 0); signal add_out,iq_out: std_logic_vector (31 downto 0); signal iout_counter2,iout_counter3,iselect: std_logic_vector (13 downto 0); signal iaddress1 : std_logic_vector (7 downto 0); component ROM1 IS PORT ( address : IN STD_LOGIC_VECTOR (7 DOWNTO 0); clken : IN STD_LOGIC ; clock : IN STD_LOGIC ; q : OUT STD_LOGIC_VECTOR (15 DOWNTO 0) ); END component; component RAM2 port (

64

address : IN STD_LOGIC_VECTOR (13 DOWNTO 0); clken : IN STD_LOGIC ; clock : IN STD_LOGIC ; data : IN STD_LOGIC_VECTOR (15 DOWNTO 0); wren : IN STD_LOGIC ; q : OUT STD_LOGIC_VECTOR (15 DOWNTO 0) ); END component; component reg16 port ( clk, reset,load: in std_logic; d: in std_logic_vector (31 downto 0); q: buffer std_logic_vector (31 downto 0) ); end component; component reg32 port ( clk,load,clear: in std_logic; d: in std_logic_vector (31 downto 0); q: buffer std_logic_vector (31 downto 0) ); end component; component counter1 port( clock,clear : in std_logic; ld_counter1: in std_logic; out_counter1 : buffer std_logic_vector (7 downto 0) ); end component; component counter2 port ( clock,reset : in std_logic; ld_counter2,decrement : in std_logic; d : in std_logic_vector (13 downto 0); out_counter2 : buffer std_logic_vector (13 downto 0)); end component; component counter3 port ( clock,reset : in std_logic; increment,decrement : in std_logic; out_counter3: buffer std_logic_vector (13 downto 0) ); end component; component MUX2to1

65

port ( A, B: in std_logic_vector(13 downto 0); Sel: in std_logic; Y: out std_logic_vector(13 downto 0)); end component; component XOR1 port ( in_xor : in std_logic_vector(13 downto 0); out_xor : out std_logic); end component; component comparator port ( input : in std_logic_vector(7 downto 0); test_out_counter1 : out std_logic ); end component; begin stage1: ROM1 port map ( address => iaddress1, clken => ram_enable1, clock => clock, q => q1 ); stage2: RAM2 port map ( address => iselect, clken => ram_enable2, clock => clock, data => data2, wren => wren2, q => q2 ); multi_out <= q1 * q2 ; add_out <= iq_out + multi_out; stage4: reg32 port map ( clk => clock, load => load_32, clear => clear, d => add_out, q => iq_out ); stage9: reg16 port map

66

( clk => clock, reset => reset, load => enable_32, d => iq_out, q => data_out ); stage5: counter1 port map ( clock => clock, clear => clear, ld_counter1 => ld_counter1, out_counter1 => iaddress1 ); stage6: counter2 port map ( clock => clock, reset => reset, ld_counter2 => ld_counter2, decrement => decrement2, d => iout_counter3, out_counter2 => iout_counter2 ); stage7: counter3 port map ( clock => clock, reset => reset, increment => increment3, decrement => decrement3, out_counter3 => iout_counter3 ); stage8: MUX2to1 port map ( A => iout_counter2, B => iout_counter3, Sel => sel, Y => iselect ); stage10: XOR1 port map ( in_xor => iout_counter2, out_xor => zero_out_counter2 ); stage11: XOR1 port map ( in_xor => iout_counter3, out_xor => zero_out_counter3 );

67

stage12: comparator port map ( input => iaddress1, test_out_counter1 => test_counter1 ); ram_out2 <= q2; end behavior;

Coding for firmware design #include <math.h> #include <stdlib.h> #include <iostream> #include <unistd.h> #include <stdio.h> #include "system.h" #include "altera_avalon_pio_regs.h" #include "alt_types.h" #include "sys/alt_timestamp.h" using namespace std; #ifndef load_data #define load_data 0x0 #endif #ifndef data2 #define data2 0x1 #endif #ifndef start #define start 0x2 #endif #ifndef done_one_point #define done_one_point 0x3 #endif #ifndef data_out #define data_out 0x4 #endif #ifndef done #define done 0x5 #endif #ifndef ram_out2 #define ram_out2 0x6 #endif #ifndef reset_hardware #define reset_hardware 0x7 #endif

68

#ifndef wait #define wait 0x8 #endif int main() { int storedata[16383]={0}; double storeoutput[16383]={0}; int a=0; int i=0,k=0; FILE *myfile, *outfile; alt_u32 time1,time2; //initialization for all the signal in hardware IOWR(FILTER_CORE_PROCESSOR_0_BASE,start,0); IORD(FILTER_CORE_PROCESSOR_0_BASE,0x15); IOWR(FILTER_CORE_PROCESSOR_0_BASE,reset_hardware,1); IOWR(FILTER_CORE_PROCESSOR_0_BASE,reset_hardware,0); IOWR(FILTER_CORE_PROCESSOR_0_BASE,wait,0); IOWR_ALTERA_AVALON_PIO_DATA(LED_RED_BASE, 0x00000); IOWR_ALTERA_AVALON_PIO_DATA(LED_GREEN_BASE, 0x00); //open data file myfile=fopen("d:/FYP2/software/fir_filter/Data3.txt","r"); if(myfile==NULL) printf("Error opening file."); else //file read and store in array { i=0; //printf("Entered.\n"); while(!feof(myfile)) { fscanf(myfile,"%d\n",&storedata[i]); i++; } //passing data from array into hardware for(a=0;a<i;a++) { //printf("%d\n",storedata[a]); IOWR(FILTER_CORE_PROCESSOR_0_BASE,data2,storedata[a]); IOWR(FILTER_CORE_PROCESSOR_0_BASE,load_data,1); IOWR(FILTER_CORE_PROCESSOR_0_BASE,load_data,0); } //filtering process starts IORD(FILTER_CORE_PROCESSOR_0_BASE,0x15); IOWR(FILTER_CORE_PROCESSOR_0_BASE,start,1); IOWR_ALTERA_AVALON_PIO_DATA(LED_RED_BASE, 0x15555); alt_timestamp_start(); time1=alt_timestamp(); //waiting for done signal to indicate the filering process is finished k=0; while(!IORD(FILTER_CORE_PROCESSOR_0_BASE,done))

69

{ storeoutput[k]=IORD(FILTER_CORE_PROCESSOR_0_BASE,data_out); IOWR(FILTER_CORE_PROCESSOR_0_BASE,wait,1); IOWR(FILTER_CORE_PROCESSOR_0_BASE,wait,0); k++; } time2=alt_timestamp(); printf("Time taken to perform operation:%u ticks\n", (unsigned int) (time2-time1)); IOWR_ALTERA_AVALON_PIO_DATA(LED_GREEN_BASE, 0xAA); //write the output data to a text file outfile=fopen("d:/FYP2/software/fir_filter/output3.txt","w"); for(a=i-1;a>-1;a--) fprintf(outfile,"%.9lf\n",storeoutput[a]); IOWR_ALTERA_AVALON_PIO_DATA(LED_RED_BASE, 0x2AAAA); IOWR_ALTERA_AVALON_PIO_DATA(LED_GREEN_BASE, 0xAA); printf("Filtering process done.\n"); IOWR_ALTERA_AVALON_PIO_DATA(LED_RED_BASE, 0x3FFFF); IOWR_ALTERA_AVALON_PIO_DATA(LED_GREEN_BASE, 0xFF); IOWR(FILTER_CORE_PROCESSOR_0_BASE,start,0); fclose(myfile); fclose(outfile); } return 0; }

70

Comparison between original filter coefficient and modified coefficient. Tap Original Coefficient in floating point Modified coefficient in integer form

1 0.000335693359375 11

2 0.00018310546875 6

3 -0.00225830078125 -74

4 -0.00811767578125 -266

5 -0.01458740234375 -478

6 -0.01528930664063 -501

7 -0.006378173828125 -209

8 0.006683349609375 219

9 0.01156616210938 379

10 0.002044677734375 67

11 -0.011962890625 -392

12 -0.01263427734375 -414

13 0.0042724609375 140

14 0.01974487304688 647

15 0.01141357421875 374

16 -0.01593017578125 -522

17 -0.02886962890625 -946

18 -0.003753662109375 -123

19 0.03631591796875 1190

20 0.03765869140625 1234

21 -0.01910400390625 -626

22 -0.07687377929688 -2519

23 -0.04403686523438 -1443

24 0.1082763671875 3548

25 0.2952575683594 9675

26 0.3797302246094 12443

27 0.2952575683594 9675

28 0.1082763671875 3548

29 -0.04403686523438 -1443

30 -0.07687377929688 -2519

31 -0.01910400390625 -626

32 0.03765869140625 1234

33 0.03631591796875 1190

34 -0.003753662109375 -123

71

35 -0.02886962890625 -946

36 -0.01593017578125 -522

37 0.01141357421875 374

38 0.01974487304688 647

39 0.0042724609375 140

40 -0.01263427734375 -414

41 -0.011962890625 -392

42 0.002044677734375 67

43 0.01156616210938 379

44 0.006683349609375 219

45 -0.006378173828125 -209

46 -0.01528930664063 -501

47 -0.01458740234375 -478

48 -0.00811767578125 -266

49 -0.00225830078125 -74

50 0.00018310546875 6

51 0.000335693359375 11