You are on page 1of 101

DSP Laboratory Experiment # 1

Introduction to MATLAB
Goals for this Lab Assignment:
In this lab we would have an introduction to MATLAB and get started with working in its
wonderfully simple environment. This lab, as a matter of fact, would lay the foundation for our next
labs. In the following paragraphs, you are provided with a tutorial on MATLAB. In addition, well go
over a detailed introduction to MATLAB in our first discussion session. This would enable you to do
simple but useful things in MATLAB.

1. You are basically responsible for learning Matlab language on your own. So read this
Experiment carefully and try to do an example of your own for each part on Matlab.

Solve all the exercises in this Experiment. If an exercise asks you to do an M-file, place a
comment at the top of your M-file, Lab1exr#, where # refers to the exercise number.

Workspace Browser
The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB
session and stored in memory. You add variables to the workspace by using functions, running Mfiles, and loading saved workspaces. To view the workspace and information about each variable, use
the Workspace browser, or use the functions who and whos.



To delete variables from the workspace, select the variable and select Delete from the Edit menu.
Alternatively, use the clear function. The workspace is not maintained after you end the MATLAB
session. To save the workspace to a file that can be read during a later MATLAB session, select
Save Workspace As from the File menu, or use the save function. This saves the workspace to a
binary file called a MAT-file, which has a .mat extension. There are options for saving to different
formats. To read in a MAT-file, select Import Data from the File menu, or use the load function.
You will use this function to load a wave signal later in this lab.

Array Editor
Double-click a variable in the Workspace browser to see it in the Array Editor. Use the Array Editor
to view and edit a visual representation of one- or two-dimensional numeric arrays, strings, and cell
arrays of strings that are in the workspace.
Change values of array elements

Change the display format

Search Path
MATLAB uses a search path to find M-files and other MATLAB-related files, which are organized in
directories on your file system. Any file you want to run in MATLAB must reside in the current
directory or in a directory that is on the search path. Add the directories containing files you create to
the MATLAB search path. By default, the files supplied with MATLAB and MathWorks toolboxes
are included in the search path. To see which directories are on the search path or to change the
search path, select Set Path from the File menu in the desktop, and use the Set Path dialog box.

1. Inside the Work folder, make a new folder and give it the name dsp.
2. Select the set path from the file menu, and use the add folder option to
reassign the path to this folder (dsp).
3. From this moment, any file you will be asked to do in this course will be
saved in this path. DO NOT FORGET THIS!!!!!


Definition of Matrices
MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices. Therefore,
vector and matrix operations are as simple as common "calculator operations".
Vectors can be defined in two ways. The first method is used for arbitrary elements:
v = [1 3 5 7];

%creates a 1x4 vector with elements 1, 3, 5 and 7.

Note that commas could have been used in place of spaces to separate the elements. Additional
elements can be added to the vector:
v(5) = 8;
Matrices are defined by entering the elements row by row:
M = [1 2 4; 3 6 8];

2 4

3 6

There are a number of special matrices that can be defined:

null matrix:

M = [ ];

nxm matrix of zeros:

M = zeros(n,m);

nxm matrix of ones:

M = ones(n,m);

nxn identity matrix:

M = eye(n);

Uniformly distributed random elements M = rand(n,m);

Normally distributed random elements M=randn(n,m);
A particular element of a matrix can be assigned:
M(1,2) = 5; % places the number 5 in the first row, second column.
Here are some examples.
Z = zeros(2,4)

N = fix(10*rand(1,10))


R = randn(4,4)
















The Colon Operator

The colon, : , is one of the most important MATLAB operators. It occurs in several different forms.
The expression 1:10 is a row vector containing the integers from 1 to 10, i.e. 1 2 3 4 5 6 7 8 9 10
To obtain non-unit spacing, specify an increment. For example,

% a row vector containing the integers

100 93 86 79 72 65 58 51

Subscript expressions involving colons refer to portions of a matrix.


% the first k elements of the jth column of A. So


%computes the sum of the fourth column.

But there is a better way. The colon by itself refers to all the elements in a row or column of a matrix
and the keyword end refers to the last row or column. So
sum(A(:,end)) %computes the sum of the elements in the last column of A.

1. Generate a matrix of size 4x4 of normally distributed random numbers.
2. Change the value of the 3rd column to [6 9 2 5].
3. Delete the 2nd row.

Dimension Functions
Dimensioning is automatic in MATLAB. You can find the dimensions of an existing matrix with the
size. Also the command length(x) returns the length of the vector x

>> X=[1 2 3;6 7 8]

>> [m,n] = size(X)

% returns the size of matrix X in separate variables m and n.

>> x = ones(1,8);
>> n = length(x)


% will assign the value 8 to n

Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your
first matrix by concatenating its individual elements. The pair of square brackets, [ ], is the
concatenation operator. To do so horizontally, we separate the arrays with spaces or commas:
>> [ones(2,3), zeros(2,3)]
To do so vertically, we separate the arrays with a semicolon:
>> [ones(2,3); zeros(2,3)]

1. Start with the 4-by-4 square, A.
2. Then form B = [A A+32; A+48 A+16]
3. Whats the size of B?

Define the following discrete time signal

0.5 0 n p 10

x[n] = 0 10 n p 15
2 15 n 20

Scripts and Functions

MATLAB is a powerful programming language as well as an interactive computational environment.
Files that contain code in the MATLAB language are called M-files. You create M-files using a text
editor, and then use them as you would use any other MATLAB function or command.
There are two kinds of M-files:

Scripts, which do not accept input arguments or return output arguments. They
operate on data in the workspace.

Functions, which can accept input arguments and return output arguments. Internal
variables are local to the function.

When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can
operate on existing data in the workspace, or they can create new data on which to operate. Although
scripts do not return output arguments, any variables that they create remain in the workspace, to be
used in subsequent computations. In addition, scripts can produce graphical output using functions
like plot.
For example, create a file called modify.m that contains these MATLAB commands.


r = rand(1,10)
causes MATLAB to execute the commands, change the value of the odd indexed elements of vector r
to zero, and assign the result to y . After execution of the file is complete, the variables y and r remain
in the workspace.

Functions are M-files that can accept input arguments and return output arguments. The name of the
M-file and of the function should be the same. Functions operate on variables within their own
workspace, separate from the workspace you access at the MATLAB command prompt.

Global Variables
If you want more than one function to share a single copy of a variable, simply declare the variable as
global in all the functions. Do the same thing at the command line if you want the base workspace to
access the variable. The global declaration must occur before the variable is actually used in a
function. Although it is not required, using capital letters for the names of global variables helps
distinguish them from other variables. For example, create an M-file called falling.m.
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
Then interactively enter the statements in MATLAB command window
global GRAVITY
y = falling((0:0.1:5)');
The two global statements make the value assigned to GRAVITY at the command prompt available
inside the function. You can then modify GRAVITY interactively and obtain new solutions without
editing any files.
It is worth mentioned that when a function returns multiple parameters, we use square brackets to
retrieve them:
>> [max_value, index] = max([4.3, 2.9, 8.6, 6.3, 1.0])
Otherwise, only one parameter is returned

Structures and cells

Matlab has a number of other data types which we will use. Structures in Matlab are just like
structures in C. They are basically containers that allow one to group together more than one type of
data under the umbrella of one variable name. The form of a structure is variableName.field. For
example: = [1 2 3 4 5];

x.offset = -1;
data: [1 2 3 4]
offset: -1
We have declared a variable x, with two fields. The data field contains an array; the offset field
contains another number. Structures of this type can be useful for us in expressing sequences in
Matlab. Matlab always assumes that the index of the first element of an array is 1. So, when we just
x = [1 2 3 4 5];
This means that x[1]=1, x[2]=2, and so on. But, what if we want to express a sequence x[-1] =1 ,
x[0]=2, ...? We obviously need to provide the user with some additional information in addition to the
array data, namely an offset. An offset of -1 tells the user that "we want you to interpret the first point
in the Matlab array as corresponding to x[-1] . We can use structures for this purpose.
For example let us define a shift function. This function takes the data x and original offset of the
vector, w and the amount of the required shift z and outputs the new shifted vector with the new
function y=shift(x,w,z);

Define a new function in MATLAB named as flip. This function flips a Matlab sequence
structure, x (containing data and offset). Use this function to flip the shifted sequence results
from the previous example. Can we call the two functions together? i.e., Can we write this
calling statement: flip(shift(x,w,3)) ?

Representing Polynomials
MATLAB represents polynomials as row vectors containing coefficients ordered by descending
powers. For example, consider the equation

p( x) = x 3 2 x 5


To enter this polynomial into MATLAB, use

p = [1 0 -2 -5];

Polynomial Roots
The roots function calculates the roots of a polynomial.
r = roots(p)
-1.0473 + 1.1359i
-1.0473 - 1.1359i
By convention, MATLAB stores roots in column vectors. The function poly returns to the polynomial
p2 = poly(r)
p2 =
1 8.8818e-16 -2 5
So the poly and roots are inverse functions.

Polynomial Evaluation
The polyval function evaluates a polynomial at a specified value. To evaluate p at s = 5, use
ans =
It is also possible to evaluate a polynomial in a matrix sense. In this case p ( x) = x 3 2 x 5
becomes p ( X ) = X 3 2 X 5 I , where X is a square matrix and I is the identity matrix. For
example, create a square matrix X and evaluate the polynomial p at X.
X = [2 4 5; -1 0 3; 7 1 5];
Y = polyvalm(p,X)
377 179 439
111 81


490 253 639


Consider the polynomial p ( x) = x 4 5 x 3 + 7 x 10
1. Find the roots of this polynomial.
2. From these roots, reconstruct p(x).
3. Find the value of p(x) at x=3.
4. Evaluate the polynomial at X (matrix sense).

Graphics in MATALB:
Creating a Plot
The plot function has different forms, depending on the input arguments. If y is a vector, plot(y)
produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you
specify two vectors as arguments, plot(x,y) produces a graph of y versus x.
For example, these statements use the colon operator to create a vector of x values ranging from zero
to 2, compute the sine of these values, and plot the result.
x = 0:pi/100:2*pi;
y = sin(x);
%Now label the axes and add a title. The characters \pi create the symbol .
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)


Multiple Data Sets in One Graph

Multiple x-y pair arguments create multiple graphs with a single call to plot. MATLAB automatically
cycles through a predefined list of colors to allow discrimination among sets of data. For example,
these statements plot three related functions of x, each curve in a separate distinguishing color.
x= 0:pi/40:2*pi;
y= sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
% The legend command provides an easy way to identify the individual plots.

Axis rescaling:
MATLAB provides automatic scaling. The command axis([x min. x max. ymin. y max.]) enforces
the manual scaling. For example
axis([-10 40 -inf inf])
produces an x-axis scale from - 10 to 40 and an automatic scaling for the y-axis scale. Typing axis
again or axis(auto) resumes auto scaling.

If you wish to use information in discrete-time using the stem command can be useful. It is very
similar to plot except it doesnt connect the dots.
The following example creates a stem plot of a cosine function.
y = linspace(0,2*pi,10);
h = stem(cos(y),'fill','-.');
set(h(3),'Color','r','LineWidth',2) % Set base line properties
axis ([0 11 -1 1])



Specifying Line Styles and Colors

It is possible to specify color, line styles, and markers (such as plus signs or circles) when you plot
your data using the plot command.
plot(x,y,'color_style_marker') , where color_style_marker is a string containing from one to four
characters (enclosed in single quotation marks) constructed from a color, a line style, and a marker

Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These correspond to cyan, magenta,
yellow, red, green, blue, white, and black.

Linestyle strings are '-' for solid, '--' for dashed, ':' for dotted, '-.' for dash-dot. Omit
the linestyle for no line.

The marker types are '+', 'o', '*', and 'x' and the filled marker types are 's' for square,
'd' for diamond, '^' for up triangle, 'v' for down triangle, '>' for right triangle, '<' for
left triangle, 'p' for pentagram, 'h' for hexagram, and none for no marker.

Adding Plots to an Existing Graph

The hold command enables you to add plots to an existing graph. When you type
hold on
MATLAB does not replace the existing graph when you issue another plotting command; it adds the
new data to the current graph, rescaling the axes if necessary. To remove the effect of the hold on
function you may use:
hold off

Multiple Plots in One Figure

The subplot command enables you to display multiple plots in the same window or print them on the
same piece of paper. Typing:
partitions the figure window into an m-by-n matrix of small subplots and selects the pth subplot for
the current plot. The plots are numbered along first the top row of the figure window, then the second
row, and so on. For example, these statements plot data in four different subregions of the figure
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)



Figure Windows
Graphing functions automatically open a new figure window if there are no figure windows already
on the screen. If a figure window exists, MATLAB uses that window for graphics output. If there are
multiple figure windows open, MATLAB targets the one that is designated the current figure (the
last figure used or clicked in).
To make an existing figure window the current figure, you can type :
>> figure(n)
where n is the number in the figure title bar. The results of subsequent graphics commands are
displayed in this window. To open a new figure window and make it the current figure, type:
>> figure

Consider the following MATLAB script:

semilogy(dB,pb) %same as plot(dB,log10(pb))
ylabel(Bit error rate)
title(Performance of antipodal signaling over AWGN)

Using MATLAB, plot the function

f (t ) = e 2t cos(3t )u (t )
where t ranges from 2 to 10. Give the x-axis the title (t sec) and the
y-axis the title (f(t) volts ). Repeat using stem function. Then use
subplot to combine the two figures in one figure and give it the
name: difference between plot and stem.



The save Function

The workspace is not maintained across MATLAB sessions. When you quit MATLAB, the
workspace is cleared. You can save any or all of the variables in the current workspace to a MAT-file,
which is a MATLAB specific binary file. You can then load the MAT-file at a later time during the
current or another session to reuse the workspace variables. MAT-files use a .mat extension.
To save all variables from the workspace in binary MAT-file, test.mat, type
save test.mat
To save variables p and q in binary MAT-file, output.mat,
p = rand(1,10);
q = ones(1,10);

The load Function

The load function reads binary files containing matrices generated by earlier MATLAB sessions, or
reads text files containing numeric data. The text file should be organized as a rectangular table of
numbers, separated by blanks, with one row per line, and an equal number of elements in each row.
For example, outside of MATLAB, create a text file containing these four lines.















Store the file under the name data.dat. Then the statement load data.dat reads the file and creates a
variable, data, containing our example matrix.

Images are represented as matrices in Matlab. So try out

>> load clown
>> imagesc (X)

% axis image

Playing Sound Files from Matlab Data

Digital signal processing is widely used in speech processing for applications ranging from speech
compression and transmission, to speech recognition and speaker identification. This exercise will
introduce the process of reading and manipulating a speech signal.
Once you have a .wav file, you can read the data into your program using MATLAB's wavread
function.. You must determine the file path first. After you read the wave file, the soundsc function
gives you the ability to hear the wave.


[x, fs] = wavread('file path\file name');

soundsc(x, fs);
MatLab may be used to convert the available Ascii files into .wav format. This permits the original
sounds to be heard using the Sound Recorder application, for example. If an Ascii version of a
sound file is loaded into MatLab, then a .wav file may be created using the wavwrite command. The
sampling frequency must be specified to use this function, for example:
wavwrite(x,22255,'mysound.wav') % x: vector containing speech samples, 22255: sampling rate

We will do this exercise on the wave file speech_dft.wav. You can find this file in
1. Read this wave file using wavread function.
2. Listen to the wave using soundsc function.
3. Create a *.wav file that contains a flipped version of speech_dft.wav
4. What are the sampling frequency, length, and size of the wave?

Useful Facts in MATLAB

1. MATLAB starts indexing its arrays from 1 rather than from 0.
2. The end keyword is exceptionally useful when indexing into arrays of unknown size.
Thus, if you want to return all elements in a vector except the first and last one, you
can use the command:
>> x(2:end-1) %equivalent to x(2:length(x)-1)
3. MATLAB automatically resizes arrays for you. Thus, if you want to add an element on
to the end of a vector, you can use the command:
>> x(end+1) = 5;



DSP Laboratory Experiment # 2

Introduction to the TMS320C6711 DSK
And Code Composer Studio
In this Experiment, our aim is to show how mathematical algorithms for digital signal processing may
be encoded for implementation on programmable hardware. In this lab, you will become familiar with
a development system for programming DSP hardware. You will study:
v Code Composer Studio
v TMS320C6711 DSP chip and supporting architecture (DSK)
v The C programming language

1. Since this lab deals with new concepts for you, you must study the following necessary
introduction carefully before going to the lab. This self-study will be evaluated by a short quiz
in the beginning of the lab. So BE CAREFULL!!!

2. Try to draw a flowchart for the C program in page 29.

Background and Motivation:

You will be hearing a lot about the term DSP throughout the course. What is DSP? Why is it
important? Why do you want to process signals in digital instead of leaving it in analog? When
should you use DSP? What are the advantages, disadvantages and tradeoffs? What are DSP
processors and how are they different than microprocessors? This Experiment will discuss briefly
these questions.

Digital Signal Processing

Digital Signal Processing is a technique that converts signals from real world sources (usually in
analog form) into digital data that can then be analyzed. Analysis is performed in digital form because
once a signal has been reduced to numbers; its components can be isolated, analyzed and rearranged
more easily than in analog form.
Eventually, when the DSP has finished its work, the digital data can be turned back into an analog
signal, with improved quality. For example, a DSP can filter noise from a signal, remove interference,
amplify frequencies and suppress others, encrypt information, or analyze a complex wave form into
its spectral components.






This process must be handled in real-time - which is often very quickly. For instance, stereo
equipment handles sound signals of up to 20 kilohertz (20,000 cycles per second), requiring a DSP to
perform hundreds of millions of operations per second.

Why Digitizing?
Why do we process signals digitally rather than working with the original signal in the analog
domain? The answer depends on the system and its requirements. For some systems, working with
the analog signals gives a better solution. For others, DSP is better. It is up to you, the designer, to
make the decision based on materials you learn through this and other courses. Here are some things
to consider in making the tradeoffs:

Reasons to go digital:
1. Flexibility: can easily change, modify and upgrade through software.
2. Reproducibility of results from one unit to another: because DSP works with binary
sequences. Analog circuits have component tolerances.
3. Reliability: memory and logic dont slowly go bad with time and are not affected by
4. Complexity: complex algorithms can be implemented on lightweight and low power
portable devices.
5. Only solution: some algorithms can only be done in the digital domain: linear phase
filters, adaptive filters, data compression, and error correcting codes.
6. Low overall cost.

Disadvantages of digital Reasons to go analog:

1. Bandwidth is limited by sampling rate and peripherals i.e. we cant process high
2. Initial design cost may be expensive (esp. for large BW signals).
3. Data size: a fixed number of bits means limited range and quantization and arithmetic
errors (may not get theoretical performance).



Applications of DSP Who has DSP processor?

DSP technology is nowadays commonplace in such devices as mobile phones, multimedia computers,
video recorders, CD players, hard disc drive controllers and modems, and will soon replace analog
circuitry in TV sets and telephones. An important application of DSP is in signal compression and
decompression. In CD systems, for example, the music recorded on the CD is in a compressed form
(to increase storage capacity) and must be decompressed for the recorded signal to be reproduced.
Signal compression is used in digital cellular phones to allow a greater number of calls to be handled
simultaneously within each local "cell". DSP signal compression technology allows people not only
to talk to one another by telephone but also to see one another on the screens of their PCs, using small
video cameras mounted on the computer monitors, with only a conventional telephone line linking
them together.

What are the typical DSP algorithms?

The Sum of Products (SOP) is the key element in most DSP algorithms. That is to say that although
the mathematical theory underlying DSP techniques such as Fast Fourier and Hilbert Transforms,
digital filter design and signal compression can be fairly complex, the numerical operations required
to implement these techniques are in fact very simple, consisting mainly of operations that could be
done on a cheap four-function calculator.

DSP Processors vs. General-purpose Microprocessors:

How do DSP processors differ from microprocessors? Like a general-purpose microprocessor, a DSP
is a programmable device, with its own native instruction code. Both types of processors perform
computations on digital signals. But the main difference is that DSP processors are tailored to process
data signals whereas microprocessors are designed to reduce the amount of computations in a general
computing environment where most signals being processed pertain to some form of program control.
DSP processors are also designed to consume less power under its target applications. DSP chips are
capable of carrying out up to tens of millions of samples per second, to provide real-time
performance: that is, the ability to process a signal "live" as it is sampled and then output the
processed signal, for example to a loudspeaker or video display. Finally you should note that the main
drawback of DSP processor is its limited on-chip memory.

Parameters to consider when choosing a DSP processor:

A. Fixed vs. Floating-Point DSPs
a. Fixed-point DSPs represent a number in 16 or 24 bit integer format. They are
cheaper and use less power but care must be taken with scaling (the data is scaled so
values lie between -1 and 1) to avoid over and underflow.
b. Floating-point DSPs stores a number as a 24 bit mantissa and an 8 bit exponent.
They are easier to program and numbers are automatically scaled. But they are more
complicated, can be slower than fixed-point counterparts, larger in size, expensive
and have a higher power consumption. Statistics point out that 95% of DSP's market
uses fixed point and only 5% for floating point DSP's.

B. Processing time measures are based on the clock (150MHz for our case)


a. MACS, multiplies and accumulates, If 2 per clock cycle, then 300 million MACs per
b. MFLOPS, million floating-point operations per second, If 6 units capable of doing
floating-point operations, then can do 900MFLOPS.
c. MIPS, million of instructions per second, If 8 units capable of doing fixed and
floating-point operations, then have a 1200MIPS system.

C. Codeword length
Sixteen-bit fixed-point DSPs are used for voice-grade systems such as phones, since they
work with a relatively narrow range of sound frequencies. Hi-fidelity stereo sound has a
wider range, calling for a 16-bit ADC (Analog/Digital Converter), and a 24-bit fixed
point DSP. Image processing, 3-D graphics and scientific simulations have a much wider
dynamic range and require a 32-bit floating-point processor.

D. Others
a. Overall cost.
b. Software development tools, simulators.
c. Commercially available DSP boards for software development and testing before the
target DSP hardware is available?
d. The likelihood of having higher-performance devices with upwards-compatible
software in the future.
e. Power Consumption: The most commonly used TMS320 DSP chips (in the year
2002) are the C2000, C5000, and C6000 series of chips. Due to their low power
consumption (40mW to 160mW of active power), they are very attractive for power
sensitive portable systems. As the dsps speed increases, so does the power
consumption. This makes an accurate knowledge of the execution time critical for
selecting the proper device.



Our system, Texas Instruments C6711 DSK :

General description:
We will be working with the TI TMS320C6711 DSP chip. The chip is very powerful by itself, but for
development purposes, a supporting architecture is required to store programs and data, and bring
signals on and off the board. In order to use this DSP chip in a lab, the chip will be on a board that
contains additional appropriate components. Together, CCS, the DSP chip, and supporting hardware
make up a DSP Starter Kit, or DSK. Here are few words about each element:

The codec (coder/decoder) is a chip located on-board the DSK. In this course, we will use the coder
or analog-to-digital converter (ADC) and decoder or digital-to-analog converter (DAC), along with
two mono headphone jacks, to interface a DSP chip to the analog world. This codec runs at a fixed
rate of 8kHz and 16 bit representation. In the next lab, we will explore the codec in more depth.

C6711 chip

Floating-point DSP, 150MHz clock, 900MFLOPS, 1200MIPS

Can fetch 8 32-bit instructions per cycle.

72kB internal memory, 8 functional or execution units, 2 sets of 32-bit registers.

Capable of fixed and floating point operations.

VLIW very long instruction word architecture.

External Memory:
The board contains 16 MB of SDRAM and 128 kB of flash ROM.

Code Composer Studio ( CCS)

CCS is a powerful integrated development environment that provides a useful transition between a
high-level (C or assembly) DSP program and an on-board machine language program. CCS consists
of a set of software tools and libraries for developing DSP programs, compiling them into machine
code, and writing them into memory on the DSP chip and on-board external memory. It also contains
diagnostic tools for analyzing and tracing algorithms as they are being implemented on-board. In this
class, we will always use CCS to interface DSP hardware with a PC.
1.8V Power



Card I/F



D. Card I/F



3.3V Power




Three User LEDs

16-bit codec (A/D & D/A)

Line Level Input

Line Level Output

C6711 DSP Chip

The C6711 DSP chip is a floating point processor which contains a CPU (Central Processing Unit),
internal memory, enhanced direct memory access (EDMA) controller, and on-chip peripherals. These
peripherals include a 32-bit external memory interface (EMIF), two Multi-channel Buffered Serial
Ports (McBSP), two 32-bit timers, a 16-bit host port interface (HPI), an interrupt selector, and a phase
lock loop (PLL), along with hardware for `Boot Configurations' and Power Down Logic.

Programming Languages
Assembly language was once the most commonly used programming language for DSP chips (such
as TI's TMS320 series) and microprocessors (such as Motorola's 68MC11 series). Coding in assembly
forces the programmer to manage CPU core registers (located on the DSP chip) and to schedule
events in the CPU core. It is the most time consuming way to program, but it is the only way to fully
optimize a program. Assembly language is specific to a given architecture and is primarily used to
schedule time critical and memory critical parts of algorithms.
The preferred way to code algorithms is to code them in C. Coding in C requires a compiler that will
convert C code to the assembly code of a given DSP instruction set. C compilers are very common, so
this is not a limitation. In fact, it is an advantage, since C coded algorithms may be implemented on a
variety platforms (provided there is a C compiler for a given architecture and instruction set). In CCS,
the C compiler has four optimization levels. The highest level of optimization does not achieve the
same level of optimization that programmer-optimized assembly programs does, but TI has done a
good job in making the optimized C compiler produce code that is comparable to programmeroptimized assembly code.
Lastly, a cross between assembly language and C exists within CCS. It is called linear assembly code.
Linear assembly looks much like assembly language code, but it allows for symbolic names and does
not require the programmer to specify delay slots and CPU core registers on the DSP. Its
advantage over C code is that it uses the DSP more efficiently, and its advantage over assembly code
is that it does not require the programmer to manage the CPU core registers. This will be apparent in
future labs when assembly and linear assembly code are written.














The DSP chip must be able to establish communication links between the CPU (DSP core) and the
codecs and memory. The two McBSPs, namely serial port 0 (SP0) and serial port 1 (SP1), are used to
establish asynchronous links between the CPU and the on-board codec, and between the CPU and
daughter card expansion, respectively. These McBSPs use frame synchronization to communicate
with external devices. Each McBSP has seven pins. Five of them are used for timing and the other
two are connected to the data receive and data transmit pins on the on-board codec or daughter card.
Also included in each McBSP is a 32-bit Serial Port Control Register (SPCR). This register is updated
when the on-board codec (or daughter card) is ready to send data to or receive data from the CPU.
The status of the SPCR will only be a concern to us when polling methods are implemented.
In this lab, we will be exploring two possible ways of establishing a real-time communication link
between the CPU and the on-board codec. The idea of real-time communication is that we want a
continuous stream of samples to be sent to the codec. In our case, we want samples to be sent at rate
8kHz (one sample every .125ms). This is controlled by the codec, which will signal serial port 0
(SP0), every .125ms.

The first method for establishing a real-time communication link between the CPU and the on-board
codec is polling. When the on-board codec is ready to receive a sample, it sets a bit 17 of the SPCR to
true. Bit 17 of the SPCR is the transmit ready (XRDY) bit, which is used to let the CPU know that it
can transmit data. In a polling application, the CPU continuously checks the status of the SPCR and
transmits a data sample as soon as the bit 17 of the SPCR is set true.
Upon transmission, the McBSP will reset bit 17 of the SPCR to false. The polling program will then
wait until the on-board codec resets bit 17 to true before transmitting the next data sample. In this
manner, a polling algorithm will maintain a constant stream of data owing to the on-board codec.
On the DSP hardware, polling is implemented mostly in software. The on-board codec will
continuously set the transmit ready bit of the SPCR and the McBSP will always reset it. However, it
is up to the programmer to write an algorithm that will constantly be checking the status of the SPCR.



Fortunately, this has already been taken care of for you. This will be explained in detail later when we
implement a polling example.

When using polling to send and receive the data from the CODEC the general processing was
WAIT for the CODEC to receive the data
Retrieve the data
Process the data
WAIT for the CODEC to be ready to accept the data
Transmit the data

This is very inefficient since there are two places in the code were processing time is used just
waiting for data to arrive. It would be better if the processor could be processing data during this
time. This is where interrupts can help speed things up.
An interrupt can be some event that is generated either by a an external hardware device, internal
hardware device or software. When an interrupt occurs the main processing is interrupted and the
processor jumps to an interrupt subroutine (ISR). This ISR is just a function that is set up to handle
the event that caused the interrupt. When the ISR is done processing, the processor jumps back to
where it left off when the interrupt occurred. The following shows how this can occur:

Main processing statement 1

Main processing statement 2
Main processing statement 3
Interrupt occurs
Processor saves the current state of the registers, etc.
Processor jumps to ISR
ISR processing statement 1
ISR processing statement 2
ISR processing statement 3
ISR completes
Processor restores the previously saved state of registers, etc.
Main processing statement 4
Main processing statement 5

The CODEC on the DSP board is connected to an internal device called the multichannel buffered
serial port (McBSP). There is more than one McBSP on the C6711, so the CODEC is connected to
the McBSP0. This device can generate an internal interrupt when it receives data from the CODEC
and when it is ready to send data to the CODEC. Therefore, two ISRs will be used to send and


receive data to and from the CODEC. Since these are separate functions, there needs to be a way to
get the data from one to the other. This is done here using "mailboxes." A mailbox is a way to send
data from one object or task to another
The figure below shows the basic structure that can be used for many different types of signal
processing applications using interrupts.



Mailbo x
ng Task


Mailbo x
Inside DSP

The circles are the ISRs, the rectangle McBSP0 is the internal McBSP0 device and the rectangle
CODEC shows the external CODEC device. Audio data is input to the CODEC were it is sampled.
This data is sent to the McBSP0, which generates a receive interrupt. The interrupt causes the
Receive ISR to run and retrieve the data. The data is put in a mailbox and sent to be processed. After
processing task, the processed data will be transmitted to the Transmit ISR. When the McBSP0 is
ready to transmit data to the CODEC it will generate an interrupt which will cause the Transmit ISR
to run. The Transmit ISR will deliver the data to the McBSP0 which will then send it to the CODEC.
Finally, the CODEC will convert the data to analog and output it.
Now, after reading this introduction, you are capable of carrying out this lab, in which we will
create the first project on the DSK.



Setting up the Equipment
For every lab in this course (with a few minor exceptions for this lab), the following equipment will
be needed at every lab station:

A pentium based computer with CCS version 2.0 or greater installed on it.

A C6711 DSK including power supply and parallel printer port cable.

A set of speakers or headphones.

An arbitrary waveform generator.

An oscilloscope.

For this lab, we will just be observing and listening to signals, so only the oscilloscope, headphones
or speakers, and one of the 3 foot headphone-to-RF connector cables will be used. At this point, turn
on the oscilloscope and connect the cable to the headphone jack on the DSK and connect the left
channel (white cable) to the RF connector on the oscilloscope.

Creating the First Project on the DSK

Creating the Project File sine_gen.pjt

Inside C:\ DSP folder create another folder named as lab2, in which we will save all the
files we need in our first project.

In CCS, select `Project' and then `New'. A window named `Project Creation' will appear.

In the field labeled `Project Name', enter `sine_gen'. In the field Location, click on the
on the right side of the field and browse to the folder C:\DSP\lab2\sine_gen. For
`Project Type', use `Executable (.out)'. Do not change this field. In the field `Target',
make sure that the TMS32067XX is selected. Finally, click on `Finish'. The file
sine_gen.pjt has been created in the folder C:\DSP\lab2\sine_gen.

Project Creation Window for sine_gen.pjt



Adding Support Files to a Project

The next step in creating a project is to add the appropriate files.

In the CCS window, go to `Project' and then Add Files to Project. In the window that
appears, click on the folder next to where it says Look In: Make sure that you are in
the folder C:\DSP\support_files. You should be able to see the file C6xdskinit.c. Notice
that the `Files of type' field is 'C source code'. Click on C6xdskinit.c and then click on

Repeat this process two more times adding the files vectors 11.asm and C6xdsk.cmd.
For field, `Files of type', select `Asm Source Files (*.a*)'. Click on vectors11.asm. For
field, `Files of type', select `Linker Command File (*.cmd)'. Click on C6xdsk.cmd.

The C source code file contains functions for initializing the DSP and peripherals. The vectors file
contains information about what interrupts (if any) will be used and gives the linker information about
resetting the CPU. This file needs to appear in the first block of program memory. The linker
command file (C6xdsk.cmd) tells the linker how the vectors file and the internal, external, and flash
memory are to be organized in memory. In addition, it specifies what parts of the program are to be
stored in internal memory and what parts are to be stored in the external memory. In general, the
program instructions and local/global variables will be stored in internal (random access) memory or

Adding Appropriate Libraries to a Project

In addition to the support files that you have been given, there are pre-compiled files from TI that
need to be included with your project. For this project, we need a run-time support library
(rts6701.lib), which our support files will use to run the DSK, and a GEL (general extension
language) file (dsk6211_6701.gel) to initialize the DSK. The GEL file was included when the project
file sine_gen.pjt was created, but the RTS (run-time support) library must be included in the same
manner used to include the previous files.

Go to `Project' and then `Add Files to Project'. For `Files of type', select `Object and
Library Files (*.o*,*.l*)'. Browse to the folder C:\DSP\support_files and select the file
rts6701.lib. In the left sub-window of the CCS main window, double-click on the folder
'Libraries' to make sure the file was added correctly.

These files, along with our other support files, form the black box that will be required
for every project created in this class. The only files that change are the source code files
that code a DSP algorithm and possibly a vectors file.

Adding Source Code Files to a Project

The last file that you need to add is your source code file. This file will contain the algorithm that will
be used to internally generate a 1kHz sine wave.

Go back to `Project' and then `Add Files to Project'. Select the file sine_gen.c and add it
to your project.

You may have noticed that the .h files cannot be added. These files are header files and are referenced
in C6xdskinit.c.



Go to `Project' and select `Scan All Dependencies'. In CCS, double-click on

`sine_gen.pjt' and then double-click on `Include'. You should see the three header files
that you downloaded plus a mystery file C6x.h.

This mystery file is included with the Code Composer Studio software, and it is used to configure the
board. CCS automatically included all of the header files when the file C6xdskinit.c was added to the
project. Open the file C6xdskinit.c and observe that the first four lines of code include the four header
files. You now have all of the files you need for this project.

Build Options
Once all of your files have been included in your project file, the compiler and linker options must be
configured so that your project gets built correctly. Go to `Project', then to `Build Options', and then
click on the `Compiler' tab. In the Category:, Basic, make sure the following are selected:
Target Version: 671x
Generate Debug Info: Full Symbolic Debug (-g)
Opt Speed vs. Size: Speed Most Critical (no ms)
Opt Level: None
Program Level Opt: None
In the top part of the current window, you should see:
-g -q -f r"C:\DSP\lab2\sine_gen\Debug" -d"_DEBUG"
Change it to:
-g -k -s -fr"C:\DSP\lab2\sine_gen\Debug" -d"_DEBUG" -mv6710

Build Options for Compiling



Now click on the Linker tab on the top of the current window and make sure the following
command appears in the top most window (See Figure below):
-q -c -o"..\Debug\sine_gen.out" -x

The options -g, -k, -s in the compiler options and -g, -c, -o in the linker options do serve
a purpose, but we will not be concerned with them just yet.
Your project has now been created. This process is cumbersome, but it only needs to be done once. In
future projects, you will be able to copy this folder into another folder and make a few simple
modifications. These modifications include altering the C code in sine_gen.c and editing one linker
option. This will be demonstrated later in this lab.

Build Options for Linking

Building and Running the Project

Now you must build and run the project. To build the first project, go to `Project' pull-down menu in
the CCS window, then select `Build' (or press the button with three red down arrows on the top
toolbar in the CCS window). A new sub-window will appear on the bottom of the CCS window.
When building is complete, you should see the following message in the new sub-window:

Build Complete,
0 Errors, 0 Warnings, 0 Remarks.



When CCS built your project, it compiled all of the C code into assembly code, using a built-in
compiler. Then it assembled the assembly code into a COFF (common object file format) file that
contains the program instructions, organized into modules. Finally, the linker organizes these modules
and the run-time support library (rts6701.lib) into memory locations to create an executable .out file.
This executable file can be downloaded onto the DSK. When this executable file is loaded onto the
DSK, the assembled program instructions, global variables, and run-time support libraries are loaded
to their linker specified memory locations.
To test your program on the DSK, you must first load the program onto the board, but before you load
a new program onto the board, it is good practice to reset the CPU.

To reset the the CPU, click on `Debug', then select `Reset CPU'.

Then, to load the program onto the DSK, click on `File', then select `Load Program'. In
the new window that appears, double-click on the folder `Debug', select the file
sine_gen, then select `Open'. This will download the executable file to the DSK. A new
window will appear within CCS entitled Disassembly, which contains the assembled
version of your program. Ignore this window for now.

Before you run this program, make sure that the cable between the 1/8th inch headphone jack on the
DSK board (the J6 connector) and the oscilloscope is connected, and make sure that the oscilloscope
is turned on.

In CCS, select the `Debug' pull down menu and then select `Run', or just simply click on
the top \running man" on the left side toolbar. Verify a 1kHz sine wave on the

Once you have verified the signal, disconnect the oscilloscope from the DSK and attach
a pair of speakers or headphones to the DSK. You should hear a 1kHz pure tone.

After you have completed both of these tasks, either click on the icon of the blue
`running man' with a red `X' on it or go to the `Debug' pull down menu then select `Halt'.

Generating a Sinusoid in Real-Time

In many of the communication systems that we design, we want to be able to generate a sinusoid with
arbitrary frequency fo. In the first project, we generated the sinusoid

x(t ) = sin(2f o t ) .1
where fo = 1kHz. In real-time digital systems, this requires samples of the signal in eqn(1) to be sent
to the codec at a fixed rate. In the case of the on-board codec, samples are being sent at rate fs =
8kHz (ts = 0.125ms). In C code, we generate samples of eqn(1), namely

x[n] = x(nt s ) = sin(2n

) 2

which is only defined for integer values of n. Here, the argument of the sine function,

[n] = 2n



is a linear function that can be easily updated at each sample point. Specifically, at the time instance n
+ 1, the argument becomes

[n + 1] = 2[n + 1]
which is the previous argument plus the offset 2

= [n] + 2 o


This makes it possible to generate any sinusoid whose frequency is fo < 3.6kHz in eqn(2). You may
have expected the maximum frequency to be fs/2 = 4kHz, but the codec requires oversampling, a
point to be clarified later.

Code Analysis and Modification

Now that you have successfully implemented your first project in hardware, it is time to analyze the
source code in sine_gen.c to see exactly how this 1kHz sine wave was generated. Note in C (or more
precisely C++) that text following `//' on any line is regarded as a comment and is ignored when the
program is compiled. Here is the sine_gen.c file.

#include <math.h>
#define PI 3.14159265359
float f0=1000;
short fs=8000;
float angle=0;
float offset;
short sine_value;

// needed for sin() function

// define the constant PI
// sinusoid frequency
// sampling frequency of codec
// angle in radians
// offset value for next sample
// value sent to codec

interrupt void c_int11()

angle = angle + offset;

// interrupt service routine

If (angle > 2*PI)

angle -= 2*PI;

// reset angle if > 2*PI

// angle = angle - 2*PI

return; // return from interrupt

// calculate current output sample

// output each sine value

void main()

// set offset value

// previous angle plus offset

// init DSK, codec, SP0 for interrupts

// wait for an interrupt to occur

It is important to notice that code is divided (via blank lines) into different sections (in this case three
sections). This format is often used and it is recommended that you adopt this style of coding.



In particular, the section containing the function main() will always come last (lines 22 through 26).
In C, the function main() is always the starting point of the program. The linker knows to look for this
function to begin execution. A C program without a main() function is meaningless.
For ease of understanding, this code will be analyzed in this order: section one (lines 1 through 7),
then section three (lines 22 through 26), and finally section two (lines 9 through 20).

Analyzing the Code

The first section of code (lines 1 through 7) is used for preprocessor directives and the definition of
global variables. In C, the # sign signifies a preprocessor directive. In this course, we will primarily
use only two preprocessor directives, namely #include and #define.
In line 1, the preprocessor directive, #include <math.h>, tells the preprocessor to insert the code
stored in the header file math.h into the first lines of the code sine_gen.c before the compiler compiles
the file. Including this header file allows us to call mathematical functions such as sin(), cos(),
tan(), etc. as well as functions for logarithms, exponentials, and hyperbolic functions. This
header file is required for the sin() function line 17. To see a full list of functions available with
math.h, use the help menu in CCS.
The next preprocessor directive defines the fixed point number PI, which approximates the irrational
number before compiling, the preprocessor will replace every occurrence of PI in sine gen.c with
the number specified . The next five lines (4 through 7) define the global variables: f0, fs, angle,
offset, and sine value. The variables fs and sine value are of type short which means they hold 16-bit
signed integer values. The variables f0, angle, and offset are of type float which means they hold
IEEE single precision (32-bit) floating point numbers.
Notice that all of the lines that contain statements end with a semicolon. This is standard in C code.
The only lines that do not get semicolons are function names, like c_int11(), conditional statements,
like if(), and opening and closing braces ({ }) associated with them.
The last section of code (lines 22 through 26) contains the function main(). The format of the main()
function will NOT change from program to program. Lines 22,23 and 26 will always be the first two
lines and last line, respectively. The first line in main() (line 24) calls the function comm_intr(). This
function is located within the file C6xdskinit.c, which is one of the support files given to you. This
function initializes the on-board codec, specifies that the transmit interrupt XINT0 will occur in SP0,
initialize the interrupt INT11 to handle this interrupt, and allows interrupts INT4 through INT15 to be
recognized by the DSP chip.
Now, the DSP chip and codec have been configured to communicate via interrupts, which the codec
will generate every 0.125ms. The program sine_gen now waits for an interrupt from the codec, so an
infinite loop keeps the processor idle until an interrupt occurs. This does not have to be the case, since
an interrupt will halt the CPU regardless whether it is processing or idling. But in this program, there
is no other processing, so we must keep the processor idling while waiting for an interrupt.
The middle section of code (lines 9 through 20) is used to define the interrupt service routine or ISR.
When an interrupt occurs, the program branches to the ISR cint11() as specified by vectors 11.asm.
This interrupt generates the current sample of the sinusoid and outputs it to the codec.
Line 11 determines the offset value 2

. For a given fo, this value will not change, so it does not

need to be calculated every time an interrupt occurs. However, by calculating this value here, we will
be able to change the value of our sinusoid using a Watch Window. This is demonstrated in the next
Line 12 calculates the current sample point by taking the value stored in the global variable angle and
adding the offset value to it. The angle variable is, of course, the angle (in radians) that is passed to


the sine function. Remember that the C the command angle += offset; is shorthand for the command
angle = angle + offset.
The sin(x) function in C approximates the value of sin(x) for any value of x, but a better and more
efficient approximation will be computed if 0 <x < 2. Therefore, lines 14 and 15 are used to reset the
value of sample if it is greater than 2. Since sin(x) is periodic 2 in x, subtracting 2 from x will not
change the value of the output.
Line 17 calculates the sine value at the current sample point. The value is typecast as (short) before it
is stored in the variable sine value. Typecasting tells the compiler to convert a value from one data
type to another before storing it in a variable or sending it to a function. In this case, the value
returned from the sin() is a single precision floating point number (between -1.0 and 1.0) that gets
scaled by 20000. By typecasting this number as a short (16-bit signed integer between the values 32768 and 32767), the CPU will round the number to the nearest integer and store it in a 16-bit signed
integer format (2's complement). This value is scaled by 20000 for two reasons. First, it is needed so
that rounding errors are minimized, and second, it amplifies the signal so it can be observed on the
oscilloscope and heard through speakers or headphones. This scaling factor must be less than 32768
to prevent overdriving the codec.
Line 18 sends the current sine value to the codec by calling the function output_sample(). The code
for output sample() is located in file C6xdskinit.c.
Upon completion of the interrupt (generating a sinusoid sample and outputting it to the on-board
codec), the interrupt service routine restores the saved execution state (see the command return; in
line 19). In this program, the saved execution state will always be the infinite while loop in the main()

Using a Watch Window

Once an algorithm has been coded, it is good to have software tools for observing and modifying the
local and global variables after a program has been loaded onto the DSK. Located in CCS is a
software tool called a Watch Window, which allows the user to view local variables and to view and
modify global variables during execution. In this lab, we will not view any local variables, but we
will view and modify global variables.
In CCS, start running the program sine_gen.out again and make sure that you have a valid output on
an oscilloscope. Then click on the pull-down menu `view', and select `Watch Window'. A subwindow should appear on the bottom of the main CCS window. You should notice two tabs on the
bottom left part of the new sub-window: `Watch Locals' and `Watch 1'. Click on the tab `Watch 1'.
Click on the highlighted field under the label `Name', type in the variable name f0, and press Enter. In
the field under the label `Value', you should see the number 1000, which is the frequency of the
observed sinusoid. Click on the value 1000 and change it to 2000. You should see a 2kHz sinusoid on
the oscilloscope.

1. Use a watch window to change the value of fs in the program above from 8000 to 6000.
How does this affect the frequency of the observed sinusoid? Does this change the rate of your digital
system (i.e. the rate of the codec changes) or does it just scale the observed frequency? Is there a
benefit to setting the value of fs in your program to a value different than the rate of the codec being


used? Explain what you see and give some intuition into how the rate of this real-time digital system
affects the generation of a sinusoid.
2. Use a watch window to change the value of fo from 1000 to 4000 Hz with a sampling frequency of
8000 Hz. What's the effect of changing the frequency? Comment on the results.

Generating a Sine Wave Using Polling

This section has three purposes: to demonstrate how to reuse a previously created project, create a
real-time communication link between the CPU and codec using polling, and generate a sinusoid using a
lookup table. To create the project sine_lookup_poll, follow these instructions:
1. Create a folder in Windows Explorer to store this project
(e.g. create the folder C:\DSP\lab2\sine_lookup_poll)
2. Copy the files sine_gen.pjt and sine_gen.c, from the previous project, into
your newly created folder.
3. Change the names of sine_gen.pjt and sine_gen.c to sine_lookup_poll.pjt
and sine_lookup_poll.c respectively.
4. Open sine_lookup_poll.pjt in CCS. When the window appears that says CCS
cannot find the file sine_gen.c, select 'ignore'.
5. In the left-hand window of CCS, select the file sine_gen. c and press the Delete key to
remove the file from the project. Also, delete the file vectors11.asm.
6. Add the renamed C source code file sine_lookup_poll. c to the project by selecting
'Project', then 'Add Files to Project', then select sine_lookup_poll. c, and then click
'Open'. Also add the other vectors file, vectors. asm, located in your 'support' folder.
7. In CCS, select the pull down menu 'Project' and go to 'Build Options'. Click on the
Linker tab and change the word sine_gen in .\Debug\sine_gen.out to
sine_lookup_poll in the field 'Output Filename (-o):'. Click 'OK'
8. In CCS, double-clicking on sine_lookup_poll. c in the left hand window. Change the
C code to the following:



Short sine_table[8] = {0,14142,20000,14142,0,-14142,-20000,-4142};

short ctr;
void main()
while( 1 )
if (ctr < 7) ++ctr;
else ctr = 0;
9. Add comments to your code where appropriate and save the file in CCS.
Now, build your project by clicking on the 'rebuild all' button (the button with three red arrows). Before
loading a new program onto the DSK, it is best to reset the DSP. This can be done within CCS by
selecting the 'Debug' pull down menu and then selecting 'Reset CPU'. Once the DSP is reset, load your
new program onto the DSK and observe a 1kHz sine wave on an oscilloscope.
Notice that the sine wave algorithm is now coded within the infinite while loop (while(1)). This is the
general structure for polling. In both polling and interrupt based programs, the algorithm must be small
enough to execute within .125ms (at an 8kHz rate) in order to maintain a constant output to the on-board
codec. Algorithms can be coded under either scheme, using polling or interrupts. In this class, most of
the algorithms will be coded using interrupts.

1. Study the code above and the code in C6xdskinit .c. Pay particular attention to
the functions output_sample() and msbsp0_write(). Where is the polling done?
Other than the fact that polling is used instead of interrupts, how is this algorithm
different from the algorithm in sine_gen.c?
2. Implement the project sine_lookup_poll.pjt using interrupts. Re-label the
project sine_lookup.pjt. Explain the procedure required to change a polling based
program to an interrupt driven program. Include a copy of your C program.
3. Implement sine_gen.pjt using polling. Re-label the project: sine_gen_poll.pjt.
Explain the procedure required to convert an interrupt-driven program to a pollingbased program.



End Notes
This lab was used to learn how to create a project and implement it on the DSK. In all real-time DSP
algorithm implementations, the processing rate of a digital signal processing system is very important.
For this lab, only an 8kHz rate was used to implement algorithms.
In the next lab, we will explore the concepts of input and output, and develop the foundation for
designing systems and processing signals on the C6711 DSK.



DSP Laboratory Experiment # 3

Sampling and Reconstruction
1. To understand the concept of sampling, aliasing, and reconstruction.
2. To demonstrate the effect of aliasing on the reconstruction process.
3. To synthesize a square wave function.

1. Compute the Fourier series expansion for the signals below in the form

x(t ) = a 0 + An sin( 2nf 0 t + k )

n =1






Note that the function after the An is sin(2nf0t + k), instead of the usual complex exponential.
The formula of the complex exponential Fourier series must be modified to accommodate this.

Solve exercise 5 in the lab theoretically.


Theoretically speaking, what is the minimum sampling frequency of a square wave having f0 = 2


If a sine wave of f0 = 6 kHz is sampled with fs= 8 kHz, determine the output of the D/A

In order to store, transmit or process analog signals using digital hardware, we must first convert them
into discrete-time signals by sampling.
The processed discrete-time signal is usually converted back to analog form by interpolation,
resulting in a reconstructed analog signal xr(t).

Figure (1) Sampling and Reconstruction process

An ideal sampler reads the values of the analog signal xa(t) at equally spaced sampling instants. The
time interval Ts between adjacent samples is known as the sampling period (or sampling interval).
The sampling rate, measured in samples per second, is fs =1/Ts. An actual (non-ideal) sampling circuit
cannot capture the value of xa(t) at a single time instant. Instead, the output of a sampling circuit is the
average value of xa(t) over a short interval, as shown, where delta is much shorter than the sampling
period Ts .

Ideal sampling circuit

x[n]= xa(nTs)
n=, -1, 0, 1, 2, .


Actual sampling circuit

nT +
1 s
x[n] =
x a (t ) dt
2 nTs-


Sampling Theorem
The bandlimiting of xa(t) also makes it possible to reconstruct xa(t) from its samples x[n] =xa(nTs).
The sampling theorem states that an analog signal xa(t) can be exactly reconstructed from its samples
by the infinite order interpolation formula

x a (t ) =

x(n) g (t nT )

provided that

n =

- The frequency content of xa(t) is ideally bandlimited to a frequency range magnitude of f is

less than or equal to fmax ; f f max .
- The sampling rate fs satisfies the Nyquist condition ; f s f 2 f max
- The interpolating function g(t) is the impulse response of an analog ideal low-pass filter with
a cut-off frequency fc such that fmax fc <fs -fmax.

As we shall presently see, the frequency content of the analog signal xa(t) has to be limited before
attempting to sample it. This means that xa(t) cannot change too fast; consequently, the average value
over the interval nTs- to nTs+ is a good approximation of the ideally sampled value xa(t) of nTs .
The need for bandlimiting the signal xa(t) is easy to demonstrate by a simple example.
The solid line describes a 0.5Hz continuous-time sinusoidal signal and the dash-dot line describes a
1.5 Hz continuous time sinusoidal signal. When both signals are sampled at the rate of fs =2
samples/sec, their samples coincide, as indicated by the circles in Figure 2. This means that x1[nTs] is
equal to x2[nTs] and there is no way to distinguish the two signals apart from their sampled versions.
This phenomenon, known as aliasing, occurs whenever f2 f1 is a multiple of the sampling rate:
in our example, fs equal f1 + f2.

Figure (2) Two sinusoidal signals are indistinguishable from their

sampled versions whenever f2 f1 is a multiple of the sampling rate fs



x1(t)=cos(2f1 t)

, f1 = 0.5 Hz

X2(t)=cos(2f2 t)

, f2 = 1.5 Hz

f2 =2 samples/sec

x1(nTs) = x2(nTs)

x1(nTs)=cos(2f1 nTs)= cos(2

x2(nTs)=cos(2f2 nTs)= cos(2

n ) = cos(0.5n)

n ) = cos(1.5n) = cos(1.5n 2n) = cos(0.5n)

Since cos(x)=cos(-x), then cos(0.5n) = cos(0.5n)

x1(nTs) = x2(nTs)

Aliasing in Frequency Domain

The sampling process can be represented by the equation

x s (t ) = x(t ) p (t )
p (t ) =

(t nT )

n =

It follows that

P( w) =


n =


(w nw )

n =

and hence,

X s ( w) =

X ( w) * P( w)

X ( w nw )

n =









T 2T 3T





T 2T 3T



Figure (3) Sampling in Time and Frequency Domains

Then Xd(w) consists of the periodic repetition at intervals ws of X(w). If fs does not satisfy the Nyquist
rate, the different components of Xd(w) overlap and will not be able to recover x(t) exactly as shown
in Figure(4). This is referred to as aliasing in frequency domain.




- WS





- WS -WB










Figure (4) Aliasing in Frequency Domain

Avoiding Aliasing
In order to avoid aliasing we must restrict the analog signal xa(t) to the frequency range, fo less than
fs/2 in magnitude. This constraint guarantees that for any two individual frequencies (f1 and f2) in this
range both the sum and the difference of f1 and f2 are bound in magnitude by the sum of the
magnitudes of f1 and f2 and this sum is, in turn, bounded by the sampling frequency fs so that aliasing
cannot occur. Thus, every sampler must be preceded by an analog low-pass filter, known as an antialiasing filter, with a cut-off frequency fc equals fs /2.
This means that the high frequency artifacts of the continuous-time signal will be lost. This
is the cost of managing aliasing. In practice, the anti-aliasing filter will have a cutoff
frequency at roughly 90% of the Nyquist frequency and use the other 10% for roll-off. The
on-board codec of the DSK has a sampling rate of fs = 8 kHz and an anti-aliasing filter with
cutoff frequency 3.6kHz, which is 90% of fs/2 (Nyquist Frequency).




fc < fs /2

fo p



f1 f 2 f1 + f 2 p f s

Figure (5) Avoiding aliasing in signal processing

If the desired sampling rate is lower than the sampling rate of the available data, in this case, we may
use a process called downsampling or decimation to reduce the sampling rate of the signal.
Decimating, or downsampling, a signal x(n) by a factor of D is the process of creating a new signal
y(n) by taking only every Dth sample of x(n). Therefore y(n) is simply x(Dn).
Using this method we can resample the discrete signals with no need for reconstruction first. This
process will give you the ability to vary the sampling rate of a discrete signal by discarding some of
its values in the time domain depending on the desired sampling rate. For example, if we want to
reduce the sampling rate to the half, we down a sample between every two samples. In this case, we
downsampled the signal by 2, or ( 2 ). Similarly, ( 3 ) x[n] will produce a signal that has a sample
rate equals one third the sampling rate of x[n] by taking every third sample of x[n] and discarding two
samples in between.
By MATLAB, we can do this in an easy way. For example,

>> x=1:1:10

9 10

>> x2=x(1:2:end)
x2 =



Part 1: Synthesis of Square Wave
The Fourier representations of signals involve the decomposition of the signal in terms of complex
exponential functions. These decompositions are very important in the analysis of linear timeinvariant (LTI) systems. The response of an LTI system to a complex exponential input is a complex
exponential of the same frequency!
Only the amplitude and phase of the input signal are changed. Therefore, studying the frequency
response of a LTI system gives complete insight into its behavior.
Once MATLAB is started, type dspLab3 to bring up a library of Simulink components. Double
click the icon labeled Synthesizer to bring up a model as shown in Figure 6. This system may be used
to synthesize periodic signals by adding together the harmonic components of a Fourier series
expansion. Each Sine Wave block can be set to a specific frequency, amplitude and phase.
The initial settings of the Sine Wave blocks are set to generate the Fourier series expansion

x(t ) = 0 +


k =1
k odd


sin(2kt )


Figure (6) Simulink model for the synthesizer experiment.

These are the first 8 terms in the Fourier series of the periodic square wave shown in Figure 7.
Run the model by selecting Start under the Simulation menu. A graph will pop up that shows the
synthesized square wave signal and its spectrum. This is the output of the Spectrum Analyzer. After
the simulation runs for a while, the Spectrum Analyzer element will update the plot of the spectral
energy and the incoming waveform.

Figure (7) The desired waveform for the synthesizer experiment.



1. Save a copy of the synthesizer file as tri_synthesizer.
2. Change the parameters of each sine wave block to the values that you obtain in your
prelab for a triangular Fourier series expansion.
3. Start simulation and see the results.

Part 2: Aliasing of sinusoidal signals

Exercise#2: Aliasing in Time Domain
The signal x(t ) = cos(2f 0 t ) can be sampled at the rate f s =

to yield x(n) = cos(2 0 n) .

Aliasing will be observed for various fo.

a. Let fs=10 kHz and fo=1 kHz. Compute and plot x[n] using stem.m. One can see the
sinusoidal envelope.
b. Use subplot to plot x[n] for fo=300 Hz, 700 Hz, 1100 Hz and 1500 Hz. The
frequencies increase as expected.
c. Use subplot to plot x[n] for fo=8500 Hz, 8900 Hz, 9300 Hz and 9700 Hz. Do the
frequencies increase or decrease? Explain.
d. Use subplot to plot x[n] for fo=10300 Hz, 10700 Hz, 11100 Hz and 11500 Hz. Do the
frequencies increase or decrease? Explain.

Exercise#3: Aliasing in Frequency domain

a. Using the blocks in the library dsplab3, construct the simulink model shown in Figure 8.

Figure (8) Simulink model to implement aliasing in frequency domain



b. Input a sine wave of fo=5 Hz frequency from the signal generator. Choose a sampling time of 0.01
sec for the pulse generator with a pulse duration of 1 % of the sampling period. Choose the cut-off
frequency of 2 fo for the Butterworth low-pass filter.
c. Start the simulation and notice the shifted versions of the frequency domain response of the input
and the output of the filter.
d. Repeat steps 2 and 3 for a sine wave with fo=95 Hz. Comment.
e. Repeat steps 2 and 3 for a sine wave with fo=105 Hz. Comment.

Exercise#4: Downsampling
a. Using MATLAB, generate a sine wave with frequency f0 of 1300 Hz, and sampling
frequency fs of 8000 Hz.
b. Save the data of the sine wave as a sound file, named as 8000.wav.
c. Listen to the tone of the 1300 Hz sine wave.
d. Downsample the data of the sine wave by 2. This will result in a sine wave with a
sampling rate of 4000 Hz. Repeat steps b, c and compare the sounds.
e. Generate a sine wave with frequency f0 of 1300 Hz, and sampling frequency fs of
4000 Hz.

Repeat steps b and c and compare the sounds.

Exercise#5: Sampling and Reconstruction using Simulink

Suppose we have the analog filter shown which is composed of an A/D, discrete time filter , which in
our example here is a moving average type , and D/A.
a. What is the digital frequency of x[n] if x(t)= sin (2 t) ?
b. Find the steady state output, yss(t), if x(t) is the same as in (a) ?
c. Find two other x(t)'s ,different analog frequency, that will give the same steady state
output as x(t)= sin (2 t) ?
d. If the sampling frequency of the A/D converter is changed to 200 Hz, while that of
the D/A is kept to 100 Hz, what is the effect on the resulted output?
e. To prevent aliasing effects a prefilter would be used on x(t) before it passes to the
A/D. What type (Low-pass, high-pass, band-pass, band-reject) of filter would be used
and what is the largest cutoff frequency that would work for the above specified


Sampling Frequency
100 Hz

Discrete-time filter
h[n]=0.5([n]+ [n-1])
Moving Average



Sampling Frequency
100 Hz

Figure (9) The block diagram for exercise 5



Part 3: TLC320AD535 Codec

Located onboard the DSK is the AD535 codec (coder/decoder). The coder part is implemented using
a sampler, delta-sigma modulator, and a decimation filter. The output rate from the codec is 8000 16bit words per second (fs = 8 kHz), but the sampler is over-sampling at rate 64 times fs. This is
common practice when using delta-sigma modulators. A delta-sigma modulator takes the current
sample and compares it with the previous sample. If the current sample is larger (or smaller) than the
previous sample, it makes the current sample the previous sample plus (or minus) some fixed
amplitude . In our case, we have a 1-bit delta-sigma modulator which means that the current sample
(16-bit finite-length word) will be the previous sample plus (or minus) a binary 1 assuming that the
current sample is larger (or smaller) than the previous sample. By over-sampling by a factor of 64, a
good representation of the original signal is captured at each sample point, since the signal, which is
essentially band-limited, will not change by more than 1 bit, or quantization level, between each
sample point. Only every 64th sample point is needed to accurately represent the bandlimited signal,
so decimation filter (LPF running at 8kHz) is used to decrease the word rate to the desired rate
8kHz. These 16-bit finite-length words are then transmitted to the CPU via serial port 0 on the DSP
chip. Notice that the CPU will treat these 16-bit finite length words as 16-bit signed integers (-32768
to +32767).

Sampling and Reconstruction using the On-Board Codec:

A Programming Example
Real-time digital signal processing involves logical operations on an incoming stream of finite-length
words to produce a processed output stream. Figure 10 illustrates this idea.
In most DSP applications, the DSP core of Figure 9 will contain local program and data memory on
the chip that is used to store the algorithm being implemented, local and global variables, and
processed data. We will implement the "DSP core" block as a

Figure (10) DSP Block Diagram

straight wire, which means that only an identity map will be implemented between the input and
output of the DSP core. No local or global variables or processed data will be stored in memory, and
no signal processing will be done. Only the program instructions will be stored in the program



DSP Core as a Straight Wire

1. In the folder C:\DSP\Lab3 the files straight_wire.pjt and straight_wire.c that you will need for this
lab are found.
2. Load the project into CCS and examine the file straight_wire.c. Notice that the file has no global
(or local) variables and that whatever is read in from the codec is immediately sent back to the
codec via the command output sample(input sample()).
3. Compile and load this program onto the DSK and run it.
4. Connect the signal generator and the oscilloscope to the DSK and set the signal generator to a 1
kHz sinusoid with amplitude 1Vpp (peak-to-peak voltage). Observe a 1 kHz sinusoid on the

Notice that the actual peak-to-peak voltage of the signal is greater than 1V (about 1.8V). This is due
to the fact that the resistance of the DSK is higher resistance than the resistance to which the signal
generator has been matched.
4. Change the peak-to-peak voltage and the frequency on the signal generator and observe the effects
on the oscilloscope. If the voltage input to the codec exceeds 3.3V, then the codec will be overdriven.
When the codec is overdriven, the output on the codec will either be amplitude clipping of the input
sine wave or two's compliment overflows effects (a sudden change in sign). If the voltage input is too
small (around 100mV or less), then coupling effects from the internal hardware will be observed. For
frequency, keep in mind that there is a lowpass filter that cuts off frequencies above 3.6 kHz.
5. Vary the frequency of the sinusoid on the signal generator and observe that sinusoids above 3.6kHz
are suppressed. (You should notice that sinusoids around 3.6 kHz are decreased in amplitude, but not
fully suppressed. This is due to the fact that the anti-aliasing filter is not ideal and therefore has a nonzero roll-off around 3.6 kHz.)

a. To observe the effects of the anti-aliasing filter, use a square wave as the input. Input square waves
with 100, 500, 800 and 1400 kHz. Use your knowledge of the Fourier series expansion of a square
wave to explain what you see. Also, listen to this signal and explain what you hear.
b. Repeat for a triangular wave as the input.
c. Sketch the output signal in each case.

Modify straight_wire.c file such that the digital signal is processed by the moving average filter used
in exercise 5.



DSP Laboratory Experiment # 4

Analog Filter Design
1. To know the different types of analog filters.
2. To understand the concepts of analog filter design.

1. Study the given background on MATLAB analog filter design and try an example for
each design function.
2. Solve the following problems theoretically from your textbook.
P3.5, P3.7, P3.8, and P3.10
3. Design an analog fourth-order Butterworth low-pass filter with a cut-off frequency
of 500 Hz and a passband gain of 10 using a suitable number of cascade operational
amplifiers and R, C components for your implementation. Let R=1k. Simulate the
circuit by Orcad to verify your design

Design of Analog Filters in MATLAB
1. Butterworth Digital and Analog Filter design
[B,A] = BUTTER(N,Wn) designs an Nth order lowpass digital Butterworth filter
and returns the
filter coefficients in length N+1 vectors B (numerator) and A (denominator). The coefficients are
listed in descending powers of z. The cutoff frequency Wn must be 0.0 < Wn < 1.0, with 1.0
corresponding to half the sample rate.
If Wn is a two-element vector, Wn = [W1 W2], BUTTER returns an order 2N bandpass filter with
passband W1 < W < W2.
[B,A] = BUTTER(N,Wn,'high') designs a highpass filter.
[B,A] = BUTTER(N,Wn,'stop') is a bandstop filter if Wn = [W1 W2].
When used with three left-hand arguments, as in
[Z,P,K] = BUTTER(...), the zeros and poles are returned in length N column vectors Z and P, and the
gain in scalar K.


When used with four left-hand arguments, as in

[A,B,C,D] = BUTTER(...), state-space matrices are returned.
BUTTER(N,Wn,'s'), BUTTER(N,Wn,'high','s') and BUTTER(N,Wn,'stop','s')
Butterworth filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.



n=5; wn=.4;

2. BUTTORD Butterworth filter order selection.

[N, Wn] = BUTTORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital Butterworth
filter that loses no more than Rp dB in the passband and has at least Rs dB of attenuation in the
Wp and Ws are the passband and stopband edge frequencies, normalized from 0 to 1 (where 1
corresponds to pi radians/sample). For example,

Wp = .1,

Ws = .2

Highpass: Wp = .2,

Ws = .1

Bandpass: Wp = [.2 .7], Ws = [.1 .8]

Bandstop: Wp = [.1 .8], Ws = [.2 .7]
BUTTORD also returns Wn, the Butterworth natural frequency (or, the "3 dB frequency") to use with
BUTTER to achieve the specifications.
[N, Wn] = BUTTORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case
Wp and Ws are in radians/second.
When Rp is chosen as 3 dB, the Wn in BUTTER is equal to Wp in BUTTORD.

w1=20; Rp=-2;
w2=30; Rs=-10;

3. CHEBY1 Chebyshev Type I digital and analog filter design.

[B,A] = CHEBY1(N,R,Wn) designs an Nth order lowpass digital Chebyshev filter with R decibels of
peak-to-peak ripple in the passband. CHEBY1 returns the filter coefficients in length N+1 vectors B
(numerator) and A (denominator). The cutoff frequency Wn must be 0.0 < Wn < 1.0, with 1.0



corresponding to half the sample rate. Use R=0.5 as a starting point, if you are unsure about choosing
If Wn is a two-element vector, Wn = [W1 W2], CHEBY1 returns an order 2N bandpass filter with
passband W1 < W < W2.
[B,A] = CHEBY1(N,R,Wn,'high') designs a highpass filter.
[B,A] = CHEBY1(N,R,Wn,'stop') is a bandstop filter if Wn = [W1 W2].
When used with three left-hand arguments, as in
[Z,P,K] = CHEBY1(...), the zeros and poles are returned in length N column vectors Z and P, and
the gain in scalar K.
When used with four left-hand arguments, as in
[A,B,C,D] = CHEBY1(...), state-space matrices are returned.
CHEBY1(N,R,Wn,'s'), CHEBY1(N,R,Wn,'high','s') and CHEBY1(N,R,Wn,'stop','s') design analog
Chebyshev Type I filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.

4. CHEB1ORD Chebyshev Type I filter order selection.

[N, Wn] = CHEB1ORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital Chebyshev
Type I filter that loses no more than Rp dB in the passband and has at least Rs dB of attenuation in
the stopband.
Wp and Ws are the passband and stopband edge frequencies, normalized from 0 to 1 (where 1
corresponds to pi radians/sample).
For example,

Wp = .1,

Ws = .2

Highpass: Wp = .2,

Ws = .1

Bandpass: Wp = [.2 .7], Ws = [.1 .8]

Bandstop: Wp = [.1 .8], Ws = [.2 .7]
CHEB1ORD also returns Wn, the Chebyshev natural frequency to use with

CHEBY1 to achieve the

[N, Wn] = CHEB1ORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case
Wp and Ws are in radians/second.

w1=1; Rp=-2;
w2=1.3; Rs=-20;
[numt,dent]=cheby1(n,-Rp, wn,s)



5. CHEBY2 Chebyshev Type II digital and analog filter design.

[B,A] = CHEBY2(N,R,Wn) designs an Nth order lowpass digital Chebyshev filter with the stopband
ripple R decibels down and stopband edge frequency Wn. CHEBY2 returns the filter coefficients in
length N+1 vectors B (numerator) and A (denominator).The cutoff frequency Wn must be 0.0 < Wn <
1.0, with 1.0 corresponding to half the sample rate. Use R = 20 as a starting point, if you are unsure
about choosing R.
If Wn is a two-element vector, Wn = [W1 W2], CHEBY2 returns an order 2N bandpass filter with
passband W1 < W < W2.
[B,A] = CHEBY2(N,R,Wn,'high') designs a highpass filter.
[B,A] = CHEBY2(N,R,Wn,'stop') is a bandstop filter if Wn = [W1 W2].
When used with three left-hand arguments, as in
[Z,P,K] = CHEBY2(...), the zeros and poles are returned in length N column vectors Z and P, and
the gain in scalar K.
When used with four left-hand arguments, as in
[A,B,C,D] = CHEBY2(...), state-space matrices are returned.
CHEBY2(N,R,Wn,'s'), CHEBY2(N,R,Wn,'high','s') and CHEBY2(N,R,Wn,'stop','s') design analog
Chebyshev Type II filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.

6. CHEB2ORD Chebyshev Type II filter order selection.

[N, Wn] = CHEB2ORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital Chebyshev
Type II filter that loses no more than Rp dB in the passband and has at least Rs dB of attenuation in
the stopband.
Wp and Ws are the passband and stopband edge frequencies, normalized from 0 to 1 (where 1
corresponds to pi radians/sample).
For example,

Wp = .1,

Ws = .2

Highpass: Wp = .2,

Ws = .1

Bandpass: Wp = [.2 .7], Ws = [.1 .8]

Bandstop: Wp = [.1 .8], Ws = [.2 .7]
CHEB2ORD also returns Wn, the Chebyshev natural frequency to use with CHEBY2 to achieve the
[N, Wn] = CHEB2ORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case
Wp and Ws are in radians/second.

7. ELLIP Elliptic or Cauer digital and analog filter design.

[B,A] = ELLIP(N,Rp,Rs,Wn) designs an Nth order lowpass digital elliptic filter with Rp decibels of
peak-to-peak ripple and a minimum stopband attenuation of Rs decibels. ELLIP returns the filter



coefficients in length N+1 vectors B (numerator) and A (denominator).The cutoff frequency Wn must
be 0.0 < Wn < 1.0, with 1.0 corresponding to half the sample rate. Use Rp = 0.5 and Rs = 20 as
starting points, if you are unsure about choosing them.
If Wn is a two-element vector, Wn = [W1 W2], ELLIP returns an order 2N bandpass filter with
passband W1 < W < W2.
[B,A] = ELLIP(N,Rp,Rs,Wn,'high') designs a highpass filter.
[B,A] = ELLIP(N,Rp,Rs,Wn,'stop') is a bandstop filter if Wn = [W1 W2].
When used with three left-hand arguments, as in
[Z,P,K] = ELLIP(...), the zeros and poles are returned in length N column vectors Z and P, and the
gain in scalar K.
When used with four left-hand arguments, as in
[A,B,C,D] = ELLIP(...), state-space matrices are returned.
ELLIP(N,Rp,Rs,Wn,'s'), ELLIP(N,Rp,Rs,Wn,'high','s') and ELLIP(N,Rp,Rs,Wn,'stop','s') design analog
elliptic filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.

8. ELLIPORD Elliptic filter order selection.

[N, Wn] = ELLIPORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital elliptic filter
that loses no more than Rp dB in the passband and has at least Rs dB of attenuation in the stopband.
Wp and Ws are the passband and stopband edge frequencies, normalized from 0 to 1 (where 1
corresponds to pi radians/sample).
For example,

Wp = .1,

Ws = .2

Highpass: Wp = .2,

Ws = .1

Bandpass: Wp = [.2 .7], Ws = [.1 .8]

Bandstop: Wp = [.1 .8], Ws = [.2 .7]
ELLIPORD also returns Wn, the elliptic natural frequency to use with ELLIP to achieve the
[N, Wn] = ELLIPORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case
Wp and Ws are in radians/second.
NOTE: If Rs is much much greater than Rp, or Wp and Ws are very close, the estimated order can be
infinite due to limitations of numerical precision.

w1=1; w2=1.21;


9. FREQS Laplace-Transform (s-domain) Frequency Response.

H = FREQS(B,A,W) returns the complex frequency response vector H of the filter B/A:

B( s ) b1 s nb 1 + b2 s ns 2 + L + bnb
H ( s) =
A( s ) a1 s na 1 + a 2 s na 2 + L + a na
given the numerator and denominator coefficients in vectors B and A.
The frequency response is evaluated at the points specified in vector W (in rad/s). The magnitude and
phase can be graphed by calling FREQS(B,A,W) with no output arguments.
[H,W] = FREQS(B,A) automatically picks a set of 200 frequencies W on which the frequency
response is computed.
FREQS(B,A,N) picks N frequencies.

num=1; den=[1 3 5 10]


10. FILTER One-dimensional digital filter.

Y = FILTER(B,A,X) filters the data in vector X with the filter described by vectors A and B to
create the filtered data Y. The filter is a "Direct Form II Transposed"
implementation of the
standard difference equation:
A1y(n) = b1 x(n) + b2x(n-1) + ... + bnb+1x(n-nb)- a2y(n-1) - ... - ana+1y(n-na)
If a1 is not equal to 1, FILTER normalizes the filter coefficients by a1. When x is a matrix, FILTER
operates on the columns of x. When x is an N-D array,FILTER operates along the first non-singleton
dimension, namely dimension 1 for column vectors and non-trivial matrices, and dimension 2 for row
[Y,Zf] = FILTER(B,A,X,Zi) gives access to initial and final conditions, Zi and Zf, of the delays. Zi is
a vector of length MAX(LENGTH(A),LENGTH(B))-1, or an array of such vectors , one for each
column of x.
FILTER(B,A,X,[],DIM) or FILTER(B,A,X,Zi,DIM) operates along the dimension DIM.



n=5; wn=30/50;
y=filter(b,a,x); %x is the input data

11. FREQZ Digital filter frequency response.

[H,W] = FREQZ(B,A,N) returns the N-point complex frequency response vector H and the N-point
frequency vector W in radians/sample of the filter B/A:

B( z ) bnb +1 z nb + L + b2 z 1 + b1
H ( z) =
A( z ) a na +1 z na + L + a 2 z 1 + 1
given numerator and denominator coefficients in vectors B and A. The frequency response is
evaluated at N points equally spaced around the upper half of the unit circle. If N isn't specified, it
defaults to 512.
[H,W] = FREQZ(B,A,N,'whole') uses N points around the whole unit circle.
H = FREQZ(B,A,W) returns the frequency response at frequencies designated in vector W, in
radians/sample (normally between 0 and pi).
[H,F] = FREQZ(B,A,N,Fs) and [H,F] = FREQZ(B,A,N,'whole',Fs) return frequency vector F (in Hz),
where Fs is the sampling frequency (in Hz).
H = FREQZ(B,A,F,Fs) returns the complex frequency response at the frequencies designated in
vector F (in Hz), where Fs is the sampling frequency (in Hz).
FREQZ(B,A,...) with no output arguments plots the magnitude and unwrapped phase of the filter in
the current figure window.

12. Analog Prototype Design

In this section, we present a number of functions that can create lowpass analog prototype filters with
cutoff frequency of one. The next table summarizes the analog prototype design functions and then a
details description of these functions.

Filter Type

Analog Prototype Function



Chebyshev type I


Chebyshev type II




a. BUTTAP Butterworth analog lowpass filter prototype.

[Z,P,K] = BUTTAP(N) returns the zeros, poles, and gain for an N-th order normalized prototype
Butterworth analog lowpass filter. The resulting filter has N poles around the unit circle in the left
half plane, and no zeros.


b. CHEB1AP Chebyshev Type I analog lowpass filter prototype.

[Z,P,K] = CHEB1AP(N,Rp) returns the zeros, poles, and gain of an N-th order normalized analog
prototype Chebyshev Type I lowpass filter with Rp decibels of ripple in the passband. Chebyshev
Type I filters are maximally flat in the stopband.

c. CHEB2AP Chebyshev Type II analog lowpass filter prototype.

[Z,P,K] = CHEB2AP(N,Rs) returns the zeros, poles, and gain of an N-th order normalized analog
prototype Chebyshev Type II lowpass filter with Rs decibels of ripple in the stopband. Chebyshev
Type II filters are maximally flat in the passband.

d. ELLIPAP Elliptic analog lowpass filter prototype.

[Z,P,K] = ELLIPAP(N,Rp,Rs) returns the zeros, poles, and gain of an N-th order normalized
prototype elliptic analog lowpass filter with Rp decibels of ripple in the passband and a stopband Rs
decibels down.

13. Frequency Transformation

The next step of the analog prototype design process is the frequency transformation of a lowpass
prototype. The table below has the transformation list where 0 = 2 w1

is the cutoff frequency

and B w = w2 w1 .

Frequency Transformation

Transformation Function

Lowpass to lowpass s ' =


[numt ,dent]=lp2lp(num,den,wo)

Lowpass to highpass s ' =



Lowpass to bandpass

s' =

s 2 + w1 w2
s ( w2 w1 )

Lowpass to bandstop

s' =

s ( w2 w1 )
s 2 + w1 w2






a. LP2LP Lowpass to lowpass analog filter transformation.

[NUMT,DENT] = LP2LP(NUM,DEN,Wo) transforms the lowpass filter prototype NUM(s)/DEN(s)
with unity cutoff frequency of 1 rad/sec to a lowpass filter with cutoff frequency Wo (rad/sec).
[AT,BT,CT,DT] = LP2LP(A,B,C,D,Wo) does the same when the filter is described in state-space

b. LP2HP Lowpass to highpass analog filter transformation.

[NUMT,DENT] = LP2HP(NUM,DEN,Wo) transforms the lowpass filter
NUM(s)/DEN(s) with unity cutoff frequency to a highpass filter with cutoff frequency Wo.
[AT,BT,CT,DT] = LP2HP(A,B,C,D,Wo) does the same when the filter is described in state-space

c. LP2BP Lowpass to bandpass analog filter transformation.

[NUMT,DENT] = LP2BP(NUM,DEN,Wo,Bw) transforms the lowpass filter
NUM(s)/DEN(s) with unity cutoff frequency to a bandpass filter with center frequency Wo and
bandwidth Bw.
[AT,BT,CT,DT] = LP2BP(A,B,C,D,Wo,Bw) does the same when the filter is described in state-space

d. LP2BS Lowpass to bandstop analog filter transformation.

[NUMT,DENT] = LP2BS(NUM,DEN,Wo,Bw) transforms the lowpass filter
NUM(s)/DEN(s) with unity cutoff frequency to a bandstop filter with center frequency Wo and
bandwidth Bw.
[AT,BT,CT,DT] = LP2BS(A,B,C,D,Wo,Bw) does the same when the filter is described in state-space

1. Using MATLAB analog filter design functions solve the following


P3.5, P3.7, P3.8, and P3.10

2. Application Example
a. Make a signal with three sinusoidal components (at frequencies of 5, 15, and 30 Hz).
b. Design an eighth order elliptic filter to keep the 15 Hz sinusoid and get rid of the 5
and 30 Hz sinusoids
c. Plot the signal after filtering. Also plot the frequency response of the signal before
and after the filtering process on the same plot.



DSP Laboratory Experiment # 5

Digital Filter Design
1. To demonstrate the concept of digital filter design.
2. To use a MATAB Filter design and Analysis Tool to design and analyze digital filters.
3. To know the use of filters in noise filtering.

1. Solve the following textbook problems theoretically.
4.15, 4.16, and 4.21
2. Bonus: Solve the application exercise in the lab theoretically.
Background on FDA TOOL
The Filter Design and Analysis Tool (FDATool) is a powerful user interface for designing and
analyzing filters. FDATool enables you to quickly design digital FIR or IIR filters by setting filter
performance specifications, by importing filters from your MATLAB workspace, or by directly
specifying filter coefficients. FDATool also provides tools for analyzing filters, such as magnitude and
phase response plots and pole-zero plots. This background contains the following topics:

1. Opening the Filter Design and Analysis Tool

To open the Filter Design and Analysis Tool, type fdatool, The Filter Design and Analysis Tool
opens in the default design mode.



2. Choosing a Filter Type

You can choose from several filter types:
Hilbert transformer
Arbitrary magnitude
Arbitrary group delay
Raised cosine
For example, to design a bandpass filter, select the radio button next to Bandpass in the Filter Type
region of the GUI.

3. Choosing a Filter Design Method

You can use the default filter design method for the filter type that youve selected, or you can select
a filter design method from the available FIR and IIR methods listed in the GUI.
To select the Remez algorithm to compute FIR filter coefficients, select the FIR radio button and
choose Equiripple from the list of methods.

You can also use the Method menu to select a filter design method.

4. Setting the Filter Design Specifications

The filter design specifications that you can set vary according to filter type and design method. For
example, to design a bandpass filter, you can enter:
Bandpass Filter Frequency Specifications
Bandpass Filter Magnitude Specifications
Filter Order


The display region illustrates filter specifications when you select Filter Specifications from the
Analysis menu.

Bandpass Filter Frequency Specifications

For a bandpass filter, you can set:
Units of frequency: (Hz, kHz, MHz)
Normalized (0 to 1)
Sampling frequency
Passband frequencies
Stopband frequencies
You specify the passband with two frequencies. The first frequency determines the lower edge of the
passband, and the second frequency determines the upper edge of the passband.
Similarly, you specify the stopband with two frequencies. The first frequency determines the upper
edge of the first stopband, and the second frequency determines the lower edge of the second
For this example:
Keep the units in Hz (default).
Set the sampling frequency (Fs) to 2000 Hz.
Set the end of the first stopband (Fstop1) to 200 Hz.
Set the beginning of the passband (Fpass1) to 300 Hz.
Set the end of the passband (Fpass2) to 700 Hz.
Set the beginning of the second stopband (Fstop2) to 800 Hz.



Bandpass Filter Magnitude Specifications

For a bandpass filter, you can specify the following magnitude response characteristics:
Units for the magnitude response (dB or linear)
Passband ripple
Stopband attenuation
For this example:
Keep the units in dB (default).
Set the passband ripple (Apass) to 0.1 dB.
Set the stopband attenuation for both stopbands (Astop1, Astop2) to 75 dB.

Filter Order
You have two mutually exclusive options for determining the filter order when you design an
equiripple filter
Minimum order: The filter design method determines the minimum order filter.
Specify order: You enter the filter order in a text box.
Select the Minimum order radio button for this example.

Note that filter order specification options depend on the filter design method you choose. Some filter
methods may not have both options available.

5. Computing the Filter Coefficients

Now that youve specified the filter design, select the Design Filter button to compute the filter
Notice that the Design Filter button is dimmed once youve computed the coefficients for your filter
design. This button is enabled again once you make any changes to the filter specifications.



6. Analyzing the Filter

Once youve designed the filter, you can view the following filter response characteristics in the
display region or in a separate window:
Magnitude response
Phase response
Overlaid magnitude and phase responses
Group delay
Impulse response
Step response
Pole-zero plot
You can also display the filter coefficients in this region.
You can access the analysis methods as items in the Analysis menu, or by using the toolbar buttons.

For example, to look at the filters magnitude response, select the Magnitude Response button
on the toolbar.

To display the filter response characteristics in a separate window, select Full View Analysis from
the Analysis menu. The Filter Visualization Tool (fvtool) opens. You can use this tool to annotate
your design, view other filter analyses, and print your filter response.



You can click on the response to add a data marker that displays information about the particular
point on the response. Right-clicking displays a menu where you can adjust the appearance of the data
markers or delete them.

7. Saving and Opening Filter Design Sessions

You can save your filter design session as a MAT-file and return to the same session
another time.
Select the Save session button
to save your session as a MAT-file. The first time you save a
session, a Save Filter Design File browser opens, prompting you for a session name.
For example, save this design session as TestFilter.fda in your current working directory by typing
TestFilter in the File name field. The .fda extension is added automatically to all filter design
sessions you save.

You can load existing sessions into the Filter Design and Analysis Tool by selecting the Open
session button, . A Load Filter Design File browser opens that allows you to select from your
previously saved filter design sessions.



1. Use the MATLAB Filter Design Functions that you have dealt with in LAB 4 to solve
the following textbook problems.
4.15, 4.16, and 4.21

2. Repeat exercise (1) using FDAtool, and compare the results.

3. Check the efficiency of your design of the lowpass digital filter described in 4.15
by applying a sinusoidal signal with angular frequency of 0.01, 0.05, 0.1, and 0.3
to the block that you have designed by FDAtool. See the filtered output in time
domain using scope at each case.

4. Application Exercise : Filtering a noise signal from a sinusoidal signal

A sinusoidal signal having f0=75Hz and amplitude of 1v is sampled at a rate of 1000
sample/sec. The discrete time sinusoidal is transmitted through a twisted pair cable.
During its transmission, the signal is corrupted by a noise signal. The noise signal can
be visualized as uniformly distributed random numbers with an amplitude ranging
from 0 to 4v and sampled at a rate of 1000 samples/sec and. This random signal will
be filtered to obtain the noise signal in the band above 250 Hz. At the receiver side,
we need to isolate the sinusoidal signal from the noisy signal.
a. Using simulink, design a model that can generate the noise signal
described in the above problem.
b. Suggest the type of the filter that can be used at the receiver side.
c. Specify the parameters of the filter you choose in part b.
d. Try to visualize the input signal, corrupted signal and the reconstructed
signal on the same figure.



DSP Laboratory Experiment # 6

Design and Implementation of Finite Impulse
Response (FIR) Filters on the C6711 DSK

1. To implement the FIR filters designed by FDAtool on the C6711 DSK.
2. To demonstrate the effect of filtering on some signals.

FIR Filter Using MATLAB's GUI Filter Design and Analysis Tool, FDATOOL
In the last lab we learn how to use the MATLAB's GUI Filter Design and design and analysis tool to
design FIR digital filters. As a revision, to design a lowpass FIR filter using FDAtool, do the
1. From the MATLAB command prompt, type
>> fdatool
This will open the Filter design and analysis window.
2. In the Filter Designer" window, make sure the following are selected:

Set the units to Hz.

Set the sampling frequency to 8000 (sampling rate of the on-board codec).

Make sure that the algorithm Equiripple FIR is selected.

Under specifications, make sure that box for Minimum order is checked.

Select Type: lowpass

Set Fpass to 1500 and Rp to 2.

Set Fstop to 1700 and Rs to 60.

Then select design filter. The following figure will appear.



Figure 1 : Low pass filter design using FDAtool

3. Your filter has been designed by MATLAB. To access this filter from the workspace, go to File
and select Export. In the window Export, complete the following fields:
Export to workspace: Export As coefficient
Variable Names, Numerator: filt1
and then click on the button apply.
4. Your filter is now available in the workspace. To see the filter coefficients, type the following in
the MATLAB workspace

>> h=filt1;
>> stem(h)
>> length(h)
To further analyze this filter, download the MATLAB m-file plotZTP_FIR.m from the course
account. This m-file contains a function that will plot the Z-transform (evaluated at z = ejwto), the polezero diagram and the impulse response in a four-panel plot. This function is a modified version of
plotZTP.m that is used to analyze all rational filters. The modifications are that the denominator
(A(z) in the representation H(z) = B(z)/A(z)) is always 1, and the impulse response is always finite, so
the entire impulse is displayed (This will not be the case for IIR filters). To analyze the filter, filt1,
type the following in the MATLAB workspace.

>> fs=8000;
>> plotZTP_FIR(h,fs)


FDAtool has many FIR filter options such as: Equiripple FIR, Least Squares FIR, and Window FIR.
The passband and stopband each have two sets of parameters Fp, Rp, Fs, and Rs. The parameters Fp
and Fs define the boundaries of the passband and stopband frequencies, respectively. The parameter
Rp determines the ripple (in dB) of the passband and Rs is the stopband rejection parameter that
denotes the relative height of the stopband compared to the passband (i.e. Rs = 60 means that the
amplitude of the stop band is -60 dB less than the passband.) In the case of bandpass and bandstop
filters, there will be two passband and stopband parameters, namely Fp1, Fp2, Fs1, and Fs2. When
designing filters using FDAtool, a transition band of frequencies must be included between Fp1 and
Fs1 as well as Fp2 and Fs2. The tighter these bands are, the larger your filter order will be.
In this lab, we will use the FDAtool, to design FIR filters. A MATLAB m-file have been created to
format the filter coefficients so these filters may be easily implemented in hardware. These files will
be discussed when we do our FIR filter implementation.

FIR Implementation on the C6711 DSK Using C

One of the most common ways to describe digital filters is to use hardware diagrams to describe the
input - output relationships. For FIR filters, one possible hardware diagram is illustrated in Figure 2.
As the input stream x[n] enters the FIR filter it is delayed by the z-1 delay operator and scaled by the

filter coefficient h[k]. The output y[n] =

h[k ]x[n k ] . This hardware diagram shows that the

k =0

output of FIR filter is calculated by doing explicit convolution.

Figure 2: Delay Tap Hardware Diagram of an FIR Filter

Another way to describe FIR filters is to say that the output at time n is the inner product of a filter
coefficient vector with an input vector containing the N +1 most recent inputs. Let's define the two
column vectors h = [h[0], h[1], . . . h[N]]T RN+1 and xn = [x[n],x[n - 1], . . . x[n - N]]T RN+1. The

output is defined to be y[n] = h, x n = h x n =

h[k ]x[n k ] ,

which can be implemented on our

k =0

DSP hardware.



To make this a real-time digital filter, the input vector x n must be updated as each sample is read in
from the codec. After the next sample has been read in, the new input vector containing the N + 1
most recent inputs is x n +1 [x[n + 1], x[n], . . . x[(n + 1) - N]]T RN+1 and the output is y[n + 1] =

h, x n +1 . The vector x n +1 is created by removing the oldest sample of x n from the bottom, shifting
all of the elements down in vector (remember x n is a column vector), and storing the newest sample
x[n + 1] at the top of the vector. This is illustrated below.

The column on the left represents the C coded array that holds the N + 1 most recent inputs and the
three columns on the right illustrate how the incoming samples are stored in the C coded array. This is
not the most efficient way to organize the data in the input vector x, but it provides a good starting
point for coding digital FIR filters in C.
Download the project FIR.pjt and accompanying files FIR.c and LPF1500.cof from the course
account and open it in CCS. Examine the code listing for FIR.c shown in Figure 3.
Within the ISR (lines 7 through 23), note the following:
A local variable k, of type short, is created as a loop counter, the current sample is read in

from the code and stored at the top of the array buffer x[0], and the accumulating variable
for the current output, global variable yn, is initialized to zero (lines 9 through 12).
The explicit convolution (multiply and accumulate operations) of the N + 1 filter

coefficients stored in the vector h[] with the N + 1 most recent inputs stored in the vector
x[] is accumulated in yn (lines 14 and 15).
The input buffer is shifted down starting at the bottom, where the last value of the array is

no longer stored in memory (lines 17 and 18).



Finally, the output is scaled (fixed point implementation) and sent to the codec, and the ISR

returns program control back to the main() function (lines 20 and 22).

The filter implemented in Figure 3 is the equiripple FIR filter designed in FDAtool. Look in the
folder include in CCS and open the file LPF1500.cof. Observe that it contains the 71 filter
coefficients of the 70th order FIR filter created earlier. Also, the filter order N = 70 is defined. By
including a separate file that contains the filter coefficients and filter order, we can keep the same
basic FIR program and include different .cof files to change our FIR filter.
Download the MATLAB m-file FIR_cof_gen.m from the account. This m-file is a function that takes
the filter coefficients, h[k], and creates a formatted .cof that can be included into the C program
1.) // FIR.c FIR filter. Include file of N order FIR filter coefficients
3.) #include "LPF1500.cof"
// coefficient file LPF @ 1500Hz
4.) int yn = 0;
// initialize filter's output
5.) short x[N+1];
// input samples
// NB: impulse duration N+1 samples
7.) interrupt void c_int11()
// ISR
8.) {
9.) short k;
11.) x[0] = input_sample();
// new input @ beginning of buffer
12.) yn = 0;
// initialize filter's output
14.) for (k = 0; k<= N; k++)
15.) yn += (h[k] * x[k]);
// y(n) += h(k)* x(n-k)
17.) for (k = N; k > 0; k--)
// starting @ end of buffer
18.) x[k] = x[k-1];
// update delays with data move
20.) output_sample((short)(yn >> 15));
// scale filtered output
22.) return;
23.) }
25.) void main()
26.) {
27.) comm_intr();
// init DSK, codec, McBSP
28.) while(1);
// infinite loop
29.) }
Figure 3: Listing of FIR.c



In the FDAtool design example from before, a lowpass filter with cutoff frequency 1500Hz was
created. Once this filter was exported to the workspace as filt1, the filter coefficients were found by
typing h=filt1; These filter coefficients are formatted into a .cof by typing
>> FIR_ cof_gen(lpf1500, h, fixed)
in the MATLAB workspace. (Notice that the m-file FIR_cof_gen.m must be stored in your current
working directory in MATLAB.) This command will create the file LPF1500.cof that may be
included in FIR.c.
At the end of the FDAtool filter design, commands were given to plot the filter coefficients. You may
noticed that the coefficients were all less than one. In fixed-point arithmetic, all of the filter
coefficients must be signed-integers, so the numbers were all scaled by 215 and rounded to the nearest
integer. This scaling undone before output by multiplying by 2-15. In fixed-point algorithms, this type
of scaling must be done. This leads to a few additional comments. First, the input samples and the
filter coefficients are 16-bit signed integers, so the accumulation variable yn is a 32-bit signed integer,
which, in C, means that the variable is declared as int yn (instead of short yn). Also, the scaling up of
the filter coefficients by 215 was done by FIR_cof_gen when the option fixed was selected, and the
down scaling was done in line 20. In binary, multiplying or dividing a number by a power of two
means shifting bits of that number either to the left or right. In this case, we are dividing yn by 215, so
we need to shift the bits of yn fifteen bits to the right, which is done in C by using the right bit shift
operator >> (see line 20). One final comment about FIR_cof_gen.m. This function performs H
scaling to scale the frequency response H(ejwto ). This scaling makes the gain 1 f or all frequencies.
This is done to help keep you from overdriving the codec.



1. Redo the FDAtool design and run FIR_cof_gen to create LPF1500.cof. Implement this filter on
the DSK. Use the signal generator and oscilloscope to verify that the filter is working properly.
Observe that the amplitude of the output sinusoid is different at various frequencies in the
passband. Explain the variations. (HINT: Use the MATLAB function plotZTP_FIR to examine
the filter.)
Take the values of Vo at different frequencies. Compute the gain Vo/ Vin in each case, then
compute the gain in dB. Plot the dB gain vs. frequency to verify the frequency response of the
2. To make the above program a floating point program, the following changes must be made.
The variable yn must be of type float and the output does not need to be bit shifted. Instead, the
output needs to be typecast as (short)yn; otherwise, the output will be garbage. The above filter
can be implemented in floating point by making the above changes and creating a new .cof file
using FIR_cof_gen.m as follows.
>> cof_gen(LPF1500fp, h, float)
Create a new project, (for example, FIR_float.pjt), that implements a floating-point version of
FIR.C. Include a copy of your C code and comment on the changes made. Notice that when
using floating-point arithmetic, you must make sure that the Target Version is set to 671x in
the Compiler tab in the Build Options.
Plot the frequency response of the filter as in exercise 1.

FIR Filter Design - Notch Filter

Suppose that we would like to design a simple notch filter that knocks out a specific tone. A notch
filter is an FIR filter that completely kills unwanted single frequency component by placing zeros on
the unit circle at the corresponding angles. This could be done by designing a filter with frequency

H ( z ) = (1 z 1e jw1to )(1 z 1e jw1to )

= 1 2 * cos( w1t o ) z 1 + z 2
= 1 2 * cos(2f 1t o ) z 1 + z 2


3. Design a notch filter for the on-board codec that knocks out 200Hz tones. Use
plotZTP_FIR() to examine this filter. Create a set of tones in MATLAB of the following
form x[n] = cos[2f1n/fs]+cos[2f2n/fs]. Let f1 = 200Hz and vary f2.
In MATLAB, 10 seconds worth of x[n] can be generated by typing
>> fs=8000; t=0:1/fs:10;f1=200;
>> f2=2000; x=.5*(cos(2*pi*f1*t)+cos(2*pi*f2*t)); sound(x,fs)
in the MATLAB workspace. Note that here f2 = 2kHz and that a factor of 0.5 has been used
to prevent overdriving the on-board codec. Observe and listen to both the filtered and
unfiltered versions of x[n] on the oscilloscope and with headphones. Do this for f2 = 2kHz,
1.5kHz, 1kHz, 500Hz, 400Hz, 300Hz, and250Hz. What can you say about the filtered output
as f2 f1 ? Does this filter have a linear phase? Comment on your results and give as much
intuition as possible.

FIR Filter Design - Zero Placement in a Transfer Function

When we analyze digital filters, we examine their poles and zeros in the Z-domain. All analyzable
filters are of the form H(z) =A(z)/B(z). In the case of FIR filters, B(z) = 1 and H(z) = A(z). This means
that FIR filters have no poles, only zeros. This also means that the coefficients of the polynomial A(z)
are the filter coefficients {h[ n]}0N . For real filter coefficients, the zeros of H(z) must appear in
complex conjugate pairs. Zeros that occur on the unit circle, z = ejwto, will translate to zeros in the
magnitude response of the filter. Frequency components that neighbor a zero on the unit circle will be
attenuated. Zeros that are not on the unit circle will also shape the magnitude response of the filter
H(z). The closer a frequency on the unit circle gets to a zero, the more it will be attenuated.

4. Design a filter by placing zeros in your transfer function H(z). Intuitively, explain how these
zeros affect the frequency response of your filter. Use at least 3 complex conjugate pairs of
zeros. Use plotZTP_FIR.m to help analyze your filter. Implement this filter on the DSK and
comment on the results seen at each frequency. Include a copy of the MATLAB figure
generated by plotZTP_FIR.m and comment on the output of this filter for input sinusoids of
various frequencies. Give as much intuition as possible.



FIR Filter Design - Delay

Delay is an echoing effect that can be found on many guitar effects boards. It produces an effect that
sounds much like the effect of hearing music at a sporting event. This effect is described by the
difference equation y[n] = x[n]+a[m]x[n-m], which is an FIR filter of the form H(z) = 1+a[m]z-m. Here

a[m] 1 controls the amplitude of the echo and m, usually large, controls the delay (e.g. m = 400
using the on-board codec translates to a 50ms delay). An example impulse response with a[m] = 0.7
and m = 8 would be coded in MATLAB as h=[1 0 0 0 0 0 0 0 0.7]. Use plotZTP_FIR() to examine
this filter. For the delay filters that we will examine next, the frequency responses will take MATLAB
too long to compute, so we will not explore them.

5. Design a digital delay filter for the on-board codec with the parameters a[m] = 0.9 and m
= 400. This will require a buffer that will store the 400 most recent inputs, but will only
require two multiply and accumulate operations. Create your C code in a way that does
(at most) two multiply and accumulate operations. Play music through the DSK and listen
to the effects. Try various values of a[m] and m to get a feel for how they affect the input.
What can say about a 50ms and 100ms delay? Does this filter have a linear phase?
Comment on your results and give as much intuition as possible.



DSP Laboratory, Experiment # 7

Design of IIR Digital Filters Using Bilinear Transformation
and LMS Technique

1. To understand the concept of bilinear transformation, adaptive filtering and least mean
squared technique.
2. To demonstrate the effect of adaptive method on noise filtering.

Part A: Prelab
Attempt to design the two exercises in the lab by means of mathematical derivation.

Bilinear Transformation Background:

The Bilinear Transformation method overcomes the effect of aliasing that is caused to due the analog
frequency response containing components at or beyond the Nyquist Frequency. The bilinear
transform is a method of compressing the infinite, straight analog frequency axis to a finite one long
enough to wrap around the unit circle once only. This is also sometimes called frequency warping.
This introduces a distortion in the frequency. This is undone by pre-warping the critical frequencies
of the analog filter (cutoff frequency, center frequency) such that when the analog filter is
transformed into the digital filter, the designed digital filter will meet the desired specifications.

2 z 1

T z + 1

This transformation is known as the Bilinear or Tustin Transformation. The Laplace transforms in the
filter expressions are replaced by the corresponding z-transforms. Replacing s =

+ j

performing algebraic manipulations, substituting z = ejw we get

w = 2 tan-1( T/2)




It can be seen that analog dc (s = 0) maps to digital dc (z = 1) and the highest analog frequency (s =

 ) maps to the highest digital frequency (z = -1). It is easy to show that the entire jw axis in the s
plane is mapped exactly once around the unit circle in the z plane. Therefore, it does not alias. With
(2/T) real and positive, the left-half s plane maps to the interior of the unit circle, and the right-half s
plane maps outside the unit circle.

The constant provides one remaining degree of freedom that can be used to map any particular finite
frequency the jw axis in the s plane to a particular desired location on the unit circle ejw in the z
plane. All other frequencies will be warped. In particular, approaching half the sampling rate, the
frequency axis compresses more and more. Filters having a single transition frequency, such as
lowpass or highpass filters, map beautifully under the bilinear transform; you simply map the cut-off
frequency where it belongs, and the response looks great. In particular, equal ripple is preserved for
optimal filters of the elliptic and Chebyshev types because the values taken on by the frequency
response are identical in both cases; only the frequency axis is warped.

Part A: Lab
1. Design an IIR filter with the following characteristics:

High Pass IIR Elliptic filter


Sampling Frequency, Fs

10 Hz

Passband Edge Frequency,

Fc1 = 2.4 Hz

Stopband Edge Frequency,

Fc2 = 2 Hz

The design should be attempted indirectly by performing the following steps:

1. First design a low pass elliptic analog prototype filter with cut-off of 1 rad/s and order 5 to meet the
required passband and stopband ripple specifications
2. Then convert this to an analog high-pass filter with the given passband edge frequency.
3. Then, using the bilinear transformation convert this analog high-pass filter to the required the
digital high-pass filter.



2. Design an IIR filter with the following characteristics:


Band Pass IIR Chebyshev Type I filter


Sampling Frequency, Fs

10 Hz

Passband Edge Frequency,

Fc1 = 2 Hz

Stopband Edge Frequency,

Fc2 = 4 Hz

Passband Ripple

1 dB

Use a similar procedure to that followed in 1.

In each exercise, plot the following:

1. Impulse response of the filter.


Pole-Zero diagram.

Comment on the results.



Part B
Adaptive Filters Background
All of the filters that we have been designing in the lab have been simple FIR or IIR fixed coefficient
filters. We have used programs like MATLAB to compute filter coefficients for a particular situation,
like low-pass or high-pass filters with some fixed frequency cutoff. Once the filter was designed and
coded, we ran it on our DSP boards and used simple inputs to test the frequency response.
Unfortunately, interference and the signals of interest can change over time.

What would happen if we designed a low-pass filter with a cutoff frequency of 500Hz, for example,
and started to process data? During the processing we discovered some noise signal at 450Hz that was
sneaking through our filter. We could go back into MATLAB, redesign the filter coefficients, and
paste them into our code and then the noise at 450Hz would be eliminated. This would be effective if
the interference does not change in time.

One solution to this problem is an adaptive filter. The coefficients of an adaptive filter change in
time. In this lab, we will look at a few ways to implement adaptive algorithms. Take a look at the
block diagram below that compares the setup of a standard filter, like we are used to, and an adaptive
filter. The first thing that should strike you is the appearance of a feedback loop.



Let's take a look at some of the terminology that will be used when we talk about adaptive filters.



Filter Structure This is the implementation of the filtering algorithm. It is set by the designer of the
filter, and may be something like a Direct Form implementation of an FIR filter. This block computes
the filter output based on the input. The filter coefficients can be updated by the Adaptive Algorithm.
Criterion of Performance This block looks at the output of the filter and compares it with some
other signal. This other signal is the desired output of the filter. If we know what the desired response
is, we can compare it to the actual response and then indicate to the Adaptive Algorithm that
something needs to be changed. From the example in the introduction, the Criterion of Performance
would detect the noise at 450Hz and tell the Adaptive Algorithm that it needs to change the filters
cutoff frequency.
Adaptive Algorithm This is the main part of an adaptive filter. This algorithm decides how to
change the filter coefficients in response to the signal given by the Criterion of Performance. This is
the most difficult part of an adaptive filter to design.
In order to design an adaptive filter, we need to know some information about the environment that
the filter will be in. We call this the Signal Operating Environment (SOE). The Signal Operating
Environment gives us a lot of statistical information about what the input signal might look like.
There are basically two things of interest:
(1) What is the average value of the signal? and (2) How far does the signal deviate from this mean
value? Once we have this information, we can start to design the filter.
In this lab we will be talking about a very specific case of a Signal Operating Environment. In this
particular case, the average value of our signal will be constant. You can think of the average value of
the signal as its DC value. Also, in this particular case of Signal Operating Environment, our signal
will stay relatively close to its average value. In other words, the input signal will not have big swings
in one direction or the other.
The last thing we need to talk about is the difference between Supervised Adaptation and
Unsupervised Adaptation. In Supervised Adaptation, the expected output of the filter is a known
quantity, and the Criterion of Performance can simply take the difference between the filter output
and the expected output. It then uses that information to tell the Adaptation Algorithm what
adjustments to make.
In Unsupervised Adaptation, the expected output of the filter is an unknown quantity. This case is
more difficult because of the work that the Criterion of Performance has to do. We cannot simply take
the difference of two signals like with Supervised Adaptation. A lot of the time, Unsupervised



Adaptation consists of looking for signal qualities. For example, the Criterion of Performance may
look for a particular signal envelope that we know should be there.
In this lab, we will deal only with Supervised Adaptation because it is easier to implement.

Adaptive Algorithm Theory

Let's first focus on the Adaptive Algorithm. This is the part of an adaptive filter that updates the filter
coefficients. The filter is a FIR filter. We will discuss two ways to calculate new filter coefficients
based on a performance criterion based on the mean squared error.

Mean Squared Error (MSE) Criterion:

Take a look at the modified block diagram below.

Signal x[n]

Signal y[n]

Response d[n]

Error Signal e[n]

Looking at the figure we can immediately do some calculations. The output of the FIR filter is:
N 1

y(n) = h(k)x(n k)
k =0

The error signal is the desired output signal, d(n) , minus the filter output, y(n):

= d(n)

N 1

h(k)x(n k )
k =0



The error criterion is the mean or average squared error. The goal is to find the filter coefficients,
h(k)s, that minimize the mean squared error:

The term E{ } is the expected value of the error over time. In this case we make the assumption that
the signal statistics do not change over time, this lets us replace the expected value with a time
A common method of minimization is to take the derivative with respect to the h(k)s and set the
result equal to zero.

This equation can be solved to give a result of

This result is known as the Weiner-Hopf equation. This result is usually not practical to compute
since the signal statistics are not usually known and it involves a matrix inversion that is difficult and
time-consuming to calculate.

Least Mean Square (LMS)

The Least Mean Square method iteratively estimates the solution to the Weiner-Hopf equations using
a method called gradient descent. This minimization method finds minima by estimating the gradient.
The basic equation in gradient descent is:


is the step size parameter or the learning coefficient.



The LMS method uses this technique to compute new coefficients that minimize the difference
between the computed output and the expected output under a few key assumptions about the nature
of the signal. The LMS method assumes that the expected value of the signal equals the instantaneous
error. Using this assumption, the gradient can be estimated as:

The equation for updating the filter parameters is:

The basic algorithm takes the form:

1. Read in the next sample, x(n), and perform the filtering operation with the previous
version of the coefficients.

2. Take the computed output and compare it with the expected output.

3. Update the coefficients using the following computation.

This algorithm is performed in a loop so that with each new sample, a new coefficient
vector, hn(k) is created. In this way, the filter coefficients change and adapt.



The output y(n) approaches d(n) if the learning coefficient is small. The learning coefficient
indicates the step size for the gradient descent method. A small step size will ensure convergence, but
it means that the filter coefficients change very slowly (a slow adaptation rate). A large step size, may
lead to skipping over the solution. In this lab we will use = 1 x 10-3.

Part B: Lab
Part 1: Unknown System Implementation
1. Design the IIR filter: A seventh order bandpass IIR filter will act as the unknown system. Using a
sampling frequency of 4 kHz, the specifications of the bandpass filter are that the filter has a
passband from /3 to 2 /3 (radians), with a stopband attenuation of 20 dB. Use the yulewalk.m
function in Matlab to design this filter. This function finds the N-th order recursive filter
coefficients num and den such that the filter Num(z)/Den(z) matches the magnitude frequency
response given by vectors f and m. Vectors f and m specify the frequency and magnitude
breakpoints for the filter such that Plot(f,m) would show a plot of the desired frequency response.
2. Plot the spectrum of this filter.

>order = 7;
>f = [0 0.32, 1/3, 2/3, 0.67, 1];
>m = [0 0 1 1 0 0];
The vector, f, defines the edges of the stopbands and passbands in frequency. It is normalized so
that 1 is equal to fs/2 (=). The vector, m, defines the desired level of the output in each band. 0
means stopband, 1 means a passband.
3. Implement this IIR filter on the C6711 board using the ideas in the last lab. Verify the functioning
of this filter by inputting three sinusoidal signals at 300, 1000, and 1500 Hertz using the signal
generator. Write down the attenuation for each signal using the oscilloscope. Does the filter meet
the specifications?

Part 2: Adaptive Filter Implementation in Matlab

1. We will use a 32-coefficient FIR filter to adapt to the output of the IIR filter. We will first
implement the filter in Matlab, then, time permitting, on the DSP board. The first step is to build a
short subroutine that updates the coefficients using the LMS algorithm. Design a subroutine that



implements the three steps of the LMS algorithm given above. The calling parameters should have
this form:

function [h,e,err_sq] = lms(input, desired, N, beta, h)

% LMS adaptive filter
% input : input signal vector (Nx1 column vector)
% desired : desired output signal (single element)
% N : no. of taps
% h : filter coefficients vector (Nx1 column vector)
% beta : learning constant
% e: error of adaptive filter
% err_sq : squared estimation error

The error terms will help us evaluate the filter performance later.

2 Check your code. Insert your filter design code and your LMS code into the lmsfilter.m file at the
marked spots. Note that this filter begins estimating at the Nth input. This is because the FIR filter
must have full inputs. Otherwise, it will try to learn the transient response of a filter.
Compare the spectrum of your learned filter with the original filter. Comment on any differences
and similarities.

3. Adaptive filters can only learn what they are taught. What this means, if you only give them input
at certain frequencies, then they will only learn the filter response at those frequencies. We will
test this phenomenon by deleting the noise term in the line:
x = sin(2*pi*f1*t)+sin(2*pi*f2*t)+sin(2*pi*f3*t);%+ 0.5*randn(size(t));
Now the filter will only learn the response of the filter at f1, f2 and f3. Run this program and look
at the results. Try changing the frequencies and look at your results, describe what you see.



DSP Laboratory, Experiment # 8

Design of Digital Filters Using Windows and
Parks-McClellan Algorithm
1. To know the effect of windows on IIR filters.
2. To know the different types of windows and the characteristics of each one especially Kaiser
3. To demonstrate the FIR filter design using Parks-McClellan Algorithm

In this lab we will cover more systematic methods of designing both FIR and IIR filters.

Part A: Filter Design Using Standard Windows

Ideally, a low-pass filter with cutoff frequency wc should have a frequency response of

w wc

H ideal (e jw ) =


wc p w

And a corresponding impulse response of

hideal (n) =


sin c(



( 2)

However, no real filter can have this frequency response because hideal(n) is both noncausal and
infinite in duration.
One method for creating a realizable approximation to an ideal filter is to truncate this impulse
response outside of n [, ].

sin c( c n)



n = ,....,0,1,......,



A truncated impulse response is of finite duration, yet the filter is still noncausl. In order to make the
FIR filter causal, it must be shifted to the right by units. As increases, the negative coefficients of
the filter will be shifted to the right making h(n) to be causal.

hideal (n) =


sin c(


(n )

( 4)

if is set to (N-1)/2, where N is a n odd integer, the shifted and truncated filter is given by

hideal (n) =


sin c(



N 1


Where wc is the cutoff frequency and N is the desired window length.

The time shift of (N-1)/2 units to the right corresponds to multiplying the frequency response by ejw(N-1)/2

. It does not affect the magnitude response of the filter, but adds a factor of -jw(N-1)/2 to the

phase response. Such a filter is called linear phase because the phase is a linear function of w.
We may generalize the idea of truncation by using different windowing functions to truncate an ideal
filter's impulse response. Note that by simply truncating the ideal filter's impulse response, we are
actually multiplying or windowing" the impulse response by a shifted rect() function. This particular
type of window is called a rectangular window. In general, the impulse response h(n) of the designed
filter is related to the impulse response hideal(n) of the ideal filter by the relation

h(n) = w(n)hideal (n)


Where w(n) is an N-point window, and hideal(n) is given in equation (5)

The rectangular window is defined as

w(n) =

n = 0, 1 ,......, N 1

The DTFT of w(n) for N = 21 is shown in Fig. 1.

The rectangular window is usually not desirable because it leads to the large stopband and passband
ripple as shown in Fig. 2.



Figure 1: DTFT of a rectangular window of length 21

Figure 2: Frequency response of low-pass filter, designed using the truncation method
More desirable frequency characteristics can be obtained by making a better selection for the window,
w(n). In fact, a variety of raised cosine windows are widely used for this purpose. Some popular
windows are listed below.
1. Hanning window (as defined in Matlab, command hann(N)):


0.5 0.5 cos

w(n) =
N 1

n = 0, 1 ,......, N 1

2. Hamming window


0.54 0.46 cos

w(n) =
N 1

n = 0,1 ,......, N 1

3. Blackman window





N 1
N 1
w(n) =

n = 0, 1 ,......, N 1

In filter design using different truncation windows, there are two key frequency domain effects that
are important to the design: the transition band roll-off, and the passband and stopband ripple (see
Fig. 3 below). There are two corresponding parameters in the spectrum of each type of window that
influence these filter parameters. The filter's roll-off is related to the width of center lobe of the
window's magnitude spectrum. The ripple is influenced by the ratio of the main lobe amplitude to the
first side lobe amplitude (or difference if using a dB scale). These two window spectrum parameters
are not independent, and you should see a trend as you examine the spectra for different windows.
The theoretical values for the main lobe width and the peak-to-side lobe amplitude are shown in
Table 1.

(Length N)

Mainlobe Width



-13 dB



-32 dB



-43 dB



-58 dB

Amplitude (dB)

Table 1: Approximate spectral parameters of truncation windows

1. Plot the rectangular, Hamming, Hanning, and Blackman window functions of length 21 on a
single figure using the subplot command. You may use the Matlab commands hamming, hanning,
and blackman.
2. Then compute and plot the DTFT magnitude of each of the four windows. Plot the magnitudes on
a decibel scale (i.e., plot 20 log 10 W (e jw ) ). Use the function DTFT.m to compute the DTFT.
Hint: Use at least 512 sample points in computing the DTFT by typing the command
DTFT(window,512). Type help DTFT for further information on this function.



3. Measure the main lobe width (in rad/sample) and the peak-to-side lobe amplitude (in dB) from
the logarithmic magnitude response plot for each window type. The Matlab commands zoom and
crosshair are helpful for this. Make a table similar to table (1 ) with these values and the
theoretical ones.
4. Now use a Hamming window to design a lowpass filter h(n) with a cutoff frequency of wc = 2
and length 21. In the same figure, plot the filter's impulse response, and the magnitude of the
filter's DTFT in decibels.
a. First use equations (4) and (6) with =100, 500, 1000 . See the effect of changing on the
filter response.
b. Then use equations (5) and (6) . See the effect of changing on the filter response.
c. Repeat b with increasing N to 51. What is the effect of N on mainlobe width and the peak-tosidelobe amplitude?


Submit the figure containing the time domain plots of the four windows.

Submit the figure containing the DTFT (in decibels) of the four windows.

Submit the table of the measured and theoretical window spectrum parameters.

Submit the plots of your designed filter's impulse response and the magnitude of the filter's

Part B: Filter Design Using the Kaiser Window

Figure 3: Tolerance specifications for the frequency response of a filter.



The standard windows of last section are an improvement over simple truncation, but these windows
still do not allow for arbitrary choices of transition bandwidth and ripple. In 1964, Kaiser found a
family of near-optimal windows that can be used to design filters which meet or exceed any filter
specification. The Kaiser window depends on two parameters: the window length N, and a parameter
which controls the shape of the window. Large values of reduce the window side lobes and
therefore result in reduced passband and stopband ripple. The only restriction to the Kaiser filter
design method is that the passband and stopband ripple must be equal in magnitude. Therefore, the
Kaiser filter must be designed to meet the smaller of the two ripple constraints:

= min{ p , s }
The Kaiser window function of length N is given by

w(n) = o

n( N 1 n)
N 1
I o ( )

n = 0, 1 ,......, N 1

where Io(.) is the zeroth order modified Bessel function of the first kind, N is the length of the
window, and is the shape parameter.
Kaiser found that values of and N could be chosen to meet any set of design parameters,

( , w p , ws ) , by defining A = -20 log 10 and using the following two equations:

0.1102( A 8.7)

= 0.5842( A 21) 0.4 + 0.07886( A 21)


N = 1 +

2.285( ws w p )

. is the ceiling function, i.e. x


A > 50
21 A 50
A < 21


( 4)

is the smallest integer which is greater than or equal to x.



Plot the Kaiser windows and their DTFT magnitudes (in dB) for N = 21 and the following values of




For each case use at least 512 points in the plot of the DTFT.
Hint: To create the Kaiser windows, use the Matlab command Kaiser (N, beta) command where N is
the length of the filter and beta is the shape parameter . To insure at least 512 points in the plot use
the command DTFT (window, 512) when computing the DTFT.


Submit the plots of the 3 Kaiser windows and the magnitude of their DTFT's in decibels. Comment
on how the value affects the shape of the window and the side lobes of the DTFT.

1. Use a Kaiser window to design a low pass filter, h(n), to remove the noise from the signal noisy.
mat using equations (1) and (2). To do this, use equations (3) and (4) to compute the values of and
N that will yield the following design specifications:
fpass=3000, fcutoff=5000, fstop=7000, fs=22050, p=0.05, s=0.005

Figure 4: DTFT of a section of noisy speech



The low pass filter designed with the Kaiser method will automatically have a cut-off frequency
centered between wp and ws.

wc =

w p + ws

2. Plot the magnitude of the DTFT of h(n) for w p .

3. Filter the noisy speech signal in noisy. mat using the filter you have designed.
4. Then compute the DTFT of the filtered signal. Plot the magnitude of the DTFT in decibels versus
frequency in radians w p . Compare this with the spectrum of the noisy speech signal shown in
Fig. 4. Play the noisy and filtered speech signals back using sound and listen to them carefully.

IN YOUR LAB REPORT: Do the following:

Submit the values of and N that you computed.

Submit the three plots of the filter's magnitude response. Make sure the plots are labeled.

Submit the magnitude plot of the DTFT in dB for the filtered signal. Compare this plot to the
plot of Fig. 4.

Part C: FIR Filter Design Using Parks-McClellan Algorithm

Kaiser windows are versatile since they allow the design of arbitrary filters which meet specific
design constraints. However, filters designed with Kaiser windows still have a number of
disadvantages. For example,

Kaiser filters are not guaranteed to be the minimum length filter which meets the design

Kaiser filters do not allow passband and stopband ripple to be varied independently.

Minimizing filter length is important because in many applications the length of the filter determines
the amount of computation. For example, an FIR filter of length N may be directly implemented in
the time domain by evaluating the expression
N 1

y ( n) = x ( n k ) h ( k )


k =0



For each output value y(n) this expression requires N multiplies and N - 1 additions. Oftentimes h(n)
is a symmetric filter so that h(n) =h(N -1- n). If the filter h(n) is symmetric and N is even, then (5)
may be more efficiently computed as

y ( n) =

N / 2 1

( x(n k ) + x(n N + 1 + k )) h(k )

k =0

This strategy reduces the computation to N=2 multiplies and N 1 adds for any value of N . Note that
the computational effort is linearly proportional to the length of the filter. The Kaiser filters do not
guarantee the minimum possible filter length. Since the filter has equal passband and stopband ripple,
it will usually exceed design requirements in one of the two bands; this results in an unnecessarily
long filter. A better design would allow the stopband and passband constraints to be specified
In 1972, Parks and McClellan devised a methodology for designing symmetric filters that minimize
filter length for a particular set of design constraints {wp, ws, p, g }. The resulting filters minimize
the maximum error between the desired frequency response and the actual frequency response by
spreading the approximation error uniformly over each band. The Parks and McClellan algorithm
makes use of the Remez exchange algorithm and Chebyshev approximation theory. Such filters that
exhibit equiripple behavior in both the passband and the stopband, and are sometimes called
equiripple filters.
As with Kaiser filters, designing a filter with the Parks and McClellan algorithm is a two step process.
First the length (i.e. order) of the filter must be computed based on the design constraints. Then the
optimal filter for a specified length can be determined. As with Kaiser windows, the filter length
computation is approximate so the resulting filter may exceed or violate the design constraints. This is
generally not a problem since the filter can be redesigned for different lengths until the constraints are
just met.
The Matlab command for computing the approximate filter length is
[n, fo, mo, w] = remezord (f, m, ripple, fs)
where the inputs are:
f is a vector containing an even number of cutoff frequencies in Hz, in ascending order between 0
and half the sampling frequency Fs . For a simple low pass filter, f=[fpass,fstop], where fpass and
fstop are the passband and stopband frequencies, respectively.
m - vector containing the ideal filter magnitudes of the filter in each band. For a simple low pass filter


ripple - vector containing the allowed ripple in each band. For a simple low pass filter
ripple=[delta_p,delta_s], where delta_p and delta_s are the passband and stopband ripples,
fs - the sampling frequency.
The outputs of the command are n = filter length - 1, and the vectors fo, mo, and w which are
intermediate filter parameters.
Once the filter length, n, is obtained, the Matlab command for designing a Parks- McClellan filter is b
= remez(n,fo,mo,w). The inputs n, fo, mo, and w are the corresponding outputs of remezord, and the
output b is a vector of FIR filter coefficients such that

H ( z ) = b(1) + b(2) z 1 + L + b(n + 1) z n

1. Design a symmetric FIR filter using remezord and remez in Matlab to meet the design
specifications given in part b. Compute the DTFT of the filter's response for at least 512 points.

IN YOUR LAB REPORT: Do the following:

Submit the final measured values of filter length, passband ripple, and stopband ripple. How
accurate was the filter order computation using Matlab's remezord? How does the length of this
filter compare to the filter designed using a Kaiser window?

Submit the plot of the filter's DTFT. How does the frequency response of the Parks- McClellan
filter compare to the filter designed using the Kaiser window? Comment on the shape of both
the passband and stopband.

2. Use the filter you have designed to remove the noise from the signal noisy. mat. Play the noisy
and filtered speech signals back using sound and listen to them carefully.
3. Compute the DTFT of the filtered signal. Plot the magnitude of the DTFT in decibels versus
frequency in radians for w p . Compare this with the spectrum of the noisy speech signal shown
in Fig. 4, and also with the magnitude of the DTFT of the Kaiser filtered signal.


Submit the plot of the DTFT magnitude for the filtered signal. Comment on how the audio
quality of the signal changes after filtering. Also comment on any differences in audio quality
between the Parks-McClellan filtered speech and the Kaiser filtered speech.



DSP Laboratory, Experiment # 9

Discrete Fourier Transform and Fast Fourier
Transform Algorithms
This lab will cover the Discrete Fourier Transform (DFT) and Fast Fourier Transform (FFT) methods.
In previous laboratories, we have used the Discrete-Time Fourier Transform (DTFT) extensively for
analyzing signals and linear time-invariant systems.

( DTFT ) X (e jw ) =

x ( n )e



n =

(inverse DTFT ) x(n) =


X (e


)e jwn dw


While the DTFT is very useful analytically, it usually cannot be exactly evaluated on a computer
because equation (1) requires an infinite sum and equation (2) requires the evaluation of an integral.
The discrete Fourier transform (DFT) is a sampled version of the DTFT, hence it is better suited to
numerical evaluation on computers.
N 1

( DFT ) X N (k ) = x(n)e j 2kn / N


n =0

(inverse DFT ) x(n) =


N 1

(k )e j 2kn / N


k =0

Here XN(k) is an N point DFT of x(n). Note that XN(k) is a function of a discrete integer k, where k
ranges from 0 to N - 1.
In the following, we will study the derivation of the DFT from the DTFT, and several DFT
implementations. The fastest and most important implementation is known as the fast Fourier
transform (FFT). The FFT is one of the cornerstones of signal processing.

Deriving the DFT from the DTFT

Truncating the Time-domain Signal
The DTFT usually cannot be computed exactly because the sum in equation (1) is infinite. However,
the DTFT may be approximately computed by truncating the sum to a finite window. Let w(n) be a
rectangular window of length N:



0 n N 1

w(n) =


Then we may define a truncated signal to be

x tr (n) = w(n) x(n)


The DTFT of xtr(n) is given by:

X tr (e ) =


(n)e jwn

(7 )

n =
N 1

= x(n)e jwn


n =0

Frequency Sampling
Equation (8) contains a summation over a finite number of terms. However, we can only evaluate (8)
for a finite set of frequencies, w. We must sample in the frequency domain to compute the DTFT on
the computer. We can pick any set of frequency points at which to evaluate (8), but it is particularly
useful to uniformly sample w at N points, in the range [0, 2). If we substitute


for k = 0, 1, . . . (N - 1) in (8), we find that

X tr (e )




(n)e jwn

n =

N 1

= x ( n )e




n =0

= X N (k )
In short, the DFT values result from sampling the DTFT of the truncated signal.

X N (k ) = X tr (e j 2k / N )


Windowing Effects
From equation (10), the spacing between DFT frequencies is 2/N , and the relationship between the
normalized discrete-time frequency variable and the continuoustime frequency variable is w = T ,
the DFT frequencies correspond to continuous-time frequencies

k =



Illustrating Example:
Consider a band-limited continuous signal xc(t) such that Xc(j)=0 for || 2 (2500). Suppose that
we will use an ideal anti-aliasing filter H(j) and the sampling rate for the A/D converter is fs=5000
samples/sec. If we want the DFT samples XN(k) to be equivalent to samples of Xc(j) that are at
most (210) rad/sec or 10 Hz apart, what is the minimum value that we must use for the DFT size N ?
From equation 11, we see that adjacent samples in the DFT correspond to continuous-time
frequencies separated by 2 /NT. Therefore, we require that

Which implies that
N 500
Satisfies the condition. Then in MATLAB, we use N =512 for an equivalent continuous-time
frequency spacing of =2 (5000/512) rad/sec.

Investigate the effect of windowing by computing the DFT of the signal x(n) = cos (n/4) truncated
with a window of size N = 20.
1. In the same figure, plot the phase and magnitude of W(ejw).
2. Determine an expression for X(ejw) (the DTFT of the non-truncated signal).
3. Truncate the signal x(n) using a window of size N = 20 and then use DFT.m to compute Xtr(ejw).
Make sure that the plot contains a least 512 points. Hint: Use the command [X,w] = DFT(x,512).
4. Plot the magnitude of Xtr(ejw).

IN LAB REPORT, do the following:

1. Submit the plot of the phase and magnitude of W(ejw).
2. Submit the analytical expression for X(ejw).
3. Submit the magnitude plot of Xtr(ejw).
4. Describe the difference between | Xtr(ejw)| and X(ejw). What is the reason for this difference?
5. Comment on the effects of using a different window for w(n).


The Discrete Fourier Transform (DFT)

Computing the DFT
We will now develop our own DFT functions to help our understanding of how the DFT comes from
the DTFT.

a. Write your own Matlab function to implement the DFT of equation (3). Use the syntax
X = DFTsum(x)
where x is an N point vector containing the values x(0), , x(N - 1) and X is the corresponding
DFT. Your routine should implement the DFT exactly as specified by (3) using for-loops for n
and k, and computing the exponentials as they appear. Note: In Matlab, j may be computed with
the command j=sqrt(-1). If you use j =

1 , remember not to use j as an index in your for-loop.

b. Test your routine DFTsum by computing XN(k) for each of the following cases:
1. x(n) = (n) for N = 10.
2. x(n) = 1 for N = 10.
3. x(n) = ej2n/10 for N = 10.
4. x(n) = cos(2n/10) for N = 10.
c. Plot the magnitude of each of the DFTs. In addition, derive simple closed-form analytical
expressions for the DFT (not the DTFT!) of each signal.

1. Submit a listing of your code for DFTsum.
2. Submit the magnitude plots.
3. Submit the corresponding analytical expressions.



a. Write a second matlab function for computing the inverse DFT of (4). Use the syntax
x = IDFTsum(X)
where X is the N point vector containing the DFT and x is the corresponding time-domain signal.
Use IDFTsum to invert each of the DFTs computed in the previous problem. Plot the magnitudes
of the inverted DFTs, and verify that those time-domain signals match the original ones. Use
abs(x) to eliminate any imaginary parts which roundoff error may produce.

1. Submit the listing of your code for IDFTsum.
2. Submit the four time-domain IDFT plots.

Shifting the Frequency Range

In this section, we will illustrate a representation for the DFT of equation (3) that is a bit more

First create a Hamming window x of length N = 20, using the Matlab command x = hamming(20).
Then use your matlab function DFTsum to compute the 20 point DFT of x. Plot the magnitude of the
DFT, |X20(k)|, versus the index k. Remember that the DFT index k starts at 0 not 1!

Hand in the plot of the |X20(k)|. Circle the regions of the plot corresponding to low frequency
Our plot of the DFT has two disadvantages. First, the DFT values are plotted against k rather then the
frequency w. Second, the arrangement of frequency samples in the DFT goes from 0 to 2 rather than
from - to , as is conventional with the DTFT. In order to plot the DFT values similar to a
conventional DTFT plot, we must compute the vector of frequencies in radians per sample, and then
rotate the plot to produce the more familiar range, - to .
Let's first consider the vector w of frequencies in radians per sample. Each element of w should be the
frequency of the corresponding DFT sample X(k), which can be computed by


w = 2k/N

k [0,.., N-1]

However, the frequencies should also lie in the range from - to . Therefore, if w then it should
be set to w-2. An easy way of making this change in Matlab is
w(w>=pi) = w(w>=pi)-2*pi.
The resulting vectors X and w are correct, but out of order. To reorder them, we must swap the first
and second halves of the vectors. Fortunately, Matlab provides a function specifically for this
purpose, called fftshift.

Write a Matlab function to compute samples of the DTFT and their corresponding frequencies in the
range - to . Use the syntax
[X,w] = DTFTsamples(x)
where x is an N point vector, X is the length N vector of DTFT samples, and w is the length N vector
of corresponding radial frequencies. Your function DTFTsamples should call your function DFTsum
and use the Matlab function fftshift.
Use your function DTFTsamples to compute DTFT samples of the Hamming window of
length N = 20. Plot the magnitude of these DTFT samples versus frequency in rad/sample.

Do the following:
1. Hand in the code for your function DTFTsamples.
2. Hand in the plot of the magnitude of the DTFT samples.

Zero Padding
The spacing between samples of the DTFT is determined by the number of points in the DFT. This
can lead to surprising results when the number of samples is too small. In order to illustrate this



Consider the infinite-duration signal


x(n) =

0 n 49

Compute the DTFT samples of x(n) using both N = 50 and N = 200 point DFT's. Notice that when N
= 200, most of the samples of x(n) will be zeros because x(n) = 0 for n 50. This technique is known
as zero padding, and may be used to produce a finer sampling of the DTFT.
For N = 50 and N = 200, do the following:
1. Compute the vector x containing the values x(0), .., x(N -1).
2. Compute the samples of X(k) using your function DTFTsamples.
3. Plot the magnitude of the DTFT samples versus frequency in rad/sample.

Do the following:
1. Submit your two plots of the DTFT samples for N = 50 and N = 200.
2. Which plot looks more like the true DTFT?
3. Explain why the plots look so different.

The Fast Fourier Transform Algorithm

FFT is simply a very efficient way to compute an existing transform, namely the DFT. As we saw, a
straight forward implementation of the DFT can be computationally expensive because the number of
multiplies grows as the square of the input length (i.e. N2 for an N point DFT). The FFT reduces this
computation time based on decomosig or breaking the transform into smaller transforms and
combinig them to give the total transform.
In MATALB, we simply imlement the Fast Fourier Transform using the MATLAB command, fft.
fft, with a single input argument x, computes the DFT of the input vector or matrix. If x is a vector, fft
computes the DFT of the vector; if x is a rectangular array, fft computes the DFT of each array



For example, create a time vector and signal.

y = fft(x); % Compute DFT of x
m = abs(y); p = unwrap(angle(y)); % Magnitude and phase

The DFT of the signal, and the magnitude and phase of the transformed sequence, are then

t = (0:1/100:10-1/100); % Time vector

x = sin(2*pi*15*t) + sin(2*pi*40*t); % Signal

A second argument to fft specifies a number of points n for the transform, representing DFT length.
y = fft(x,n);
In this case, fft pads the input sequence with zeros if it is shorter than n, or truncates the sequence if it
is longer than n. If n is not specified, it defaults to the length of the input sequence. Execution time for
fft depends on the length, n, of the DFT it performs.
The inverse discrete Fourier transform function ifft also accepts an input sequence and, optionally, the
number of desired points for the transform. Try the example below; the original sequence x and the
reconstructed sequence are identical (within rounding error).

t = (0:1/255:1);
x = sin(2*pi*120*t);
y = real(ifft(fft(x)));

Another important point that should be mentioned here, MATLAB also includes functions for the
two-dimensional FFT and its inverse, fft2 and ifft2. These functions are useful for two-dimensional
signal or image processing. The goertzel function, which is another algorithm to compute the DFT,
also is included in MATLAB DSP Toolbox. This function is efficient for computing the DFT of a
portion of a long signal.
It is sometimes convenient to rearrange the output of the fft or fft2 function so the zero frequency
component is at the center of the sequence. The MATLAB function fftshift moves the zero frequency
component to the center of a vector or matrix.


Consider the continuous sinc function
x(t) =sinc(200t)
1. Is this function bandlimited ? If yes, what is its bandwidth ?
2. If this signal is to be sampled, suggest a suitable sampling time according to sampling
3. Now the response of the sampled signal will be truncated by a rectangular window such that
the resoultion of the windowed signal will be less than 2 rad/sec. What is the minimum
value of N that will achieve this resolution ?
4. Find and plot the disctere fourier transform of the windowed signal using fft. Are your
results as expeced in 1 ? ( What is the bandwidth of the signal ) ?
5. Now, repeat steps 2, 3, 4 with tring other suitable T, and the corresonding N such that the
resolution still the same. What is the relation between T and N ? What is the effect of
changing T on the discrete fourier transform of the signal ?

Find and plot the discrete fourier transform of the function