DSP Manual1
DSP Manual1
DSP Manual1
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 M-file, place a comment at the top of your M-file, 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 MAT-file, which has a .mat extension. There are options for saving to different formats. To read in a MAT-file, select Import Data from the File menu, or use the load function. You will use this function to load a wave signal later in this lab.
Array Editor
Double-click a variable in the Workspace browser to see it in the Array Editor. Use the Array Editor to view and edit a visual representation of one- or two-dimensional numeric arrays, strings, and cell arrays of strings that are in the workspace.
Change values of array elements Change the display format
Search Path
MATLAB uses a search path to find M-files and other MATLAB-related files, which are organized in directories on your file system. Any file you want to run in MATLAB must reside in the current directory or in a directory that is on the search path. Add the directories containing files you create to the MATLAB search path. By default, the files supplied with MATLAB and MathWorks toolboxes are included in the search path. To see which directories are on the search path or to change the search path, select Set Path from the File menu in the desktop, and use the Set Path dialog box.
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]; %creates a 1x4 vector with elements 1, 3, 5 and 7.
Note that commas could have been used in place of spaces to separate the elements. Additional elements can be added to the vector: v(5) = 8; Matrices are defined by entering the elements row by row: M = [1 2 4; 3 6 8]; 1 2 4 8 3 6
There are a number of special matrices that can be defined: null matrix: nxm matrix of zeros: nxm matrix of ones: nxn identity matrix: M = [ ]; M = zeros(n,m); M = ones(n,m); M = eye(n);
Uniformly distributed random elements M = rand(n,m); Normally distributed random elements M=randn(n,m); A particular element of a matrix can be assigned: M(1,2) = 5; % places the number 5 in the first row, second column. Here are some examples. Z = zeros(2,4) Z= 0000 0000
N = fix(10*rand(1,10)) N= 4944852680
DSP LABORATORY
R = randn(4,4) R= 1.0668 0.0593 -0.0956 -0.8323 0.2944 -1.3362 0.7143 1.6236 -0.6918 0.8580 1.2540 -1.5937 -1.4410 0.5711 -0.3999 0.6900
Subscript expressions involving colons refer to portions of a matrix. A(1:k,j) sum(A(1:4,4)) % the first k elements of the jth column of A. So %computes the sum of the fourth column.
But there is a better way. The colon by itself refers to all the elements in a row or column of a matrix and the keyword end refers to the last row or column. So sum(A(:,end)) %computes the sum of the elements in the last column of A.
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=[1 2 3;6 7 8] >> [m,n] = size(X) >> x = ones(1,8); >> n = length(x) % will assign the value 8 to n % returns the size of matrix X in separate variables m and n.
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 4-by-4 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
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 M-files that can accept input arguments and return output arguments. The name of the M-file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt.
Global Variables
If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functions. Do the same thing at the command line if you want the base workspace to access the variable. The global declaration must occur before the variable is actually used in a function. Although it is not required, using capital letters for the names of global variables helps distinguish them from other variables. For example, create an M-file called falling.m. function h = falling(t) global GRAVITY h = 1/2*GRAVITY*t.^2; Then interactively enter the statements in MATLAB command window global GRAVITY 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.offset-1 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.8818e-16 -2 5 So the poly and roots are inverse functions.
Polynomial Evaluation
The polyval function evaluates a polynomial at a specified value. To evaluate p at s = 5, use 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 490 253 639
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).
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 x-axis scale from - 10 to 40 and an automatic scaling for the y-axis scale. Typing axis again or axis(auto) resumes auto scaling.
Stem
If you wish to use information in discrete-time using the stem command can be useful. It is very similar to plot except it doesnt connect the dots. The following example creates a stem plot of a cosine function. y = linspace(0,2*pi,10); h = stem(cos(y),'fill','-.'); set(h(3),'Color','r','LineWidth',2) % Set base line properties axis ([0 11 -1 1])
DSP LABORATORY
10
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 x-axis the title (t sec) and the y-axis the title (f(t) volts ). Repeat using stem function. Then use subplot to combine the two figures in one figure and give it the name: difference between plot and stem.
DSP LABORATORY
12
Store the file under the name data.dat. Then the statement load data.dat reads the file and creates a variable, data, containing our example matrix.
Images are represented as matrices in Matlab. So try out >> load clown >> imagesc (X) % axis image
[x, fs] = wavread('file path\file name'); soundsc(x, fs); MatLab may be used to convert the available Ascii files into .wav format. This permits the original sounds to be heard using the Sound Recorder application, for example. If an Ascii version of a sound file is loaded into MatLab, then a .wav file may be created using the wavwrite command. The sampling frequency must be specified to use this function, for example: wavwrite(x,22255,'mysound.wav') % x: vector containing speech samples, 22255: sampling rate
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
DSP Laboratory Experiment # 2 Introduction to the TMS320C6711 DSK And Code Composer Studio
Goals
In this Experiment, our aim is to show how mathematical algorithms for digital signal processing may be encoded for implementation on programmable hardware. In this lab, you will become familiar with a development system for programming DSP hardware. You will study: Code Composer Studio TMS320C6711 DSP chip and supporting architecture (DSK) The C programming language
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 self-study 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 real-time - which is often very quickly. For instance, stereo equipment handles sound signals of up to 20 kilohertz (20,000 cycles per second), requiring a DSP to perform hundreds of millions of operations per second.
Why Digitizing?
Why do we process signals digitally rather than working with the original signal in the analog domain? The answer depends on the system and its requirements. For some systems, working with the analog signals gives a better solution. For others, DSP is better. It is up to you, the designer, to make the decision based on materials you learn through this and other courses. Here are some things to consider in making the tradeoffs:
Reasons to go digital:
1. Flexibility: can easily change, modify and upgrade through software. 2. Reproducibility of results from one unit to another: because DSP works with binary sequences. Analog circuits have component tolerances. 3. Reliability: memory and logic dont slowly go bad with time and are not affected by 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 floating-point operations per second, If 6 units capable of doing floating-point operations, then can do 900MFLOPS. c. MIPS, million of instructions per second, If 8 units capable of doing fixed and floating-point operations, then have a 1200MIPS system.
C. Codeword length
Sixteen-bit fixed-point DSPs are used for voice-grade systems such as phones, since they work with a relatively narrow range of sound frequencies. Hi-fidelity stereo sound has a wider range, calling for a 16-bit ADC (Analog/Digital Converter), and a 24-bit fixed point DSP. Image processing, 3-D graphics and scientific simulations have a much wider dynamic range and require a 32-bit floating-point processor.
D. Others
a. Overall cost. b. Software development tools, simulators. c. Commercially available DSP boards for software development and testing before the target DSP hardware is available? d. The likelihood of having higher-performance devices with upwards-compatible software in the future. e. Power Consumption: The most commonly used TMS320 DSP chips (in the year 2002) are the C2000, C5000, and C6000 series of chips. Due to their low power consumption (40mW to 160mW of active power), they are very attractive for power sensitive portable systems. As the dsps speed increases, so does the power consumption. This makes an accurate knowledge of the execution time critical for selecting the proper device.
DSP LABORATORY
18
Codec
The codec (coder/decoder) is a chip located on-board the DSK. In this course, we will use the coder or analog-to-digital converter (ADC) and decoder or digital-to-analog converter (DAC), along with two mono headphone jacks, to interface a DSP chip to the analog world. This codec runs at a fixed rate of 8kHz and 16 bit representation. In the next lab, we will explore the codec in more depth.
C6711 chip
Floating-point DSP, 150MHz clock, 900MFLOPS, 1200MIPS Can fetch 8 32-bit instructions per cycle. 72kB internal memory, 8 functional or execution units, 2 sets of 32-bit registers. Capable of fixed and floating point operations. VLIW very long instruction word architecture.
External Memory:
The board contains 16 MB of SDRAM and 128 kB of flash ROM.
Parallel Port
TMS320C67
Power Jack Power LED
3.3V Power
JTAG
Reset
Emulation 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 programmer-optimized assembly programs does, but TI has done a good job in making the optimized C compiler produce code that is comparable to programmeroptimized assembly code. Lastly, a cross between assembly language and C exists within CCS. It is called linear assembly code. Linear assembly looks much like assembly language code, but it allows for symbolic names and does not require the programmer to specify delay slots and CPU core registers on the DSP. Its advantage over C code is that it uses the DSP more efficiently, and its advantage over assembly code is that it does not require the programmer to manage the CPU core registers. This will be apparent in future labs when assembly and linear assembly code are written.
DSP LABORATORY
20
.sa
Text Editor
.asm
.asm Assembler
.obj
.c
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 on-board codec, and between the CPU and daughter card expansion, respectively. These McBSPs use frame synchronization to communicate with external devices. Each McBSP has seven pins. Five of them are used for timing and the other two are connected to the data receive and data transmit pins on the on-board codec or daughter card. Also included in each McBSP is a 32-bit Serial Port Control Register (SPCR). This register is updated when the on-board codec (or daughter card) is ready to send data to or receive data from the CPU. The status of the SPCR will only be a concern to us when polling methods are implemented. In this lab, we will be exploring two possible ways of establishing a real-time communication link between the CPU and the on-board codec. The idea of real-time communication is that we want a continuous stream of samples to be sent to the codec. In our case, we want samples to be sent at rate 8kHz (one sample every .125ms). This is controlled by the codec, which will signal serial port 0 (SP0), every .125ms.
Polling
The first method for establishing a real-time communication link between the CPU and the on-board codec is polling. When the on-board codec is ready to receive a sample, it sets a bit 17 of the SPCR to true. Bit 17 of the SPCR is the transmit ready (XRDY) bit, which is used to let the CPU know that it can transmit data. In a polling application, the CPU continuously checks the status of the SPCR and transmits a data sample as soon as the bit 17 of the SPCR is set true. Upon transmission, the McBSP will reset bit 17 of the SPCR to false. The polling program will then wait until the on-board codec resets bit 17 to true before transmitting the next data sample. In this manner, a polling algorithm will maintain a constant stream of data owing to the on-board codec. On the DSP hardware, polling is implemented mostly in software. The on-board codec will continuously set the transmit ready bit of the SPCR and the McBSP will always reset it. However, it is up to the programmer to write an algorithm that will constantly be checking the status of the SPCR.
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:
Main processing statement 1 Main processing statement 2 Main processing statement 3 Interrupt occurs Processor saves the current state of the registers, etc. Processor jumps to ISR ISR processing statement 1 ISR processing statement 2 ISR processing statement 3 ISR completes Processor restores the previously saved state of registers, etc. Main processing statement 4 Main processing statement 5 Etc.
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.
CODEC
McBSP0
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
For this lab, we will just be observing and listening to signals, so only the oscilloscope, headphones or speakers, and one of the 3 foot headphone-to-RF connector cables will be used. At this point, turn on the oscilloscope and connect the cable to the headphone jack on the DSK and connect the left channel (white cable) to the RF connector on the oscilloscope.
DSP LABORATORY
24
Adding Support Files to a Project The next step in creating a project is to add the appropriate files. In the CCS window, go to `Project' and then Add Files to Project. In the window that appears, click on the folder next to where it says Look In: Make sure that you are in the folder C:\DSP\support_files. You should be able to see the file C6xdskinit.c. Notice that the `Files of type' field is 'C source code'. Click on C6xdskinit.c and then click on `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.
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
Go to `Project' and select `Scan All Dependencies'. In CCS, double-click on `sine_gen.pjt' and then double-click on `Include'. You should see the three header files that you downloaded plus a mystery file C6x.h.
This mystery file is included with the Code Composer Studio software, and it is used to configure the board. CCS automatically included all of the header files when the file C6xdskinit.c was added to the project. Open the file C6xdskinit.c and observe that the first four lines of code include the four header files. You now have all of the files you need for this project.
Build Options
Once all of your files have been included in your project file, the compiler and linker options must be configured so that your project gets built correctly. Go to `Project', then to `Build Options', and then click on the `Compiler' tab. In the Category:, Basic, make sure the following are selected: Target Version: 671x Generate Debug Info: Full Symbolic Debug (-g) Opt Speed vs. Size: Speed Most Critical (no ms) Opt Level: None Program Level Opt: None In the top part of the current window, you should see: -g -q -f r"C:\DSP\lab2\sine_gen\Debug" -d"_DEBUG" Change it to: -g -k -s -fr"C:\DSP\lab2\sine_gen\Debug" -d"_DEBUG" -mv6710
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.
DSP LABORATORY
27
When CCS built your project, it compiled all of the C code into assembly code, using a built-in compiler. Then it assembled the assembly code into a COFF (common object file format) file that contains the program instructions, organized into modules. Finally, the linker organizes these modules and the run-time support library (rts6701.lib) into memory locations to create an executable .out file. This executable file can be downloaded onto the DSK. When this executable file is loaded onto the DSK, the assembled program instructions, global variables, and run-time support libraries are loaded to their linker specified memory locations. To test your program on the DSK, you must first load the program onto the board, but before you load a new program onto the board, it is good practice to reset the CPU. To reset the the CPU, click on `Debug', then select `Reset CPU'. Then, to load the program onto the DSK, click on `File', then select `Load Program'. In the new window that appears, double-click on the folder `Debug', select the file sine_gen, then select `Open'. This will download the executable file to the DSK. A new window will appear within CCS entitled Disassembly, which contains the assembled version of your program. Ignore this window for now.
Before you run this program, make sure that the cable between the 1/8th inch headphone jack on the DSK board (the J6 connector) and the oscilloscope is connected, and make sure that the oscilloscope is turned on. In CCS, select the `Debug' pull down menu and then select `Run', or just simply click on the top \running man" on the left side toolbar. Verify a 1kHz sine wave on the 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 real-time digital systems, this requires samples of the signal in eqn(1) to be sent to the codec at a fixed rate. In the case of the on-board codec, samples are being sent at rate fs = 8kHz (ts = 0.125ms). In C code, we generate samples of eqn(1), namely
fo ) 2 fs
which is only defined for integer values of n. Here, the argument of the sine function,
[n] = 2n
fo fs
28
DSP LABORATORY
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.
// init DSK, codec, SP0 for interrupts // wait for an interrupt to occur
It is important to notice that code is divided (via blank lines) into different sections (in this case three sections). This format is often used and it is recommended that you adopt this style of coding.
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 (16-bit signed integer between the values 32768 and 32767), the CPU will round the number to the nearest integer and store it in a 16-bit signed integer format (2's complement). This value is scaled by 20000 for two reasons. First, it is needed so that rounding errors are minimized, and second, it amplifies the signal so it can be observed on the oscilloscope and heard through speakers or headphones. This scaling factor must be less than 32768 to prevent overdriving the codec. Line 18 sends the current sine value to the codec by calling the function output_sample(). The code for output sample() is located in file C6xdskinit.c. Upon completion of the interrupt (generating a sinusoid sample and outputting it to the on-board codec), the interrupt service routine restores the saved execution state (see the command return; in line 19). In this program, the saved execution state will always be the infinite while loop in the main() 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 real-time digital system affects the generation of a sinusoid. 2. Use a watch window to change the value of fo from 1000 to 4000 Hz with a sampling frequency of 8000 Hz. What's the effect of changing the frequency? Comment on the results.
DSP LABORATORY
32
Short sine_table[8] = {0,14142,20000,14142,0,-14142,-20000,-4142}; short ctr; void main() { ctr=0; comm_poll(); while( 1 ) { output_sample(sine_table[ctr]); if (ctr < 7) ++ctr; else ctr = 0; } } 9. Add comments to your code where appropriate and save the file in CCS. Now, build your project by clicking on the 'rebuild all' button (the button with three red arrows). Before loading a new program onto the DSK, it is best to reset the DSP. This can be done within CCS by selecting the 'Debug' pull down menu and then selecting 'Reset CPU'. Once the DSP is reset, load your new program onto the DSK and observe a 1kHz sine wave on an oscilloscope. Notice that the sine wave algorithm is now coded within the infinite while loop (while(1)). This is the general structure for polling. In both polling and interrupt based programs, the algorithm must be small enough to execute within .125ms (at an 8kHz rate) in order to maintain a constant output to the on-board codec. Algorithms can be coded under either scheme, using polling or interrupts. In this class, most of the algorithms will be coded using interrupts.
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. Re-label the project sine_lookup.pjt. Explain the procedure required to change a polling based program to an interrupt driven program. Include a copy of your C program. 3. Implement sine_gen.pjt using polling. Re-label the project: sine_gen_poll.pjt. Explain the procedure required to convert an interrupt-driven program to a pollingbased program.
DSP LABORATORY
33
End Notes
This lab was used to learn how to create a project and implement it on the DSK. In all real-time DSP algorithm implementations, the processing rate of a digital signal processing system is very important. For this lab, only an 8kHz rate was used to implement algorithms. In the next lab, we will explore the concepts of input and output, and develop the foundation for designing systems and processing signals on the C6711 DSK.
DSP LABORATORY
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. 4. Solve exercise 5 in the lab theoretically. Theoretically speaking, what is the minimum sampling frequency of a square wave having f0 = 2 kHz. 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 discrete-time signals by sampling. The processed discrete-time signal is usually converted back to analog form by interpolation, resulting in a reconstructed analog signal xr(t).
Figure (1) Sampling and Reconstruction process An ideal sampler reads the values of the analog signal xa(t) at equally spaced sampling instants. The time interval Ts between adjacent samples is known as the sampling period (or sampling interval). The sampling rate, measured in samples per second, is fs =1/Ts. An actual (non-ideal) sampling circuit cannot capture the value of xa(t) at a single time instant. Instead, the output of a sampling circuit is the average value of xa(t) over a short interval, as shown, where delta is much shorter than the sampling period Ts .
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 n =
provided that
- The frequency content of xa(t) is ideally bandlimited to a frequency range magnitude of f is less than or equal to fmax ; f f max . - The sampling rate fs satisfies the Nyquist condition ; f s f 2 f max - The interpolating function g(t) is the impulse response of an analog ideal low-pass filter with a cut-off frequency fc such that fmax fc <fs -fmax.
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 continuous-time sinusoidal signal and the dash-dot line describes a 1.5 Hz continuous time sinusoidal signal. When both signals are sampled at the rate of fs =2 samples/sec, their samples coincide, as indicated by the circles in Figure 2. This means that x1[nTs] is equal to x2[nTs] and there is no way to distinguish the two signals apart from their sampled versions. This phenomenon, known as aliasing, occurs whenever f2 f1 is a multiple of the sampling rate: in our example, fs equal f1 + f2.
Figure (2) Two sinusoidal signals are indistinguishable from their sampled versions whenever f2 f1 is a multiple of the sampling rate fs
DSP LABORATORY
37
x1(t)=cos(2f1 t) X2(t)=cos(2f2 t)
f2 =2 samples/sec
, f1 = 0.5 Hz , f2 = 1.5 Hz
x1(nTs) = x2(nTs)
1 1 n ) = cos(0.5n) 2 2
x s (t ) = x(t ) p (t ) p (t ) =
It follows that
(t nT )
s n =
P( w) =
and hence,
2 Ts
(w
n =
2n 2 )= Ts Ts
(w nw )
s n =
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
T 2T 3T xd(t) |Xd(w)|
-WT
2WT
X(0)/T
T 2T 3T
-WT
2WT
Figure (3) Sampling in Time and Frequency Domains Then Xd(w) consists of the periodic repetition at intervals ws of X(w). If fs does not satisfy the Nyquist rate, the different components of Xd(w) overlap and will not be able to recover x(t) exactly as shown in Figure(4). This is referred to as aliasing in frequency domain.
DSP LABORATORY
39
|Xd(w)| X(0)/T
- WS
-WB |Xd(w)|
WB
WS
X(0)/T
WB
WS |Xd(w)| X(0)/T
- WS B -W
WB WS
- WS B -W
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 low-pass filter, known as an antialiasing filter, with a cut-off frequency fc equals fs /2. This means that the high frequency artifacts of the continuous-time signal will be lost. This is the cost of managing aliasing. In practice, the anti-aliasing filter will have a cutoff frequency at roughly 90% of the Nyquist frequency and use the other 10% for roll-off. The on-board codec of the DSK has a sampling rate of fs = 8 kHz and an anti-aliasing filter with cutoff frequency 3.6kHz, which is 90% of fs/2 (Nyquist Frequency).
DSP LABORATORY
40
xa(t)
sampler
x[n]
fo p
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 2 3 4 5 6 7 8 9 10
>> x2=x(1:2:end) x2 = 1 3 5 7 9
DSP LABORATORY
41
x(t ) = 0 +
k =1 k odd
4 sin(2kt ) k
DSP LABORATORY
42
Figure (6) Simulink model for the synthesizer experiment. These are the first 8 terms in the Fourier series of the periodic square wave shown in Figure 7. Run the model by selecting Start under the Simulation menu. A graph will pop up that shows the synthesized square wave signal and its spectrum. This is the output of the Spectrum Analyzer. After the simulation runs for a while, the Spectrum Analyzer element will update the plot of the spectral energy and the incoming waveform.
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.
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 cut-off frequency of 2 fo for the Butterworth low-pass filter. c. Start the simulation and notice the shifted versions of the frequency domain response of the input and the output of the filter. d. Repeat steps 2 and 3 for a sine wave with fo=95 Hz. Comment. e. Repeat steps 2 and 3 for a sine wave with fo=105 Hz. Comment.
Exercise#4: Downsampling
a. Using MATLAB, generate a sine wave with frequency f0 of 1300 Hz, and sampling frequency fs of 8000 Hz. b. Save the data of the sine wave as a sound file, named as 8000.wav. c. Listen to the tone of the 1300 Hz sine wave. d. Downsample the data of the sine wave by 2. This will result in a sine wave with a sampling rate of 4000 Hz. Repeat steps b, c and compare the sounds. e. Generate a sine wave with frequency f0 of 1300 Hz, and sampling frequency fs of 4000 Hz. f. Repeat steps b and c and compare the sounds.
x(t) A/D
x[n]
y(t)
Figure (10) DSP Block Diagram straight wire, which means that only an identity map will be implemented between the input and output of the DSP core. No local or global variables or processed data will be stored in memory, and no signal processing will be done. Only the program instructions will be stored in the program memory.
DSP LABORATORY
46
Notice that the actual peak-to-peak voltage of the signal is greater than 1V (about 1.8V). This is due to the fact that the resistance of the DSK is higher resistance than the resistance to which the signal generator has been matched. 4. Change the peak-to-peak voltage and the frequency on the signal generator and observe the effects on the oscilloscope. If the voltage input to the codec exceeds 3.3V, then the codec will be overdriven. When the codec is overdriven, the output on the codec will either be amplitude clipping of the input sine wave or two's compliment overflows effects (a sudden change in sign). If the voltage input is too small (around 100mV or less), then coupling effects from the internal hardware will be observed. For frequency, keep in mind that there is a lowpass filter that cuts off frequencies above 3.6 kHz. 5. Vary the frequency of the sinusoid on the signal generator and observe that sinusoids above 3.6kHz are suppressed. (You should notice that sinusoids around 3.6 kHz are decreased in amplitude, but not fully suppressed. This is due to the fact that the anti-aliasing filter is not ideal and therefore has a nonzero roll-off around 3.6 kHz.)
Exercise#6:
a. To observe the effects of the anti-aliasing filter, use a square wave as the input. Input square waves with 100, 500, 800 and 1400 kHz. Use your knowledge of the Fourier series expansion of a square wave to explain what you see. Also, listen to this signal and explain what you hear. b. Repeat for a triangular wave as the input. c. Sketch the output signal in each case.
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 fourth-order Butterworth low-pass filter with a cut-off frequency of 500 Hz and a passband gain of 10 using a suitable number of cascade operational amplifiers and R, C components for your implementation. Let R=1k. Simulate the circuit by Orcad to verify your design
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 two-element vector, Wn = [W1 W2], BUTTER returns an order 2N bandpass filter with passband W1 < W < W2. [B,A] = BUTTER(N,Wn,'high') designs a highpass filter. [B,A] = BUTTER(N,Wn,'stop') is a bandstop filter if Wn = [W1 W2]. When used with three left-hand arguments, as in [Z,P,K] = BUTTER(...), the zeros and poles are returned in length N column vectors Z and P, and the gain in scalar K.
DSP LABORATORY 48
When used with four left-hand arguments, as in [A,B,C,D] = BUTTER(...), state-space matrices are returned. BUTTER(N,Wn,'s'), BUTTER(N,Wn,'high','s') and BUTTER(N,Wn,'stop','s') Butterworth filters. In this case, Wn is in [rad/s] and it can be greater than 1.0. design analog
Bandpass: Wp = [.2 .7], Ws = [.1 .8] Bandstop: Wp = [.1 .8], Ws = [.2 .7] BUTTORD also returns Wn, the Butterworth natural frequency (or, the "3 dB frequency") to use with BUTTER to achieve the specifications. [N, Wn] = BUTTORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case Wp and Ws are in radians/second. When Rp is chosen as 3 dB, the Wn in BUTTER is equal to Wp in BUTTORD.
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 two-element vector, Wn = [W1 W2], CHEBY1 returns an order 2N bandpass filter with passband W1 < W < W2. [B,A] = CHEBY1(N,R,Wn,'high') designs a highpass filter. [B,A] = CHEBY1(N,R,Wn,'stop') is a bandstop filter if Wn = [W1 W2]. When used with three left-hand arguments, as in [Z,P,K] = CHEBY1(...), the zeros and poles are returned in length N column vectors Z and P, and the gain in scalar K. When used with four left-hand arguments, as in [A,B,C,D] = CHEBY1(...), state-space matrices are returned. CHEBY1(N,R,Wn,'s'), CHEBY1(N,R,Wn,'high','s') and CHEBY1(N,R,Wn,'stop','s') design analog Chebyshev Type I filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.
Bandpass: Wp = [.2 .7], Ws = [.1 .8] Bandstop: Wp = [.1 .8], Ws = [.2 .7] CHEB1ORD also returns Wn, the Chebyshev natural frequency to use with specifications. CHEBY1 to achieve the
[N, Wn] = CHEB1ORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case Wp and Ws are in radians/second.
DSP LABORATORY
50
Bandpass: Wp = [.2 .7], Ws = [.1 .8] Bandstop: Wp = [.1 .8], Ws = [.2 .7] CHEB2ORD also returns Wn, the Chebyshev natural frequency to use with CHEBY2 to achieve the specifications. [N, Wn] = CHEB2ORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case Wp and Ws are in radians/second.
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 two-element vector, Wn = [W1 W2], ELLIP returns an order 2N bandpass filter with passband W1 < W < W2. [B,A] = ELLIP(N,Rp,Rs,Wn,'high') designs a highpass filter. [B,A] = ELLIP(N,Rp,Rs,Wn,'stop') is a bandstop filter if Wn = [W1 W2]. When used with three left-hand arguments, as in [Z,P,K] = ELLIP(...), the zeros and poles are returned in length N column vectors Z and P, and the gain in scalar K. When used with four left-hand arguments, as in [A,B,C,D] = ELLIP(...), state-space matrices are returned. ELLIP(N,Rp,Rs,Wn,'s'), ELLIP(N,Rp,Rs,Wn,'high','s') and ELLIP(N,Rp,Rs,Wn,'stop','s') design analog elliptic filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.
Highpass: Wp = .2,
Bandpass: Wp = [.2 .7], Ws = [.1 .8] Bandstop: Wp = [.1 .8], Ws = [.2 .7] ELLIPORD also returns Wn, the elliptic natural frequency to use with ELLIP to achieve the specifications. [N, Wn] = ELLIPORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case Wp and Ws are in radians/second. NOTE: If Rs is much much greater than Rp, or Wp and Ws are very close, the estimated order can be infinite due to limitations of numerical precision.
B( s ) b1 s nb 1 + b2 s ns 2 + L + bnb H ( s) = = A( s ) a1 s na 1 + a 2 s na 2 + L + a na
given the numerator and denominator coefficients in vectors B and A. The frequency response is evaluated at the points specified in vector W (in rad/s). The magnitude and phase can be graphed by calling FREQS(B,A,W) with no output arguments. [H,W] = FREQS(B,A) automatically picks a set of 200 frequencies W on which the frequency response is computed. FREQS(B,A,N) picks N frequencies.
num=1; den=[1 3 5 10] w=linspace(0,4,400); h=freqs(num,den,w); mag=20*log10(abs(h)); phase=180/pi*angle(h); subplot(211) semilogx(w,mag) subplot(212) semilogx(w,phase)
DSP LABORATORY
53
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.
s w0 w0 s
Lowpass to bandpass
s' =
s 2 + w1 w2 s ( w2 w1 )
Lowpass to bandstop
[numt,dent]=lp2bs(num,den,wo,Bw) [At,Bt.Ct,Dt]=lp2bs(A,B,C,D,wo,Bw)
s' =
s ( w2 w1 ) s 2 + w1 w2
DSP LABORATORY
55
Lab
1. Using MATLAB analog filter design functions solve the following problems. P3.5, P3.7, P3.8, and P3.10 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 pole-zero plots. This background contains the following topics:
DSP LABORATORY
57
You can also use the Method menu to select a filter design method.
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. Right-clicking 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
DSP Laboratory Experiment # 6 Design and Implementation of Finite Impulse Response (FIR) Filters on the C6711 DSK
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 units to Hz. Set the sampling frequency to 8000 (sampling rate of the on-board codec). Make sure that the algorithm Equiripple FIR is selected. Under specifications, make sure that box for Minimum order is checked. Select Type: lowpass Set Fpass to 1500 and Rp to 2. Set Fstop to 1700 and Rs to 60.
DSP LABORATORY
64
Figure 1 : Low pass filter design using FDAtool 3. Your filter has been designed by MATLAB. To access this filter from the workspace, go to File and select Export. In the window Export, complete the following fields: Export to workspace: Export As coefficient Variable Names, Numerator: filt1 and then click on the button apply. 4. Your filter is now available in the workspace. To see the filter coefficients, type the following in the MATLAB workspace
FDAtool has many FIR filter options such as: Equiripple FIR, Least Squares FIR, and Window FIR. The passband and stopband each have two sets of parameters Fp, Rp, Fs, and Rs. The parameters Fp and Fs define the boundaries of the passband and stopband frequencies, respectively. The parameter Rp determines the ripple (in dB) of the passband and Rs is the stopband rejection parameter that denotes the relative height of the stopband compared to the passband (i.e. Rs = 60 means that the amplitude of the stop band is -60 dB less than the passband.) In the case of bandpass and bandstop filters, there will be two passband and stopband parameters, namely Fp1, Fp2, Fs1, and Fs2. When designing filters using FDAtool, a transition band of frequencies must be included between Fp1 and Fs1 as well as Fp2 and Fs2. The tighter these bands are, the larger your filter order will be. In this lab, we will use the FDAtool, to design FIR filters. A MATLAB m-file have been created to format the filter coefficients so these filters may be easily implemented in hardware. These files will be discussed when we do our FIR filter implementation.
Figure 2: Delay Tap Hardware Diagram of an FIR Filter Another way to describe FIR filters is to say that the output at time n is the inner product of a filter coefficient vector with an input vector containing the N +1 most recent inputs. Let's define the two column vectors h = [h[0], h[1], . . . h[N]]T RN+1 and xn = [x[n],x[n - 1], . . . x[n - N]]T RN+1. The output is defined to be y[n] = h, x n = h x n = DSP hardware.
T
h[k ]x[n k ] ,
k =0
DSP LABORATORY
66
To make this a real-time digital filter, the input vector x n must be updated as each sample is read in from the codec. After the next sample has been read in, the new input vector containing the N + 1 most recent inputs is x n +1 [x[n + 1], x[n], . . . x[(n + 1) - N]]T RN+1 and the output is y[n + 1] =
h, x n +1 . The vector x n +1 is created by removing the oldest sample of x n from the bottom, shifting
all of the elements down in vector (remember x n is a column vector), and storing the newest sample x[n + 1] at the top of the vector. This is illustrated below.
The column on the left represents the C coded array that holds the N + 1 most recent inputs and the three columns on the right illustrate how the incoming samples are stored in the C coded array. This is not the most efficient way to organize the data in the input vector x, but it provides a good starting point for coding digital FIR filters in C. Download the project FIR.pjt and accompanying files FIR.c and LPF1500.cof from the course account and open it in CCS. Examine the code listing for FIR.c shown in Figure 3. Within the ISR (lines 7 through 23), note the following:
A local variable k, of type short, is created as a loop counter, the current sample is read in
from the code and stored at the top of the array buffer x[0], and the accumulating variable for the current output, global variable yn, is initialized to zero (lines 9 through 12).
The explicit convolution (multiply and accumulate operations) of the N + 1 filter
coefficients stored in the vector h[] with the N + 1 most recent inputs stored in the vector x[] is accumulated in yn (lines 14 and 15).
The input buffer is shifted down starting at the bottom, where the last value of the array is
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 m-file FIR_cof_gen.m from the account. This m-file is a function that takes the filter coefficients, h[k], and creates a formatted .cof that can be included into the C program 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(n-k) 16.) 17.) for (k = N; k > 0; k--) // starting @ end of buffer 18.) x[k] = x[k-1]; // 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 m-file FIR_cof_gen.m must be stored in your current working directory in MATLAB.) This command will create the file LPF1500.cof that may be included in FIR.c. At the end of the FDAtool filter design, commands were given to plot the filter coefficients. You may noticed that the coefficients were all less than one. In fixed-point arithmetic, all of the filter coefficients must be signed-integers, so the numbers were all scaled by 215 and rounded to the nearest integer. This scaling undone before output by multiplying by 2-15. In fixed-point algorithms, this type of scaling must be done. This leads to a few additional comments. First, the input samples and the filter coefficients are 16-bit signed integers, so the accumulation variable yn is a 32-bit signed integer, which, in C, means that the variable is declared as int yn (instead of short yn). Also, the scaling up of the filter coefficients by 215 was done by FIR_cof_gen when the option fixed was selected, and the down scaling was done in line 20. In binary, multiplying or dividing a number by a power of two means shifting bits of that number either to the left or right. In this case, we are dividing yn by 215, so we need to shift the bits of yn fifteen bits to the right, which is done in C by using the right bit shift operator >> (see line 20). One final comment about FIR_cof_gen.m. This function performs H scaling to scale the frequency response H(ejwto ). This scaling makes the gain 1 f or all frequencies. This is done to help keep you from overdriving the codec.
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 floating-point version of FIR.C. Include a copy of your C code and comment on the changes made. Notice that when using floating-point arithmetic, you must make sure that the Target Version is set to 671x in the Compiler tab in the Build Options. Plot the frequency response of the filter as in exercise 1.
3. Design a notch filter for the on-board codec that knocks out 200Hz tones. Use plotZTP_FIR() to examine this filter. Create a set of tones in MATLAB of the following form x[n] = cos[2f1n/fs]+cos[2f2n/fs]. Let f1 = 200Hz and vary f2. In MATLAB, 10 seconds worth of x[n] can be generated by typing >> fs=8000; t=0:1/fs:10;f1=200; >> f2=2000; x=.5*(cos(2*pi*f1*t)+cos(2*pi*f2*t)); sound(x,fs) in the MATLAB workspace. Note that here f2 = 2kHz and that a factor of 0.5 has been used to prevent overdriving the on-board codec. Observe and listen to both the filtered and unfiltered versions of x[n] on the oscilloscope and with headphones. Do this for f2 = 2kHz, 1.5kHz, 1kHz, 500Hz, 400Hz, 300Hz, and250Hz. What can you say about the filtered output as f2 f1 ? Does this filter have a linear phase? Comment on your results and give as much intuition as possible.
complex conjugate pairs. Zeros that occur on the unit circle, z = ejwto, will translate to zeros in the magnitude response of the filter. Frequency components that neighbor a zero on the unit circle will be attenuated. Zeros that are not on the unit circle will also shape the magnitude response of the filter H(z). The closer a frequency on the unit circle gets to a zero, the more it will be attenuated.
4. Design a filter by placing zeros in your transfer function H(z). Intuitively, explain how these zeros affect the frequency response of your filter. Use at least 3 complex conjugate pairs of zeros. Use plotZTP_FIR.m to help analyze your filter. Implement this filter on the DSK and comment on the results seen at each frequency. Include a copy of the MATLAB figure generated by plotZTP_FIR.m and comment on the output of this filter for input sinusoids of various frequencies. Give as much intuition as possible.
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 on-board codec translates to a 50ms delay). An example impulse response with a[m] = 0.7 and m = 8 would be coded in MATLAB as h=[1 0 0 0 0 0 0 0 0.7]. Use plotZTP_FIR() to examine this filter. For the delay filters that we will examine next, the frequency responses will take MATLAB too long to compute, so we will not explore them.
5. Design a digital delay filter for the on-board codec with the parameters a[m] = 0.9 and m = 400. This will require a buffer that will store the 400 most recent inputs, but will only require two multiply and accumulate operations. Create your C code in a way that does (at most) two multiply and accumulate operations. Play music through the DSK and listen to the effects. Try various values of a[m] and m to get a feel for how they affect the input. What can say about a 50ms and 100ms delay? Does this filter have a linear phase? Comment on your results and give as much intuition as possible.
DSP LABORATORY
72
DSP Laboratory, Experiment # 7 Design of IIR Digital Filters Using Bilinear Transformation and LMS Technique
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 z-transforms. Replacing s = performing algebraic manipulations, substituting z = ejw we get w = 2 tan-1( T/2) + j
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 left-half s plane maps to the interior of the unit circle, and the right-half s plane maps outside the unit circle.
The constant provides one remaining degree of freedom that can be used to map any particular finite frequency the jw axis in the s plane to a particular desired location on the unit circle ejw in the z plane. All other frequencies will be warped. In particular, approaching half the sampling rate, the frequency axis compresses more and more. Filters having a single transition frequency, such as lowpass or highpass filters, map beautifully under the bilinear transform; you simply map the cut-off frequency where it belongs, and the response looks great. In particular, equal ripple is preserved for optimal filters of the elliptic and Chebyshev types because the values taken on by the frequency response are identical in both cases; only the frequency axis is warped.
1. Design an IIR filter with the following characteristics: Type: Order Sampling Frequency, Fs Passband Edge Frequency, Stopband Edge Frequency, High Pass IIR Elliptic filter 5 10 Hz Fc1 = 2.4 Hz Fc2 = 2 Hz
The design should be attempted indirectly by performing the following steps: 1. First design a low pass elliptic analog prototype filter with cut-off of 1 rad/s and order 5 to meet the required passband and stopband ripple specifications 2. Then convert this to an analog high-pass filter with the given passband edge frequency. 3. Then, using the bilinear transformation convert this analog high-pass filter to the required the digital high-pass filter.
Part A: Lab
DSP LABORATORY
74
Type: Order Sampling Frequency, Fs Passband Edge Frequency, Stopband Edge Frequency, Passband Ripple
DSP LABORATORY
75
What would happen if we designed a low-pass filter with a cutoff frequency of 500Hz, for example, and started to process data? During the processing we discovered some noise signal at 450Hz that was sneaking through our filter. We could go back into MATLAB, redesign the filter coefficients, and paste them into our code and then the noise at 450Hz would be eliminated. This would be effective if the interference does not change in time.
One solution to this problem is an adaptive filter. The coefficients of an adaptive filter change in time. In this lab, we will look at a few ways to implement adaptive algorithms. Take a look at the block diagram below that compares the setup of a standard filter, like we are used to, and an adaptive filter. The first thing that should strike you is the appearance of a feedback loop.
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.
Looking at the figure we can immediately do some calculations. The output of the FIR filter is:
y(n) = h(k)x(n k)
k =0
N 1
The error signal is the desired output signal, d(n) , minus the filter output, y(n): e(n)=d(n)-y(n)
= d(n)
h(k)x(n k )
k =0
N 1
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 Weiner-Hopf equation. This result is usually not practical to compute since the signal statistics are not usually known and it involves a matrix inversion that is difficult and time-consuming to calculate.
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 10-3.
>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:
function [h,e,err_sq] = lms(input, desired, N, beta, h) % LMS adaptive filter % input : input signal vector (Nx1 column vector) % desired : desired output signal (single element) % N : no. of taps % h : filter coefficients vector (Nx1 column vector) % beta : learning constant % e: error of adaptive filter % err_sq : squared estimation error
The error terms will help us evaluate the filter performance later.
2 Check your code. Insert your filter design code and your LMS code into the lmsfilter.m file at the marked spots. Note that this filter begins estimating at the Nth input. This is because the FIR filter must have full inputs. Otherwise, it will try to learn the transient response of a filter. Compare the spectrum of your learned filter with the original filter. Comment on any differences and similarities.
3. Adaptive filters can only learn what they are taught. What this means, if you only give them input at certain frequencies, then they will only learn the filter response at those frequencies. We will test this phenomenon by deleting the noise term in the line: x = sin(2*pi*f1*t)+sin(2*pi*f2*t)+sin(2*pi*f3*t);%+ 0.5*randn(size(t)); Now the filter will only learn the response of the filter at f1, f2 and f3. Run this program and look at the results. Try changing the frequencies and look at your results, describe what you see.
DSP LABORATORY
82
DSP Laboratory, Experiment # 8 Design of Digital Filters Using Windows and Parks-McClellan Algorithm
Objectives:
1. To know the effect of windows on IIR filters. 2. To know the different types of windows and the characteristics of each one especially Kaiser Window. 3. To demonstrate the FIR filter design using Parks-McClellan Algorithm
Introduction
In this lab we will cover more systematic methods of designing both FIR and IIR filters.
1 H ideal (e jw ) = 0
And a corresponding impulse response of
w wc wc p w
(1)
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 [, ].
htrunc(n)=
w wc sin c( c n)
n = ,....,0,1,......, otherwise
(3)
DSP LABORATORY
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 (N-1)/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)
Where wc is the cutoff frequency and N is the desired window length. The time shift of (N-1)/2 units to the right corresponds to multiplying the frequency response by ejw(N-1)/2
. It does not affect the magnitude response of the filter, but adds a factor of -jw(N-1)/2 to the
phase response. Such a filter is called linear phase because the phase is a linear function of w. We may generalize the idea of truncation by using different windowing functions to truncate an ideal filter's impulse response. Note that by simply truncating the ideal filter's impulse response, we are actually multiplying or windowing" the impulse response by a shifted rect() function. This particular type of window is called a rectangular window. In general, the impulse response h(n) of the designed filter is related to the impulse response hideal(n) of the ideal filter by the relation
(6)
Where w(n) is an N-point window, and hideal(n) is given in equation (5) The rectangular window is defined as
1 w(n) = 0
The DTFT of w(n) for N = 21 is shown in Fig. 1.
n = 0, 1 ,......, N 1 otherwise
The rectangular window is usually not desirable because it leads to the large stopband and passband ripple as shown in Fig. 2.
DSP LABORATORY
84
Figure 2: Frequency response of low-pass filter, designed using the truncation method More desirable frequency characteristics can be obtained by making a better selection for the window, w(n). In fact, a variety of raised cosine windows are widely used for this purpose. Some popular windows are listed below. 1. Hanning window (as defined in Matlab, command hann(N)):
n = 0, 1 ,......, N 1 otherwise
DSP LABORATORY
85
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 roll-off, and the passband and stopband ripple (see Fig. 3 below). There are two corresponding parameters in the spectrum of each type of window that influence these filter parameters. The filter's roll-off is related to the width of center lobe of the window's magnitude spectrum. The ripple is influenced by the ratio of the main lobe amplitude to the first side lobe amplitude (or difference if using a dB scale). These two window spectrum parameters are not independent, and you should see a trend as you examine the spectra for different windows. The theoretical values for the main lobe width and the peak-to-side lobe amplitude are shown in Table 1. Window (Length N) Rectangular Hanning Hamming Blackman Mainlobe Width 4/N 8/N 8/N 12/N Peak-To-Sidelobe Amplitude (dB) -13 dB -32 dB -43 dB -58 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 peak-to-side lobe amplitude (in dB) from the logarithmic magnitude response plot for each window type. The Matlab commands zoom and crosshair are helpful for this. Make a table similar to table (1 ) with these values and the theoretical ones. 4. Now use a Hamming window to design a lowpass filter h(n) with a cutoff frequency of wc = 2 and length 21. In the same figure, plot the filter's impulse response, and the magnitude of the filter's DTFT in decibels. a. First use equations (4) and (6) with =100, 500, 1000 . See the effect of changing on the filter response. b. Then use equations (5) and (6) . See the effect of changing on the filter response. c. Repeat b with increasing N to 51. What is the effect of N on mainlobe width and the peak-tosidelobe amplitude?
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 near-optimal windows that can be used to design filters which meet or exceed any filter specification. The Kaiser window depends on two parameters: the window length N, and a parameter which controls the shape of the window. Large values of reduce the window side lobes and therefore result in reduced passband and stopband ripple. The only restriction to the Kaiser filter design method is that the passband and stopband ripple must be equal in magnitude. Therefore, the Kaiser filter must be designed to meet the smaller of the two ripple constraints:
= min{ p , s }
The Kaiser window function of length N is given by
( I w(n) = o
n( N 1 n) N 1 I o ( ) 0
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,
A > 50 21 A 50 A < 21
( 4)
(3)
DSP LABORATORY
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 cut-off frequency centered between wp and ws.
wc =
w p + ws 2
2. Plot the magnitude of the DTFT of h(n) for w p . 3. Filter the noisy speech signal in noisy. mat using the filter you have designed. 4. Then compute the DTFT of the filtered signal. Plot the magnitude of the DTFT in decibels versus frequency in radians w p . Compare this with the spectrum of the noisy speech signal shown in Fig. 4. Play the noisy and filtered speech signals back using sound and listen to them carefully.
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
y ( n) = x ( n k ) h ( k )
k =0
N 1
(5)
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 k =0
This strategy reduces the computation to N=2 multiplies and N 1 adds for any value of N . Note that the computational effort is linearly proportional to the length of the filter. The Kaiser filters do not guarantee the minimum possible filter length. Since the filter has equal passband and stopband ripple, it will usually exceed design requirements in one of the two bands; this results in an unnecessarily long filter. A better design would allow the stopband and passband constraints to be specified 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.
DSP LABORATORY
92
DSP Laboratory, Experiment # 9 Discrete Fourier Transform and Fast Fourier Transform Algorithms
Introduction
This lab will cover the Discrete Fourier Transform (DFT) and Fast Fourier Transform (FFT) methods. In previous laboratories, we have used the Discrete-Time Fourier Transform (DTFT) extensively for analyzing signals and linear time-invariant systems.
( DTFT ) X (e jw ) =
x ( n )e
n =
jwn
(1)
jw
1 2
X (e
)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) (4)
1 N
X
k =0
N 1
(k )e j 2kn / N
Here XN(k) is an N point DFT of x(n). Note that XN(k) is a function of a discrete integer k, where k ranges from 0 to N - 1. In the following, we will study the derivation of the DFT from the DTFT, and several DFT implementations. The fastest and most important implementation is known as the fast Fourier transform (FFT). The FFT is one of the cornerstones of signal processing.
Deriving the DFT from the DTFT Truncating the Time-domain Signal
The DTFT usually cannot be computed exactly because the sum in equation (1) is infinite. However, the DTFT may be approximately computed by truncating the sum to a finite window. Let w(n) be a rectangular window of length N:
DSP LABORATORY
93
1 w(n) = 0
0 n N 1 else
(5)
(6)
X tr (e ) =
jw
x
n = N 1 n =0
tr
(n)e jwn
(7 ) (8)
= x(n)e jwn
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 for k = 0, 1, . . . (N - 1) in (8), we find that (9)
X tr (e )
jw
w=
2k N
x
n = j
tr
(n)e jwn
w=
2k N
= x ( n )e
n =0
N 1
2k n N
= 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 discrete-time frequency variable and the continuoustime frequency variable is w = T , the DFT frequencies correspond to continuous-time frequencies
k =
DSP LABORATORY
2k NT
(11)
94
Illustrating Example:
Consider a band-limited continuous signal xc(t) such that Xc(j)=0 for || 2 (2500). Suppose that we will use an ideal anti-aliasing filter H(j) and the sampling rate for the A/D converter is fs=5000 samples/sec. If we want the DFT samples XN(k) to be equivalent to samples of Xc(j) that are at most (210) rad/sec or 10 Hz apart, what is the minimum value that we must use for the DFT size N ? From equation 11, we see that adjacent samples in the DFT correspond to continuous-time frequencies separated by 2 /NT. Therefore, we require that
2 20 NT
Which implies that N 500 Satisfies the condition. Then in MATLAB, we use N =512 for an equivalent continuous-time frequency spacing of =2 (5000/512) rad/sec.
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 non-truncated signal). 3. Truncate the signal x(n) using a window of size N = 20 and then use DFT.m to compute Xtr(ejw). Make sure that the plot contains a least 512 points. Hint: Use the command [X,w] = DFT(x,512). 4. Plot the magnitude of Xtr(ejw).
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 for-loops for n and k, and computing the exponentials as they appear. Note: In Matlab, j may be computed with the command j=sqrt(-1). If you use j =
b. Test your routine DFTsum by computing XN(k) for each of the following cases: 1. x(n) = (n) for N = 10. 2. x(n) = 1 for N = 10. 3. x(n) = ej2n/10 for N = 10. 4. x(n) = cos(2n/10) for N = 10. c. Plot the magnitude of each of the DFTs. In addition, derive simple closed-form analytical expressions for the DFT (not the DTFT!) of each signal.
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 time-domain signal. Use IDFTsum to invert each of the DFTs computed in the previous problem. Plot the magnitudes of the inverted DFTs, and verify that those time-domain signals match the original ones. Use abs(x) to eliminate any imaginary parts which roundoff error may produce.
INLAB REPORT:
1. Submit the listing of your code for IDFTsum. 2. Submit the four time-domain 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,.., N-1]
However, the frequencies should also lie in the range from - to . Therefore, if w then it should be set to w-2. An easy way of making this change in Matlab is w(w>=pi) = w(w>=pi)-2*pi. The resulting vectors X and w are correct, but out of order. To reorder them, we must swap the first and second halves of the vectors. Fortunately, Matlab provides a function specifically for this purpose, called fftshift.
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 infinite-duration signal x(n) =
sin(0.1n) 0
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).
Another important point that should be mentioned here, MATLAB also includes functions for the two-dimensional FFT and its inverse, fft2 and ifft2. These functions are useful for two-dimensional signal or image processing. The goertzel function, which is another algorithm to compute the DFT, also is included in MATLAB DSP Toolbox. This function is efficient for computing the DFT of a portion of a long signal. It is sometimes convenient to rearrange the output of the fft or fft2 function so the zero frequency component is at the center of the sequence. The MATLAB function fftshift moves the zero frequency component to the center of a vector or matrix.
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