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.
Prelab
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.
2.
Solve all the exercises in this Experiment. If an exercise asks you to do an Mfile, place a
comment at the top of your Mfile, Lab1exr#, where # refers to the exercise number.
Lab
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.
Double
Click
DSP LABORATORY
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 MATfile, which has a .mat extension. There are options for saving to different
formats. To read in a MATfile, 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
Doubleclick 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 twodimensional numeric arrays, strings, and cell
arrays of strings that are in the workspace.
Change values of array elements
Search Path
MATLAB uses a search path to find Mfiles and other MATLABrelated 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.
Exercise#1
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!!!!!
DSP LABORATORY
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];
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];
1
2 4
3 6
M = [ ];
M = zeros(n,m);
M = ones(n,m);
M = eye(n);
N = fix(10*rand(1,10))
N=
4944852680
DSP LABORATORY
R = randn(4,4)
R=
1.0668
0.2944
0.6918
1.4410
0.0593
1.3362
0.8580
0.5711
0.0956
0.7143
1.2540
0.3999
0.8323
1.6236
1.5937
0.6900
100 93 86 79 72 65 58 51
sum(A(1:4,4))
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.
Exercise#2
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 = ones(1,8);
>> n = length(x)
DSP LABORATORY
Concatenation:
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)]
Exercise#3
1. Start with the 4by4 square, A.
2. Then form B = [A A+32; A+48 A+16]
3. Whats the size of B?
Exercise#4
Define the following discrete time signal
0.5 0 n p 10
x[n] = 0 10 n p 15
2 15 n 20
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.
Scripts
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.
DSP LABORATORY
r = rand(1,10)
r(1:2:length(r))=0;
y=r
modify
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
Functions are Mfiles that can accept input arguments and return output arguments. The name of the
Mfile 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 Mfile 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
GRAVITY = 32;
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
x.offset = 1;
x
x=
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
say
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
index.
function y=shift(x,w,z)
y.data=x;
y.offset=w+z;
figure
i=y.offset:1:length(y.data)+y.offset1
stem(i,y.data)
Exercise#5
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
DSP LABORATORY
Polynomial Roots
The roots function calculates the roots of a polynomial.
r = roots(p)
r=
2.0946
1.0473 + 1.1359i
1.0473  1.1359i
By convention, MATLAB stores roots in column vectors. The function poly returns to the polynomial
coefficients.
p2 = poly(r)
p2 =
1 8.8818e16 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
polyval(p,5)
ans =
110
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)
Y=
377 179 439
111 81
136
DSP LABORATORY
Exercise#6
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);
plot(x,y)
%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)
DSP LABORATORY
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 xaxis scale from  10 to 40 and an automatic scaling for the yaxis scale. Typing axis
again or axis(auto) resumes auto scaling.
Stem
If you wish to use information in discretetime 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])
DSP LABORATORY
10
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 dashdot. 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.
DSP LABORATORY
11
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
Exercise#7
Using MATLAB, plot the function
f (t ) = e 2t cos(3t )u (t )
where t ranges from 2 to 10. Give the xaxis the title (t sec) and the
yaxis 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.
DSP LABORATORY
12
3.0
2.0
13.0
5.0
10.0
11.0
8.0
9.0
6.0
7.0
4.0
15.0
14.0
12.0
1.0
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.
% axis image
13
Exercise#8
We will do this exercise on the wave file speech_dft.wav. You can find this file in
matlab13\toolbox\dspblks\dspblks\speech_dft.wav
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?
DSP LABORATORY
14
Prelab
1. Since this lab deals with new concepts for you, you must study the following necessary
introduction carefully before going to the lab. This selfstudy will be evaluated by a short quiz
in the beginning of the lab. So BE CAREFULL!!!
DSP LABORATORY
15
A/D
DSP
D/A
This process must be handled in realtime  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
temperature.
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.
DSP LABORATORY
16
B. Processing time measures are based on the clock (150MHz for our case)
DSP LABORATORY
17
a. MACS, multiplies and accumulates, If 2 per clock cycle, then 300 million MACs per
second.
b. MFLOPS, million floatingpoint operations per second, If 6 units capable of doing
floatingpoint operations, then can do 900MFLOPS.
c. MIPS, million of instructions per second, If 8 units capable of doing fixed and
floatingpoint operations, then have a 1200MIPS system.
C. Codeword length
Sixteenbit fixedpoint DSPs are used for voicegrade systems such as phones, since they
work with a relatively narrow range of sound frequencies. Hifidelity stereo sound has a
wider range, calling for a 16bit ADC (Analog/Digital Converter), and a 24bit fixed
point DSP. Image processing, 3D graphics and scientific simulations have a much wider
dynamic range and require a 32bit floatingpoint 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 higherperformance devices with upwardscompatible
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.
DSP LABORATORY
18
Codec
The codec (coder/decoder) is a chip located onboard the DSK. In this course, we will use the coder
or analogtodigital converter (ADC) and decoder or digitaltoanalog 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
External Memory:
The board contains 16 MB of SDRAM and 128 kB of flash ROM.
16M
128K
Daughter
Card I/F
Parallel
Port
C6711
DSP
TMS320C67
Power
Jack
D. Card I/F
Power
LED
User
Switch
Reset
3.3V Power
Emulation
JTAG
JTAG
DSP LABORATORY
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 programmeroptimized 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.
DSP LABORATORY
20
.sa
Text
Editor
Assembler
Optimizer
.asm
.c
.asm
Assembler
.obj
*.cmd
m
Linker
.out
Debug
Profile
Graph
Watch
Compiler
Timing
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 onboard 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 onboard codec or daughter card.
Also included in each McBSP is a 32bit Serial Port Control Register (SPCR). This register is updated
when the onboard 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 realtime communication link
between the CPU and the onboard codec. The idea of realtime 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.
Polling
The first method for establishing a realtime communication link between the CPU and the onboard
codec is polling. When the onboard 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 onboard 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 onboard codec.
On the DSP hardware, polling is implemented mostly in software. The onboard 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.
DSP LABORATORY
21
Fortunately, this has already been taken care of for you. This will be explained in detail later when we
implement a polling example.
Interrupts
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:
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
DSP LABORATORY
22
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.
Receive
ISR
Receive
Data
Audio
Inputs
CODEC
Mailbo x
Signal
Processi
ng Task
McBSP0
Mailbo x
Transmit
Data
Transmit
ISR
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.
DSP LABORATORY
23
Lab
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.
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 headphonetoRF 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.
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.
DSP LABORATORY
24
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
`Open'.
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
IRAM.
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 subwindow of the CCS main window, doubleclick 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.
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.
DSP LABORATORY
25
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
DSP LABORATORY
26
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 Complete,
0 Errors, 0 Warnings, 0 Remarks.
DSP LABORATORY
27
When CCS built your project, it compiled all of the C code into assembly code, using a builtin
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 runtime 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 runtime 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, doubleclick 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
oscilloscope.
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'.
x(t ) = sin(2f o t ) .1
where fo = 1kHz. In realtime 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 onboard codec, samples are being sent at rate fs =
8kHz (ts = 0.125ms). In C code, we generate samples of eqn(1), namely
fo
) 2
fs
which is only defined for integer values of n. Here, the argument of the sine function,
[n] = 2n
DSP LABORATORY
fo
fs
28
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
fo
f
= [n] + 2 o
fs
fs
fo
.
fs
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.
#include <math.h>
#define PI 3.14159265359
float f0=1000;
short fs=8000;
float angle=0;
float offset;
short sine_value;
sine_value=(short)20000*sin(angle);
output_sample(sine_value);
return; // return from interrupt
}
void main()
{
comm_intr();
while(1);
}
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.
DSP LABORATORY
29
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).
fo
. For a given fo, this value will not change, so it does not
fs
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
section.
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
DSP LABORATORY
30
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 (16bit signed integer between the values 32768 and 32767), the CPU will round the number to the nearest integer and store it in a 16bit 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 onboard
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()
function.
Exercise#1
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
DSP LABORATORY
31
used? Explain what you see and give some intuition into how the rate of this realtime 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.
DSP LABORATORY
32
Exercise#2
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. Relabel 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. Relabel the project: sine_gen_poll.pjt.
Explain the procedure required to convert an interruptdriven program to a pollingbased program.
DSP LABORATORY
33
End Notes
This lab was used to learn how to create a project and implement it on the DSK. In all realtime 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
34
Prelab
1. Compute the Fourier series expansion for the signals below in the form
a.
x(t)
b.
x(t)
DSP LABORATORY
35
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.
2.
3.
Theoretically speaking, what is the minimum sampling frequency of a square wave having f0 = 2
kHz.
4.
If a sine wave of f0 = 6 kHz is sampled with fs= 8 kHz, determine the output of the D/A
converter.
Background
Sampling
In order to store, transmit or process analog signals using digital hardware, we must first convert them
into discretetime signals by sampling.
The processed discretetime signal is usually converted back to analog form by interpolation,
resulting in a reconstructed analog signal xr(t).
DSP LABORATORY
36
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 )
s
provided that
n =
Aliasing
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 continuoustime sinusoidal signal and the dashdot 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.
DSP LABORATORY
37
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)
1
1
n ) = cos(0.5n)
2
2
3
1
n ) = cos(1.5n) = cos(1.5n 2n) = cos(0.5n)
2
2
x1(nTs) = x2(nTs)
x s (t ) = x(t ) p (t )
p (t ) =
(t nT )
s
n =
It follows that
P( w) =
2
Ts
(w
n =
2n
2
)=
Ts
Ts
(w nw )
s
n =
and hence,
X s ( w) =
=
1
X ( w) * P( w)
2
X ( w nw )
s
n =
DSP LABORATORY
38
x(t)
X(w)
X(0)
WB
WB
2/T
WT
T 2T 3T
2WT
Xd(w)
xd(t)
X(0)/T
T 2T 3T
WT
2WT
DSP LABORATORY
39
Xd(w)
X(0)/T
 WS
WB
WB
WS
Xd(w)
X(0)/T
 WS WB
WB
WS
Xd(w)
Xd(w)
X(0)/T
X(0)/T
 WSWB
WB WS
 WSWB
WB WS
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 lowpass filter, known as an antialiasing filter, with a cutoff frequency fc equals fs /2.
This means that the high frequency artifacts of the continuoustime signal will be lost. This
is the cost of managing aliasing. In practice, the antialiasing filter will have a cutoff
frequency at roughly 90% of the Nyquist frequency and use the other 10% for rolloff. The
onboard codec of the DSK has a sampling rate of fs = 8 kHz and an antialiasing filter with
cutoff frequency 3.6kHz, which is 90% of fs/2 (Nyquist Frequency).
DSP LABORATORY
40
xa(t)
Antialiasing
filter
fc < fs /2
fo p
sampler
x[n]
fs
f1 f 2 f1 + f 2 p f s
2
Downsampling
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
x=
1
9 10
>> x2=x(1:2:end)
x2 =
1
DSP LABORATORY
41
Lab
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 +
13
k =1
k odd
DSP LABORATORY
4
sin(2kt )
k
42
DSP LABORATORY
43
Exercise#1:
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.
f
1
to yield x(n) = cos(2 0 n) .
fs
Ts
DSP LABORATORY
44
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 cutoff
frequency of 2 fo for the Butterworth lowpass 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.
f.
x(t)
x[n]
A/D
Sampling Frequency
100 Hz
Discretetime filter
h[n]=0.5([n]+ [n1])
Moving Average
y[n]
y(t)
D/A
Sampling Frequency
100 Hz
45
DSP LABORATORY
46
Notice that the actual peaktopeak 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 peaktopeak 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 antialiasing filter is not ideal and therefore has a nonzero rolloff around 3.6 kHz.)
Exercise#6:
a. To observe the effects of the antialiasing 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.
Exercise#7:
Modify straight_wire.c file such that the digital signal is processed by the moving average filter used
in exercise 5.
DSP LABORATORY
47
Prelab
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 fourthorder Butterworth lowpass filter with a cutoff 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
Background
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 twoelement 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 lefthand 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.
DSP LABORATORY
48
design
analog
n=5; wn=.4;
[b,a]=butter(n,wn,s);
Wp = .1,
Ws = .2
Highpass: Wp = .2,
Ws = .1
w1=20; Rp=2;
w2=30; Rs=10;
[n,wn]=buttord(w1,w2,Rp,Rs,s);
[num,den]=butter(n,wn,s)
DSP LABORATORY
49
corresponding to half the sample rate. Use R=0.5 as a starting point, if you are unsure about choosing
R.
If Wn is a twoelement 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 lefthand 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 lefthand arguments, as in
[A,B,C,D] = CHEBY1(...), statespace 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.
Wp = .1,
Ws = .2
Highpass: Wp = .2,
Ws = .1
[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;
[n,wn]=cheb1ord(w1,w2,Rp,Rs,s);
[numt,dent]=cheby1(n,Rp, wn,s)
DSP LABORATORY
50
Wp = .1,
Ws = .2
Highpass: Wp = .2,
Ws = .1
DSP LABORATORY
51
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 twoelement 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 lefthand 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 lefthand arguments, as in
[A,B,C,D] = ELLIP(...), statespace 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.
Wp = .1,
Ws = .2
Highpass: Wp = .2,
Ws = .1
G1=0.5;G2=30;wr=1.21;
w1=1; w2=1.21;
[n,wn]=ellipord(w1,w2,G1,G2,s);
[numt,dent]=ellip(n,G1,G2,wn,s)
DSP LABORATORY
52
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.
DSP LABORATORY
53
n=5; wn=30/50;
[b,a]=butter(n,wn);
y=filter(b,a,x); %x is the input data
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.
Filter Type
Butterworth
[z,p,k]=buttap(n)
Chebyshev type I
[z,p,k]=cheb1ap(n,Rp)
Chebyshev type II
[z,p,k]=cheb2ap(n,Rs)
Elliptic
[z,p,k]=ellipap(n,Rp,Rs)
54
and B w = w2 w1 .
Frequency Transformation
Transformation Function
s
w0
[numt ,dent]=lp2lp(num,den,wo)
w0
s
[numt,dent]=lp2hp(num,den,wo)
Lowpass to bandpass
s' =
s 2 + w1 w2
s ( w2 w1 )
Lowpass to bandstop
s' =
s ( w2 w1 )
s 2 + w1 w2
DSP LABORATORY
[At,Bt.Ct,Dt]=lp2lp(A,B,C,D,wo)
[At,Bt.Ct,Dt]=lp2hp(A,B,C,D,wo)
[numt,dent]=lp2bp(num,den,wo,Bw)
[At,Bt.Ct,Dt]=lp2bp(A,B,C,D,wo,Bw)
[numt,dent]=lp2bs(num,den,wo,Bw)
[At,Bt.Ct,Dt]=lp2bs(A,B,C,D,wo,Bw)
55
Lab
1. Using MATLAB analog filter design functions solve the following
problems.
textbook
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
56
Prelab
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 polezero plots. This background contains the following topics:
DSP LABORATORY
57
You can also use the Method menu to select a filter design method.
58
The display region illustrates filter specifications when you select Filter Specifications from the
Analysis menu.
DSP LABORATORY
59
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.
DSP LABORATORY
60
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.
DSP LABORATORY
61
You can click on the response to add a data marker that displays information about the particular
point on the response. Rightclicking displays a menu where you can adjust the appearance of the data
markers or delete them.
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.
DSP LABORATORY
62
Lab
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
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.
DSP LABORATORY
63
Objectives:
1. To implement the FIR filters designed by FDAtool on the C6711 DSK.
2. To demonstrate the effect of filtering on some signals.
Introduction:
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
following:
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 sampling frequency to 8000 (sampling rate of the onboard codec).
Under specifications, make sure that box for Minimum order is checked.
DSP LABORATORY
64
>> h=filt1;
>> stem(h)
>> length(h)
To further analyze this filter, download the MATLAB mfile plotZTP_FIR.m from the course
account. This mfile contains a function that will plot the Ztransform (evaluated at z = ejwto), the polezero diagram and the impulse response in a fourpanel 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)
DSP LABORATORY
65
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 mfile 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.
h[k ]x[n k ] ,
k =0
DSP hardware.
DSP LABORATORY
66
To make this a realtime 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
DSP LABORATORY
67
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 mfile FIR_cof_gen.m from the account. This mfile is a function that takes
the filter coefficients, h[k], and creates a formatted .cof that can be included into the C program
FIR.c.
1.) // FIR.c FIR filter. Include file of N order FIR filter coefficients
2.)
3.) #include "LPF1500.cof"
// coefficient file LPF @ 1500Hz
4.) int yn = 0;
// initialize filter's output
5.) short x[N+1];
// input samples
6.)
// NB: impulse duration N+1 samples
7.) interrupt void c_int11()
// ISR
8.) {
9.) short k;
10.)
11.) x[0] = input_sample();
// new input @ beginning of buffer
12.) yn = 0;
// initialize filter's output
13.)
14.) for (k = 0; k<= N; k++)
15.) yn += (h[k] * x[k]);
// y(n) += h(k)* x(nk)
16.)
17.) for (k = N; k > 0; k)
// starting @ end of buffer
18.) x[k] = x[k1];
// update delays with data move
19.)
20.) output_sample((short)(yn >> 15));
21.)
// scale filtered output
22.) return;
23.) }
24.)
25.) void main()
26.) {
27.) comm_intr();
// init DSK, codec, McBSP
28.) while(1);
// infinite loop
29.) }
Figure 3: Listing of FIR.c
DSP LABORATORY
68
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 mfile 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 fixedpoint arithmetic, all of the filter
coefficients must be signedintegers, so the numbers were all scaled by 215 and rounded to the nearest
integer. This scaling undone before output by multiplying by 215. In fixedpoint algorithms, this type
of scaling must be done. This leads to a few additional comments. First, the input samples and the
filter coefficients are 16bit signed integers, so the accumulation variable yn is a 32bit 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.
DSP LABORATORY
69
Exercises
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
filter.
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 floatingpoint version of
FIR.C. Include a copy of your C code and comment on the changes made. Notice that when
using floatingpoint 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.
70
3. Design a notch filter for the onboard 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 onboard 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.
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.
DSP LABORATORY
71
a[m] 1 controls the amplitude of the echo and m, usually large, controls the delay (e.g. m = 400
using the onboard 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 onboard 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
72
Objectives:
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.
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 ztransforms. Replacing s =
+ j
w = 2 tan1( T/2)
DSP LABORATORY
73
and
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 lefthalf s plane maps to the interior of the unit circle, and the righthalf 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 cutoff
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:
Type:
Order
Sampling Frequency, Fs
10 Hz
Fc1 = 2.4 Hz
Fc2 = 2 Hz
DSP LABORATORY
74
Type:
Order
Sampling Frequency, Fs
10 Hz
Fc1 = 2 Hz
Fc2 = 4 Hz
Passband Ripple
1 dB
PoleZero diagram.
DSP LABORATORY
75
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 lowpass or highpass 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 lowpass 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.
Input
Signal
Output
Signal
Let's take a look at some of the terminology that will be used when we talk about adaptive filters.
DSP LABORATORY
76
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
DSP LABORATORY
77
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.
Input
Signal x[n]
Output
Signal y[n]

Expected
Response d[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):
e(n)=d(n)y(n)
= d(n)
N 1
h(k)x(n k )
k =0
DSP LABORATORY
78
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
average.
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 result is known as the WeinerHopf 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
timeconsuming to calculate.
Where
DSP LABORATORY
79
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:
2. Take the computed output and compare it with the expected output.
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.
DSP LABORATORY
80
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 103.
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 Nth 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];
>[num,den]=yulewalk(order,f,m);
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?
DSP LABORATORY
81
implements the three steps of the LMS algorithm given above. The calling parameters should have
this form:
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
82
Introduction
In this lab we will cover more systematic methods of designing both FIR and IIR filters.
w wc
1
H ideal (e jw ) =
0
(1)
wc p w
hideal (n) =
wc
sin c(
wc
n)
( 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 [, ].
w
wc
sin c( c n)
htrunc(n)=
DSP LABORATORY
n = ,....,0,1,......,
otherwise
(3)
83
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) =
wc
sin c(
wc
(n )
( 4)
if is set to (N1)/2, where N is a n odd integer, the shifted and truncated filter is given by
hideal (n) =
wc
sin c(
wc
(n
N 1
))
2
(5)
. It does not affect the magnitude response of the filter, but adds a factor of jw(N1)/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
(6)
1
w(n) =
0
n = 0, 1 ,......, N 1
otherwise
DSP LABORATORY
84
Figure 2: Frequency response of lowpass 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)):
2n
n = 0, 1 ,......, N 1
otherwise
2. Hamming window
2n
n = 0,1 ,......, N 1
otherwise
3. Blackman window
DSP LABORATORY
85
2n
4n
0
.
42
0
.
5
cos
0
.
08
cos
N 1
N 1
w(n) =
n = 0, 1 ,......, N 1
otherwise
In filter design using different truncation windows, there are two key frequency domain effects that
are important to the design: the transition band rolloff, 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 rolloff 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 peaktoside lobe amplitude are shown in
Table 1.
PeakToSidelobe
Window
(Length N)
Mainlobe Width
Rectangular
4/N
13 dB
Hanning
8/N
32 dB
Hamming
8/N
43 dB
Blackman
12/N
58 dB
Amplitude (dB)
Exercise#1
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.
DSP LABORATORY
86
3. Measure the main lobe width (in rad/sample) and the peaktoside 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 peaktosidelobe 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
DTFT.
DSP LABORATORY
87
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 nearoptimal 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
(
I
w(n) = o
n( N 1 n)
N 1
I o ( )
n = 0, 1 ,......, N 1
otherwise
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,
0.1102( A 8.7)
0.0
A8
N = 1 +
2.285( ws w p )
where
DSP LABORATORY
A > 50
21 A 50
A < 21
(3)
( 4)
88
Exercise#2
Plot the Kaiser windows and their DTFT magnitudes (in dB) for N = 21 and the following values of
:
=0
=1
=5
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.
Exercise#3
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
DSP LABORATORY
89
The low pass filter designed with the Kaiser method will automatically have a cutoff frequency
centered between wp and ws.
wc =
w p + ws
2
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.
Kaiser filters are not guaranteed to be the minimum length filter which meets the design
constraints.
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 )
(5)
k =0
DSP LABORATORY
90
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
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
separately.
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
m=[1,0].
DSP LABORATORY
91
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,
respectively.
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
Exercise#4
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.
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 ParksMcClellan filtered speech and the Kaiser filtered speech.
DSP LABORATORY
92
( DTFT ) X (e jw ) =
x ( n )e
jwn
(1)
n =
1
2
X (e
jw
)e jwn dw
(2)
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
(3)
n =0
1
N
N 1
(k )e j 2kn / N
(4)
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.
DSP LABORATORY
93
0 n N 1
else
1
w(n) =
0
(5)
(6)
X tr (e ) =
jw
tr
(n)e jwn
(7 )
n =
N 1
= x(n)e jwn
(8)
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
w=2k/N
(9)
X tr (e )
jw
w=
2k
N
tr
(n)e jwn
n =
N 1
= x ( n )e
w=
2k
N
2k
n
N
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 )
(10)
Windowing Effects
From equation (10), the spacing between DFT frequencies is 2/N , and the relationship between the
normalized discretetime frequency variable and the continuoustime frequency variable is w = T ,
the DFT frequencies correspond to continuoustime frequencies
k =
DSP LABORATORY
2k
NT
(11)
94
Illustrating Example:
Consider a bandlimited continuous signal xc(t) such that Xc(j)=0 for  2 (2500). Suppose that
we will use an ideal antialiasing 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 continuoustime
frequencies separated by 2 /NT. Therefore, we require that
2
20
NT
Which implies that
N 500
Satisfies the condition. Then in MATLAB, we use N =512 for an equivalent continuoustime
frequency spacing of =2 (5000/512) rad/sec.
Exercise#1
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 nontruncated 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).
95
Exercise#2
1.
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 forloops 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 =
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 closedform analytical
expressions for the DFT (not the DTFT!) of each signal.
INLAB REPORT:
1. Submit a listing of your code for DFTsum.
2. Submit the magnitude plots.
3. Submit the corresponding analytical expressions.
DSP LABORATORY
96
2.
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 timedomain 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 timedomain signals match the original ones. Use
abs(x) to eliminate any imaginary parts which roundoff error may produce.
INLAB REPORT:
1. Submit the listing of your code for IDFTsum.
2. Submit the four timedomain IDFT plots.
Exercise#3
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!
INLAB REPORT:
Hand in the plot of the X20(k). Circle the regions of the plot corresponding to low frequency
components.
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
DSP LABORATORY
97
w = 2k/N
k [0,.., N1]
However, the frequencies should also lie in the range from  to . Therefore, if w then it should
be set to w2. 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.
Exercise#4
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.
INLAB REPORT:
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
effect.
DSP LABORATORY
98
Exercise#5
Consider the infiniteduration signal
sin(0.1n)
0
x(n) =
0 n 49
otherwise
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.
INLAB REPORT:
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.
DSP LABORATORY
99
The DFT of the signal, and the magnitude and phase of the transformed sequence, are then
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
twodimensional FFT and its inverse, fft2 and ifft2. These functions are useful for twodimensional
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.
DSP LABORATORY
100
Exercise#6
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
theorem.
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 ?
Exercise#7
Find and plot the discrete fourier transform of the function
y(t)=sinc2(200t)
DSP LABORATORY
101