Sei sulla pagina 1di 188

JANUARY 3, 2014

DIGITAL SIGNAL PROCESSING


LAB MANUAL

DEPARTMENT OF ELECGTRICAL ENGINEERING


SCHOOL OF ENGINEERING
UNIVERSITY OF MANAGEMENT AND TECHNOLOGY
LAHORE
LIST OF LABS
1 Getting Started with MATLAB for Digital Signal Processing
2 Discrete Time Signals and Systems
3 Z-transform
4 Discrete Time Fourier Transform (DTFT)
5 Frequency Analysis of Signals and Systems
6 Discrete Fourier Transform (DFT) using an Audio Example and Power
spectrum of an Audio Signal
7 Introduction to DSP Starter Kit (DSK) TMS320C6713 DSP Kit and Code
Composer Studio
8 Simple Audio Loop back on TMS320C6713 by programming Audio Codec
AIC23
9 Effects of Sampling and Aliasing
10 Effects of Quantization
11 Signal Reconstruction using sinc, ZOH and FOH
12 Signal Reconstruction using analog Low Pass filters
13 Design of FIR Filter using FDATool and FVTool
14 Design of FIR Filter using Windowing and Frequency sampling
15 Design of IIR Filter in MATLAB
16 IIR and FIR Filter Design using DSK 6713

UMT Lahore Page 1


Table of Contents
Lab No.No-1 Getting Started with MATLAB for Digital Signal Processing ............................................... 7
Equipment/Software: ................................................................................................................................ 7
Conclusion:.............................................................................................................................................. 18
Write-Up ................................................................................................................................................. 18
Lab No. 2: Discrete Time signals and Systems........................................................................................ 19
Objective(s): ............................................................................................................................................ 19
Equipment/Software: ............................................................................................................................. 19
Related Topics from the course textbook: Chapter 2 Sec 2.1 to sec 2.4 ............................................... 19
Procedure:............................................................................................................................................... 19
Theoretical Background .......................................................................................................................... 19
LAB TASK ................................................................................................................................................. 21
TASK 1. .................................................................................................................................................... 22
Task-2 ...................................................................................................................................................... 22
TASK 3 ..................................................................................................................................................... 23
LAB ASSIGNMENT ................................................................................................................................... 24
Write-Up ................................................................................................................................................. 24
Lab No: 3 Z-Transform............................................................................................................................... 25
Objective(s): ............................................................................................................................................ 25
Equipment/Software: ............................................................................................................................. 25
Related Topics from the course textbook: Chapter 3 Sec 3.1 and sec 3.2 ............................................. 25
Procedure:............................................................................................................................................... 25
Theoretical Background .......................................................................................................................... 25
TASK1. ..................................................................................................................................................... 27
TASK2. ..................................................................................................................................................... 27
TAK3. ....................................................................................................................................................... 28
TASK4.a: .................................................................................................................................................. 28
TASK4.b: .................................................................................................................................................. 28
LAB ASSIGNMENT ................................................................................................................................... 29
Write-Up ................................................................................................................................................. 29
Lab No: 4 Discrete-Time Fourier Transform ............................................................................................... 30
Objective(s):............................................................................................................................................ 30

UMT Lahore Page 2


Equipment/Software: ............................................................................................................................. 30
Related Topics from the course textbook: Chapter 4 Sec 4.1 and sec 4.2 ............................................. 30
Procedure:............................................................................................................................................... 30
Theoretical Background: ......................................................................................................................... 30
Task-1:..................................................................................................................................................... 31
Task-2:..................................................................................................................................................... 32
TASK-3: .................................................................................................................................................... 33
Task-4:..................................................................................................................................................... 34
Lab Assignment ....................................................................................................................................... 35
Write-Up ................................................................................................................................................. 36
Lab N0: 5 Frequency Analysis of Signals and Systems ............................................................................. 37
Objective(s):............................................................................................................................................ 37
Equipment/Software: ............................................................................................................................. 37
Related Topics from the course textbook: Chapter 4 Sec 4.2 and 4.3.................................................... 37
Procedure:............................................................................................................................................... 37
Theoretical Background: ......................................................................................................................... 37
Properties of DTFT .................................................................................................................................. 38
Task-1 ...................................................................................................................................................... 38
Task-2:..................................................................................................................................................... 39
Task-3 ...................................................................................................................................................... 40
TASK-4: .................................................................................................................................................... 40
Lab Assignment ....................................................................................................................................... 42
Write-Up ................................................................................................................................................. 42
Lab No: 6 Discrete Fourier Transform (DFT) using an Audio Example and Audio Power spectrum ..... 43
Objective(s): ............................................................................................................................................ 43
Equipment/Software: ............................................................................................................................. 43
Related Topics from the course textbook: Chapter 7 Sec 7.1 and sec 7.2 ............................................. 43
Procedure:............................................................................................................................................... 43
Theoretical Background .......................................................................................................................... 43
Task-1 ...................................................................................................................................................... 44
Task-2 ...................................................................................................................................................... 46
Lab Assignment ....................................................................................................................................... 47
Write-Up ................................................................................................................................................. 47

UMT Lahore Page 3


Lab No 7 Introduction to DSP Starter Kit (DSK) TMS320C6713 DSP Kit and Code Composer Studio
(CCS) .......................................................................................................................................................... 48
Objectives ............................................................................................................................................... 48
Equipment/Software: .............................................................................................................................. 48
Task-1 ...................................................................................................................................................... 56
Task-2 ...................................................................................................................................................... 62
TASK-3 ..................................................................................................................................................... 65
Task-4:..................................................................................................................................................... 69
Task-5:..................................................................................................................................................... 71
Lab No 8 Simple Audio Loop back on TMS320C6713 by programming Audio Codec AIC23................. 74
Equipment/Software: .............................................................................................................................. 74
Task-1 ...................................................................................................................................................... 75
TASK-2 ..................................................................................................................................................... 82
TASK-3 ..................................................................................................................................................... 83
Lab No-9: Sampling Process and Study of Aliasing.................................................................................. 84
Objective(s): ............................................................................................................................................ 84
Equipment/Software: ............................................................................................................................. 84
Related Topics from the course textbook: Chapter 6 Sec 6.1 ................................................................ 84
Theoretical Background: ......................................................................................................................... 84
Task-1:..................................................................................................................................................... 85
Task-2:Analysis........................................................................................................................................ 86
Task-3:..................................................................................................................................................... 88
Lab No-10: Quantization Effects for Digitized Sound................................................................................. 92
Objective(s): ............................................................................................................................................ 92
Equipment/Software: ............................................................................................................................. 92
Related Topics from the course textbook: Chapter 6 Sec 6.3 ................................................................ 92
Equipment/Procedure: ........................................................................................................................... 92
Theoretical Background: ......................................................................................................................... 92
Task-1:..................................................................................................................................................... 93
Task-2 ...................................................................................................................................................... 97
Task-3:..................................................................................................................................................... 99
Write-up.................................................................................................................................................. 99
Lab No.11 Reconstruction of analog signal.............................................................................................. 100

UMT Lahore Page 4


Objective(s): .......................................................................................................................................... 100
Equipment/Software: ........................................................................................................................... 100
Related Topics from the course textbook: Chapter 6 Sec 6.4 and sec 6.5 ........................................... 100
Theoretical Background ........................................................................................................................ 100
Task-1:................................................................................................................................................... 105
Task-2:................................................................................................................................................... 107
Task-3:................................................................................................................................................... 109
Lab No.12 Reconstruction using Analog Low-Pass Filter........................................................................ 111
Objective(s): .......................................................................................................................................... 111
Equipment/Software: ........................................................................................................................... 111
Related Topics from the course textbook: Chapter 6 Sec 6.4 .............................................................. 111
Theoretical Background ........................................................................................................................ 111
Task-1:................................................................................................................................................... 112
Task-2 .................................................................................................................................................... 114
Write-Up ............................................................................................................................................... 120
Lab No 13 Design of FIR Filter by Windowing and Frequency Sampling ................................................ 121
Objective(s): .......................................................................................................................................... 121
Equipment/Software: ........................................................................................................................... 121
Required Files:....................................................................................................................................... 121
Theoretical Background ........................................................................................................................ 121
Task-1:................................................................................................................................................... 123
Task-2 .................................................................................................................................................... 130
Task-3 .................................................................................................................................................... 132
Task-4 .................................................................................................................................................... 135
Lab No-14: Filter Design and Analysis using FDATool and FVTool..................................................... 137
Objective(s): .......................................................................................................................................... 137
Equipment/Software: ........................................................................................................................... 137
Theoretical Background ........................................................................................................................ 137
Task 1 .................................................................................................................................................... 138
Task 2 .................................................................................................................................................... 138
Task-3:................................................................................................................................................... 147
Task 4: ................................................................................................................................................... 147
Lab No 15 Design of IIR Filter in MATLAB ........................................................................................... 148

UMT Lahore Page 5


Objective(s): .......................................................................................................................................... 148
Equipment/Software: ........................................................................................................................... 148
Theoretical Background ........................................................................................................................ 148
Task-1 .................................................................................................................................................... 150
Task-2:................................................................................................................................................... 152
Task-3 .................................................................................................................................................... 154
Task-4 .................................................................................................................................................... 157
Lab No 16 IIR and FIR Filter design using DSK 6713............................................................................. 159

UMT Lahore Page 6


Lab No.No-1 Getting Started with MATLAB for Digital
Signal Processing
Objective(s):
To familiarize students with MATLAB software and general functions
Write a MATLAB program (. M file)
Equipment/Software: A PC running Windows OS/ MATLAB with SIMULINK installed
Required Output Files for this lab: .m files for various tasks
Reference Book: Digital Signal Processing Principles,Algorithms and Applications 4TH Edition
John G Proakis, Dimitris G. Manolakis
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the next lab
5. Save your files for
future usage

MATLAB: MATLAB is a software package for high performance numerical computation and
visualization provides an interactive environment with hundreds of built in functions for
technical computation, graphics and animation. The MATLAB name stands for MATrix
Laboratory produced by Mathworks Inc., USA.

At its core ,MATLAB is essentially a set (a toolbox) of routines (called m files or mex
files) that sit on your computer and a window that allows you to create new variables with
names (e.g. voltage and time) and process those variables with any of those routines (e.g. plot
voltage against time, find the largest voltage, etc.).

MATLAB Windows: MATLAB works with through three basic windows.


Command Window: This is the main window. It is characterized by MATLAB command
prompt
>> when you launch the application program MATLAB puts you in this window all commands
including those for user-written programs ,are typed in this window at the MATLAB prompt.

UMT Lahore Page 7


Graphics window: the output of all graphics commands typed in the command window are
flushed to the graphics or figure window, a separate gray window with white background
color the user can create as many windows as the system memory will allow.

Edit window: This is where you write edit, create and save your own programs in files called
M files.

Input-output: MATLAB supports interactive computation taking the input from the screen and
flushing, the output to the screen. In addition it can read input files and write output files.

Data Type: The fundamental data type in MATLAB is the array. It encompasses several
distinct data objects- integers, real numbers, matrices, character strings, structures and cells.
There is no need to declare variables as real or complex, MATLAB automatically sets the
variable to be real.
Dimensioning: Dimensioning is automatic in MATLAB. No dimension statements are required
for vectors or arrays. We can find the dimensions of an existing matrix or a vector with the size
and length commands.

Where to work in MATLAB?

All programs and commands can be entered either in the

a) Command window.
b) As an M file using Matlab editor.

UMT Lahore Page 8


Note: Save all M files in the folder 'work' in the current directory. Otherwise you have to locate
the file during compiling. Typing quit in the command prompt >> quit, will close MATLAB
Development Environment.

Basic commands in Matlab

1. T = 0:1:10
This instruction indicates a vector T which has initial value 0 and final value 10 with an
increment of 1
Therefore T = [0 1 2 3 4 5 6 7 8 9 10]

2. F= 20:1:100
Therefore F = [20 21 22 23 24 100]

3. T= 0: 1/pi: 1
Therefore T= [0, 0.3183, 0.6366, 0.9549]

4. zeros (1, 3)
The above instruction creates a vector of one row and three columns whose values are zero
Output= [0 0 0]

5. zeros (2,4)
Output =
0000
0000

6. ones (5,2)
The above instruction creates a vector of five rows and two columns
ans =

1 1
1 1
1 1
1 1
1 1
7 a = [ 1 2 3]

a=

1 2 3

b = [4 5 6]

UMT Lahore Page 9


b=

4 5 6

a.*b

ans =

4 10 18
8. If C= [2 2 2]
b.*C results in [8 10 12]
9. plot (t, x)
If x = [6 7 8 9]
t = [1 2 3 4]
This instruction will display a figure window which indicates the plot of x versus t.

Graphing functions MATLAB command

Label the horizontal axis. xlabel('text')

Label the vertical axis. ylabel('text')

Attach a title to the plot. title('text')

Change the limits on the x and y axis. axis([xmin xmax ymin ymax])

"Keep plotting in the same window." hold on

Turn off the "keep-plotting-in-the-same-window-command". hold off

10. stem (t,x) :-


This instruction will display a figure window as shown

UMT Lahore Page 10


11. Subplot: This function divides the figure window into rows and columns.
Subplot (2 2 1) divides the figure window into 2 rows and 2 columns 1 represent number of the
figure

12. Conv
Syntax: w = conv(u,v)

Description: w = conv(u,v) convolves


vectors u and v. Algebraically, convolution
is the same operation as multiplying the
polynomials whose coefficients are the
elements of u and v.

13. Disp
Syntax: disp(X)

Description: disp(X) displays an array, without printing the array name. If X contains a text
string, the string is displayed. Another way to display an array on the screen is to type its name,

UMT Lahore Page 11


but this prints a leading "X=," which is not always desirable. Note that disp does not display
empty arrays.

14. xlabel
Syntax: xlabel('string')

Description: xlabel('string') labels the x-axis of the current axes.

15. ylabel
Syntax : ylabel('string')

Description: ylabel('string') labels the y-axis of the current axes.

16. Title
Syntax : title('string')

Description: title('string') outputs the string at the top and in the center of the current axes.

17. grid on
Syntax : grid on

Description: grid on adds major grid lines to the current axes.

18. FFT
FFT(X) is the discrete Fast Fourier transform (FFT) of vector X. For matrices, the FFT operation
is applied to each column. For N-D arrays, the FFT operation operates on the first non-singleton
dimension. FFT(X,N) is the N-point FFT, padded with zeros if X has less than N points and
truncated if it has more.

19. ABS
Absolute value.

ABS(X) is the absolute value of the elements of X. When X is complex, ABS(X) is the complex
modulus (magnitude) of the elements of X.

20. ANGLE Phase angle.

ANGLE(H) returns the phase angles, in radians, of a matrix with complex elements.
21. INTERP
Resample data at a higher rate using low-pass interpolation.

UMT Lahore Page 12


Y = INTERP(X,L) re-samples the sequence in vector X at L times the original sample rate. The
resulting re-sampled vector Y is L times longer, LENGTH(Y) = L*LENGTH(X).

22. DECIMATE
Resample data at a lower rate after low-pass filtering.

Y = DECIMATE(X,M) re-samples the sequence in vector X at 1/M times the original sample
rate. The resulting re-sampled vector Y is M times shorter,
i.e., LENGTH(Y) = CEIL(LENGTH(X)/M). By default, DECIMATE filters the data with an 8th
order Chebyshev Type I low-pass filter with cut-off frequency .8*(Fs/2)/R, before re-sampling.

Some important commands in MATLAB


Help List topics on which help is available Help command name provides help on the topic
selected
Demo Runs the demo program
Who Lists variables currently in the workspace
Whos Lists variables currently in the workspace with their size
Clear Clears the workspace, all the variables are removed
Clear x,y,z Clears only variables x,y,z
Quit Quits MATLAB

For More information MATLAB basics please go to APPENDIX-A at the end of this
manual.

MATLAB Code: Generating different continuous time signals

You can now practice with basic MATLAB script writing as shown below. From MATLAB
window go to
File- New-Script this will open Editor Window. Copy the text inside the box

a. Sinusoidal Waveform File name: sine.m


clc;
clear all;
close all;

t = 0 : 0.001 : 5;
f = input ('Enter the value of frequency');
a = input ('Enter the value of amplitude');
y =a*sin(2*pi*f*t);
plot (t,y,'r');
xlabel ('time');
ylabel ('amplitude');
title ('sine wave')

UMT Lahore Page 13


grid on;

Output:
Enter the value of frequency 2
Enter the value of amplitude 5

clc;
clear all;
close all;
t = 0 : 0.001 : 5;
f = input ('Enter the value of frequency');
a = input ('Enter the value of amplitude');
y =a*square(2*pi*f*t);
plot (t,y,'r');
xlabel ('time');
ylabel ('amplitude'); title ('Square wave')
grid on;

b. Square Waveform File name: square_wave.m


Enter the value of frequency 2
Enter the value of amplitude 5

UMT Lahore Page 14


%c. Complex Waveform File name: complex_wave.m
clc;
clear all;
close all;
t = 0 : 0.001 : 5;
f = input ('Enter the value of frequency');
a = input ('Enter the value of amplitude');
y = [exp((-0.2+2*i)*t)];
plot (t,y,'r');
xlabel ('time');
ylabel ('amplitude'); title ('Complex wave')
grid on;

UMT Lahore Page 15


f. Exponential Waveform

clc;
clear all;
close all;

a=0.5;
t=0:0.1:10;

disp('EXPONENTIAL DECAYING SIGNAL');


x=a.^t;

subplot(2,1,1); plot(t,x); xlabel('Time');


ylabel('Amplitude');
title('Exponential Decaying Signal Response');
grid on;
disp('EXPONENTIAL GROWING SIGNAL');
x=a.^-t;

subplot(2,1,2); plot(t,x); xlabel('Time'); ylabel('Amplitude');


title('Exponential Growing Signal Response');
grid on;

UMT Lahore Page 16


G: Noisy signal
clc;
clear all;
close all;
t=0:0.01:50;

% generate the uncorrupted signal


s=2*t.*(0.9.^t);
subplot(3,1,1);
plot(t,s)
title('Uncorrupted sequence');
xlabel('Time index');
ylabel('Amplitude');

% generate the noise signal


subplot(3,1,2);
x=rand(length(t),1);
plot(x); title('Noise');
xlabel('Time index');
ylabel('Amplitude');

% Add noise in signal


subplot(3,1,3);
y=s'+x;
plot(y); title('Noisy signal');
xlabel('Time index');
ylabel('Amplitude');

UMT Lahore Page 17


Conclusion:
Have you realized the power of MATLAB? You can do a lot of things with it. Please refer
to Appendix-A for more options and functions.
What else would you like to do with MATLAB?
Try to find on Google l Signal Processing Toolbox documentation.
Would you like to experiment with your recorded voice and apply DSP concepts on your
digitized sound?
On MATLAB command prompt do the following
>>demo
And watch videos, familiarize with scripts, GUI, visualization

Next lab will be even more exciting.

Write-Up

Write down a paragraph of your understanding developed in this Lab.

UMT Lahore Page 18


Lab No. 2: Discrete Time signals and Systems
Objective(s): To develop a good understanding of Discrete time signal and system.
Equipment/Software: A PC running Windows OS/ MATLAB with SIMULINK installed
Required Output Files for this lab: .m files for various tasks
Background: Familiarity with MATLAB
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH Edition
John G Proakis, Dimitris G. Manolakis
Related Topics from the course textbook: Chapter 2 Sec 2.1 to sec 2.4
Students responsibilities in this lab
1. Write MATLAB 2. Generate all the
script (.m file) MATLAB code
3. Do all the tasks 4. Submit report
write-up for
previous lab at the
start of the next lab
5. Save your files for 6. Show your work to
future usage lab instructor

Procedure:
Open MATLAB
Open new M-file
Type the program
Save in current directory
Compile and Run the program
For the output see command window\ Figure window

Theoretical Background
CONTINUOUS-TIME SYSTEM
A system in which continuous-time signals are applied and results in continuous-time output,
such a system has ( ) ( ) as input and output respectively.
DISCRETE-TIME SYSTEM
A discrete-time system is described as an operator [ . ] that takes a sequence x(n) called
excitation and transforms it into another sequence y(n) called response. i.e
( ) = [ ( )] (1)
CLASSIFICATION:
LINEAR SYSTEM
A discrete system [ . ] is a linear if and only if L[ . ] satisfies the principle of superposition as
shown in Eq. 2.

UMT Lahore Page 19


[ ( )+ ( )] = [ ( )] + [ ( )], , , ( ), ( )
(2)
The output ( ) of a linear system to an arbitrary input ( ) is given by

( ) = [ ( )] = [ ( ) ( ) = ( ) ( )
(3)

( ) is called the response of linear system , called the impulse response.


LINEAR TIME-INVARIANT (LTI) SYSTEM

( ) [.] ( ) ( )

( ) ( ) [.] ( )


(4)
( )= [ ( )] = ( ) ( )

Hence we can say that LTI system is completely characterized in the time domain by the impulse
response h(n) as shown below.

( ) ( ) ( )= ( ) ( )
STABILITY
A system is said to be bounded-input boundedoutput (BIBO) stable if every bounded input
produces a bounded output.
| ( )| < | ( )| <, ,
Note: An LTI system is BIBO stable if and only if its impulse response is absolutely summable.

(5)
| ( )| <

CAUSALITY
A system is said to be causal if the output doesnt depend on the future values of the input. An
LTI system is causal if and only if the impulse response

( )= , >0 (6)

An LTI discrete system can also be described by a linear constant coefficient difference equation
of the form

(7)
( ) = ( ),

UMT Lahore Page 20


aN 0, then the difference equation is of order N.
In practice this equation is computed forward in time, from n = to n = . Therefore
another form of the equation is

(8)
( )= ( ) ( )

Solution to this problem can be obtained in the form


( )= ( )+ ( ) (9)

The homogeneous part of the solution, Yh(n) , is given by

( )= (10)

Where zk , k= 1,. N, are N roots (also called natural frequencies) of the characteristic
equation.

(11)

This characteristic equation is important in determining the stability of systems. If roots zk


satisfy the condition.

|zk| < 1, = 1, . . ,

LAB TASK
Note: make m-file, show functions plot, xlabel, ylabel, hold, stem and observe the output and
show to the instructor, see MATLAB help.
A routine called the FILTER is available to solve difference equations numerically, given the
input and the difference equation coefficients. This routine is invoked by
y = filter (b, a, x)
Where
B = [b0,b1,b2, bM]; a=[a0,a1,a2,.aN];
X is input sequence array. Y output has the same length as input x. one must ensure that
coefficient a0 not be zero.
y(n) y(n 1) + 0.9(n 2) = x(n), n
Calculate and plot the impulse response h(n) at n= -20, ., 100.
Calculate and plot the unit step response s(n) at n= -20, ., 100.

UMT Lahore Page 21


Is the system specified by h(n) stable?

TASK 1. MATLAB SCRIPT FOR IMPULSE RESPONSE

>> b = [1]; a = [1, -1, 0.9]; n = [-20:120];


>> x= impseq(0, -20, 120); n = [-20:120];
>> h=filter(b,a,x);
>> subplot(2,1,1); stem(n,h);
>> title(Impulse Response); xlabel(n); ylabel(h(n))

Task-2
MATLAB script for step response

>> x = stepseq(0,-20,120); s = filter(b,a,x);


>> subplot(2,1,2); stem(n,s)
>> title(Step Response); xlabel(n); ylabel(s(n))

Note: Impulse function is provided as below. Figure out the step function on your own. Also try
to use builtin impz function in matlab.

UMT Lahore Page 22


function [x,n] = impseq(n0,n1,n2)
% Generates x(n) = delta(n-n0); n1 <= n <= n2
% ----------------------------------------------
% [x,n] = impseq(n0,n1,n2)
%
n = [n1:n2]; x = [(n-n0) == 0];

To determine the stability of the system, we have to determine h(n) for all n. we can use the plot
of impulse response to observe that h(n) is practically zero for n > 120. Hence the sum |h(n) |
can be determined from MATLAB using.
sum(abs(h))
ans =14.8785
This implies that the system is stable. An alternate approach is to use the matlab stability
condition using MATLABs root function.
>>z = roots(a); magz = abs(z)
magz = 0.9487
0.9487
Since the magnitudes of both roots are less than one, the system is stable.

TASK 3 Computing the Output of a system

The input sequence is of finite duration ( ) = ( ) ( 10) while the impulse response
is of infinite duration ( ) = (0.9) ( ). Determine ( ) = ( ) ( ).

Solution
If the LTI system, given by the impulse response h(n), can be described by a difference equation,
then y(n) can be obtained from the filter function. From the ( ) expression
0. ( 1) = 0.9(0.9) ( 1)
= (0.9) ( 1)
or
( ) 0.9 ( 1) = (0.9) ( ) (0.9) ( 1)
= (0.9) ( ( ) ( 1) )
= (0.9) ( )
= ( )

The last step follows from the fact that ( ) is nonzero only at n = 0. By definition ( ) is the
output of an LTI system when the input is ( ). Hence substituting ( ) for ( ) and ( )
for ( ), the difference equation is ( ) 0.9 ( 1) = ( ).

UMT Lahore Page 23


MATLAB Implementation

>> b = [1]; a = [1,-0.9];


>> n = -5:50; x = stepseq(0,-5,50) - stepseq(10,-5,50);
>> y = filter(b,a,x);
>> subplot(2,1,2); stem(n,y); title(Output sequence)
>> xlabel(n); ylabel(y(n)); axis([-5,50,-0.5,8])

LAB ASSIGNMENT

P1. A particular linear and time-invarient system is described by the difference equations

y(n) 0.5y(n 1) + 0.25y(n 2) = x(n) + 2x(n 1) + x(n 3)


Determine the stability of the system.
Determine and plot the impulse response of the system over 0 n 100. Determine the
stability from this impulse response.

P2. Let ( ) = ( . ) ( ) .
a. Determine ( ) ( ) analytically.
b. Using the filter function, determine the first 50 samples of ( ) ( ).

P3. A simple digital differentiator is given by

y(n) = x(n) x(n 1)


This computes a backward first-order difference of the input sequence. Implement this
differentiator on the following sequence and plot the results.
x(n) = 5[u(n) u(n 20)] rectangle
x(n) = n u(n) u(n 10) + (20 n)[u(n 10) u(n 20)]: a triangular pulse
x(n) = sin(n/25)[u(n) u(n 100)]

Write-Up

Write down a paragraph of your understanding developed in this Lab.

UMT Lahore Page 24


Lab No: 3 Z-Transform
Objective(s): Study & implement the useful properties of Z-Transform using Matlab
Equipment/Software: A PC running Windows OS/ MATLAB with SIMULINK installed
Required Output Files for this lab: .m files for various tasks
Background: Familiarity with MATLAB
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH Edition
John G Proakis, Dimitris G. Manolakis

Related Topics from the course textbook: Chapter 3 Sec 3.1 and sec 3.2
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor

Procedure:
Open MATLAB
Open new M-file
Type the program
Save in current directory
Compile and Run the program
For the output see command window\ Figure window

Theoretical Background
Just as the Fourier transform forms the basis of signal analysis, the z-transform forms the basis of
system analysis. If x[n] is a discrete signal, its z-transform X(z) is given by:

( ) = [ ( )] = ( ) Rx < |z| < +



Where z is a complex variable. The set of z values for which X(z) exists is called the region of
convergence (ROC) is given by

PROPERTIES OF THE Z-TRANSFORM

LINEARITY
[ ( )+ ( )] = ( )+ ( )]; :

UMT Lahore Page 25


SAMPLE SHIFTING
[ ( )] = ( ),

Frequency shifting
[ ( )] = =;
| |

FOLDING
[ ( )] = =;

COMPLEX CONJUGATION
[ ( )] = ( );

DIFFERENTIATION IN THE Z- DOMAIN

[ ( )]
( )
=

MULTIPLICATION
[ ( ) ( )]

= ( ) ( ) ;

CONVOLUTION

[ ( ) ( )] = ( ) ( );

INVERSION OF THE Z-TRANSFORM

( ) [ ( )]

= ( )

UMT Lahore Page 26


Where C is a counterclockwise contour encircling the origin and lying in the ROC.
The integral from is a complicated procedure. The most practical approach is to use the partial
fraction expansion method. The z-transform , however must be a rational function.

+ + ..+
( )= , < | |
+ + ,+
< +

Performing a partial fraction expansion on the proper rational part of X(z) to obtain.
+ + ..+
( )= +
+ + ,+
Proper rational part polynomial part MN

( )= +

TASK1. Let ( ) = ( ), < | | , find x(z) by definition also find out ROC.
Solution:

a 1 a
X(z) = a z = = if <1
z 1 az z
= , |z| > 1: |a| < <
( )
=X(z) ( )
=
B(z) is called the zeros of x(z)and A(z)is called the poles of X(z).

TASK2. Let ( ) = + + and ( )= + + + .


Determine ( )= ( ) ( ).

MATLAB SCRIPT:

x1 =[2,3,4];
x2 =[3,4,5,6];
x3 =conv(x1,x2)

X3 = 6 17 34 43 38 24

UMT Lahore Page 27


Hence

x3(z) = 6 + 17z + 34z + 43z + 38z + 24z

TAK3. Similarly in MATLAB [p,r]=deconv(b,a) computes the result of dividing b by a in


a polynomial part P , and a remainder r.
x3 =[6,17,34,43,38,24];
x1=[2,3,4];
[x2,r] =deconv(x3,x1);
X2 =

3 4 5 6

r=

0 0 0 0

TASK4.a: In MATLAB fucntion residuez is available to compute the residue part and
direct (or polynomial) terms of a rational function in .
z
X(Z) =
3z 4z + 1
Solution.
First rearrange X(Z) so that it is a function in ascending powers of z .
z
X(Z) =
3 4z + z

b=[0,1];
a=[3,-4,1];
[R,p,C]=residuez[b,a];

R =
0.5000
-0.5000
P =
1.0000
0.3333

So,
0.5 0.5
X(Z) =
1z 1 0.333z
TASK4.b: Similarly to convert back to the rational function form

UMT Lahore Page 28


[b,a]=residuez[R,p,C];
b =
0.0000
0.3333
a =
1.0000
-1.3333
0.3333
So that
1
0 + 3z z z
x(z) = = =
4 1 3 4z + 1z 3z 4z + 1
1 3z + 3z
Now applying the same procedure determine inverse z-transform of
1
x(z) =
(1 0.9z ) (1 + 0.9z )
Hint: use a=poly(0.9,0.9,-0.9) to determine polynimials of a. then apply residuez method

LAB ASSIGNMENT

P1. Determine the inverse Z-transform of


1 + 0.42z
X(z) =
1 0.82z + 0.64z
So that resulting response is causal and contains no complex numbes.
P2. A causal LTI system is stable if and only if the system function ( ) has all its poles
inside the unit circle. So a causal LTI system is descirbed bye the difference equation as

y(n) = 0.8y(n 2) + x(n) x(n 2)


Determine
(a) The system function H(z) (b) The unit impulse response h(n) (c) The step response u(n)

Write-Up

Write down a paragraph of your understanding developed in this Lab.

UMT Lahore Page 29


Lab No: 4 Discrete-Time Fourier Transform
Objective(s): To develop the basic understanding of DTFT by Matlab implementation
Equipment/Software: A PC running Windows OS/ MATLAB with SIMULINK installed
Required Output Files for this lab: .m files for various tasks
Background: Familiarity with MATLAB
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH
Edition John G Proakis, Dimitris G. Manolakis
Related Topics from the course textbook: Chapter 4 Sec 4.1 and sec 4.2
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor

Procedure:
Open MATLAB and open new M-file
Type the program
Save in current directory
Compile and Run the program
For the output see command window\ Figure window

Theoretical Background:
If x(t) is a periodic function with period T, then x(t) may be written as the infinite Fourier series,
( )= + cos + sin (1)
where
= + ( ) cos dt and = + ( ) sin dt
we can write the complex form of the Fourier series as

x(t) = cn with cn = ( ) (2)

n = 0, 1, 2.... We can then extend the ideas of frequency decomposition to non-periodic signals
via the Fourier Transform so that the equivalent of the above discrete equations becomes

X() = ( ) dt x(t) = X() d

UMT Lahore Page 30


we can find an invertible discrete transform which approximates the Fourier series as
follows:


Xk = ( ) k = 0, 1, 2, . . . , N 1 (3)

( )= Xk k = 0, 1, 2, . . . , N 1 (4)

These equations are known as the Discrete Fourier Transform (DFT) and Inverse Discrete
Fourier Transform (IDFT) respectively.
Matlab Implementation:
If x(n) is of infinite duration, then MATLAB cannot be used directly to compute X(ejw) from
x(n). However, we can use it to evaluate the expression X(ejw) over [0, ] frequencies and then
plot its magnitude and angle (or real and imaginary parts).

Task-1: Evaluate X(ejw) in Example 1 at 501 equispaced points between [0,] and plot its
magnitude, angle, real, and imaginary parts.

Matlab Script
>> w=[0:1:500]*pi/500; % [0,pi] axis divided into 501 points.
>> X= exp(j*w) ./ (exp(j*w)- 0.5*ones(1,501));
>> magX = abs(X); angX = angle(X);
>> realX = real(X); imagX = imag(X);
>> subplot(2,2,1); plot(w/pi, magX); grid
>> xlabel('frequency in pi units'); title('Magnitude Part'); ylabel('Magnitude')
>> subplot(2,2,3); plot(w/pi, angX); grid
>> xlabel('frequency in pi units'); title('Angle Part'); ylabel('Radians')
>> subplot(2,2,2); plot(w/pi, realX); grid
>> xlabel('frequency in pi units'); title('Real Part'); ylabel('Real')
>> subplot(2,2,4); plot(w/pi, imagX); grid
>> xlabel('frequency in pi units'); title('Imaginary Part'); ylabel('Imaginary')

UMT Lahore Page 31


Task-2: Evaluate X(ejw) in Example 2 at 501 equispaced points between [0,] and plot its
magnitude, angle, real, and imaginary parts.

Matlab Script
>> n = -1:3; x = 1:5;
>> k = 0:500; w = (pi/500)*k;
>> X = x*(exp(-j*pi/500)).^ (n'*k);
>> magX = abs(X); angX = angle(X);
>> realX = real(X); imagX = imag(X);
>> subplot(2,2,1); plot(k/500, magX); grid
>> xlabel('frequency in pi units'); title('Magnitude Part'); ylabel('Magnitude')
>> subplot(2,2,3); plot(k/500, angX/pi); grid
>> xlabel('frequency in pi units'); title('Angle Part'); ylabel('Radians')
>> subplot(2,2,2); plot(k/500, realX); grid
>> xlabel('frequency in pi units'); title('Real Part'); ylabel('Real')
>> subplot(2,2,4); plot(k/500, imagX); grid
>> xlabel('frequency in pi units'); title('Imaginary Part'); ylabel('Imaginary')

UMT Lahore Page 32


TASK-3: Let x(n) = (0.9ej/3), 0 n 10. Determine X (ej) and investigate its periodicity.
Solution:
Since x(n) is complex-valued, it satisfies only the periodicity property. Therefore, it is uniquely
defined over one period of 2. However, we will evaluate and plot it at 401 frequencies over two
periods between [-2, 2] to observe its periodicity.

Matlab Script
>> n = 0:10; x = (0.9*exp(j*pi/3)).^n;
>> k = -200:200; w = (pi/100)*k;
>>X = x*(exp(-j*pi/100)).^ (n'*k);
>> magX = abs(X); angX = angle(X);
>> subplot(2,1,1); plot(w/pi, magX); grid
>> xlabel('frequency in pi units'); title('Magnitude Part'); ylabel('Magnitude')
>> subplot(2,1,2); plot(w/pi, angX/pi); grid
>> xlabel('frequency in pi units'); title('Angle Part'); ylabel('Radians/pi')

UMT Lahore Page 33


From the plots we observe that X (ej) is periodic in but is not conjugate-symmetric.

Task-4: Let x(n) = (-0.9)n , -10 n 10. Investigate the conjugate-symmetry property of its
discrete-time Fourier transform.
Matlab Script
>> subplot(1,1,1)
>> n = -5:5; x = (-0.9).^n;
>> k = -200:200; w = (pi/100)*k;
>> X = x*(exp(-j*pi/100)).^ (n'*k);
>> magX = abs(X); angX = angle(X);
>> subplot(2,1,1); plot(w/pi, magX); grid
>> axis([-2,2,0,15])
>> xlabel('frequency in pi units'); title('Magnitude Part'); ylabel('Magnitude')
>> subplot(2,1,2); plot(w/pi, angX/pi); grid
>> axis([-2,2,-1,1])
>> xlabel('frequency in pi units'); title('Angle Part'); ylabel('radians/pi')

UMT Lahore Page 34


From the plots we observe that X (ej) is not only periodic in but is also conjugate-symmetric.
Therefore for real sequences we will plot their Fourier transform magnitude and angle responses
from 0 to .

Lab Assignment
P1.
Write a MATLAB function to compute the DTFT of a finite-duration sequence. The format of
the function should be

function [X] = dtft(x,n,w)


% Computes Discrete-time Fourier Transform
% [X] = dtft(x.n,w)
% X = DTFT values computed at w frequencies
% x = finite duration sequence over n
% n = sample position vector
% Y frequency location vector

Use this function to compute the DTFT in the Task-1 and II.
P2.
For each of the following sequences, determine the DTFT X(ejw). Plot the magnitude and angle
of X(ejw).
x(n) = 3(0.9)nu(n)
x(n) = { 4, 3, 2, 1, -1,-2, -3, -4}

P3.
Repeat Problem II for the following sequence.
x(n) = 5(-0.9)n cos (0.1n) u(n)

UMT Lahore Page 35


P4.
A symmetric rectangular pulse is given by
1 ,
N (n) =
0
Determine the DTFT for N =5, 15, 25, 100. Scale the DTFT so that X (ej0) = 1. Plot the
normalized DTFT over [-, ]. Study these plots and comment on their behavior as a function of
N.

Write-Up

Write down a paragraph of your understanding developed in this Lab.

UMT Lahore Page 36


Lab N0: 5 Frequency Analysis of Signals and Systems

Objective(s): Analyze the frequency response of DTFT by Matlab implementation


Equipment/Software: A PC running Windows OS/ MATLAB with SIMULINK installed
Required Output Files for this lab: .m files for various tasks
Background: Familiarity with MATLAB
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH
Edition John G Proakis, Dimitris G. Manolakis
Related Topics from the course textbook: Chapter 4 Sec 4.2 and 4.3
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor

Procedure:
Open MATLAB and open new M-file
Type the program
Save in current directory
Compile and Run the program
For the output see command window\ Figure window

Theoretical Background:
If x(n) is absolutely summable, then its discrete-time Fourier transform is given by
[ ( )] = ( )

The inverse discrete-time Fourier transform (IDTFT) of is given by

1
( ) =
2
Provide the plots for the following along with the title of each by matching its response to
Low pass, high pass, band pass or band stop filter. Also include in the title whether the system is
FIR or IIR. The frequency response can be obtained using freqz(num,den). Poles and zero plot is
obtained using zplane(num,den). Comment on the poles and zeros location of each filter.

UMT Lahore Page 37


a. Y[n] = 0.08x[n] + 0.34x [n-1] + 0.34x [n-2] + .34x [n-3] + 0.08x[n]

b = [0.08 0.34 0.34 0.34 0.08];


subplot(2,1,1), freqz(b,1)
subplot(2,1,2), zplane(b,1)

b. Y[n] 1.11y[n-1] + 0.57 y[n-2] = x[n] + 2x[n-1] + x[n-2]

b = [ 1 2 1];
a = [1 -1.11 0.57 ];
figure
subplot(2,1,1), freqz(b,a)
subplot(2,1,2), zplane(b,a)

c. Y[n] = -0.21x[n] -0.17x[n-1] + 0.81x[n-2] -0.17x[n-3] -0.21x[n-4]

b = [-0.21 -0.17 0.81 -0.17 -0.21];


figure
subplot(2,1,1), freqz(b,1)
subplot(2,1,2), zplane(b,1)

d. Y[n] 1.11y[n-1] + 0.57y[n-2] = x[n] 2x[n-1] + x[n-2]

b = [1 -2 1];
a = [ 1 -1.11 0.57];
figure
subplot(2,1,1), freqz(b,a)
subplot(2,1,2), zplane(b,a)

e. Y[n] = -0.35x[n] + 0.2x[n-1] -0.07x[n-2] + 0.20x[n-3] 0.35x[n-4]

b = [-0.35 0.20 -0.07 0.20 -0.35];


figure
subplot(2,1,1), freqz(b,1)
subplot(2,1,2), zplane(b,1)
f. 2y[n] + 1.63y[n-1] + 0.65y[n-2] = x[n] x[n-2]
b = [ 1 0 -1];
a = [2 1.63 0.65];
figure
subplot(2,1,1), freqz(b,a)
subplot(2,1,2), zplane(b,a)

Properties of DTFT
In this part fft(x,n) function will be used to prove some of the Fourier transform properties.

Task-1
Verify the linearity property using real-values finite duration sequences

UMT Lahore Page 38


Solution
Let x1(n) and x2(n) be two random sequences uniformly distributed between [0, 1] over 0 n
10. Then use numerical discrete-time Fourier transform procedure as follows.
Matlab Script
>> x1 = rand(1,11); x2 = rand(1,11); n = 0:10;
>> alpha = 2; beta = 3;
>> k = 0:500; w = (pi/500)*k;
>> X1 = x1 * (exp(-j*pi/500)).^(n'*k); % DTFT of x1
>> X2 = x2 * (exp(-j*pi/500)).^(n'*k); % DTFT of x2
>> x = alpha*x1 + beta*x2; % Linear combination of x1 & x2
>> X = x * (exp(-j*pi/500)).^(n'*k); % DTFT of x
>> % verification
>> X_check = alpha*X1 + beta*X2; % Linear combination of X1 & X2
>> error = max(abs(X-X_check))
error = 7.3241e-015

Since the maximum absolute error between the two Fourier transform arrays is less than 10-14,
the two arrays are identical within the limited numerical precision of MATLAB.

Task-2: Verify the frequency shift property;

Solution: We will use the graphical approach.


Let, x(n) = cos ( n/2), 0 n 100 and y(n) = x( n). exp( n/4)

Matlab Script
>> n = 0:100; x = cos(pi*n/2);
>> k = -100:100; w = (pi/100)*k; % frequency between -pi and +pi
>> X = x * (exp(-j*pi/100)).^(n'*k); % DTFT of x
>> y = exp(j*pi*n/4).*x; % signal multiplied by exp(j*pi*n/4)
>> Y = y * (exp(-j*pi/100)).^(n'*k); % DTFT of y
>> subplot(1,1,1)
>> subplot(2,2,1); plot(w/pi, abs(X)); grid; axis([-1,1,0,60])
>> xlabel('frequency in pi units'); ylabel('Magnitude');
>> title('Magnitude of X')
>> subplot(2,2,2); plot(w/pi, angle(X)/pi); grid; axis([-1,1,-1,1])
>> xlabel('frequency in pi units'); ylabel('radians/pi')
>> title('Angle of X')
>> subplot(2,2,3); plot(w/pi, abs(Y)); grid; axis([-1,1,0,60])
>> xlabel('frequency in pi units'); ylabel('Magnitude')
>> title('Magnitude of Y')
>> subplot(2,2,4); plot(w/pi, angle(Y)/pi); grid; axis([-1,1,-1,1])
>> xlabel('frequency in pi units'); ylabel('radians/pi')

UMT Lahore Page 39


>> title('Angle of Y')

And from plots we observe that X (ej) is indeed shifted /4 in both magnitude and angle.

Task-3
To verify the folding property

Solution: Let x(n) be a random sequence over -5 n 10 uniformly distributed between [0,
1]. The MATLAB verification is as follows.
Matlab Script
>> n = -5:10; x = rand(1,length(n));
>> k = -100:100; w = (pi/100)*k; % frequency between -pi and +pi
>> X = x * (exp(-j*pi/100)).^(n'*k); % DTFT of x
>> % folding propery
>> y = fliplr(x); m = -fliplr(n); % signal folding
>> Y = y * (exp(-j*pi/100)).^(m'*k); % DTFT of y
>> % verification
>> Y_check = fliplr(X); % X(-w)
>> error = max(abs(Y-Y_check)) % Difference

error = 1.8310e-015

TASK-4: Verify the symmetry property of real signals.


Solution

Let
x(n) = sin( n/2), -5 n 10
Then using the evenodd function we can compute the even and odd parts of x(n) and then
evaluate their discrete-time Fourier transforms. We will provide numerical as well as graphical
verification. It is a good exercise to develop a simple MATLAB function to decompose a given
sequence into its even and odd components. This is done in evenodd function.

Matlab Script

UMT Lahore Page 40


>> n = -5:10; x = sin(pi*n/2);
>> k = -100:100; w = (pi/100)*k; % frequency between -pi and +pi
>> X = x * (exp(-j*pi/100)).^(n'*k); % DTFT of x
>> % signal decomposition
>> [xe,xo,m] = evenodd(x,n); % even and odd parts
>> XE = xe * (exp(-j*pi/100)).^(m'*k); % DTFT of xe
>> XO = xo * (exp(-j*pi/100)).^(m'*k); % DTFT of xo
>> XR = real(X); % real part of X
>> error1 = max(abs(XE-XR)) % Difference

error1 = 6.4467e-014

>> XI = imag(X); % imag part of X


>> error2 = max(abs(XO-j*XI)) % Difference

error2 = 6.4712e-014

>> % Graphical verification


>> subplot(1,1,1)
>> subplot(2,2,1); plot(w/pi, XR); grid; axis([-1,1,-2,2])
>> xlabel('frequency in pi units'); ylabel('Re(X)');
>> title('Real part of X')
>> subplot(2,2,2); plot(w/pi, XI); grid; axis([-1,1,-10,10])
>> xlabel('frequency in pi units'); ylabel('Im(X)');
>> title('Imaginary part of X')
>> subplot(2,2,3); plot(w/pi, real(XE)); grid; axis([-1,1,-2,2])
>> xlabel('frequency in pi units'); ylabel('XE');
>> title('Transform of even part')
>> subplot(2,2,4); plot(w/pi, imag(XO)); grid; axis([-1,1,-10,10])
>> xlabel('frequency in pi units'); ylabel('XO');
>> title('Transform of odd part')

function [xe,xo,m] = evenodd(x,n)


% Real signal decomposition into even and odd parts
% -------------------------------------------------
% [xe,xo,m] = evenodd(x,n)
%
if any(imag(x) ~= 0)
error('x is not a real sequence')
end
m = -fliplr(n);
m1 = min([m,n]); m2 = max([m,n]); m = m1:m2;

UMT Lahore Page 41


nm =
n(1) -
m(1);
n1 =

1:length(n);
x1 = zeros(1,length(m));
x1(n1+nm) = x; x = x1;
xe = 0.5*(x + fliplr(x));
xo = 0.5*(x - fliplr(x));

From the plots we observe that the real part of X (ej) (or the imaginary part of X (ej) is equal to
the discrete-time Fourier transform of xe(n) (or xo(n).

Lab Assignment
P1. Verify the time shifting and conjugation property of DTFT using matlab.
P2. Using the frequency-shifting property, show that the DTFT of a sinusoidal pulse
X(n) = cos (on). N (n)
is given by
( ) ( )
X(ej) = [ ]+ [ ]
( ) ( )

where N (n) is the rectangular pulse as given is previous lab. Compute and plot X(ej) for o =
2 and N = 5, 15, 25, 100. Use the plotting interval [- , ]. Comment on your results.

Write-Up
Write down a paragraph of your understanding developed in this Lab.

UMT Lahore Page 42


Lab No: 6 Discrete Fourier Transform (DFT) using an Audio
Example and Audio Power spectrum
Objective(s):
Load an audio file noisy.wav into Matlab. There is a tone added to the speech in this
file. The Objective(s) is to find the frequency of this tone.
Computing the DFT of this signal;
Generating frequency vector in Hz.
Displaying the DFT and observing the frequency of the added tone.
Power spectral density (PSD) of the signal in linear and log scale
Equipment/Software: A PC running Windows OS/ MATLAB with SIMULINK installed
Required Output Files for this lab: .m files for various tasks
Background: Familiarity with MATLAB
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH Edition
John G Proakis, Dimitris G. Manolakis
Related Topics from the course textbook: Chapter 7 Sec 7.1 and sec 7.2
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor

Procedure:
Open MATLAB
Open new M-file
Type the program
Save in current directory
Compile and Run the program
For the output see command window\ Figure window

Theoretical Background:
DF analysis equation is given below

( )= ( )

UMT Lahore Page 43


1 ( )
( )= ( )

Task-1
Generate DFT Spectrum of a noisy signal
Matlab Script
clear all; clc; close all;
[y,Fs,bits] = wavread('noisy.wav');
Ts = 1/Fs;
n = [0:length(y)-1];
t = n.*Ts;
k = n;
Df = Fs./length(y);
F = k.*Df;
Y = fft(y);
magY = abs(Y);
sound(y,Fs);
figure,
subplot(2,1,1);
plot(F,magY);
grid on;
xlim([0 Fs/2]);
xlabel('Frequency (Hz)');
ylabel('DFT Magnitude');
title('Discrete Fourier Transform');
subplot(2,1,2);
plot(F,magY);
grid on;
xlim([0 2000]);
xlabel('Frequency (Hz)');
ylabel('DFT Magnitude');
title('Discrete Fourier Transform');

Audio spectrum of an audio signal

UMT Lahore Page 44


clear all;
[signal,fs,nbits] = wavread('male.wav');% It is windows file
sound(signal)
signal = signal(:,1);% One channel data
signal=signal(1:2048)% just 2048 data points
subplot(121)
stem(signal) % plot your wave file
title('your wave file Your sound')
xlabel('time'),ylabel('magnitude')
subplot(122)
X1=fft(signal(1:128),1024);
f=[0:512]*8000/1024;
plot(f,20*log10(abs(X1(1:513))))
grid on
title('Original Spectrum')
xlabel('Frequency (Hz)'),ylabel('Magnitude in dB')

UMT Lahore Page 45


Task-2
Generate PSD (Power spectral density) of the signal
clc;
clear all;
close all;
t=0:0.01:0.6;
x=sin(2*pi*50*t);
y=x+(2*randn(size(t)));
figure,plot(1000*t(1:50),y(1:50))
title('Signal corrupted with zero mean random noise');
xlabel('time(msec)');
y=fft(y,512);
pyy=y.*conj(y)/512;
f=1000*(0:256)/512;
figure,plot(f,pyy(1:257))
title('frequency content of y');
xlabel('frequency(hz)');

UMT Lahore Page 46


Lab Assignment
Try and remove the tone spikes from the spectra of the noisy signal.
Take Inverse DFT (IFFT) of the modified spectra.
Listen to this new time-domain signal and see if the tone noise is removed.

Write-Up

What is the significance of finding DFT and PSD? How these are different from one
another?
What are different applications of DFT. Go to section 7.3 of your text book
An efficient implementation of DFT is Fast Fourier Transform. Google it and write
a 1-page summary on FFT and its engineering applications.
Discrete Cosine Transform (DCT) is a special form of DFT. Describe briefly what is
DCT. Read sec 7.5 for some details.

UMT Lahore Page 47


Lab No 7 Introduction to DSP Starter Kit (DSK)
TMS320C6713 DSP Kit and Code Composer Studio
(CCS)
Objectives
Familiarize students with the basics of a DSP Processor
Familiarize students with Code Composer Studio (CCS)
Experimenting with LEDs on the DSP Trainer kit
Writing and modifying code in code composer studio
Using DSP/BIOS to schedule blink of LEDs and
1KHz tone :Sine wave generation

The goal of this weeks assignment is simple. First, you are to get your development environment
set up. Second, you are to become familiar with the tools so that you can write your own basic
software and debug it on the DSK. This assignment is the (only!) one where you do not need to
understand absolutely everything about your code. Code examples can be taken as is, and
understood at a basic level.
Equipment/Software:
For most exercises in this laboratory, the following equipment will be needed at every lab station:

Pentium-based computer with CCS version 2.0 or greater installed on it


A C6713 DSK including power supply and parallel printer port cable
Two coaxial cables with an 1/8-inch stereo headphone male jack on one end and two
BNC male connectors (RF connectors) on the other end
A set of speakers or headphones
One coaxial cable with 1/8-inch stereo headphone jacks on both ends
A signal generator
An oscilloscope
Trainer Kit, DSK 6713 from Texas Instruments, headphone, and stereo cables
Required Output Files for this lab: .c files for various tasks
Background: Familiarity with C language (Assuming student has taken a basic course like
Programming Fundamentals)
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH Edition
John G Proakis, Dimitris G. Manolakis

Students responsibilities in this lab


1. Write C code in CCS 2. Do all the tasks
3. Submit report write-up 4. Save your files for
for previous lab at the future usage
start of the lab
5. Show your work to 6. Show your CCS work
your lab instructor and understanding

UMT Lahore Page 48


Watch Training videos: available in your working
directory
1. DSP Kit Tutorial 1A - Quick setup and Test example programs.mp4
2. DSP Kit Tutorial 2A - Quick setup and Test example programs.mp4
3. DSP Kit Tutorial 3A - Quick setup and Test example programs.mp4

Architecture of DSP chips - TMS 320C 6713 DSP Processor


INTRODUCTION TO DSP PROCESSORS:

A signal can be defined as a function that conveys information, generally about the state or behavior
of a physical system. There are two basic types of signals viz. Analog (continuous time signals which
are defined along a continuum of times) and Digital (Discrete-time). Remarkably, under reasonable
constraints, a continuous time signal can be adequately represented by samples, obtaining discrete time
signals. Thus digital signal processing is an ideal choice for anyone who needs the performance
advantage of digital manipulation along with today's analog reality. Hence a processor which is
designed to perform the special operations (digital manipulations) on the digital signal within very less
time can be called as a Digital signal processor. The difference between a DSP processor, conventional
microprocessor and a Microcontroller are listed below.
Microprocessor or General Purpose Processor such as Intel xx86 or Motorola 680xx family
Contains
- Only CPU
-No RAM
-No ROM
-No I/O ports
-No Timer
Microcontroller such as 8051 family
Contains - CPU
- RAM
- ROM
-I/O ports
- Timer
- Interrupt circuitry Some Micro Controllers also contain A/D, D/A and Flash Memory
DSP Processors such as Texas instruments and Analog Devices
Contains - CPU
- RAM
-ROM
- I/O ports
- Timers
Optimized for - fast arithmetic
- Extended precision
- Dual operand fetch
- Zero overhead loop

UMT Lahore Page 49


FEATURES OF A TYPICAL DSP PROCESSOR
Feature Use

Fast-Multiply accumulate Most DSP algorithms, including filtering, transforms, etc.


are multiplication- intensive

Multiple - access memory architecture Many data-intensive DSP operations require reading a
program instruction and multiple data items during each
instruction cycle for best performance
Specialized addressing modes Efficient handling of data arrays and first-in, first-out FIFO
buffers in memory
Specialized program control Efficient control of loops for many iterative DSP
algorithms. Fast interrupt handling for frequent I/O
operations.
On-chip peripherals and I/O On-chip peripherals like A/D converters allow for small
interfaces low cost system designs. Similarly I/O interfaces tailored
for common peripherals allow clean interfaces to off-chip
I/O devices.

Architectural Overview of 6713 DSP Starter Kit (DSK)


The 6713 DSP Starter Kit (DSK) is a low-cost platform which lets customers evaluate and develop
applications for the Texas Instruments C67X DSP family. The primary features of the DSK are:

225 MHz TMS320C6713 Floating Point DSP


AIC23 Stereo Codec
Four Position User DIP Switch and Four User LEDs
On-board Flash and SDRAM
TIs Code Composer Studio development tools are bundled with the 6713 DSK providing the user
with an industrial-strength integrated development environment (IDE) for C and assembly
programming. Code Composer Studio communicates with the DSP using an on-board JTAG
emulator through a USB interface.
Board Tour
The figure below illustrates the main sections of the board:

UMT Lahore Page 50


UMT Lahore Page 51
Functional Block diagram off C6713 DSK

Reference: TMS320C6713 DSK Technical Reference, 506735-0001 Rev. B


November 2003, SPECTRUM DIGITAL, INC. 12502 Exchange Drive, Suite 440
Stafford, TX. 77477

Basic Operation: Installation and Power up


The DSK is designed to work with TIs Code Composer Studio development environment and
ships with a version specifically tailored to work with the board. Code Composer communicates
with the board through the on-board JTAG emulator. To start, follow the instructions in the Quick
Start Guide to install Code Composer.
This process will install all of the necessary development tools, documentation and drivers. After
the install is complete, follow these steps to run Code Composer. The DSK must be fully connected
to launch the DSK version of Code Composer.
1) Connect the included power supply to the DSK.
2) Connect the DSK to your PC with a standard USB cable (also included).
3) Launch Code Composer from its icon on your desktop

Introduction to DSP Processor chips


Digital signal processing, or DSP, is a rapidly growing industry within Electrical and Computer
Engineering. With processing power doubling every 18 months (according to Moores law), the
number of applications suitable for DSP is increasing at a comparable rate. In this course, our aim
is to show how mathematical algorithms for digital signal processing may be encoded for
implementation on programmable hardware. In this first lab, you will become familiar with a
development system for programming DSP hardware. You will study:
Code Composer Studio
TMS320C6713 DSP chip and supporting chip set (DSK) architecture

UMT Lahore Page 52


The C programming language
Hardware and Software
DSP Chip Manufacturers
Many companies produce DSP chips. Some of the more well-known include Agere Systems,
Analog Devices, Motorola, Lucent Technologies, NEC, SGS-Thompson, Conexant, and Texas
Instruments. In this course, we will use DSP chips designed and manufactured by Texas
Instruments (TI). These DSP chips will be interfaced through Code Composer Studio (CCS)
software developed by TI.
Code Composer Studio (CCS)
CCS is a powerful integrated development environment that provides a useful transition between
a high-level (C or assembly) DSP program and an on-board machine language program. CCS
consists of a set of software tools and libraries for developing DSP programs, compiling and
linking them into machine code, and writing them into memory on the DSP chip and on-board
external memory. It also contains diagnostic tools for analyzing and tracing algorithms as they are
being implemented on-board. In this class, we will always use CCS to develop, compile, and link
programs that will be downloaded from a PC to DSP hardware.
TMS320 DSP Chips
In 1983, Texas Instruments released their first generation of DSP chips, the TMS320 single-chip
DSP series. The first generation chips (C1x family) could execute an instruction in a single 200-
nanosecond (ns) instruction cycle. The current generation of TI DSPs includes the C2000, C5000,
and C6000 series, which can run up to 8 32-bit parallel instructions in one 4.44ns instruction cycle,
for an instruction rate of 1.8*109 instructions per second. The C2000, and C5000 series are fixed-
point processors. The C6000 series contains both fixed point and floating-point processors. For
this lab, we will be using the C6713 processor, a member of C67x family of floating-point
processors. The different families in the TMS320 series are targeted at different applications. The
C2000 and C5000 series of chips are primarily used for digital control. They consume very little
power and are used in many portable devices including 3G cell phones, GPS (Global Positioning
System) receivers, portable medical equipment, and digital music players. Due to their low power
consumption (40mW to 160mW of active power), they are very attractive for power sensitive
portable systems. The C6000 series of chips provides both fixed and floating point processors that
are used in systems that require high performance. Since these chips are not as power efficient as
the C5000 series of chips (.5W to 1.4W of active power), they are generally not used in portable
devices.
Instead, the C6000 series of chips is used in high quality digital audio applications, broadband
infrastructure, and digital video/imaging, the latter being associated almost exclusively with the
fixed-point C64x family of processors. When designing a product, the issues of power
consumption, processing power, size, reliability, efficiency, etc. will be a concern. Learning how
to implement basic DSP algorithms on the C6713 will provide you with the tools to execute
complex designs under various constraints in future projects. At one time, assembly language was
preferred for DSP programming. Today, C is the preferred way to code algorithms, and we shall
use it for fixed- and floating-point processing.
DSP Starter Kit (DSK)
The TMS320C6713 DSP chip is very powerful by itself, but for development of programs, a
supporting architecture is required to store programs and data, and bring signals on and off the
board. In order to use this DSP chip in a lab or development environment, a circuit board
containing appropriate components, designed and manufactured by Spectrum Digital, Inc., is
provided. Together, CCS, the DSP chip, and supporting hardware make up the DSP Starter Kit, or
DSK.

UMT Lahore Page 53


In this lab, we will go over the basic components of the DSK and show how software may be
downloaded onto the DSK.
Programming Languages
Assembly language was once the most commonly used programming language for DSP chips
(such as TIs TMS320 series) and microprocessors (such as Motorolas 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. In this course,
we will use assembly code to gain intuition into the structure of digital filtering 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). Most of the programs created in this course will be coded in C. In CCS, the C
compiler has four optimization levels. The highest level of optimization will not achieve the same
level of optimization that programmer-optimized assembly programs will, but TI has done a good
job in making the optimized C compiler produce code that is comparable to programmer-
optimized 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 schedule events and manage 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 requires less time to program with. This will be apparent in future labs when
assembly and linear assembly code are given.
Codec
The codec (coder/decoder) is a chip located on-board the DSK which interfaces the DSP chip to
the analog world, specifically signal generator(s) and either an oscilloscope or stereo headphones.
The codec contains a coder, or analog-to-digital converter (ADC), and a decoder or digital-to-
analog converter (DAC). Both coder and decoder run at sample rates which can be set from 8 KHz
to 96 KHz and support data word lengths of 16b, 20b, 24b, and 32b at the digital interfaces.
C6713 DSP Chip
The C6713 DSP chip is a floating point processor which contains a CPU (Central Processing Unit),
internal memory, enhanced direct memory access (EDMA) controller, and on-chip peripheral
interfaces. These interface include a 32-bit external memory interface (EMIF), four Multi-channel
Buffered Serial Ports (McASP and McBSP), two 32-bit timers, a host port interface (HPI) for high-
speed communication between chips in a multi-DSP system, an interrupt selector, and a phase lock
loop (PLL), along with hardware for Boot Configurations and Power Down Logic.
Timing
The DSP chip must be able to establish communication links between the CPU (DSP core), the
codecs, and memory. The two McBSPs, serial port 0 (SP0) and serial port 1 (SP1), are used to
establish bidirectional asynchronous links between the CPU and the codec or alternately an
external daughter card (not used in this course). SP0 is used to send control data between the codec
and CPU; SP1 plays a similar role for digital audio data. The 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

UMT Lahore Page 54


(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.
Establishing a File Structure
In this section, we are going to develop a file structure on your u:\ drive that will make
implementing DSP algorithms easier on the DSK. Specifically, there is a set of support files that
are needed to run the DSK for every algorithm implemented in this class. Since these files will be
used many times, it will prove to be beneficial to store them in a specific folder.
Our goal here is to create the following two paths on your u:\ drive that contain the following types
of files:

1. u:\DSP\Support {h initialization header files, .c initialization source code files, .lib pre-compiled
binary library files, .asm vector files, and .cmd linker command file}
2. u:\DSP\Lab x\ {.c project source code}
To create the first path, open Windows Explorer and create the folder DSP to save your work for
this class. This folder will contain all of the sub-folders in this class. This organization is crucial
and cannot be over-stressed. Now double click on your new folder DSP and copy the sub-folder
Support. The Support folder contains the following files:
c6713dskinit.c
c6713dskinit.h
dsk6713.h
dsk6713 aic23.h
dsk6713 dip.h
dsk6713 flash.h
dsk6713 led.h
csl6713.lib
dsk6713bsl.lib
rts6700.lib
Vectors intr.asm
Vectors poll.asm

UMT Lahore Page 55


c6713dsk.cmd

OR Visit this folder after CCS installation and see the file hierarchy
C:\CCStudio_v3.1\C6000\dsk6713

Generating C code and compiling in the Code


Composer Studio (CCS)
The Code Composer Studio (CCS) is a powerful integrated development environment (IDE) that
provides a useful transition between a high-level (C or assembly) DSP program and an on-board
machine language program. CCS consists of a set of software tools and libraries for developing
DSP programs, compiling them into machine code, and writing them into memory on the DSP
chip and on-board external memory. It also contains diagnostic tools for analyzing and tracing
algorithms as they are being implemented on-board. This exercise will familiarize you with the
software while covering the following key sections:

Task-1
Creating Projects, Debugging and Analysis, and Resets

Step 1: Creating a Project

In CCS, Choose Project > New.


Type in a Project Name and a location where it will be stored.
The type should be .out and the target 67xx.
Hit Finish key.
Your project name.pjt should be in the Project View window on the lefthand side.
Step 2: Creating a Source File

Choose File > New > Source File.


An Editor window comes up.
Type in the following assembly code, which declares 10 values:

.sect .data
.short 0
.short 7
.short 10
.short 7
.short 0
.short 7
.short 10
.short 7
.short 0
.short 7

UMT Lahore Page 56


Choose File > Save As

In your project folder, Save the file as initializemem, and choose type .asm.
Create another source file, main.c, given below, and save in your project folder.

//main.c C program

#include <stdio.h>
void main()
{

printf("Begin\n");
printf("End\n");
}

Currently, the program does nothing. However, it will be developed later.

Step 3: Creating a Command File

Locate the Hello.cmd file on the computer.


* ======== hello.cmd ========
*
*/

MEMORY
{
IRAM : origin = 0x0, len = 0x10000
}

SECTIONS
{
.vectors > IRAM
.text > IRAM
.bss > IRAM
.cinit > IRAM
.const > IRAM
.far > IRAM
.stack > IRAM
.cio > IRAM
.sysmem > IRAM
}

Choose File > Open and open the file.


After the line: Sections {
Type in .data > SDRAM.
This will put the data from your initializemem file in a part of SDRAM starting at address
0x80000000.

UMT Lahore Page 57


Choose File > Save as. Save the file in your project folder as Lab1.cmd. Although the
files you have created are in your project folder, they have not been put in the folders that
will be used for assembling and linking. We have to add these files to the project for this
purpose.

Step 4: Adding Files to a Project

Select Project > Add Files to Project.


Open the initializemem.asm file from your project folder. This file should now be under
the Source folder in the P roject View window. Repeat the above instruction for the
main.c and Lab1.cmd files.

We must also add the run-time support library for the board, since we have a C program. Add
the file located at c:\ti\c6000\cgtools\lib\rts6701.lib. This file should now appear under the
Libraries folder in the Project View window.
Step 5: Creating the executable file, lab1.out
Before we compile, assemble, and link, there are a number of options we can choose to
determine the amount of optimization to be done. There are four levels (Opt Levels) of
optimization: 0, 1, 2, and 3. The lowest level is 0. However, sometimes, debugging cannot be
done when we use optimization.

Select Project > Build Options.

Select Compiler and in the Category column, click on Basic. Check that Target
Version is 671x and Opt Level is .
Similarly, select Linker and then Basic. You can change the name of the executable file
that will be produced. Change the output file name to Lab1.out.
Project > Rebuild All compiles, assembles, and links all of the files in the project and
produces the executable file lab1.out. A window at the bottom shows if there are errors.
Project > Build can be used when you have made a change to only a few files and now
wish to compile, assemble, and link with the changed files. There are shortcut buttons on
the window to do Project Build and Rebuild.
Upon building, there should have been a lot of errors. Scroll up until you reach the first red line
with error! in it. Double click on the line. The file initializemem.asm opens at the line where
the error occurred. Assembly code requires that all of the lines in the assembly file not start in
the first column. So enter a space at the beginning of each line in the file and then save the file.
Since we didnt change every file in the project, we can do a Project > Build.

Step 6: Running the Program

In order to run the program, we need to load the program into the DSP memory.

Select File > Load Program.


Open the LAB1.out program, which is in the Debug folder of your LAB1 project folder.
A Disassembly window should appear.
To run select Debug > Run.

Begin and End should appear in the bottom Stdout window.

UMT Lahore Page 58


Step 7: Viewing Memory

This step is to check if the values of our intializemem file are in the memory location that we
established in the .cmd file.
Select View > memory.
Type in 0x80000000 in Address memory location.
Select Format: 16bit Signed Int.
A Memory window appears with the memory addresses and their contents.
Compare the first 10 values with the initializemem file data.

Step 8: Graphical Display of Data


In order to view the graph of data in memory, complete the following instructions:
View > Graph > Time/frequency.
Set Start Address: 0x80000000.
Set Acquisition Buffer Size: 10.
Set Display Data Size: 10.
Set DSP Data Type: 16-bit signed integer.
A graph should appear on the screen with a plot of your data.
Compare the first 10 values with the initializemem file data

Step 9: Main.c Program Modification


Double click on main.c in the project window.
Modify main.c program so that it looks like the following:

//main.c C program Modification 1


#include <stdio.h>
void main()
{
int i;
short *point;
point = (short *) 0x80000000;
printf(Begin\n);
for (i=0;i<10;i++)
{
printf([%d]%d\n,i, point[i]);
}
printf(End\n);
}

Save, Rebuild, and Load the program into the DSP memory.
Run the program.

A pointer is assigned to the beginning of our data in memory. This allows us to bring data into our
c program and print out the data.

Step 10: Checking a Variable during Program Execution

UMT Lahore Page 59


Breakpoints and watch windows are used to watch variables while a program runs. In order to
look at the values of the variable pointer in main.c, before and after the pointer assignment, as
well as the value of variable i, first we establish breakpoints as follows:
Select File > Reload to reload the program into DSP memory.
Double click on main.c in the project window.
Put a cursor on the line: point = (short*) 0x80000000.
Right click and choose Toggle Breakpoint.
Click on Stdout window in order to see the output results.
Repeat the above procedure with the line: printf([%d]%d\n,i, point[i]);.

In order to add variables to watch window:

Use the mouse to highlight the variable point in the line beginning with: point = (short*).
Right click and select Add to Watch window. A watch window should open with variable
point.
Repeat above procedure for variable i in the line beginning with: printf([%d].
Select Debug > Run.

The program stops at the breakpoint and the watch window shows the value of point before the
pointer is set. To advance the program or move through the breakpoint, hit the shortcut button
step over a line or select Debug > Step Over. The pointer is now set and you can see the value
of the pointer is 0x80000000.

To watch the variable i as the program progresses:


Hit the shortcut button animate or select Debug > animate or hit the shortcut button step
over the line over and over to see the variable i change.
After using animate, you need to halt the system. You can do this with Debug > Halt.
If you want to do this exercise over again, go to Debug > Restart, Run, Step Over, etc.
Remove the breakpoints before continuing by hitting the shortcut button Remove All
Breakpoints.
Double click on main.c in the project window and modify the C program so that it
matches the program below. This C program will sum the values.

//main.c C program Modification 2


#include <stdio.h>
void main()

{
int i, ret; short *point;
point= (short *) 0x80000000;
printf(Begin\n);
for (i=0;i<10;i++)
{
printf([%d]%d\n,i, point[i]);
}
ret = ret_sum(point,10); printf(Sum =%d\n,ret); printf(End\n);
}

UMT Lahore Page 60


int ret_sum(const short* array, int N)

{
int count, sum; sum=0;
for(count=0; count<N; count++)
sum += array[count];
return(sum);
}

Go through all the steps required to run the program.

Step 11: Benchmarking

Now we will benchmark or time the subroutine to determine how long it takes to return the sum.
Reload the program.
Select Profiler > Start New Session.
Title the session Lab 1. A profile window comes up in the bottom.
Double click on main.c in the project window.
Put your cursor on the line: int ret_sum(const short* array, int N).
Several shortcut buttons are on the left side of the Profile window.
Hit the Create Profile Area button. Make sure the type is Function and the line number
corresponds to the beginning of the function, since this is where you placed the cursor.
Hit OK.
Expand Lab1.out under the Files window pane. The function ret_sum should be there.
Run the program.
The value for the Incl. Total in the profiler window is the number of clock cycles needed
to run the function ret_sum.
To redo this exercise, highlight ret_sum in the Files window pane, right click, and
select Clear Selected.
Then hit Debug > Restart and Run the program.

Optimization can change the amount of time required to run the function. To observe the effects,
follow these instructions:

Select Project > Build Options.


Choose Compiler, Basic, and Opt Level o0.
Select Project > Rebuild All.
Select File > Load Program Lab1.out.
Highlight ret_sum in the Files pane, right click, and select Clear Selected.
Hit Debug > Run.
Repeat the above for the other levels of optimization o1, o2, and o3, and compare the number of
clock cycles for each optimization.

Step 12: Resets


Sometimes it might be necessary to reset the DSK. There are several ways to do this at different
levels.
In CCS go to Debug > Reset CPU A Disassembly window appears.
Close CCS.

UMT Lahore Page 61


Select Start button of Windows > Programs > Texas Instruments > Code Composer
Studio DSK Tools > Hardware Resets > Reset.
Close CCS. Unplug the board and turn it back on after a few seconds. Wait for the LEDs
to quit flashing before trying to use the board or opening CCS again.
Press the Reset button on the DSK. Note: Do not press this button while CCS is still
running. Also, this reset does not perform the full reset.
Loading and Running a Built-in Program
Task-2
Turning ON and OF an LED on DSP Board
Use examples DSK6713 from Spectrum Digital Inc. website

The best way to get started with Code Composer is to run some of the simple examples
included with the DSK. The LED example is the easiest example to get started with to become
familiar with the DSK and make sure your development tools are configured correctly. When run,
it will:

Continuously blink LED #0 about 2.5 times per second.


Continuously read the value of DIP switch #3 and display it on LED #3.
STEPS
To run the program, perform the following steps:
1. Open the led.pjt in Code Composer project using Project ----Open and selecting
led.pjt. It is in the directory c:\CCStudio_v3.1\examples\dsk6713\bsl\led.
2. The default install directory for Code Composer is c:\CCStudio_v3.1. If Code
Composer is installed in c:\CCStudio_v3.1dsk6713 the led example would be located at
c:\CCStudio_v3.1\dsk6713\examples\dsk6713\bsl\led.
3. Load the led.out executable file. Select File-> Load Program. It will open a file
browser dialog. Select the led.out file in the led\Debug directory in the file browser and
hit "Open" to load the executable file. You must reload the compiled executable every
time you make changes to the program.
4. Select the Debug-> Run option under the Debug menu. LED #0 will start blinking
slowly.
5. Move DIP switch #3 up and down, you will see LED #3 change with it.
6. When you are satisfied that the program is indeed running correctly, stop the program
by selecting Debug -> Halt.

To examine the program code, expand the Projects tree at the left of the workspace, then expand
the led.pjt and Source sub items. Double click on led.c to see its contents. You should something
like this:

UMT Lahore Page 62


LED Example Program led.c details
Program execution starts at the beginning of main ( ). The first call is to DSK6713_init ( )
which initializes the Board Support Library (BSL). The BSL is a library designed specifically to
make it easier to use the components on the DSK board. DSK6713_init ( ) should be called
before any other BSL functions. You can recognize BSL calls easily because they all start with
the prefix DSK6713. The BSL programming interface is described fully in the BSL section of
help file. The BSL functions are included as a library called dsk6713bsl.lib.

The LED example demonstrates use of the LED and DIP switch BSL modules. Each has its own
initialization function that must be called before other functions in the module. The
DSK6713_LED_toggle( ) call toggles the state of LED #0. A software delay loop:
/* Spin in a software delay loop for about 200ms */
DSK6713_waitusec (200000);
introduces roughly 200 millisecond delay before toggling the LED again. This delay loop is
responsible for controlling the speed of the blinking LED.

UMT Lahore Page 63


The DSK6713_DIP_get( ) function reads the state of LED #3. If the switch is pressed down,
the call will return 0, prompting the call to DSK6713_LED_on ( ) to turn LED #3 on. If the
switch is up, the opposite will occur and DSK6713_LED_off ( ) will be called to turn the LED
off. Since all of this code is in a while loop with no termination condition, the program will run
forever unless you halt it with Code Composer. The complete code for led.c is given below.

// led.c
#include "ledcfg.h"

/*
* The Board Support Library is divided into several modules, each
* of which has its own include file. The file dsk6713.h must be included
* in every program that uses the BSL. This example also includes
* dsk6713_led.h and dsk6713_dip.h because it uses the LED and DIP modules.
*/
#include "dsk6713.h"
#include "dsk6713_led.h"
#include "dsk6713_dip.h"

/*
* main() - Main code routine, initializes BSL and runs LED application
*/

/*
* EXTRA: Pressing DIP switch #3 changes LED #3 from off to on.
*/

void main()
{
/* Initialize the board support library, must be first BSL call */
DSK6713_init();

/* Initialize the LED and DIP switch modules of the BSL */


DSK6713_LED_init();
DSK6713_DIP_init();

while(1)
{
/* Toggle LED #0 */
DSK6713_LED_toggle(0);

/* Check DIP switch #3 and light LED #3 accordingly, 0 = switch pressed */


if (DSK6713_DIP_get(3) == 0)
/* Switch pressed, turn LED #3 on */
DSK6713_LED_on(3);
else
/* Switch not pressed, turn LED #3 off */

UMT Lahore Page 64


DSK6713_LED_off(3);
/* Spin in a software delay loop for about 200ms */
DSK6713_waitusec(200000);
}
}

TASK-3
Making Simple Changes in led.c program. Modify the loop to make LED blink at approximately 100ms

In order to become familiar with Code Composer, this example will take a quick walk through the
steps involved in making simple changes to the example. One of the easiest changes to make is to
make the LED blink at a higher rate.
To try out your new changes:

1) Save the program code that was just modified. Select File-> Save.

2) Re-compile your program. Every time you make changes to your code you must re-compile
the source code to generate a new executable file. Select Project -> Build. Wait for the build
to complete before continuing.

3) Load the new led.out executable file. Select File-> Load Program then select led.out in the
led\Debug directory in the file browser.

4) Select the Debug-> Run. LED #0 will start blinking twice as quickly as the original version.

5) When you are satisfied that the changes youve made have actually made the LED blink
faster, stop the program by selecting Debug -> Halt.

Introduction to DSP/BIOS
Watch training videos:
1. DSP Kit Tutorial 3A - Make new project with _without DSP_BIOS using CCS 3.1.mp4
2. DSP Kit Tutorial 3B - Make new project with_without DSP_BIOS using CCS 3.1.mp4
3. DSP Kit Tutorial 3C - Make new project with_without DSP_BIOS using CCS 3.1.mp4

Even though the LED example may seem simple, it is built on top of TIs DSP/BIOS, a real-time
multitasking kernel. One of the features of the Code Composer development environment is its
close integration with DSP/BIOS which allows users to easily add functionality to their code that
typically requires a considerable amount of effort with other tools. All of the DSK specific
examples use DSP/BIOS.
DSP/BIOS programs are organized such that logically independent parts of a program are executed
as independent tasks and threads. In the context of an application like a mobile phone, one task
could be assigned to listening for wireless communication transfers, another assigned to wait for
user input, another to periodically check the battery level and so on rather than have a single task

UMT Lahore Page 65


try to do all of these things at once. In addition to basic task scheduling, DSP/BIOS also includes
components that allow communication and synchronization between tasks and devices.
Using the BIOS Configuration Tool to control LED blink
The ledprd example is a separate example that performs the exact same function as the led
example using the DSP/BIOS scheduler to run a periodic thread every 200ms instead of using the
software delay loop. Follow these instructions to load and run the ledprd example.
1. Close the LED project you were working with previously by selecting Project -> Close.
You should also close any open files you have open in your workspace such as led.c and
led.cdb to avoid confusion.
2. Open the ledprd.pjt Code Composer project using Project ->Open and selecting
ledprd.pjt. It is in the directory c:\CCStudio_v3.1\examples\dsk6713\bsl\ledprd.
3. Load the led.out executable file. Select File Load Program. It will open a file browser
dialog. Select the led.out file in the ledprd\Debug directory in the file browser and hit
"Open" to load the executable file.
4. Select the Debug-> Run option under the Debug menu. LED #0 will start blinking
slowly.
5. Move DIP switch #3 up and down, you will see LED #3 change with it.
6. When you are satisfied that the program is indeed running correctly, stop the program
by selecting Debug->Halt.

To examine the program code, expand the Projects tree at the left of the workspace, then expand
the ledprd.pjt and Source subitems. Double click on ledprd.c to see its contents.
You can see that only initialization is done in the main() function. When main() is finished, it
returns back to the DSP/BIOS scheduler which takes over responsibility of finding more work to
be done. In this case, blinkLED0() is defined as a periodic thread that is scheduled to run every
200ms. Advantages of this method are:

No time is wasted spinning in loops. Work is done when it is scheduled or a resource that
work depends on becomes available.
Independent work can be separated into logical threads that are managed by DSP/BIOS,
simplifying your code.
* ======== ledprd.c ========
*
* This example blinks LED #0 at a rate of about 4 times per second using
* the LED module of the the 6713 DSK Board Support Library. The example
* also reads the state of DIP switch #3 and lights LED #3 if the switch
* is depressed or turns it off if the switch is not depressed.
*
* When the program is run, DSP/BIOS initializes itself and calls the main()
* function. Main() initializes the BSL then exits and returns control back
* To DSP/BIOS. The real work is done inside blinkLED0() which is a DSP/BIOS
* periodic thread that is run every 125ms.
* A second thread named blinkLED1() is also included that blinks LED #1
* Asynchronously with blinkLED0 () to demonstrate DSP/BIOS multitasking.
* It is not enabled by default but can be added by creating a new periodic
* thread entry for it in the DSP/BIOS scheduler.

UMT Lahore Page 66


* Please see the 6713 DSK help file under Software/Examples for more
* detailed information.
*/
/*
* DSP/BIOS is configured using the DSP/BIOS configuration tool. Settings
* for this example are stored in a configuration file called ledprd.cdb. At
* compile time, Code Composer will auto-generate DSP/BIOS related files
* based on these settings. A header file called ledprdcfg.h contains the
* results of the autogeneration and must be included for proper operation.
* The name of the file is taken from ledprd.cdb and adding cfg.h.
Scheduler Settings To view the scheduler settings:
1) Expand the "DSP/BIOS Config" entry in the project view. Double-click on the ledprd.cdb
file to open it with the BIOS configuration tool.
2) Expand the "Scheduling" entry in the configuration tool view. This exposes groups of
configurable parameters related to scheduling.
3) Expand the PRD - Periodic Function Manager section to see a list of currently scheduled
periodic threads. There will be one scheduled entry called PRD_blinkLED0. Right click on it
and select Properties.

You should see something like this:

UMT Lahore Page 67


The function is the name of the thread containing the code to be run, in this case _blinkLED0. The
leading underscore is required because blinkLED0() is a C function. Functions written in assembly
do not need the underscore. The period is the period blinkLED0() should be called with in ticks.
Each tick is equivalent to 1ms, so it will be run every 200ms. Hit cancel to exit out of the properties
view.
Adding a Second Thread to toggle LED#1
A second thread is included in the ledprd.c source file called blinkLED1( ). It simply toggles
LED #1. This section shows how to add it as a second thread that blinks LED #1 at a different rate
than LED #0.

1) Expand the Scheduling entry in the DSP/BIOS Configuration Tool and right clock on PRD -
Periodic Function Manager. Select the Insert PRD menu option. It will create a new scheduling
entry called PRD0.
2) Right click on PRD0 and select Properties. Change the period field to 100 and the function
field to _blinkLED1. It will look like this when you are done:
3) Hit OK to confirm the settings. Single click on PRD0 and the Configuration Tool will let
you change the name. Change it to PRD_blinkLED1.
4) Save the new DSP/BIOS configuration file. Select File Save.
5) Re-compile your program. Select Project ->Build.
6) Load the new led.out executable file. Select File -> Load Program then select ledprd.out
in the ledprd\Debug directory in the file browser.

UMT Lahore Page 68


7) Select the Debug -> Run. LED #0 will be blinking as before but LED #1 will also be blinking
at twice the rate.
8) When you are satisfied that both tasks are running, stop the program by selecting Debug ->
Halt

Task-4:
TONE Example-A 1 KHz sine wave

UMT Lahore Page 69


The tone example (in c:\CCStudio_v3.1\examples\dsk6713\bsl\tone) is a slightly more
complicated program that directs the AIC23 codec to generate a 1 KHz sine wave on the line and
headphone outputs. Follow these instructions to load and run the tone example.
1) Close all projects you were working with previously by selecting Project--Close. You
should also close any open files you have opened in your workspace avoid confusion. Click on
the X in the upper right hand corner of their windows to close them.
2) Plug a pair of headphones or speakers into the DSKs headphone jack.
3) Open the tone.pjt Code Composer project using Project Open and selecting tone.pjt. It is
in the directory c:\CCStudio_v3.1\examples\dsk6713\bsl\tone.
4) Load the tone.out executable file. Select File -> Load Program. It will open a file browser
dialog. Select the tone.out file in the tone\Debug directory in the file browser and hit "Open" to
load the executable file.
5) Select the Debug -> Run option under the Debug menu. You will hear a 1KHz tone.
6) After 5 seconds the sound will stop.

When you are satisfied that the program is indeed running correctly, stop the program by
selecting Debug ->Halt.

The array sinetable contains a pre-generated sine wave using signed 16-bit data that matches the
AIC23. The data covers exactly one period and the amplitude matches the full range of the codec.

#define SINE_TABLE_SIZE 48
/* Pre-generated sine wave data, 16-bit signed samples */
Int16 sinetable[SINE_TABLE_SIZE] = {
0x0000, 0x10b4, 0x2120, 0x30fb, 0x3fff, 0x4dea, 0x5a81, 0x658b,
0x6ed8, 0x763f, 0x7ba1, 0x7ee5, 0x7ffd, 0x7ee5, 0x7ba1, 0x76ef,
0x6ed8, 0x658b, 0x5a81, 0x4dea, 0x3fff, 0x30fb, 0x2120, 0x10b4,
0x0000, 0xef4c, 0xdee0, 0xcf06, 0xc002, 0xb216, 0xa57f, 0x9a75,
0x9128, 0x89c1, 0x845f, 0x811b, 0x8002, 0x811b, 0x845f, 0x89c1,
0x9128, 0x9a76, 0xa57f, 0xb216, 0xc002, 0xcf06, 0xdee0, 0xef4c
};

The main loop of the code writes each data point in the sine wave table out to the codec using the
AIC23 codec package of the BSL. Each write function sends a single 16 bit sample to the codec.
In this case the same data is sent out twice, once to the left channel and once to the right channel.
The codec is configured to accept data at a rate of 48,000 stereo samples per second. Since the
sine table is 48 entries long, the resulting output wave will be a 1KHz sine wave with the same
output on both the left and right channels.

// Generate a 1KHz sine wave for 5 seconds


for (msec = 0; msec < 5000; msec++)
{
for (sample = 0; sample < SINE_TABLE_SIZE; sample++)
{
while (!DSK6713_AIC23_write(hCodec, sinetable[sample]));
while (!DSK6713_AIC23_write(hCodec, sinetable[sample]));

UMT Lahore Page 70


}
}

The serial port McBSP1 is used to transmit data to the codec at a much slower rate than the DSP
can process data. It accepts data 16 bits at a time and shifts them out slowly one at a time. The
write function returns a 1 if the write is completed successfully or a 0 if the serial channel is busy.
The while( ) loop around the writes waits while the serial port is busy so program can be
synchronized to the data rate of the codec.

The following two commands are used to initialize and shut down the codec and are found at the
beginning and end of all programs that use BSL codec module. The DSK6713_openCodec()
command returns a handle that is passed each of the other codec functions.

// Start the codec


hCodec = DSK6713_AIC23_openCodec(0, &config);
// Close the codec
DSK6713_AIC23_closeCodec(hCodec);

Task-5:
DSK Application Example: Playing a song or some audio file

The DSK_App example digitally processes audio data from the line input on the AIC23 codec
and plays the result on the headphone and line output. It uses the McBSP and EDMA (Enhanced
Direct Memory Access) to efficiently handle the data transfer without intervention from the DSP.
The example resides in c:\CCStudio_v3.1\examples\dsk6713\bsl\dsk_app.

The EDMA driven audio implemented by the audio example is highly optimized and
representative of what might be used in production code. It is a good base to use for your own
audio code.

UMT Lahore Page 71


If no DIP switches are pressed, the example simply passes the audio from the line-in to the audio
outputs. LEDs #2 and #3 toggle as the data is being transferred. If the DIP switches are depressed,
the following things occur:
Dip Switch # Function
0 Blink LED #0 once per second
1 Add a dummy load that takes 20-25% of the
processor time
The functions are independently controlled so you can, for example, blink LED #0 and add the
dummy load at the same time.

Follow these instructions to load and run the DSK_App example.


1) Close and projects you were working with previously by selecting Project -
>Close. You should also close any open files you have open in your
workspace avoid confusion. Click on the X in the upper right hand corner of
their windows to close them.
2) Plug a pair of headphones or speakers into the DSKs headphone jack. Also
connect an audio source like a CD player to the line input of the DSK using
a standard 1/8" male to male audio cable.
3) Make sure all your DIP switches are in the up position.
4) Open the DSK_App.pjt Code Composer project using Project Open and
selecting DSK_App.pjt. It is in the directory
c:\CCStudio_v3.1\examples\dsk6713\bsl\DSK_App.
5) Enable RTDX by selecting ToolsRTDXConfiguration Control and
checking the Enable RTDX checkbox. RDTX is a communication protocol
that allows your program to communicate with Code Composer through the
embedded USB emulator. The settings should be set for non-continuous
mode with a buffer size of 1024. You can close this window by right clicking
on the gray window area and selecting close. For more information about
RTDX refer to RTDX section in the main Code Composer help.

UMT Lahore Page 72


6) Enable the CPU load plugin by selecting DSP/BIOS CPU Load Graph. The
load graph will appear at the bottom of your Code Composer window. You
can make it a movable window by right-clicking on it and selecting Float In
Main Window.
7) Load the DSK_App.out executable file. Select File Load Program. It will
open a file browser dialog. Select the DSK_App.out file in the
DSK_App\Debug directory in the file browser and hit "Open" to load the
executable file.
8) Select the Debug -> Run option under the Debug menu. You will hear your
audio source playing through the DSK on the headphone output. Adjust the
volume of your audio source until you get to a comfortable listening level.
9) You will see LEDs #2 and #3 blinking. They toggle every time a ping or
pong buffer is received. You will also see a display on the CPU load graph
indicating what percentage of the total cycles are spent doing real work. It
should be well under 10%.
10) Press DIP switch #0. This will instruct the periodic thread blinkLED() to
blink LED #0.
11) Press DIP switch #1. This will enable a 20-25% dummy CPU load that
represents other computation the DSP may be doing. You will see the CPU
load go up by a substantial amount.

When you are satisfied that the program is indeed running correctly, stop the program by
selecting Debug -> Halt.

UMT Lahore Page 73


Lab No 8 Simple Audio Loop back on TMS320C6713 by
programming Audio Codec AIC23
Objective(s)s
To understand DSP Starter Kit DSK-6713
Further understand Code Composer functionalities
Reading and writing on Audio Codec AIC23
Playing audio using Audio codec
Equipment/Software:
1. A PC running Windows OS/ MATLAB with SIMULINK installed
2. DSP Trainer Kit (DSK 6713)
Required Output Files for this lab: .m files for various tasks
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH Edition
John G Proakis, Dimitris G. Manolakis
Students responsibilities in this lab
1. Write MATLAB 2. Generate all the
script (.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-
up for previous lab at
the start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor
7. Show your instructor 8.
the sound of the tone

UMT Lahore Page 74


Task-1
Getting Started with a Simple Audio Loop through Program:
Learning to Use the Hardware and Software Tools by Generating a Sine
Wave
The goal of this experiment is to learn how to use the hardware and software tools available at
each station. The hardware includes a PC, TMS320C6713 DSK, a signal generator, and an
oscilloscope. The main software tool you will use is Code Composer Studio (CCS) which
contains an editor and a project building facility which automates calling the C compiler,
assembler, and linker. You will also use CCS to load programs into the DSP boards, run them,
and monitor their execution. You will gradually learn about the DSPs architecture including
the McBSPs serial ports, interrupt controller, and EDMA controllers by generating a sine wave.
The experiments in this lab assume that the TMS320C6713 DSK is being used along with the
support library dsk6713bsl32.lib.The codec initialization function in this library configures
McBSP1 to transmit and receive 16-bit left and right channel sample pairs packed into a single
32-bit word with the left channel sample in the upper 16 bits and the right channel sample in the
lower 16 bits. Functions for setting up a simple interrupt environment and interfacing with the
interrupt registers were also added to this library.

A Linker Command File and Beginning C Program


First copy the linker command file, dsk6713.cmd, listed below to your working directory from
the directory C:\c6713dsk. Linker command files are used to define how relocatable program
sections are mapped into the physical system memory. They can also contain assembler options
and lists of object programs to be included in the output modules. Additional object modules can
also be included on the linker command line. The modules are loaded in the order in which they
appear in the command line list of .cmd and .obj files. Command files are convenient for saving
definitions and operations that will be ordinarily used when linking programs for a particular
project.

1. The -c line in dsk6713.cmd tells the linker to use the auto initialization feature of C
programs. The TI C compiler builds a table containing the data required to initialize all
variables initialized in the C program. Code is included in the executable module to load
the data values in the table into the variables when the program starts. The -heap and
2. -stack lines allocate memory for the heap and stack. The number after these commands
is the allocated memory size in bytes.
3. The -lrts6700.lib line tells the linker to search the C run-time library rts6700.lib for
unresolved references. This library provides the standard functions the C compiler expects.
4. The line -lcsl6713.lib tells the linker to search the Chip Support Library (CSL) csl6713.lib.
CCS has been set to know the path to these libraries. They are almost always used by C
programs. Including these lines in the linker command file automatically includes them in
the linker search path without any further effort on your part.
5. The MEMORY portion of the command file is used to define the physical memory layout.
For example, the line
IRAM : origin = 0x0, len = 0x40000 /* 256 Kbytes */ defines the internal program memory to
be a region called IRAM which starts at byte address 0x00000000, and has a length of 0x00040000
bytes which is 256 Kbytes.

UMT Lahore Page 75


The C compiler puts data and program code into named sections. Named sections can also be
created by the programmer in assembly source code. The SECTIONS portion of the linker
command file tells the linker how to place sections into defined memory regions. The standard
conventions are to place program instructions in the .text section, initialized constants in the
.const section, global and static variables in the .bss section, initialization tables for variables
and constants in the .cinit section, local variables in the .stack section, and buffers for C I/O
functions in the .cio section. Data from assembly programs can be put in the .data section. C does
not use the .data section. There are many more options for linker command files that allow complex
mappings of programs into physical memory.
See the TMS320C6000 Assembly Language Tools Users Guide for complete details.

Linker Command File dsk6713.cmd


/**************************************************************/
/* File dsk6713.cmd */
/* This linker command file can be used as the starting */
/* point for linking programs for the TMS320C6713 DSK. */
/* */
/* This CMD file assumes everything fits into internal RAM. */
/* If thats not true, map some sections to the external */
/* SDRAM. */
/**************************************************************/
-c
-heap 0x1000
-stack 0x400
-lrts6700.lib
-lcsl6713.lib
MEMORY
{
IRAM : origin = 0x0, len = 0x40000 /* 256 Kbytes */
SDRAM : origin = 0x80000000, len = 0x1000000 /* 16 Mbytes SDRAM */
FLASH : origin = 0x90000000, len = 0x40000 /* 256 Kbytes */
}
SECTIONS
{
.vec: load = 0x00000000 /* Interrupt vectors included */
/* by using intr_reset() */
.text: load = IRAM /* Executable code */
.const: load = IRAM /* Initialized constants */
.bss: load = IRAM /* Global and static variables */
.data: load = IRAM /* Data from .asm programs */
.cinit: load = IRAM /* Tables for initializing */
/* variables and constants */
.stack: load = IRAM /* Stack for local variables */
.far: load = IRAM /* Global and static variables */
/* declared far */
.sysmem: load = IRAM /* Used by malloc, etc. (heap) */

UMT Lahore Page 76


.cio: load = IRAM /* Used for C I/O functions */
.csldata load = IRAM
.switch load = IRAM
}
a) Before executing the code that performs your desired signal processing algorithm, the DSK
and DSP have to be initialized. This is partially taken care of when you start Code
Composer. The version of CCS supplied with the C6713 DSK has been configured to
automatically load the general extension language (GEL) file DSK6713.gel in the directory
C:\CCStudio_v3.1 for CCS v3.1. This file defines a memory map, creates some GEL
functions for the CCS GEL menu, sets some CPLD registers to configure components on
the DSK board, and initializes the EMIF for the memory on the board. Your program must
do the remaining initialization.
b) Copy the file dskstart32.c from the directory C:\c6713dsk to your workspace. A listings
of this file is shown below. You will add it to a project file shortly. This file can be used as
the starting point for all your programs. It uses functions from the UMD modified Board
Support Library (BSL), dsk6713bsl32.lib, in the directory C:\c6713dsk\dsk6713bsl32\lib.
c) The required header files and source files can be found in the parallel sub-directories,
include and sources. You can find detailed documentation for the BSL by starting Code
Composer and clicking on Help Contents TMS320C6713 DSK
Software Board Support.
d) First, dskstart32.c calls DSK6713_init( ) to initialize the board support library. The
source code for this function is in the BSL file dsk6713.c. The function initializes the chips
PLL, configures the EMF based on the DSK version, and sets the CPLD registers to a
default state.
e) Next dskstart32.c initializes the interrupt controller registers and installs the default
interrupt service routines by calling the function intr_reset() in the UMD added file
intr.c. This function clears GIE and PGIE, disables all interrupts except RESET in IER,
clears the flags in the IFR for the maskable interrupts INT4 through INT15, resets the
interrupt multiplexers, initializes the interrupt service table pointer (ISTP), and sets up the
Interrupt Service Routine Jump Table. The object modules intr.obj and intr_.obj were
added to BSL library so you should not include intr.c and intr_.asm in your project. For
complete details, see the source files intr.c and intr.h .
f) Next the codec is started by calling the function DSK6713_AIC23_openCodec( ). This
function configures serial port McBSP0 to act as a unidirectional control channel in the
SPI mode transmitting 16-bit words. Then it configures the AIC23 stereo codec to operate
in the DSP mode with 16-bit data words with a sampling rate of 48 kHz. Then McBSP1 is
configured to send data samples to the codec or receive data samples from the codec in the
DSP format using 32-bit words. The first word transmitted by the AIC23 is the left channel
sample. The right channel sample is transmitted immediately after the left sample. The
AIC23 generates a single frame sync at the beginning of the left channel sample. Therefore,
a 32-bit word received by McBSP1 contains the left sample in the upper 16 bits and the
right sample in the lower 16 bits. The 16-bit samples are in 2s complement format. Words
transmitted from McBSP1 to AIC23 must have the same format. The codec and McBSP1
are configured so that the codec generates the frame syncs and shift clocks. See the text at
the top of dskstart32.c for more details about the UMD modifications of
DSK6713_AIC23_openCodec.c from the TI BSL version which sets McBSP1 to transmit
and receive 16-bit words.

UMT Lahore Page 77


g) Finally, dskstart32.c enters an infinite loop that reads pairs of left and right channel samples
from the codec ADC and loops them back out to the codec DAC. This loop should be
replaced by the C code to achieve the goals of your experiments.

dskstart32.c
/*************************************************************/
/* Function DSK6713_AIC23_openCodec() in dsk6713_opencodec.c */
/* is a modification of the same function in the BSL module */
/* DSK6713_AIC23_openCodec.c. It configures McBSP1 to trans- */
/* mit and receive 32-bit words rather than 16-bit words by */
/* changing the RWDLEN1 value to 32BIT, XWDLEN1 to 32BIT, */
/* RFRLEN1 to OF(0), and XFRLEN1 to OF(0) in structure */
/* mcbspCfgData in dsk6713_opencodec.c. This causes McBSP1 */
/* to use a single phase frame consisting of one 32-bit word */
/* per frame. Words are sent to the codec by using the BSL */
/* function DSK6713_AIC23_write() and read from the codec by */
/* using the function DSK6713_AIC23_read(). */
/*************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <dsk6713.h>
#include <dsk6713_aic23.h>
#include <intr.h>
#include <math.h>
/* Codec configuration settings */
/* See dsk6713_aic23.h and the TLV320AIC23 Stereo Audio CODEC Data Manual */
/* for a detailed description of the bits in each of the 10 AIC23 control */
/* registers in the following configuration structure. */

DSK6713_AIC23_Config config = { \
0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Left line input channel volume */ \
0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume */\
0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */ \
0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */ \
0x0011, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */ \
0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */ \
0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */ \
0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */ \
0x0081, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control (48 kHz) */ \
0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \
};

/***********************************************************/
/* Main program: Replace with your code */
/***********************************************************/
void main(void){
DSK6713_AIC23_CodecHandle hCodec;

UMT Lahore Page 78


Uint32 sample_pair = 0;
/* Initialize the interrupt system */
intr_reset();
/* dsk6713_init() must be called before other BSL functions */
DSK6713_init(); /* In the BSL library */
/* Start the codec */
hCodec = DSK6713_AIC23_openCodec(0, &config);
/* Change the sampling rate to 16 kHz */
DSK6713_AIC23_setFreq(hCodec, DSK6713_AIC23_FREQ_16KHZ);
/* Read left and right channel samples from the ADC and loop */
/* them back out to the DAC. */
for(;;){
while(!DSK6713_AIC23_read(hCodec, &sample_pair));
while(!DSK6713_AIC23_write(hCodec, sample_pair));
}
}

How Samples are sent to the Codec


Left and right sample pairs are sent to the codec as 32-bit words with the left channel sample in
the upper 16 bits and the right channel sample in the lower 16 bits. Each sample is in 16-bit twos
complement format. These 32-bit words are sent to the codec by the BSL function
DSK6713_AIC23_write( ). This function polls the McBSP1 XRDY flag and returns immediately
without sending the sample if it is false and also returns the value 0 (FALSE). It sends the sample
word by writing it to the Data Transmit Register (DXR) of McBSP1 if XRDY is 1 (TRUE) and
returns the value 1. The C code for this function is shown below.
#include <dsk6713.h>
#include <dsk6713_aic23.h>
Int16 DSK6713_AIC23_write(DSK6713_AIC23_CodecHandle hCodec, Uint32 val)
{ /* If McBSP not ready for new data, return false */
if (!MCBSP_xrdy(DSK6713_AIC23_DATAHANDLE)) {
return (FALSE);
}
/* Write 16 bit data value to DXR */
MCBSP_write(DSK6713_AIC23_DATAHANDLE, val);
/* Short delay for McBSP state machine to update */
asm(" nop");
asm(" nop");
asm(" nop");
asm(" nop");
asm(" nop");
asm(" nop");
asm(" nop");
asm(" nop");
return(TRUE);
}

The lower level functions McBSP_xrdy( ) and MCBSP_write( ) are in TIs CSL library.

UMT Lahore Page 79


How Samples are Read from the Codec
Words are read from the codec by using the function DSK6713_AIC23_read( ). This function
polls the RRDY flag of McBSP1 and returns immediately if it is FALSE without reading a word
and also returns the value FALSE. If RRDY is TRUE it reads a word from the Data Receive
Register (DRR) of McBSP1 and returns the value TRUE. The source code for this function is
shown below.
#include <dsk6713.h>
#include <dsk6713_aic23.h>
Int16 DSK6713_AIC23_read(DSK6713_AIC23_CodecHandle hCodec, Uint32 *val)
{/* If no new data available, return false */
if (!MCBSP_rrdy(DSK6713_AIC23_DATAHANDLE)) {
return (FALSE);
}
/* Read the data */
*val = MCBSP_read(DSK6713_AIC23_DATAHANDLE);
return (TRUE);
}

MCBSP_rrdy() and MCBSP_read() are in TIs CSL library. MCBSP_rrdy() tests the receive ready
(RRDY) flag of the McBSP associated with the handle. MCBSP_read() reads a 32-bit word from
the Data Receive Register (DRR) of the McBSP. Notice that the word read is typed as an unsigned
int.

Properties of the Audio Codec AIC23


The TMS320C6713 DSK supplies a 12 MHz clock to the AIC23 codec which is divided down
internally in the AIC23 to give the sampling rates shown in the table below. The codec can be
set to these sampling rates by using the function DSK6713_AIC23_setFreq(handle,freq ID) from
the BSL library. This function puts the quantity Value into AIC23 control register 8.

Some of the AIC23 analog interface properties are


The ADC for the line inputs has a full-scale range of 1.0 V RMS.
The microphone input is a high-impedance, low-capacitance input compatible with a wide
range of microphones.

AIC23 Sampling Rates


freq ID Value Frequency
DSK6713 AIC23 FREQ 8KHZ 0x06 8000 Hz
DSK6713 AIC23 FREQ 16KHZ 0x2c 16000 Hz
DSK6713 AIC23 FREQ 24KHZ 0x20 24000 Hz
DSK6713 AIC23 FREQ 32KHZ 0x0c 32000 Hz
DSK6713 AIC23 FREQ 44KHZ 0x11 44100 Hz
DSK6713 AIC23 FREQ 48KHZ 0x00 48000 Hz
DSK6713 AIC23 FREQ 96KHZ 0x0e 96000 Hz

UMT Lahore Page 80


The DAC for the line outputs has a full-scale output voltage range of 1.0 V RMS.
The stereo headphone outputs are designed to drive 16 or 32-ohm headphones.
The AIC23 has an analog bypass mode that directly connects the analog line inputs
to the analog line outputs.
The AIC23 has a side tone insertion mode where the microphone input is routed to
the line and headphone outputs.
For complete details on the AIC23 codec including input and output filter frequency
responses, see the TLV320AIC23B Stereo Audio CODEC Data Manual

UMT Lahore Page 81


TASK-2
Creating a CCS Project for dskstart32.c
Now that you have gotten the starting C program and linker command file, it is time to make a project
file and build the executable output file. Perform the following tasks:
1. The first time you use Code Composer Studio you need to save your Workspace in a place where
you have write permission. To do this, start CCS, click on File, then Workspace, and then Save
Workspace As ... and give it a valid name in your private workspace.
2. To start a project in CCS, click on Project, select New, and fill out the boxes as follows:
Project Name: give it a name
Location: a directory in your private workspace
Project type: Executable (.out)
Target TMS320C67xx
3. Copy C:\c6713dsk\dskstart32.c to your workspace and add the copied C source file to the
project.
4. Next set the build options for Code Composer Studio. Click on Project and select Build Options.
Enter the following options:
Compiler -> Basic
Target Version: 671x (-mv6710)
Generate Debug Info: Full Symbolic Debug (-g)
Opt Speed vs Size: Speed Most Critical (no ms)
Opt Level: None
Program Level Opt: None
Compiler -> Preprocessor
Include Search Path (-i): .; c:\c6713dsk\dsk6713bsl32\include
Define Symbols (-d): CHIP_6713
Preprocessing: None
Compiler -> Files
Asm Directory: "a directory in your workspace"
Obj Directory: "a directory in your workspace"
Linker -> Basic
Output Filename (-o): dskstart32.out (You can change this.)
Map Filename (-m): dskstart32.map (optional)
Autoinit Model: Run-time autoinitialization
Library Search Path:
5. Add to the project the linker command file c:\c6713dsk\dsk6713.cmd and the library
c:\c6713dsk\dsk6713bsl32\lib\dsk6713bsl32.lib

UMT Lahore Page 82


TASK-3
Building and Testing dskstart32.c
The program, dskstart32.c, simply loops the input ADC samples back to the output DAC.
To check that your project builds and runs correctly, do the following:
1. Plug a stereo cable into the DSK Line Input and connect both channels to the same
signal generator output. The program dskstart32 should set the codec to sample at
16000 Hz, so set the signal generator to output a sine wave of less than 8000 Hz.
2. Plug a stereo cable into the DSK Line Output. Connect the left and right outputs to
two different oscilloscope channels. You should use channels 1 and 4 on the HP
oscilloscopes. NOTE: The right channel is the white plug and the left channel is the
red plug. Make sure the sampling rate is set to 16000 Hz in dskstart32.c.
3. After your project options have been set, build the executable module by clicking
on the Rebuild All icon or Project Rebuild All.
4. Load the program using File Load Program
5. Start the program running and check that the sine waves appear on the scope. Make
sure the input level is small enough so that there is no clipping.
6. Increase the input signal level until the clipping occurs and the output is distorted
so you can recognize this problem in future experiments. Then reduce the level
again so there is no clipping.
7. Vary the sine wave frequency. What happens when it is more than 8000 Hz? Why?
8. Measure the amplitude response of the system by varying the input frequency and
dividing the output amplitude by the input amplitude. Plot the amplitude response.
Use enough frequencies to get a smooth curve, particularly in regions where the
amplitude response changes quickly.

UMT Lahore Page 83


Lab No-9: Sampling Process and Study of Aliasing
Objective(s):
Study the sampling process for different analog signals
Study sampling using Nyquist theorem and Observe Aliasing Effects

Equipment/Software:
A PC running Windows OS and MATLAB
Required Output Files for this lab: .m files for various tasks
Background: Familiarity with MATLAB
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH
Edition John G Proakis, Dimitris G. Manolakis
Related Topics from the course textbook: Chapter 6 Sec 6.1
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor

Theoretical Background:
Related topics from course textbook: section
Background on Sampling, Quantization and Reconstruction
Analog signal is sampled at a fixed time interval so the ADC (Analog-to-Digital Converter) will
convert the sampled voltage level to a digital value; this is called the sampling process.

The fixed time interval between two samples is the sampling period, and the reciprocal of the
sampling period is the sampling rate. Half of the sampling rate is the folding frequency (Nyquist
limit).
The sampling theorem condition that the sampling rate be larger than twice the highest frequency
of the analog signal to be sampled must be met in order to have the analog signal be recovered.
The sampled spectrum is explained using the well-known formula

UMT Lahore Page 84


( ) = ( 2 )+ ( )+ ( )+ ( + )+ ( +2 ) +
that is, the sampled signal spectrum is a scaled and shifted version of its analog signal
spectrum and its replicas centered at the frequencies that are multiples of the sampling rate.
The analog anti-aliasing low-pass filter is used before ADC to remove frequency components
having high frequencies larger than the folding frequency to avoid aliasing.
The reconstruction (analog low-pass) filter is adopted after DAC to remove the spectral images
that exist in the sample-and-hold signal and obtain the smoothed analog signal. The sample-and-
hold DAC effect may distort the baseband spectrum, but it also reduces image spectrum.
Quantization means that the ADC unit converts the analog signal amplitude with infinite
precision to digital data with finite precision (a finite number of codes).
When the DAC unit converts a digital code to a voltage level, quantization error occurs. The
quantization error is bounded by half of the quantization step size (ADC resolution), which is a
ratio of the full range of the signal over the number of the quantization levels (number of the
codes).
The performance of the quantizer in terms of the signal to quantization noise ratio (SQNR), in
dB, is related to the number of bits in ADC. Increasing 1 bit used in each ADC code will
improve 6 dB SNR due to quantization.
Procedure for this LAB
Open the MATLAB and locate the directory on your PC folder with name: sampling_Lab
Locate the corresponding MATLAB file Lab_sampling_code.m
Open this file in MATLAB editor, read it and hit the simulation. Perform Task1 to Task-3 and
show your work to Lab instructor.
We will study ideal impulse sampling of a continuous-time signal to produce a discrete-time
signal. Several different sampling periods Ts will be used to study the effect of the sampling
period on the ability of the continuous-time signal to be reconstructed from the discrete-time
samples. The continuous-time signal considered here is the sum of two pure cosine terms as
shown by the equation below and illustrated in the figure
Original Continuous-Time Signal ( ) = cos(7 ) + cos(23 )

Task-1:
Generate the graph for continuous-time signal ( ) as shown below and save the figure
in your working directory.
Determine the highest frequency in ( ) . What is the corresponding sampling
frequency and sampling period using Nyquist Theorem?
Generate the graph for sampled signal with Ts1 = 0.05 s. Complete the values in Colum-3
of the following table.
Do you see any aliasing? How you will determine if aliasing is happening.

Sampling periods used Sampling frequency=2/Ts, Sampling Frequency,


rad/sec Hz
Ts1 = 0.05 s ws1 = 125.6637 rad/sec Fs1=
Ts2 = 0.1 s ws2 = 62.8319 rad/sec Fs2=
Ts3 = 0.2 s ws3 = 31.4159 rad/sec Fs3=

UMT Lahore Page 85


Sampling at Ts1 = 0.05 seconds
First, consider Ts1 = 0.05 seconds (ws1 = 125.6637 rad/sec). We will call the sampled signal
x*(t). The frequencies that appear in the sampled signal will be the frequencies in the original
signal (w1 = 7 rad/sec and w2 = 23 rad/sec), the negatives of those values (-7 rad/sec and -23
rad/sec), and integer multiples of the sampling frequency added to those frequencies in
accordance with the following equation, where X(jw) is the Fourier Transform of x(t) and
( )=
X*(jw) is the Fourier Transform of x*(t) [( + )]
Note that both of the sinusoidal frequencies which make up x(t), w1 = 7 rad/sec and w2 = 23
rad/sec, are less than 1/2 of the sampling frequency (ws1/2 = 62.8319 rad/sec).
Task-2:Analysis Determine the first few replicated frequencies which appear in X*(jw)
when Ts = 0.05 sec and draw the sampled spectrum. Verify how the following frequencies
appear in the sampled spectrum.
See % Computing the first few frequencies in the sampled signals in the MATLAB code

W, [-132.6637 -118.6637 -102.6637 -23.0000 -7.0000 7.0000 23.0000


Frequencies 102.6637 118.6637 132.6637] rad/sec
generated
Note that the original frequencies are there, and also note that there are no frequencies between -
ws1/2 and +ws1/2 other than the original frequencies (and their negative values). Therefore, the
original continuous-time signal x(t) could be recovered from the samples using an ideal low-pass

UMT Lahore Page 86


filter with a bandwidth of ws1/2. Even with practical filters, x(t) could be recovered fairly well
since the next higher frequency is 102.7 rad/sec. In the figure below, note that the sample values
are close enough together in time to give an accurate picture of the continuous-time x(t).
Samples of x(t) with Ts1 = 0.05 s

Sampling at Ts1 = 0.1 seconds


Next, consider Ts2 = 0.1 seconds (ws2 = 62.8319 rad/sec). The frequency content of the sampled
signal x*(t) is computed in the same way as before. Both of the frequencies in x(t) are less than
ws2/2 = 31.4159 rad/sec, but now the higher frequency (23 rad/sec) is closer to the top of the
primary strip (defined by +/- ws/2) than with the first sampling period. The first few frequencies
which appear in X*(jw) when Ts = 0.1 s are:
W [-69.8319 -55.8319 -39.8319 -23.0000 -7.0000 7.0000 23.0000
39.8319 55.8319 69.8319 85.8319] rad/sec

Note that there are no frequencies between -ws2/2 and +ws2/2 except the original frequencies, but
now the filter used to recover x(t) from the samples must be much closer to ideal than before
since the next frequencies outside the band of +/- ws2/2 are at +/- 39.8 rad/sec. In the figure
below, It is clear that the samples exactly equal the x(t) values at the sample points,
but if you looked only at the sample values, you would not have as clear an idea of what x(t)
actually looks like as you would be the Ts1=0.05 sampling period.
Samples of x(t) with Ts2 = 0.1 s

UMT Lahore Page 87


Sampling at Ts1 = 0.2 seconds
Now, consider Ts3 = 0.2 seconds (ws3 = 31.4159 rad/sec). Now the higher frequency in x(t) (23
rad/sec) is larger than ws3/2 = 15.7080 rad/sec. Aliasing occurs in this situation. This means that
there will be frequencies in X*(jw) which have values between -ws/2 and +ws/2 which are
not in the original signal. "High" frequencies in the original signal (23 rad/sec in this example)
are appearing under the "alias" of low frequencies. For our example, the frequency content in
X*(jw) will have a term (23 rad/sec - 31.4159 rad/sec) in it, so the frequency -8.4159 rad/sec will
appear in X*(jw) (as well as +8.4159 rad/sec). The first few frequencies which appear in X*(jw)
when Ts = 0.2 s are:
W [-38.4159 -24.4159 -23.0000 -8.4159 -7.0000 7.0000 8.4159
23.0000 24.4159 38.4159] rad/sec

Task-3: Identify the aliased frequencies that appear in the sampled spectrum.

If an ideal low-pass filter with a cut-off frequency of ws3/2 = 15.7080 rad/sec is used to process
the discrete-time samples, the original frequency of 23 rad/sec would be eliminated, and the
frequency of 8.4159 rad/sec would be included. This produces a completely different signal than
the original x(t), even though the sample values correspond to x(t) exactly. If we define the new
signal by. ( ) = cos(7 ) + cos(8.4159 )
We can see that the samples with Ts3 = 0.2 seconds exactly equal the values of x(t) and x1(t) at
the sample points even though they are two completely different signals. This illustrates the fact
that in order to recover the original continuous-time signal from discrete-time samples, the
sampling frequency must be at least twice as high as the highest frequency in the continuous-
time signal. The higher the sampling frequency, the more reliable and easier will be the recovery
-- compare the sampled signals using ws1 vs. ws2. When the sampling frequency is less than twice
the highest frequency in the continuous-time signal, recovery cannot be accomplished using only
the sample values, even with ideal filtering.

UMT Lahore Page 88


MATLAB Code for demonstrating Sampling Process and Aliasing
%lab_sampling_code.m

% ***** MATLAB Code Starts Here


% illustrating the problem of aliasing caused by sampling
% Sampling periods and sampling frequencies to be used.
% ws1 = 125.6637, ws2 = 62.8319, ws3 = 31.4159
fig_size = [232 84 774 624];
Ts1 = 0.05; Ts2 = 0.1; Ts3 = 0.2;
ws1 = 2*pi/Ts1; ws2 = 2*pi/Ts2; ws3 = 2*pi/Ts3;
% Frequencies for the continuous-time signal and the time vector.
w1 = 7; w2 = 23;
t = [0:0.005:2];
% Original continuous-time signal is the sum of two cosines, with frequencies of 7
rad/sec and 23 rad/sec, respectively.
x = cos(w1*t) + cos(w2*t);
figure(1),clf,plot(t,x),grid,xlabel('Time (s)'),ylabel('Amplitude'),...
title('Continuous-Time Signal; x(t) = cos(7t) + cos(23t)'),...
set(gcf,'Position',fig_size)
% Sampling the continuous-time signal with a sampling period Ts = 0.05 s.
t1 = [0:Ts1:2];
xs1 = cos(w1*t1) + cos(w2*t1);
figure(2),clf,stem(t1,xs1);grid,hold on,plot(t,x,'r:'),hold off,...
xlabel('Time (s)'),ylabel('Amplitude'),...
title('Sampled Version of x(t) with T_s = 0.05 s'),...
set(gcf,'Position',fig_size)
% Sampling the continuous-time signal with a sampling period Ts = 0.1 s.
t2 = [0:Ts2:2];
xs2 = cos(w1*t2) + cos(w2*t2);
figure(3),clf,stem(t2,xs2);grid,hold on,plot(t,x,'r:'),hold off,...
xlabel('Time (s)'),ylabel('Amplitude'),...
title('Sampled Version of x(t) with T_s = 0.1 s'),...
set(gcf,'Position',fig_size)
% Sampling the continuous-time signal with a sampling period Ts = 0.2 s.
t3 = [0:Ts3:2];
xs3 = cos(w1*t3) + cos(w2*t3);
figure(4),clf,stem(t3,xs3);grid,hold on,plot(t,x,'r:'),hold off,...

UMT Lahore Page 89


xlabel('Time (s)'),ylabel('Amplitude'),...
title('Sampled Version of x(t) with T_s = 0.2 s'),...
set(gcf,'Position',fig_size)
w2s3 = w2 - ws3;
x1 = cos(w1*t) + cos(w2s3*t);
figure(5),clf,stem(t3,xs3);grid,hold on,plot(t,x,'k:',t,x1,'r:'),...
hold off,xlabel('Time (s)'),ylabel('Amplitude'),...
title('Sampling x(t) and x_1(t) with T_s = 0.2 s'),...
set(gcf,'Position',fig_size),...
text(1.13,1.2,'x(t)'),text(0.1,1.6,'x_1(t)')
% Computing the first few frequencies in the sampled signals.
n = [-1 0 1]; wx = [-w2 -w1 w1 w2];
wx1 = []; wx2 = []; wx3 = [];
for i = 1:length(n)
wx1 = [wx1 (wx + n(i)*ws1)];
wx2 = [wx2 (wx + n(i)*ws2)];
wx3 = [wx3 (wx + n(i)*ws3)];
end
wx1 = sort(wx1); wx2 = sort(wx2); wx3 = sort(wx3);
clear i
% ***** MATLAB Code Stops Here

Write-up
Why do we need an anti-aliasing filter before sampling? The fact that the signal is band-limited
before sampling is a very powerful constraint in the reconstruction of the continuous-time signal.
Can we faithfully recover the following two sampled sinusoids of 200Hz frequency? How can
we do that? Why we sampled this sinusoid at a much higher rate of 8192 Hz than Nyquist rate.

UMT Lahore Page 90


UMT Lahore Page 91
Lab No-10: Quantization Effects for Digitized
Sound
Objective(s):
Study the effect of changing the Quantization Levels and Signal-to-Quantization-Ratio (SQNR)
Equipment/Software: A PC running Windows OS/ MATLAB with SIMULINK installed
Required Output Files for this lab: .m files for various tasks
Background: Familiarity with MATLAB
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH Edition
John G Proakis, Dimitris G. Manolakis
Related Topics from the course textbook: Chapter 6 Sec 6.3
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor

Equipment/Procedure:
A PC running Windows OS and MATLAB/Audacity
Related topics from Course textbook: Section
Procedure for this LAB
Open the MATLAB and locate the directory on your PC folder with name: Quantization_Lab
Locate the corresponding MATLAB file Lab_quantization_round.m
Open this file in MATLAB editor, read it and hit the simulation. Perform Task1 to Task-3 and
show your work to Lab instructor.

Theoretical Background:
Quantization
Quantization of Sinusoidal Signal (rounding to nearest integer bit) and Signal-to-Quantization-
Noise Ratio (SQNR) calculation
In this experiment you will explore the experimental and theoretical SQNRs. It is expected that
by increasing the quantization bits improve the SQNR. Run the following Matlab script. Note: X
denotes the original signal and xd is the quantized signal for all graphs in this lab.
%Lab_quantization_round.m
t=0:0.1:4*pi;

UMT Lahore Page 92


fprintf('Exp\t\tTh\t\tMean\t\tVar\n');
for n=2:2:8, % bits are changed from 2 to 8
x=sin(t); %Analog signal
xd=round(x*2^(n-1))/2^(n-1);
error=xd-x;
error_mean=mean(abs(error));
error_variance=var(error);
figure; plot(t,x,t,xd,t,error)
legend('x','xd','error')
SQNR=10*log10(sum(x.^2)/sum(error.^2));
SQNR_eqn=1.76+6.02*n; % Formula for SQNR calculation
title(strcat(num2str(n),' bits. SQNR=',num2str(SQNR),' dB.'))
fprintf('%0.4f\t%0.4f\t%0.3e\t%0.3e\n',SQNR,SQNR_eqn,error_mean,error_variance);end
Graphs for only 2bit and 4-bit quantization are shown here.

Task-1: After running the MATLAB script fill the following table

Theoretical Mean Variance in


Experimental
Bits SQNR Quantization Quantization
SQNR (dB)
(dB) Noise Noise
2
6
16
32

UMT Lahore Page 93


2. Sound recording and Quantization of digitized sound
In this part you will investigate the influence of the sampling rate and the number of quantization
levels on the quality of digitized sound. The sampling rate standard for audio CD is 44,100
samples per second (441.Ksamples/sec) so the highest frequency that can be sampled without
aliasing, 22,050 Hz, is above the audible range of frequencies. Also, the standard of 16bit
quantization yields quantization noise below the threshold of hearing. Thus any ill effects of the
limited sampling rate and finite number of quantization levels are largely inaudible to humans.
In this lab you will use a digital recording and manipulation program (Audacity software)
and Matlab on the PC audio workstations. Audacity will enable you to record and save
digital audio as a ".wav "file as well as to convert the sampling rate. Audacity does not have
much flexibility for converting the number of quantization levels so we will use a furnished
Matlab file Quantlevels.m for this purpose. Sample rate manipulation is just the "tip of the
iceberg" of the capabilities of Audacity and this lab serves as a simple introduction to using this
program. . Audacity may be downloaded for free from http://audacity.sourceforge.net/.

UMT Lahore Page 94


How is sound recorded digitally?
Recording onto a tape is an example of analog recording. Audacity deals with digital recordings -
recordings that have been sampled so that they can be used by a digital computer, like the one
you're using now. The main device used in digital recording is a Analog-to-Digital Converter
(ADC). The ADC captures a snapshot of the electric voltage on an audio line and represents it as
a digital number that can be sent to a computer.

Each dot in the figure above represents one audio sample. There are two factors that determine
the quality of a digital recording:
Sample rate: The rate at which the samples are captured or played back, measured in Hertz
(Hz), or samples per second. An audio CD has a sample rate of 44,100 Hz, often written as 44
KHz for short. This is also the default sample rate that Audacity uses, because audio CDs are so
prevalent.
Sample format or sample size: Essentially this is the number of digits in the digital
representation of each sample. An audio CD has a precision of 16 bits, which corresponds to
about 5 decimal digits.
Higher sampling rates allow a digital recording to accurately record higher frequencies of sound.
The sampling rate should be at least twice the highest frequency you want to represent. Humans
can't hear frequencies above about 20,000 Hz, so 44,100 Hz was chosen as the rate for audio
CDs to just include all human frequencies. Sample rates of 96 and 192 KHz are starting to

UMT Lahore Page 95


become more common, particularly in DVD-Audio, but many people honestly can't hear the
difference.
Higher sample sizes allow for more dynamic range - louder louds and softer softs. If you are
familiar with the decibel (dB) scale, the dynamic range on an audio CD is theoretically about 90
dB, but realistically signals that are -24 dB or more in volume are greatly reduced in quality.
Audacity supports two additional sample sizes: 24-bit, which is commonly used in digital
recording, and 32-bit float, which has almost infinite dynamic range, and only takes up twice as
much storage as 16-bit samples.
Playback of digital audio uses a Digital-to-Analog Converter (DAC). This takes the sample and
sets a certain voltage on the analog outputs to recreate the signal, that the Analog-to-Digital
Converter originally took to create the sample. Nowadays DACs use Oversampling to smooth
out the audio signal. The quality of the filters in the DAC also contribute to the quality of the
recreated analog audio signal. The filter is part of a multitude of stages that make up a DAC.
How does audio get digitized on your computer?
Your computer has a soundcard - it could be a separate card, like a SoundBlaster, or it could be
built-in to your computer. Either way, your soundcard comes with an Analog-to-Digital
Converter (ADC) for recording, and a Digital-to-Analog Converter (DAC) for playing audio.
Your operating system (Windows, Mac OS X, Linux, etc.) talks to the sound card to actually
handle the recording and playback, and Audacity talks to your operating system so that you can
capture sounds to a file, edit them, and mix multiple tracks while playing.
Standard file formats for PCM audio
There are two main types of audio files on a computer:
PCM stands for Pulse Code Modulation. This is just a fancy name for the technique described
above, where each number in the digital audio file represents exactly one sample in the
waveform. Common examples of PCM files are WAV files, AIFF files, and Sound Designer II
files. Audacity supports WAV, AIFF, and many other PCM files.
The other type is compressed files. Earlier formats used logarithmic encodings to squeeze more
dynamic range out of fewer bits for each sample, like the -law or A-law encoding in the Sun
AU format. Modern compressed audio files use sophisticated psychoacoustics algorithms to
represent the essential frequencies of the audio signal in far less space. Examples include MP3
(MPEG I, layer 3), Ogg Vorbis, and WMA (Windows Media Audio). Audacity supports MP3
and Ogg Vorbis, but not the proprietary WMA format or the MPEG4 format (AAC) used by
Apple's iTunes.
Procedure
CD Quality Hard disk recording of sound
NOTE: If you have an equivalent computer sound recording program on your home
computer you may do this lab using your own software

Sound Recording: Set up a microphone and use Audacity to record a few seconds of your
speech at 44,100 Hz and 16 bits, which are the default settings for Audacity. The lab
instructor will show you how to set up the microphone and record if you have difficulty. You

UMT Lahore Page 96


may also use any of the prerecorded sounds on the computer for the remainder of the
lab or you may even record a few seconds of sound from an audio CD.

Sampling rate conversion

After you record (or otherwise obtain) a short sound file you may use Audacity to change the
sampling rate. This may be accomplished by going to the Project Rate area in the lower
left hand corner of the project window. You are shown a pop up menu in which you may
choose among fixed sample rate options or you can type in any sample rate value you want.
Make sure that you start with sound files that are in 44.1 kHz 16 bit format.
Task-2 Convert and save your files to 22,050 kHz, 11 kHz, 5.5 kHz, 2 kHz, and
1 kHz and comment on the audible artifacts of reducing the sampling rate. Play
the files in Audacity.

3. Quantization levels and distortion


In this part of the lab you can use the furnished Matlab program QuantlevelsCD.m to
manipulate the number of quantization levels of an audio file (as determined by the number
of bits). Here are the first few lines of that program.
% QuantlevelsCD.m
% M-file to convert number of quantization levels of a wav file
clear
close all
Nsec = 10; % Number of seconds of the sound file to process
bits = 4; % change Number of bits for re-quantization
[x,R, nbits] = wavread('salinasCDAudio.wav'); % Read in your wave file, use any file you
like
[x,R, nbits] = wavread('salinasCDAudio.wav');

R, nbits % Print out the sample rate R and the number of quantization levels nbits

UMT Lahore Page 97


x = x(1:Nsec*R)*2^(nbits-1); % Just keep the first Nsec of the file and normalize to integer
levels
soundsc(x,R) % Play back the original
pause(Nsec + 0.5)
xq = round(x/2^(nbits-bits)); % Scale wave file up to +- 2^nbits
soundsc(xq,R) % listen to the requantized sound
start = 1; % Select the part of the file to plot
stop = length(x); % If stop = length(x) the entire file is plotted
len = stop-start;
subplot(211)
plot(x(start:stop), 'k.')
hold on
plot(x(start:stop),'r')
axis([0 len -2^(nbits-1) 2^(nbits-1)])
grid on
title('Original audio')
xlabel('Sample Number')
ylabel('Level')
subplot(212)
plot(xq(start:stop), 'k.')
hold on
plot(xq(start:stop))
axis([0 len -2^(bits-1) 2^(bits-1)])
grid on
title('Re-quantized audio')
xlabel('Sample Number')
ylabel('Level')

The number of quantization levels may be adjusted by changing the value of bits. On
the following line put in the name of the wav file that you want to manipulate,
salinasCDAudio.wav is a guitar recording. This is a good recording with which to

UMT Lahore Page 98


experiment because there are many quiet intervals between the notes. Also experiment
w i t h your recording of yourself speaking. Reduce the number of bits by 1 or 2 bit
increments all the way down to 1-bit.
Analyzing Quantization Effects on a CD Quality Audio
Task-3: Vary No of Quantization bits and observe change in CD Audio quality and Re-
Quantized signal. Save figures. for 4 bit, 8bit,16bit and 32bits and show your work to your lab
instructor.

Analytical Questions
For both recorded speech and the music files at what bit resolution do the quantization
effects become audible? Describe the audible effects in both the spoken and music files at the
different bit-resolution levels. Can you still recognize the sound at 4-bit and 2-bit (even 1-
bit) quantization?

Construct a table of the Signal to Noise Ratio (in decibels) for bit resolutions from 4 bit to
32 bits. (each additional bit is a 6 dB increase of signal to quantization noise ratio)
Sampling Quantization Quality of SQNR, dB
Bits
Rate, R Levels Audio
4
8
16
32

Keeping in mind that a perceived loudness increase of a factor of two corresponds to


approximately 9 dB increase, comment on your perception of the signal to noise ratio at the
various bit resolution levels. For example, referring to the table, how many bits of
resolution would give a quantization noise that is "twice" as loud as it is at 12 bits? Prepare
sound files to check your perception against the table predictions. Keep in mind that this is
subjective.
Maximum compression and intelligibility of speech:
In the final part of this lab you will investigate the maximum extent that you can compress a
speech sound file and maintain its intelligibility. Note that the total size (number of bytes) of a
sound file is determined by the sampling rate AND the bit resolution. Determine the tradeoff of
sampling rate and bit resolution that best maintains intelligibility, i.e., is it better to use a high
sample rate and small number of bits or a low sample rate and a greater number of bits. What is
the greatest data compression factor compared to 44,100 Hz 16-bit sound that you can
achieve?

Write-up
Your write-up should answer all questions posed above and well as to furnish qualitative
descriptions of what you heard in the various tests.

UMT Lahore Page 99


Lab No.11 Reconstruction of analog signal
Objective(s):
Study the effect of signal reconstruction to recover the original analog signal
from a sampled signal using ideal sinc interpolation
Study the effect of signal reconstruction to recover the original analog signal
from a sampled signal using zero-order-hold (ZOH)
Study the effect of signal reconstruction to recover the original analog signal
from a sampled signal using first-order-hold (FOH)

Equipment/Software:
A PC running Windows OS and MATLAB
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH
Edition John G Proakis, Dimitris G. Manolakis
Related Topics from the course textbook: Chapter 6 Sec 6.4 and sec 6.5

Students responsibilities in this lab


1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor

Theoretical Background
Pre-lab: Lab instructor should provide a document: Butterworth Filter design to students for next
lab. Background on Reconstruction
Analog signal is sampled at a fixed time interval so the ADC (Analog-to-Digital Converter) will
convert the sampled voltage level to a digital value; this is called the sampling process.

UMT Lahore Page 100


A band-limited analog signal ( ) with bandwidth F0 can be reconstructed from its sample
values ( ) = ( ) if the sampling frequency Fs = 1/Ts is greater than twice the bandwidth
F0 of ( ) i.e. Fs > 2F0.Otherwise aliasing would result in ( ). The sampling rate of 2F0 for
an analog band-limited signal is called the Nyquist rate.
Samples ( )are converted into weighted impulse train

( ) ( )

Then the impulse train is filtered through an ideal analog low-pass filter band-limited to the
[Fs/2, Fs/2] band.

This two-step procedure can be described mathematically using an interpolating formula

( )= ( ) [ ( )]

UMT Lahore Page 101


Physical interpretation of signal reconstruction using sinc function

Using sinc function is of infinite order and not causal, not practical so in practice we need a
different approach. The two-step procedure is still feasible, but now we replace the ideal low-
pass filter by a practical analog low-pass filter. Ideal Interpolation via sinc function, Zero-Order-
Hold (ZOH), First-Order-hold (FOH), Spline interpolation are familiar methods to reconstruct
the original band-limited analog signal.
The reconstruction (analog low-pass) filter is adopted after DAC to remove the spectral images
that exist in the sample-and-hold signal and obtain the smoothed analog signal. The sample-and-
hold DAC effect may distort the baseband spectrum, but it also reduces image spectrum.
Procedure for this LAB
Open the MATLAB and locate the directory on your PC folder with name: Reconstruction_Lab
Run the reconstruction demos by running the Matlab files. reconstruction_demo_SINC.m,
reconstruction_demo_ZOH.m, reconstruction_demo_FOH.m by locating these files in your
working directory.
Open this file in MATLAB editor, read it and hit the simulation. Perform Task1 to Task-3 and
show your work to Lab instructor.
Sinc Reconstruction

UMT Lahore Page 102


% reconstruction_demo_SINC.m
% SINC RECONSTRUCTION
clear all,clf
endt=1;
ylims=[-1.2 1.2];
% SINC RECONSTRUCTION
t=-endt:1/100:2*endt;
x=cos(2*pi*t);% Analog signal
%x=cost(7*t)+cos(23*t)% another analog signal
figure(1), clf
N=[0 1 2 21];
numplots=length(N)+1;
% original signal
subplot(numplots,1,1), plot(t,x); ylim(ylims);
title('Cos(2{\pi}t) and Its Sinc Reconstructions');
% sinc reconstructions
for i=1:length(N),
ts=(1/2-N(i)*1/2):(1/2):(1/2+N(i)*1/2);
xs=cos(2*pi*ts);
xhat=[];
xhatall=zeros(size(x));
for n=1:length(ts);
xhat(n,:)=xs(n)*sinc(2*(t-ts(n)));
xhatall=xhatall+xhat(n,:);

UMT Lahore Page 103


end;
subplot(numplots,1,i+1), plot(t,xhatall); hold on;
plot(t,xhat,':'); ylim(ylims);
plot(ts,xs,'o');
xlim([-1 2]);
if length(ts)==1,
ylabel('1 term');
else
str=sprintf('%d terms',length(ts)); ylabel(str);
end;
end;

Run the following code


Reconstruction using sinc function for an exponential signal
% sinc_reconstruction.m
%Reconstruction of an exponential signal: exp(-1000t)using ideal Interpolation i.e. sinc
function
clear all;
clf;
close all;
Ts = 0.0002;
Fs=1/Ts;
n = -25:1:25;
nTs = n*Ts;
step = 0.00005;
t = -0.005:step:0.005;
xa = exp(-1000*abs(t)); % Analog signal
xn = exp(-1000*abs(nTs));% Analog sampled Signal with sampling at Ts
% Analog Signal reconstruction

UMT Lahore Page 104


xr = xn * sinc(Fs*(ones(length(n),1)*t-nTs'*ones(1,length(t))));
% ideal interpolation
plot(t,xr,'r',t,xa,'b')
title('Orignal and Reconstructed signal')
legend('reconstructed','original')

error = max(abs(xr - exp(-1000*abs(t))))


%error =0.0363

The maximum error between the reconstructed and the actual analog signal is 0.0363, which is
due to the fact that xa(t) is not strictly band-limited (and also we have a finite number of
samples).

Task-1:
Reconstruct the analog ( ) = exp(| |) using Ts=0.001 and record your observations. Try
different Ts.
Revisit reconstruction_demo_SINC.m and change the analog signal to x(t)=cos7t+cos23t .
Again run the code. Check if sinc interpolation is working or not. Change Ts and try to recover
x(t).What is the error.

Reconstruction using ZOH interpolation


In this interpolation a given sample value is held for the sample interval until the next sample is
received.

which can be obtained by filtering the impulse train through an interpolating filter of the form

UMT Lahore Page 105


which is a rectangular pulse. The resulting signal is a piecewise-constant (staircase) waveform
which requires an appropriately designed analog postfilter for accurate waveform reconstruction.

MATLAB approach for signal reconstruction is a plotting approach. The stairs function plots a
staircase (ZOH) rendition of the analog signal, given its samples,

%% reconstruction_demo_ZOH.m

% reconstruction demo_ZOH
clear all,clf
endt=10;
ylims=[-1.2 1.2];
t=0:1/100:endt;
multiplier=2
x=cos(multiplier*t);
fs=[1 2 3 4];% Sampling Frequencies
%
% ZOH RECONSTRUCTION
%
figure(1), clf;
numplots=length(fs)+1; % no of plots
% original signal
subplot(numplots,1,1), plot(t,x);
title('Cosine function and Its ZOH Reconstructions');

UMT Lahore Page 106


% zoh reconstructions
for i=1:length(fs),
ts=0:1/fs(i):endt;
xs=cos(multiplier*ts);% Sampled Analog Signal
subplot(numplots,1,i+1), plot(ts,xs,'o'), hold on, stairs(ts,xs); ylim(ylims);
str=sprintf('f_s = %d', fs(i)); ylabel(str);
end;
xlabel('time');

Task-2:
Now change the analog signal to x(t)=cos(5*t) and make the following changes in the code at
appropriate places
endt=10;
x=cos(5*t);
xs=cos(5*ts)
fs=[3 6 9 12];% Sampling Frequencies
and run MATLAB script reconstruction_demo_ZOH.m again. Check if ZOH interpolation is
working or not. Change fs vector according to signal and try to recover x(t).

Reconstruction using FOH interpolation


In this case the adjacent samples are joined by straight lines. This can be obtained by filtering the
impulse train through

UMT Lahore Page 107


plot function in MATLAB depicts a linear (FOH) interpolation between samples.
Run the following code
% reconstruction demo_FOH (First order hold)
clear all,clf
endt=10;
ylims=[-1.2 1.2];
t=0:1/100:endt;
x=cos(2*pi*t);
% FOH RECONSTRUCTION
figure(1), clf;
fs=[2 4 8 16];
numplots=length(fs)+1;
% original signal
subplot(numplots,1,1), plot(t,x); ylim(ylims);
title('Cosine function and its FOH Reconstructions');
% foh reconstructions
for i=1:length(fs),
ts=0:1/fs(i):endt;
xs=cos(2*pi*ts);
subplot(numplots,1,i+1), plot(ts,xs,'o',ts,xs); ylim(ylims);
str=sprintf('f_s = %d', fs(i)); ylabel(str);
end;
xlabel('time');

UMT Lahore Page 108


Task-3:
Now change the analog signal to x(t)=cos(5*t) and make the following changes in the code at
appropriate places
x=cos(5*t);
xs=cos(5*ts)
fs=[1 2 3 4];% Sampling Frequencies and run reconstruction_demo_FOH.m again. Check if
FOH interpolation is working or not. Change fs vector according to signal and try to recover
x(t).
Analysis and Write-up
What three types of reconstruction techniques did you learn in this lab? Write a 1 page summary
on various issues related to signal reconstruction and accuracy of the methods. What will happen
if we do up-sampling or discrete-time interpolation: the sampling rate is increased by a factor of
M in discrete time, in order to reduce the demands of the D/A conversion. This allows us to use a
very simple D/A converter. This is used in CD players. Explain why? This will open another
exciting DSP field called multi-rate signal processing.

UMT Lahore Page 109


In CD players data sampling rate is 44.1 kHz. This rate is up sampled by a factor of 8 to 352.8
kHz. By doing so, the need for correction of the ZOH pass band distortion is effectively
eliminated.
In next lab you will design analog low-pass filters as reconstruction filters.
Pre-lab: Lab instructor should provide a document: Butterworth Filters - Laplace Domain.pdf to
students for next lab. Student should read it before coming to next lab.

UMT Lahore Page 110


Lab No.12 Reconstruction using Analog Low-Pass Filter
Objective(s):
Study the effect of signal reconstruction to recover the original analog signal from a
sampled signal using Analog Low-pass filters
Study Butterworth filter magnitude and phase responses
Butterworth filters used as reconstruction filters

Equipment/Software:
A PC running Windows OS and MATLAB
Required Output Files for this lab: .m files for various tasks none
Background: Familiarity with MATLAB
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH
Edition John G Proakis, Dimitris G. Manolakis
Related Topics from the course textbook: Chapter 6 Sec 6.4
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor

Theoretical Background
Analog signal is sampled at a fixed time interval so the ADC (Analog-to-Digital Converter) will
convert the sampled voltage level to a digital value; this is called the sampling process.

A band-limited analog signal ( ) with bandwidth F0 can be reconstructed from its sample
values ( ) = ( ) if the sampling frequency Fs = 1/Ts is greater than twice the bandwidth
F0 of ( ) i.e. Fs > 2F0.Otherwise aliasing would result in ( ). The sampling rate of 2F0 for
an analog band-limited signal is called the Nyquist rate.
Samples ( )are converted into weighted impulse train

( ) ( )

UMT Lahore Page 111


Then the impulse train is filtered through an ideal analog low-pass filter band-limited to the
[Fs/2, Fs/2] band.

This two-step procedure can be described mathematically using an interpolating formula

( )= ( ) [ ( )]

Using sinc function is of infinite order and not causal, not practical so in practice we need a
different approach. The two-step procedure is still feasible, but now we replace the ideal low-
pass filter by a practical analog low-pass filter. Ideal Interpolation via sinc function, Zero-Order-
Hold (ZOH), First-Order-hold (FOH), Spline interpolation are familiar methods to reconstruct
the original band-limited analog signal.
The reconstruction (analog low-pass) filter is adopted after DAC to remove the spectral images
that exist in the sample-and-hold signal and obtain the smoothed analog signal. The sample-and-
hold DAC effect may distort the baseband spectrum, but it also reduces image spectrum.
Reconstruction using Analog Low-Pass Filter
In practice, we often use one of the standard analog low pass filters having order 2 to 10 (or so)
as reconstruction filters. In the previous labs we dealt with basic sampling theory, quantization
and reconstruction using sinc, ZOH and FOH in MATLAB.

This lab
is a
continuation of the sampling and quantization lab. A continuous-time signal which is the sum of
sinusoids, with frequencies of 7 rad/sec and 23 rad/sec, is sampled at three different rates T s1 =
0.05 seconds, Ts2 = 0.1 seconds, and Ts3 = 0.2 seconds. This lab will look at what happens when
these three sampled signals are passed through a low-pass filter in an attempt to reconstruct the
original x(t). For reference, the signal x(t) is shown in the following figure.
( ) = cos(7 ) + cos(23 )
Task-1: Determine the highest frequency in ( ) . What is the corresponding sampling
frequency and sampling period using Nyquist Theorem?

UMT Lahore Page 112


Original Signal x(t)
Butterworth filters constitute a family of filters which share certain characteristics. We will
consider only low-pass Butterworth filters in this lab. The characteristic shared by these filters is
that the locations of the poles of the transfer functions fall into a certain pattern, called the
"Butterworth pattern". The poles of different order filters are all the same distance away from the
origin of the s-plane, with that distance being the cutoff frequency wn rad/sec. The result is that
at the cutoff frequency, the filter's magnitude is -3 db, regardless of the order of the filter. The
roll off of the magnitude curve for frequencies above the cutoff frequency is -20n dB/decade,
where n is the number of poles in the filter (there are no zeros). Bode plots for the magnitudes
and phases of Butterworth filters for orders 1-4 are shown below.

Butterworth Filter Magnitude Response

Butterworth Filter Phase Response

UMT Lahore Page 113


Note that the higher the order of the filter, the steeper the roll-off in the magnitude is. This means
that there can be a narrower band of frequencies between those which are passed by the filter and
those which are rejected. This is normally a benefit. There is a cost associated with the steeper
roll-off, however. The cost is more phase shift in the higher order filters. This phase shift
corresponds to a time delay between input and output. Ideally, we would like to have a filter
which has a magnitude = 1 for frequencies you want to pass and magnitude = 0 for frequencies
you want to reject and have no phase shift from input to output. The transfer functions for the
first 4 Butterworth filters (assuming the cutoff frequency = 1 rad/sec) and the general equation
for the transfer function for an nth-order filter are

( )=( )( )( )
Butterworth Coefficients
n a1 c a2 c2 a3 c3 a4 c4 a5 c5 a6 c6 a7 c7 a8 c8
1 1.0000
2 1.4141 1.0000
3 2.0000 2.0000 1.0000
4 2.6131 3.4142 2.6131 1.0000
5 3.2361 5.2361 5.2361 3.2361 1.0000
Task-2 Generate Magnitude and Phase response for Butterworth Filter of 5th order by
modifying MATLAB code and using coefficients from table above.
We will start by passing the signal which was sampled with Ts1 = 0.05 seconds through the 4th
order Butterworth filter. Remember that both of the sinusoidal frequencies which make up x(t),
w1 = 7 rad/sec and w2 = 23 rad/sec, are less than 1/2 of the sampling frequency (ws1/2 = 62.8319
rad/sec) and that the first few frequencies which appear in X*(jw) when Ts = 0.05 s are:
[-132.6637 -118.6637 -102.6637 -23.0000 -7.0000 7.0000 23.0000
102.6637 118.6637 132.6637] rad/sec
The cutoff frequency for the filter is ws1/2. In the figure below, you can see that the filtered
signal approximates the original x(t) quite well. There is a slight time delay between the original
and reconstructed signal, but not much distortion. One reason for this is that with Ts = 0.05 s,
there is a big gap between the frequencies in x(t) and the next frequency in the sampled signal.

UMT Lahore Page 114


Signal Reconstruction of x(t) with Ts1 = 0.05 s

Observation: Why there is a delay between original signal and reconstructed signal?
Signal Reconstruction of x(t) with Ts2 = 0.1 s
Next, consider Ts2 = 0.1 seconds (ws2 = 62.8319 rad/sec). Both of the frequencies in x(t) are less
than ws2/2 = 31.4159 rad/sec, but now the higher frequency (23 rad/sec) is closer to the top of the
primary strip than with the first sampling period. The first few frequencies which appear in
X*(jw) when Ts = 0.1 s are:
[-69.8319 -55.8319 -39.8319 -23.0000 -7.0000 7.0000 23.0000
39.8319 55.8319 69.8319 85.8319] rad/sec
We will pass this sampled signal through the 4th-order Butter worth filter. The cutoff frequency
is ws2/2 rad/sec. The filtered signal approximates the original x(t) fairly well, in that most of the
peaks and valleys of x(t) are also in the filtered signal. Now there is more time delay and more
distortion in the signal. There is less gap between the frequencies in x(t) and the next frequency
in the sampled signal.
Signal Reconstruction of x(t) with Ts2 = 0.1 s

UMT Lahore Page 115


Signal Reconstruction of x(t) with Ts3 = 0.2 s
Now, consider Ts3 = 0.2 seconds (ws3 = 31.4159 rad/sec). Aliasing has occurred in sampling this
signal because the sampling frequency is less than twice the highest frequency in x(t). The first
few frequencies which appear in X*(jw) when Ts = 0.2 s are:
[-38.4159 -24.4159 -23.0000 -8.4159 -7.0000 7.0000 8.4159
23.0000 24.4159 38.4159] rad/sec
A 4th-order Butterworth filter with a cut-off frequency of ws3/2 = 15.7080 rad/sec is now used to
process the discrete-time samples. The next figure shows that there is significant distortion in the
filtered signal relative to x(t). The higher frequency oscillations in x(t) are absent in the filtered
version of the sampled signal. This filtered signal does not represent the characteristics of the
original x(t) very well at all.
If we compare the filtered signal just produced from the signal sampled at Ts3 = 0.2 seconds with
the signal x1(t) described in the Lab on sampling (x1(t) has frequencies of 7 rad/sec and 8.4159
rad/sec), we see that they are very similar except for the time delay. The aliasing has produced a
sampled signal which accurately describes a different signal, not the original signal. The original
x(t) cannot be recovered from its samples when Ts3 = 0.2 seconds is used as the sampling period.
The false signal x1(t) is the result of low-pass (LP) filtering of the sampled signal.
Comparison of Filtered Signal with x1(t) with Ts3 = 0.2 s

UMT Lahore Page 116


MATLAB Code
% ***** MATLAB Code Starts Here
% Defining the sampling periods and sampling frequencies
fig_size = [232 84 774 624];
Ts1 = 0.05; Ts2 = 0.1; Ts3 = 0.2;
ws1 = 2*pi/Ts1; ws2 = 2*pi/Ts2; ws3 = 2*pi/Ts3;
%
% Frequencies for the continuous-time signal and the time vector.
w1 = 7; w2 = 23;
t = [0:0.005:2];
x = cos(w1*t) + cos(w2*t);
% computing the first few frequencies in the sampled signals.
n = [-1 0 1]; wx = [-w2 -w1 w1 w2];
wx1 = []; wx2 = []; wx3 = [];
for i = 1:length(n)
wx1 = [wx1 (wx + n(i)*ws1)];
wx2 = [wx2 (wx + n(i)*ws2)];
wx3 = [wx3 (wx + n(i)*ws3)];
end
wx1 = sort(wx1); wx2 = sort(wx2); wx3 = sort(wx3);
% Create the low-pass Butterworth filters of orders 1 - 4, with a cutoff
% frequency of 1 rad/sec.
wn = 1;
% Locations of the filters' poles
olp1 = wn*[-1];
olp2 = wn*(1/sqrt(2))*[-1+j;-1-j];
olp3 = wn*[-0.5+j*0.866;-0.5-j*0.866;-1];
ang1 = 112.5*pi/180; ang2 = 157.5*pi/180;
olp4 = wn*[cos(ang1)+j*sin(ang1); cos(ang1)-j*sin(ang1);

UMT Lahore Page 117


cos(ang2)+j*sin(ang2); cos(ang2)-j*sin(ang2)];
% Numerator and denominator polynomials
num = wn;
den1 = real(poly(olp1));
den2 = real(poly(olp2));
den3 = real(poly(olp3));
den4 = real(poly(olp4));
% Magnitudes and phases for the filters
w = logspace(-2,2,401);
[mag1,ph1] = bode(num,den1,w);
[mag2,ph2] = bode(num,den2,w);
[mag3,ph3] = bode(num,den3,w);
[mag4,ph4] = bode(num,den4,w);
% Plots of the magnitudes and phases
figure(1),clf,semilogx(w,20*log10(mag1),w,20*log10(mag2),w,...
20*log10(mag3),w,20*log10(mag4)),grid,xlabel('Frequency (rad/sec)'),...
ylabel('Magnitude (db)'),title('1st - 4th Order Butterworth Filters'),...
axis([.01 100 -100 20]),...
set(gcf,'Position',fig_size),text(13,-25,'1'),text(13,-47,'2'),...
text(13,-72,'3'),text(13,-93,'4')
figure(2),clf,semilogx(w,ph1,w,ph2,w,ph3,w,ph4),grid,...
xlabel('Frequency (rad/sec)'),ylabel('Phase (deg)'),...
title('1st - 4th Order Butterworth Filters'),...
set(gcf,'Position',fig_size),text(13,-80,'1'),text(13,-165,'2'),...
text(13,-270,'3'),text(13,-340,'4')
% Filter the sampled signal from Ts = 0.05 seconds with the 4th-order
% filter. The filter must be re-created with the appropriate cutoff frequency = ws/2.
wn = ws1/2;
olp4 = wn*[cos(ang1)+j*sin(ang1); cos(ang1)-j*sin(ang1);cos(ang2)+j*sin(ang2); cos(ang2)-
j*sin(ang2)];
% Numerator and denominator polynomials
num4 = wn^4; den4 = real(poly(olp4));
% Create the sampled signal from the first several frequencies.
xs1 = 0;
for i = 1:length(wx1)
xs1 = xs1 + 0.5 * cos(wx1(i)*t);
end
% Pass the sampled signal through the filter.
xr14 = lsim(num4,den4,xs1',t);
% Plot the filtered signal and compare with the original signal x(t)
figure(3),clf,plot(t,xr14,'b',t,x,'r:'),grid,...
xlabel('Time (s)'),ylabel('Amplitude'),

UMT Lahore Page 118


title('Reconstructed Signal -- T_s = 0.05, 4th-Order Filter'),...
set(gcf,'Position',fig_size)
% Repeat for the signal sampled with Ts = 0.1 seconds
wn = ws2/2;
olp4 = wn*[cos(ang1)+j*sin(ang1); cos(ang1)-j*sin(ang1);
cos(ang2)+j*sin(ang2); cos(ang2)-j*sin(ang2)];
% Numerator and denominator polynomials
num4 = wn^4; den4 = real(poly(olp4));
% Create the sampled signal from the first several frequencies.
xs2 = 0;
for i = 1:length(wx1)
xs2 = xs2 + 0.5 * cos(wx2(i)*t);
end
% Pass the sampled signal through the filter.
xr24 = lsim(num4,den4,xs2',t);
% Plot the filtered signal and compare with the original signal x(t)
figure(4),clf,plot(t,xr24,'b',t,x,'r:'),grid,...
xlabel('Time (s)'),ylabel('Amplitude'),
title('Reconstructed Signal -- T_s = 0.1, 4th-Order Filter'),...
set(gcf,'Position',fig_size)
% Repeat for the signal sampled with Ts = 0.2 seconds
wn = ws3/2;
olp4 = wn*[cos(ang1)+j*sin(ang1); cos(ang1)-j*sin(ang1);
cos(ang2)+j*sin(ang2); cos(ang2)-j*sin(ang2)];
% Numerator and denominator polynomials
num4 = wn^4; den4 = real(poly(olp4));
% Create the sampled signal from the first several frequencies.
xs3 = 0;
for i = 1:length(wx1)
xs3 = xs3 + 0.5 * cos(wx3(i)*t);
end
% Pass the sampled signal through the filter.
xr34 = lsim(num4,den4,xs3',t);
% Plot the filtered signal and compare with the original signal x(t)
figure(5),clf,plot(t,xr34,'b',t,x,'r:'),grid,...
xlabel('Time (s)'),ylabel('Amplitude'),
title('Reconstructed Signal and x(t) -- T_s = 0.2, 4th-Order Filter'),...
set(gcf,'Position',fig_size)
w2s3 = w2 - ws3;
x1 = cos(w1*t) + cos(w2s3*t);
figure(6),clf,plot(t,xr34,'b',t,x1,'r:'),grid,...
xlabel('Time (s)'),ylabel('Amplitude'),

UMT Lahore Page 119


title('Reconstructed Signal and x_1(t) -- T_s = 0.2, 4th-Order Filter'),...
set(gcf,'Position',fig_size)
clear i
% ***** MATLAB Code Stops Here

Write-Up

Write down a paragraph of your understanding developed in this Lab.

UMT Lahore Page 120


Lab No 13 Design of FIR Filter by Windowing and
Frequency Sampling
Objective(s):
Design of FIR Filters using MATLAB functions
Learn the basis of a digital Finite Impulse Response (FIR) filter design using
Windowing method according to a given filter specification.
Designing FIR Filters using Frequency Sampling approach
Equipment/Software: A PC running Windows OS/sound card with headphone and
MATLAB
Background: Familiarity with MATLAB
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH
Edition John G Proakis, Dimitris G. Manolakis
Required Files: chirp.mat, bat.wav, fir_LP_kaiser.m, fir_LP_hamming, freqz_m, ideal_lp.m
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor

Theoretical Background: Familiarity with FIR Filter structures and design methodologies
Related Topics from the course textbook: Chapter 9 section 9.2, chapter 10 Sec 10.2
MATLAB abs, fdatool, fft, fir1, fir2, fircls1, freqz,
Commands fvtool, imag, impz, log, stem, unwrap, window,.
and functions
The digital filters are used to modify the digital signal amplitude (the gain of the signal
frequency components) according to a desired frequency response. The linear phase
response of the FIR filter means that all of the signal frequency components in the input
are delayed by the same amount.
General Procedure for this LAB
Open the MATLAB editor for writing .m script files
Do examples 1-2 to see the magnitude response of FIR filters
Select the appropriate FIR filter design method (Window Method).
Select the type of the window for the truncation of desired filter impulse response.
Set the appropriate sampling (Fs) and cutoff (Fc) frequencies and design formulas.
Calculate the order of the FIR filter to satisfy the given stopband attenuation.
FIR Filters Design Method: Available MATLAB functions

UMT Lahore Page 121


Filter Design Description Filter
Method Functions
Windowing Apply window to truncated inverse Fourier transform of fir1, fir2,
desired "brick wall" filter kaiserord

Characteristics of fir1 MATLAB function


fir1: FIR filter design (using the window method) function

B = fir1(N,Wn) designs an N'th order lowpass FIR digital filter and returns the filter
coefficients in length N+1 vector B. The cut-off frequency Wn must be between 0 < Wn < 1.0,
with 1.0 corresponding to half the sample rate. The filter B is real and has linear phase,
i.e., even symmetric coefficients obeying B(k) = B(N+2-k), k = 1,2,...,N+1.

If Wn is a two-element vector, Wn = [W1 W2], FIR1 returns an order N bandpass filter with
passband W1 < W < W2.
B = FIR1(N,Wn,'high') designs a highpass filter.
B = FIR1(N,Wn,'stop') is a bandstop filter if Wn = [W1 W2].
B = FIR1(N,Wn,'DC-1') makes the first band a passband.
B = FIR1(N,Wn,'DC-0') makes the first band a stopband.

For filters with a passband near Fs/2, e.g., highpass and bandstop filters, N must be even.
By default FIR1 uses a Hamming window. Other available windows, including Boxcar,
Hanning, Bartlett, Blackman, Kaiser and Chebwin can be specified with an optional trailing
argument.
For example,
B = FIR1(N,Wn,kaiser(N+1,4)) uses a Kaiser window with beta=4.
B = FIR1(N,Wn,'high',chebwin(N+1,R)) uses a Chebyshev window.

FILTER One-dimensional digital filter function


Y = FILTER(B,A,X) filters the data in vector X with the filter described by vectors A and B
to create the filtered data Y. The filter is a "Direct Form II Transposed" implementation of the
standard difference equation:

a(1)*y(n) = b(1)*x(n) + b(2)*x(n-1) + ... + b(nb+1)*x(n-nb) - a(2)*y(n-1) - ... -


a(na+1)*y(n-na)

If a(1) is not equal to 1, FILTER normalizes the filter coefficients by a(1)

FREQZ Z-transform digital filter frequency response function


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

UMT Lahore Page 122


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.

Task-1: Do examples 1-2 to get familiarized with fir1 function

Example 1: Design a 48th-order Linear Phase FIR bandpass filter with passband
0.35 0.65: Run the following code in MATLAB for a bandpass FIR filter.
b = fir1(48,[0.35 0.65]);
freqz(b,1,512)

Example 2: Design a 34th-order FIR highpass filter for a Chirp signal


The chirp.mat data file contains a signal, y that has most of its power above fs/4, or half the
Nyquist frequency. Design a 34th-order FIR highpass filter to attenuate the components of the
signal below fs/4. Use a cutoff frequency of 0.48 and a Chebyshev window with 30 dB of ripple:
clc
clear all
load chirp % Load y and fs. Locate chirp.mat data in your working directory
%Fs =8192Hz chirp is sampled at this frequency
figure(1), plot(y), title('Chirp')
sound(y) % Use headphone to listen to the sound
b = fir1(34,0.48,'high',chebwin(35,30));% filter coefficients in vector b
figure(2) ,freqz(b,1,512)
y=filter(b,1,y); % Apply Highpass filter
figure(3)
psd(y)
title('Power spectral density of filtered signal')

UMT Lahore Page 123


HighPass Filter Frequency Response

Spectral contents after HighPass Filtering

UMT Lahore Page 124


FIR Filter Design using Window Functions
The design of the FIR filter usually is performed by selecting the specification of the filter (the
desired impulse response/frequency response).The general equation of FIR filter is given by
( )= and desired frequency response is given by

( )= ( )

Desired Impulse response:

1
( )= ( )
2

The desired impulse response defined above is infinite in duration and must be truncated and
shifted by( M1)/2 samples to design a real valued and causal FIR filter. Truncation can be
performed by multiplying the desired impulse response ( ) by a window function. The
rectangular window is defined by
1, , = 0,12, . , 1
( )= 0,

The effect of application of rectangular window to the desired frequency response of the filter
can be evaluated by convolution of ( ) with ( )

1
( )= ( ) ( )
2
The Fourier transform W (w) of the rectangular window w (n) is defined by

UMT Lahore Page 125


( )
( )= = sin /sin( )
2 2

Basic window design idea


For the given filter specifications, choose the filter length M and a window function w(n) for
the narrowest main lobe width and the smallest side lobe attenuation possible.

UMT Lahore Page 126


Rectangular window , M=45

Many different windows are available in MATLAB


(The MathWorks, Inc. 2010b) and is used to specify various windows (@bartlett, @hann,
@barthannwin, @blackman, @bohmanwin, @chebwin, @kaiser, @flattopwin, @taylorwin,
@gausswin, @nuttallwin, @hamming, @parzenwin, @rectwin, @tukeywin, @triang,
@blackmanharris)

UMT Lahore Page 127


UMT Lahore Page 128
Pls refer to John G Proakis Book: Digital Signal Processing using MATLAB, 3rd ed.,
Chapter-7, Cengage Learning, 2010

KAISER WINDOW: This is an adjustable window function widely used in practice.

Where I0 [ ]is the modified zero-order Bessel function and controls the stopband
attenuation,
Empirical equations:

UMT Lahore Page 129


Task-2
Design a digital FIR lowpass filter with the following specifications:
p = 0.2=passband frequency
s = 0.3=stopband frequency
Rp = 0.25 dB=Passband ripple
As = 50 dB=Stop band attenuation
Choose an appropriate window function from Table above .Determine the impulse response
and provide a plot of the frequency response of the designed filter. Use Hamming Window.

Write Matlab code and save your graphs.

% fir_LP_hamming.m
wp = 0.2*pi; ws = 0.3*pi; tr_width = ws - wp;5 Delta_W
M = ceil(6.6*pi/tr_width) + 1; % window size
n=0:1:M-1;
wc = (ws+wp)/2; % Ideal LPF cutoff frequency
hd = ideal_lp(wc,M);% ideal low pass filter function
w_ham = (hamming(M))'; % Using Haming window
h = hd .* w_ham;% Actual windowed response

[db,mag,pha,grd,w] = freqz_m(h,1); %Frequency response


delta_w = 2*pi/1000;
Rp = -(min(db(1:1:wp/delta_w+1))); % Actual Passband Ripple
As = -round(max(db(ws/delta_w+1:1:501))); % Min Stopband attenuation
% plots
subplot(2,2,1); stem(n,hd); title('Ideal Impulse Response')
axis([0 M-1 -0.1 0.3]); xlabel('n'); ylabel('hd(n)')
subplot(2,2,2); stem(n,w_ham);title('Hamming Window')
axis([0 M-1 0 1.1]); xlabel('n'); ylabel('w(n)')
subplot(2,2,3); stem(n,h);title('Actual Impulse Response')
axis([0 M-1 -0.1 0.3]); xlabel('n'); ylabel('h(n)')
subplot(2,2,4); plot(w/pi,db);title('Magnitude Response in dB');grid

UMT Lahore Page 130


axis([0 1 -100 10]); xlabel('frequency in pi units'); ylabel('Decibels')

%ideal_lp.m
function hd = ideal_lp(wc,M);
% Ideal LowPass filter computation
% --------------------------------
% [hd] = ideal_lp(wc,M)
% hd = ideal impulse response between 0 to M-1
% wc = cutoff frequency in radians
% M = length of the ideal filter
%
alpha = (M-1)/2; n = 0:1:(M-1);
m = n - alpha; fc = wc/pi; hd = fc*sinc(fc*m);

function [db,mag,pha,grd,w] = freqz_m(b,a)


% Modified version of freqz subroutine
% ------------------------------------
% [db,mag,pha,grd,w] = freqz_m(b,a);
% db = Relative magnitude in dB computed over 0 to pi radians
% mag = absolute magnitude computed over 0 to pi radians
% pha = Phase response in radians over 0 to pi radians
% grd = Group delay over 0 to pi radians
% w = 501 frequency samples between 0 to pi radians
% b = numerator polynomial of H(z) (for FIR: b=h)
% a = denominator polynomial of H(z) (for FIR: a=[1])
%
[H,w] = freqz(b,a,1000,'whole');
H = (H(1:1:501))'; w = (w(1:1:501))';
mag = abs(H); db = 20*log10((mag+eps)/max(mag));
pha = angle(H); grd = grpdelay(b,a,w);

RESPONSE

UMT Lahore Page 131


Task-3
Design a digital FIR lowpass filter with the following specifications:
p = 0.2=passband frequency
s = 0.3=stopband frequency
Rp = 0.25 dB=Passband ripple
As = 50 dB=Stop band attenuation
Choose an appropriate window function from Table above .Determine the impulse response
and provide a plot of the frequency response of the designed filter. Use Kaiser Window.

Write Matlab code and save your graphs.

%fir_lp_kaiser.m
% Low Pass filter design using Kaiser window
wp = 0.2*pi; ws = 0.3*pi; As = 50; tr_width = ws wp;
M = ceil((As-7.95)/(2.285*tr_width)+ 1);
n=0:1:M-1;
beta = 0.1102*(As-8.7);

wc = (ws+wp)/2;
hd = ideal_lp(wc,M);% ideal low pass filter function
w_kai = (132aiser(M,beta));
h = hd .* w_kai;
[db,mag,pha,grd,w] = freqz_m(h,1); delta_w = 2*pi/1000;
As = -round(max(db(ws/delta_w+1:1:501))); % Min Stopband Attenuation

% plots
subplot(2,2,1); stem(n,hd); title(Ideal Impulse Response)
axis([0 M-1 -0.1 0.3]); xlabel(n); ylabel(hd(n))
subplot(2,2,2); stem(n,w_kai);title(Kaiser Window)
axis([0 M-1 0 1.1]); xlabel(n); ylabel(w(n))
subplot(2,2,3); stem(n,h);title(Actual Impulse Response)
axis([0 M-1 -0.1 0.3]); xlabel(n); ylabel(h(n))
subplot(2,2,4); plot(w/pi,db);title(Magnitude Response in dB);grid
axis([0 1 -100 10]); xlabel(frequency in pi units); ylabel(Decibels)

Your graphs should look like this

UMT Lahore Page 132


FIR Filter design using windowingcomplete program
% MATLAB program for FIR Filter using windowing Techniques
clc;
clear all;
close all;
rp=input('enter passband ripple');
rs=input('enter the stopband ripple');
fp=input('enter passband freq');
fs=input('enter stopband freq');
f=input('enter sampling freq ');
wp=2*fp/f;
ws=2*fs/f;
num=-20*log10(sqrt(rp*rs))-13;
dem=14.6*(fs-fp)/f;
n=ceil(num/dem);
n1=n+1;
if(rem(n,2)~=0)
n1=n;
n=n-1;
end
c=input('enter your choice of window function 1. rectangular 2. triangular
3.kaiser: \n ');
if(c==1)
y=rectwin(n1);
disp('Rectangular window filter response');
end
if (c==2)
y=triang(n1);
disp('Triangular window filter response');
end
if(c==3)
y=kaiser(n1);
disp('kaiser window filter response');
end
%LPF
b=fir1(n,wp,y);
[h,o]=freqz(b,1,256);

UMT Lahore Page 133


m=20*log10(abs(h));
subplot(2,2,1);plot(o/pi,m);
title('LPF');
ylabel('Gain in dB-->');
xlabel('(a) Normalized frequency-->');
%HPF
b=fir1(n,wp,'high',y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,2);plot(o/pi,m);
title('HPF');
ylabel('Gain in dB-->');
xlabel('(b) Normalized frequency-->');
%BPF
wn=[wp ws];
b=fir1(n,wn,y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,3);plot(o/pi,m);
title('BPF');
ylabel('Gain in dB-->');
xlabel('(c) Normalized frequency-->');
%BSF
b=fir1(n,wn,'stop',y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,4);plot(o/pi,m);
title('BSF');
ylabel('Gain in dB-->');
xlabel('(d) Normalized frequency-->');

enter passband ripple0.02


enter the stopband ripple0.01
enter passband freq1000
enter stopband freq1500
enter sampling freq 10000
enter your choice of window function 1. rectangular 2. triangular 3.kaiser:
3
kaiser window filter response

UMT Lahore Page 134


FIR Filter Design using Frequency sampling approach

Please refer to John G Proakis : Digital Signal Processing using MATLAB, 3rd edition, Cengage
Learning, 2010 Chapter-7 Section 7.4 for more details.

Task-4
Design a digital FIR lowpass filter with the following specifications:
p = 0.2=passband frequency
s = 0.3=stopband frequency
Rp = 0.25 dB=Passband ripple
As = 50 dB=Stop band attenuation
Use Frequency Sampling method.

Run the following code in MATLAB

% Freq. Samp. Tech.: Lowpass,Naive method

M = 20; alpha = (M-1)/2; l = 0:M-1; wl = (2*pi/M)*l;


Hrs = [1,1,1,zeros(1,15),1,1];
Hdr = [1,1,0,0]; wdl = [0,0.25,0.25,1];
k1 = 0:floor((M-1)/2); k2 = floor((M-1)/2)+1:M-1;
angH = [-alpha*(2*pi)/M*k1, alpha*(2*pi)/M*(M-k2)];
H = Hrs.*exp(j*angH);
h = real(ifft(H,M));
[db,mag,pha,grd,w] = freqz_m(h,1);
[Hr,ww,a,L] = Hr_Type2(h);
subplot(1,1,1)
subplot(2,2,1);plot(wl(1:11)/pi,Hrs(1:11),'o',wdl,Hdr);
axis([0,1,-0.1,1.1]); title('Frequency Samples: M=20')
xlabel('frequency in pi units'); ylabel('Hr(k)')

% Computes Amplitude response of Type-2 LP FIR filter


function [Hr,w,b,L] = Hr_Type2(h);

UMT Lahore Page 135


% ---------------------------------------------------
% [Hr,w,b,L] = Hr_Type2(h)
% Hr = Amplitude Response
% w = frequencies between [0 pi] over which Hr is computed
% b = Type-2 LP filter coefficients
% L = Order of Hr
% h = Type-2 LP impulse response
%
M = length(h);
L = M/2;
b = 2*[h(L:-1:1)];
n = [1:1:L]; n = n-0.5;
w = [0:1:500]'*pi/500;
Hr = cos(w*n)*b';

UMT Lahore Page 136


Lab No-14: Filter Design and Analysis using FDATool and
FVTool
Objective(s):
Design of FIR Filters using MATLAB FDATool and FVTool
Learn the basis of a digital Finite Impulse Response (FIR) filter design according to
a given filter specification.
Analysis of Linear FIR filter, having no feedback from past outputs and linear
phase response
Equipment/Software: A PC running Windows OS and MATLAB
Theoretical Background: Familiarity with FIR and IIR Filter structures and design
procedures
Related Topics from the course textbook: Chapter 9 sec 9.2 and sec 9.3 Chapter 10 sec 10.2
and sec 10.3
Required Output Files for this lab: .m files for various tasks
Background: Familiarity with MATLAB, FDATool and FVTool
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH Edition
John G Proakis, Dimitris G. Manolakis
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor
MATLAB abs, fdatool, fft, fir1, fir2, fircls1, freqz,
Commands and fvtool, imag, impz, log, stem, unwrap, window,.
functions

The digital filters are used to modify the digital signal amplitude (the gain of the signal
frequency components) according to a desired frequency response. The linear phase
response of the FIR filter means that all of the signal frequency components in the input
are delayed by the same amount.
General Procedure for this LAB
Open the MATLAB get familiar with the graphical user interface (GUI) for digital filter design
found in DSP System Toolbox (The MathWorks, Inc.).
Start the Filter Design and Analysis Tool
Select the filter response type accordingly to the task requirements.
Select the appropriate FIR filter design method (Window).
Select the type of the window for the truncation of desired filter impulse response.
Set the appropriate sampling (Fs) and cutoff (Fc) frequencies.

UMT Lahore Page 137


Change the order of the FIR filter to satisfy the given stopband attenuation.
After designing the filter in FDATool, go to FVTool for analysis
Task 1: Low-Pass Filter design specification
Tool: fdatool
Stopband attenuation of 60 dB
Frequency at the edge of the pass band: 1500 Hz
Frequency at the beginning of the stopband: 1600 Hz
use Kaiser window
Order: Minimum

Task 2: Band-Pass Filter design specification


Tool: fdatool
Stopband attenuation of 40 dB
Frequencies at the edge of the pass band: 320 Hz and 460 Hz
Frequencies at the edge of the stopband: 270 Hz and 510 Hz
use Blackman-Harris window
Order: Minimum

FIR Filter Design


Digital filters with finite-duration impulse response (all-zero, or FIR filters) have both
advantages and disadvantages compared to infinite-duration impulse response (IIR) filters.
FIR filters have the following primary advantages:
They can have exactly linear phase.
They are always stable.
The design methods are generally linear.
They can be realized efficiently in hardware.
The filter startup transients have finite duration.
The primary disadvantage of FIR filters is that they often require a much higher filter order than
IIR filters to achieve a given level of performance. Correspondingly, the delay of these filters is
often much greater than for an equal performance IIR filter.
Method Description MATLAB
Functions
Windowing Apply window to truncated inverse Fourier transform fir1, fir2,
of desired "brick wall" filter kaiserord
Multiband with Equiripple or least squares approach over sub-bands firls, remez,
Transition Bands of the frequency range remezord
Constrained Least Minimize squared integral error over entire frequency fircls, fircls1
Squares range subject to maximum error constraints

UMT Lahore Page 138


Arbitrary Response Arbitrary responses, including nonlinear phase and cremez
complex filters
Raised Cosine Lowpass response with smooth, sinusoidal transition firrcos

FDATool: 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. FVTool, which can be launched
from FDATool, provides a separate window for analyzing filters. You can use FDATool as a
convenient alternative to the command line filter design functions. This chapter contains the
following sections, which walk you through a typical filter design session using the FDATool:
fdatool opens the Filter Design and Analysis Tool (FDATool). Use this tool to
Design filters
Analyze filters
Modify existing filter designs
Getting Started
Type fdatool at the MATLAB command prompt:
>>fdatool

UMT Lahore Page 139


Choosing a Filter Response Type
You can choose from several filter types:
Lowpass
Highpass
Bandpass
Bandstop
Differentiator
Hilbert transformer
Multiband
Arbitrary magnitude
Raised cosine
Choosing a Filter Design Method
You can use the default filter design method for the filter type that you've selected, or you can
select a filter design method from the available FIR and IIR methods listed in the GUI.
To select the Remez algorithm to compute FIR filter coefficients, select the FIR radio button and
choose Equiripple from the list of methods.

UMT Lahore Page 140


Setting the Filter Design Specifications
The filter design specifications that you can set vary according to filter type and design method.
For example, to design a bandpass filter, you can enter
Filter Order
Options
Bandpass Filter Frequency Specifications
Bandpass Filter Magnitude Specifications
The display region illustrates filter specifications when you select Filter Specifications from the
Analysis menu or when you click the Filter Specifications toolbar button.

Filter Order You have two mutually exclusive options for determining the filter order when
you design an Equiripple filter:
Specify order: You enter the filter order in a text box.
Minimum order: The filter design method determines the minimum order filter.
Bandpass Filter Frequency Specifications
For a bandpass filter, you can set
Units of frequency:
Hz
kHz
MHz
Normalized (0 to 1)
Sampling frequency
Passband frequencies
Stopband frequencies
You specify the passband with two frequencies. The first frequency determines the lower edge of
the passband, and the second frequency determines the upper edge of the passband.

UMT Lahore Page 141


Similarly, you specify the stopband with two frequencies. The first frequency determines the
upper edge of the first stopband, and the second frequency determines the lower edge of the
second stopband.
EXAMPLE
Keep the units in Hz (default).
Set the sampling frequency (Fs) to 2000 Hz.
Set the end of the first stopband (Fstop1) to 200 Hz.
Set the beginning of the passband (Fpass1) to 300 Hz.
Set the end of the passband (Fpass2) to 700 Hz.
Set the beginning of the second stopband (Fstop2) to 800 Hz.

Bandpass Filter Magnitude Specifications


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

Computing the Filter Coefficients

UMT Lahore Page 142


Now that you've specified the filter design, click the Design Filter button to compute the filter
coefficients. Notice that the Design Filter button is disabled once you've computed the
coefficients for your filter design. This button is enabled again once you make any changes to the
filter specifications.
Analyzing the Filter
Once you've designed the filter, you can view the following filter response characteristics in the
display region or in a separate window (see displaying the Response in FVTool):
Magnitude response
Phase response
Overlaid magnitude and phase responses
Group delay response
Impulse response
Step response
Pole-zero plot
Zero-phase response--available from the y-axis context menu in a Magnitude or Magnitude and
Phase response plot.
You can also display the filter coefficients in this region.
For all the analysis methods, except zero-phase response, you can access them from the Analysis
menu, the Analysis Parameters dialog box from the context menu, or by using the toolbar
buttons. For zero-phase, right-click on the y-axis of the plot and select Zero-phase from the
context menu.

Displaying the Response in FVTool


To display the filter response characteristics in a separate window, select Full View Analysis

from the Analysis menu or click the Full View Analysis button:
This launches the Filter Visualization Tool (fvtool).
You can use this tool to annotate your design, view other filter characteristics, and print your
filter response. You can link FDATool and FVTool so that changes made in FDATool are
immediately reflected in FVTool. See fvtool for more information.

UMT Lahore Page 143


Using Data Markers You can click on the response to add plot data markers that display
information about particular points on the response.

To move a data marker, grab its black square at the corner of the marker. Dragging the marker
with your mouse changes the Frequency and Magnitude values.
To change the properties of a data marker, right-click on the marker to display the properties
menu:
Alignment--Change the position of the marker. Available options are top-right, top-left, bottom-
right, and bottom-left.
Font Size--Change the font size.
Movable--Allow the marker to be moved on the response.
Interpolation--Select Nearest to force the marker to snap to nearest point along the plotted
curve. Select Linear to interpolate between points along the plotted curve.

UMT Lahore Page 144


Track Mode--Restrict the marker to be movable in the x, y, or xy direction.
Delete--Delete the selected marker.
Delete all--Delete all markers.
fvtool
Open Filter Visualization Tool
Syntax
fvtool(b,a)
fvtool(sos)
h=fvtool(...)
Description
fvtool(b,a) opens FVTool and displays the magnitude response of the digital filter defined with
numerator, b and denominator, a. Using FVTool you can display the phase response, group
delay, impulse response, step response, pole-zero plot, and coefficients of the filter. You can
export the displayed response to a file with File > Export.
Converting the Filter Structure
Converting to a New Structure
You can use Edit->Convert Structure to convert the current filter to a new structure. All filters
can be converted to the following representations:
Direct form I
Direct form II
Direct form I transposed
Direct form II transposed
State-space
Lattice ARMA
Exporting Coefficients or Objects to the Workspace
You can save the filter as filter coefficients variables or as a dfilt or qfilt filter object variable. To
save the filter to the MATLAB workspace:
Select Export from the File menu. The Export dialog box appears.
Select Workspace from the Export To menu.
Select Coefficients from the Export As menu to save the filter coefficients or select Objects to
save the filter in a filter object.
For coefficients, assign variable names using the Numerator and Denominator text boxes in the
Variable Names region. For objects, assign the variable name in the Discrete or Quantized
filter text box. If you have variables with the same names in your workspace and you want to
overwrite them, select the Overwrite Variables box.
Click the OK button

UMT Lahore Page 145


Exporting Coefficients to a Text-File
To save filter coefficients to a text file:
Select Export from the File menu. The Export dialog box appears.
Select Text-file from the Export To menu.
Select Coefficients from the Export As menu to save the filter coefficients.
For coefficients, assign variable names using the Numerator and Denominator text boxes in the
Variable Names region.
Click the OK button. The Export Filter Coefficients to a Text-file dialog box appears.
Choose a filename and click the Save button.
The coefficients are saved in the text file that you specified, and the MATLAB Editor opens to
display the file.
Exporting Coefficients or Objects to a MAT-File
To save filter coefficients or a filter object as variables in a MAT file:
Select Export from the File menu. The Export dialog box appears.
Select MAT-file from the Export To menu.
Select Coefficients from the Export As menu to save the filter coefficients or select Objects to
save the filter in a filter object.
For coefficients, assign variable names using the Numerator and Denominator text boxes in the
Variable Names region. For objects, assign the variable name in the Discrete or Quantized
filter text box.
Click the OK button. The Export Filter Coefficients to a MAT-file dialog box appears.
Choose or enter a filename and click the Save button.
Realizing Filters as Simulink Subsystem Blocks
After you design or import a filter in FDATool, the realize model feature lets you create a
Simulink subsystem block that implements your filter. The generated filter subsystem block uses
the delay, gain, and sum fixed-point blocks from the Fixed-Point Blockset. If you do not own the
Fixed-Point Blockset, FDATool still realizes your model using fixed-point blocks from
Simulink, but you cannot run any model that includes your filter subsystem block in Simulink.
About the Realize Model Panel in FDATool

UMT Lahore Page 146


Switching FDATool to realize model mode, by clicking

on the sidebar, gives you access to the Realize Model panel and the options for realizing
your quantized filter as a Simulink subsystem block.
On the panel, as shown here, are the options provided for configuring how FDATool realizes
your model.

Task-3: Very important: After hands-on experience with fdatool and fvtool
For Task 1
Using FDATool/FVTool
Plot Magnitude and phase response
Plot Group delay response
Plot Impulse response
Plot Step response
Pole-zero plot
Export filter coefficients into a text file (.mat file)
What is the order of the filter that you designed in Task-1
Is it stable?
In fdatool select Quantization icon and quantize filter coefficients to fixed-point filter
arithmetic
What is the filter-structure

Task 4: TAKE-HOME
Design Band-stop Filter
design specifications
Tool: fdatool
Design Method: FIREquiripple
Stopband attenuation of 45 dB
Frequencies at the edge of the pass band: 610 Hz and 1050 Hz
Frequencies at the edge of the stopband: 680 Hz and 940 Hz
use Hamming window
Order: Minimum
Write-up and Analysis: Explore different features of fdatool, FVTool along with SPTool. Write
a one page summary how would you implement your designed filters in hardware, say you have
a DSP processor board and CODE Composer software studio from Texas Instruments and you
have a quantized coefficients of the filter. You do the simulation in MATLAB and your design is
ready for hardware implementation.

UMT Lahore Page 147


Lab No 15 Design of IIR Filter in MATLAB
Objective(s):
Design of IIR Filters using MATLAB functions
Learn the basis of a digital Infinite Impulse Response (IIR) filter design using
Impulse Invariance and Bilinear Transformation
Analyze the designed filter using FVTool
Equipment/Software: A PC running Windows OS/sound card and MATLAB
Theoretical Background: Familiarity with IIR Filter structures and design methodologies
Related Topics from the course textbook: Chapter 10 Sec 10.3
Required Output Files for this lab: .m files for various tasks
Reference Book: Digital Signal Processing Principles, Algorithms and Applications 4TH
Edition John G Proakis, Dimitris G. Manolakis
Students responsibilities in this lab
1. Write MATLAB script 2. Generate all the
(.m file) MATLAB
/SIMULINK graphs
3. Do all the tasks 4. Submit report write-up
for previous lab at the
start of the lab
5. Save your files for 6. Show your work to
future usage your lab instructor
MATLAB buttord, butter
Commands cheb1ord, cheby1, cheb2ord, cheby2 and ellipord , ellip, besself
and functions
There are two approaches as shown below to design IIR filter. Approach-1 is used in
MATLAB.

The primary advantage of IIR Filters over FIR filters is that they typically meet a given set of
specifications with a much lower filter order than a corresponding FIR filter. This has the
obvious implementation advantages. IIR filters have nonlinear phase (they cannot have linear
phase; they might almost have linear phase).However, if data processing is to be performed
offline, then the effects of the nonlinear phase can be eliminated. So let us assume that the entire

UMT Lahore Page 148


input data sequence is available prior to filtering. This allows for a non-causal, zero-phase
filtering approach (via the filtfilt function), which eliminates the nonlinear phase distortion of an
IIR filter.
Types of IIR Filters
The classical IIR filters - Butterworth, Chebyshev Types I and II, elliptic, and Bessel - all
approximate the ideal \brick wall" filter in different ways. The Signal Processing Toolbox
provides functions to create all these types of IIR filters in both the analog and digital domains
(except Bessel, for which only the analog case is supported and in lowpass, highpass, bandpass,
and bandstop configurations). For most filter types, you can also find the lowest filter order that
fits a given filter specification in terms of passband ripple, stopband attenuation, and the
transition band widths.
Butterworth filter
Provides the best Taylor series approximation to the ideal lowpass filter response at analog
frequencies = 0 = for any order n, the magnitude squared response has 2n-1 zero
derivatives (that is, it is maximally flat) at these locations. Response is monotonic overall,
decreasing smoothly from = 0 = .
Chebyshev Type I filter
Minimizes the absolute difference between the ideal and the actual frequency response over the
entire Passband by using an equal ripple in the passband. Stopband response is maximally flat
.The transition from passband to stopband is more rapid than for the Butterworth filter.
Chebyshev Type II filter
Minimizes the absolute difference between the ideal and the actual frequency response over the
entire stopband by using an equal ripple in the stopband. Passband response is maximally flat.
The stopband does not approach zero as quickly as the type I filter (and does not approach zero
at all for even-valued filter order n). The absence of ripple in the passband, however, is often an
important advantage.
Elliptic filter
Equiripple in both the passband and stopband. Generally meets filter requirements with the
lowest order of any supported filter type. Given a filter order n, passband ripple, and stopband
ripple, elliptic filters minimize transition width.
Bessel filter
Analog lowpass filters have maximally at group delay at zero frequency and retain nearly
constant group delay across the entire passband. Filtered signals therefore maintain their
waveform in the passband. Digital Bessel filters, however, do not have this maximally at
property, and are not supported by Matlab .Generally require a higher filter order than other
filters for satisfactory stopband attenuation.
Analog Prototyping
The principal design technique for digital IIR filters supported by the Signal Processing Toolbox
is based on the conversion of classical lowpass analog filters to their digital equivalents. The
technique involves three steps:
Find an analog lowpass filter with cutoff frequency of 1 and translate this prototype filter to the
desired band configuration.

UMT Lahore Page 149


Transform the filter to the digital domain.
Discretize the filter.
Filter Order Calculations buttord, butter
MATLAB Functions for cheb1ord, cheby1, cheb2ord, cheby2 and ellipord , ellip,
Butterworth and Chebyshev besself functions perform minimum order computations
Type-1 and Type-2 Filters for IIR filters and do all the deign

The toolbox provides functions


Design task Available Low level functions
Analog Low Pass prototype buttap, cheb1ap, besselap,
ellipap, cheb2ap
Frequency Transformation lp2lp, lp2hp, lp2bp, lp2bs
Discretization bilinear, impinvar

Task-1
Design first Butterworth Lowpass IIR Filter and then convert it into High pass filter
Get the passband and stopband ripples
Get the passband and stopband edge frequencies
Calculate the order of the filter using buttord function
Find the filter coefficients, using butter function
Draw the magnitude and phase response
% Lowpass Butterworth Filter
clc;
clear all;
close all;
rp=input('enter the passband attenuation:');
rs=input('enter the stop band attenuation:');
wp=input('enter the pass band frequency:');
ws=input('enter the stop band frequency:');
[N,wn]=buttord(wp/pi,ws/pi,rp,rs);
[b,a]=butter(N,wn);
freqz(b,a);
Lowpass and Highpass Butterworth IIR Filters
Use SAMPLE INPUT for Lowpass filter
enter the passband attenuation:0.4
enter the stop band attenuation:50
enter the pass band frequency:0.2*pi
enter the stop band frequency:0.4*pi
Use SAMPLE INPUT for Highpass filter
% for Highpass use [b,a]=butter(N,wn,high);
enter the passband attenuation:0.4
enter the stop band attenuation:30
enter the pass band frequency:0.6*pi
enter the stop band frequency:0.4*pi

UMT Lahore Page 150


Lowpass Butterworth filter Magnitude and Phase response

Highpass Butterworth filter Magnitude and Phase response

UMT Lahore Page 151


Task-2: Bandpass and Bandstop Butterworth IIR Filter Design

First change the code [b,a]=butter(N,wn,'high'); to [b,a]=butter(N,wn);


For BandPASS filter enter the following after running the same above code
enter the passband attenuation:0.2
enter the stop band attenuation:30
enter the pass band frequency:[0.2*pi,0.4*pi]
enter the stop band frequency: [0.1*pi,0.5*pi]

For BandSTOP enter the following after running the same above code
Use [b,a]=butter(N,wn,stop);
% Note the difference: vector of frequencies are provided
enter the passband attenuation:0.2
enter the stop band attenuation:30
enter the pass band frequency:[0.1*pi,0.5*pi]
enter the stop band frequency:[0.2*pi,0.4*pi]

You should get the following graphs for BandPASS filter

UMT Lahore Page 152


You should get the following graphs for BandSTOP filter

UMT Lahore Page 153


Task-3
Design Lowpass, highpass, bandpass and bandstop Chebyshev Type-1&2 Filters.Use the
following code segments
For Lowpass and Highpass filter write the corresponding system function H(z) using[ b, a]
vectors. For example if
b0 = 0.1214
B = 1.0000 -1.4211 1.0000
1.0000 1.0000 0
A = 1.0000 -1.4928 0.8612
1.0000 -0.6183 0
The corresponding system function is

%Sample code for sample input

%code
clc;
clear all;
close all;
rp=input ('Enter the pass band attenuation:');
rs=input ('Enter the stop band attenuation:');
wp=input ('Enter the pass band frequency:');
ws=input ('Enter the stop band frequency:');
[N,wn]=cheb1ord(wp/pi,ws/pi,rp,rs);
[b,a]=cheby1(N,rp,wn);
freqz(b,a);

Sample input:
Enter the pass band attenuation:2
Enter the stop band attenuation:80
Enter the pass band frequency:0.3*pi
Enter the stop band frequency:0.4*pi

UMT Lahore Page 154


Type-1 Chebyshev Filters
For Highpass: use
[N,wn]=cheb1ord(wp/pi,ws/pi,rp,rs);
[b,a]=cheby1(N,rp,wn,'high'); Chebyshev Type-1

For Bandstop:use
[N,wn]=cheb1ord(wp/pi,ws/pi,rp,rs); % Chebyshev Type-1
[b,a]=cheby1(N,rp,wn,'stop');
Type-2 Chebyshev Filters

[N,wn]=cheb2ord(wp/pi,ws/pi,rp,rs);
[b,a]=cheby2(N,rp,wn);%Lowpass and Bandpass depending upon wn
%[N,wn]=cheb2ord(wp/pi,ws/pi,rp,rs);
%[b,a]=cheby2(N,rp,wn,'high');%Highpass

[N,wn]=cheb2ord(wp/pi,ws/pi,rp,rs);
[b,a]=cheby2(N,rp,wn,'stop');%Bandstop

Elliptic filters
Finally, for designing an elliptic digital filter, the commands are
[num,den] = ellip(N,Rp,Rs,Wn)
[num,den] = ellip(N,Rp,Rs,Wn,filtertype)

IIR Filter design using Bi-Linear Transformation

UMT Lahore Page 155


Frequency Transformations:

MATLAB function for Bilinear Transformation

UMT Lahore Page 156


Task-4
IIR Filter Design using Bilinear Transformation (BLT)
The normalized lowpass filter with a cutoff frequency of 1 rad/sec is given as:
( ) = 1/( + 1)
Use the given H(s) and the BLT to design a corresponding digital IIR Highpass filter with a
cutoff frequency of 15 Hz and a sampling rate of 90 Hz.
Plot the magnitude response and phase response of H(z).
Code for Lowpass filter is given below. Convert this code to Highpass Digital IIR filter with
given specifications.
Use the command fvtool(b,a) at MATLAB command prompt and do filter visualization and
analysis.
Get the following information using >>fvtool(b,a) then Analysis- Filter information

%Design a Lowpass Filter using Bilinear Transformation


% Plot the magnitude and phase responses
clear all
clc
fs =90;% Sampling rate (Hz)
[B, A]=lp2lp(1,[1 1],103.92);
[b, a]=bilinear(B, A, fs);
%b =[0.3660 0.3660] numerator coefficients of the digital filter from MATLAB
%a =[1 _0:2679]denominator coefficients of the digital filter from MATLAB
[hz, f]=freqz([0.3660 0.3660],[1 -0.2679],512,fs);%the frequency response
phi=180*unwrap(angle(hz))/pi;
subplot(2,1,1), plot(f, abs(hz)),grid;
axis([0 fs/2 0 1]);
xlabel('Frequency (Hz)'); ylabel('Magnitude Response')
subplot(2,1,2), plot(f, phi); grid;
axis([0 fs/2 -100 0]);
xlabel('Frequency (Hz)'); ylabel('Phase (degrees)')

UMT Lahore Page 157


% convert this code to Highpass Digital IIR filter with specifications given above

Get the following information using >>fvtool(b,a) then Analysis- Filter information

Analysis and Write-Up:


Can you write H(z) from [b,a] for Highpass filter, its difference equation and implement
the resulting structure using Direct-Form-II Transposed as seen from FVTOOL filter
information. How many adders, multipliers and delay units are required for this
implementation?

UMT Lahore Page 158


Lab No 16 IIR and FIR Filter design using DSK 6713
EQUIPMENTS:
Operating System - Windows XP Service Pack 3
Constructor - Simulator
Software - CC Studio 3 & MATLAB
THEORY:
IIR Filters:
The IIR filter can realize both the poles and zeroes of a system because it has a rational transfer
function, described by polynomials in z in both the numerator and the denominator. IIR filters can be
expanded as infinite impulse response filters. In designing IIR filters, cutoff frequencies of the filters
should be mentioned. The order of the filter can be estimated using butter worth polynomial. Thats
why the filters are named as butter worth filters. Filter coefficients can be found and the response can
be plotted.

Procedure: IIR

1. open DSP lab folder.


2. double click on setup ccstudio 3.1
3. select all in family
4. simulator in platform.
5. little in endianness.
6. Select c6713 device functional simulator,little endian.
7. next click on import.
8. next click on save and quit.
9. say yes on start code composer studio on exit?.
10. a window will open named on the tool bar as : /c6713 device functional
simulator/cpu_1-c6713(simulator) code composer studio
11. click on the Project new and type the project name example Linear
Convolution and say finish.
12. iir.pjt will be appeared under files menu left side. 13. iir.pjt will consist a.
dependent projects b. documents c.dsp/bios config d. generated files e. include f.
libraries g. source
13. Click on the menu File and again click on the New option and click on the right
side window Source File , So a new window will be opened for typing the program.
14. For example type a Program with name Program and save it.
15. Next click on Project on the main menu and click on Add Files to Project.
16. A window will be opened with name Add Files to Project with Project name iir
containing the program name saved to the program typed.
17. Give a double click on the program name which was saved as Program which
will be added under Source with the file name iir.c under the left side menu under
iir.pjt.
18. Next again click on Add Files to Project and place the path indicating server app
virt(q) and next select ccstudio and next click on open.
19. You will find another ccstudio folder and then select the folder and click on open
and you will find several folders located in the window.
20. 21. Next select c6000 folder and open it, next select cgtools folder and open it,
next select lib folder and open it.

UMT Lahore Page 159


21. You will find a blank window and place object and library files(*.0*;*.1*)
changing at files of type and you will be finding six files appeared and in that select
rts6700 file and click on open so that the file rts6700 will be added under
libraries folder with the name rts6700.lib file under the Project iir.pjt which is
visible at left side of the window.
22. Next again click on Add Files to Project and next select ccstudio and next click
on open.
23. You will find another ccstudio folder and then select the folder and click on open
and you will find several folders located in the window.
24. Next select tutorial folder and open it, next select sim64xx folder and open it,
next select hello1 folder and open it.
25. You will find a blank window and place Linker Command File(*.cmd;*.lcf)
changing at files of type and you will be finding a file with name hello.
26. Select the file hello and click on open so that the file hello will be added under
source folder under iir.c file as hello.cmd file under the Project iir.pjt which is
visible at left side of the window.
27. Now click on Project on the main menu and click on Compile file and if there are
no errors in the program it will display the entire path from the project name to the
program file attached.
28. Next click on Project on the main menu and click on the option build, so that it
will display the errors if found in the program with mentioning the line numbers for
rectifying the errors and if there are no errors it will display 0 errors and you need
not bother about warnings.
29. Next click on File on the main menu and click on the option Load Program, so
that a window will be opened with a folder named Debug and select the folder
Debug and click on open and in that folder you will find a file with name iir.out
and select the file iir.out and click on open.
30. The format in the main window will be entirely changed with indicating all binary
numbers as the total process of the execution of the Project is completed.
31. Next click on Debug option on the main menu bar and select the option Run for
simulating the Program for asking inputs and getting the result.
32. For again Rechecking the output giving another values as input go to Debug menu
click on Restart and click on Run and provide the inputs once again.

IIR Low pass/ High Pass Filter C-language Program


/*IIR Filter response in CCS/ DSP KIT 6713*/
/* Written by Jameel Ahmad December 28,2013*/
#include<stdio.h>
#include<math.h>

/*
* main() - Main code routine, initializes BSL and Creates Filter response
* Based on User input
*/

int i,w,wc,c,N;
float H[100];/*Filter Magnitude Array*/

UMT Lahore Page 160


float mul(float,int);
void main()
{
printf("\n Enter order of filter");
scanf("%d",&N);
printf("\n Enter the cut off frequency");
scanf("%d",&wc);
printf("\n Enter the choice for IIR Filter 1.LPF 2.HPF");
scanf("%d",&c);
switch(c)
{
case 1:
for(w=0;w<100;w++)
{
H[w]=1/sqrt(1+mul((w/(float)wc),2*N));
printf("H[%d]=%f\n",w,H[w]);
}
break;
case 2:
for(w=0;w<=100;w++)
{
H[w]=1/sqrt(1+mul((float)wc/w,2*N));
printf("H[%d]=%f\n",w,H[w]);
}
break;
}
}
float mul(float a,int x)
{
for(i=0;i<x-1;i++)
a*=a;
return(a);
}

Result:
Enter order of filter 2
Enter the cut off frequency 50
Enter the choice for IIR Filter 1.LPF 2.HPF 2
The Highpass filter coefficients are calculated as follows:
H[0]=0.000000
H[1]=0.000000
H[2]=0.000003
H[3]=0.000013
H[4]=0.000041
H[5]=0.000100
H[6]=0.000207

UMT Lahore Page 161


H[7]=0.000384
H[8]=0.000655
H[9]=0.001050
H[10]=0.001600
H[11]=0.002343
H[12]=0.003318
H[13]=0.004570
H[14]=0.006146
H[15]=0.008100
H[16]=0.010485
H[17]=0.013362
H[18]=0.016794
H[19]=0.020847
H[20]=0.025592
H[21]=0.031102
H[22]=0.037455
H[23]=0.044730
H[24]=0.053010
H[25]=0.062378
H[26]=0.072921
H[27]=0.084725
H[28]=0.097873
H[29]=0.112447
H[30]=0.128525
H[31]=0.146176
H[32]=0.165460
H[33]=0.186421
H[34]=0.209088
H[35]=0.233465
H[36]=0.259530
H[37]=0.287230
H[38]=0.316474
H[39]=0.347133
H[40]=0.379036
H[41]=0.411972
H[42]=0.445688
H[43]=0.479902
H[44]=0.514304
H[45]=0.548569
H[46]=0.582372
H[47]=0.615399
H[48]=0.647359
H[49]=0.677999
H[50]=0.707107
H[51]=0.734522
H[52]=0.760134
H[53]=0.783883
H[54]=0.805753
H[55]=0.825768
H[56]=0.843985

UMT Lahore Page 162


H[57]=0.860485
H[58]=0.875368
H[59]=0.888744
H[60]=0.900730
H[61]=0.911444
H[62]=0.921001
H[63]=0.929514
H[64]=0.937088
H[65]=0.943821
H[66]=0.949802
H[67]=0.955115
H[68]=0.959834
H[69]=0.964025
H[70]=0.967750
H[71]=0.971061
H[72]=0.974006
H[73]=0.976627
H[74]=0.978962
H[75]=0.981044
H[76]=0.982901
H[77]=0.984560
H[78]=0.986042
H[79]=0.987369
H[80]=0.988558
H[81]=0.989624
H[82]=0.990580
H[83]=0.991439
H[84]=0.992212
H[85]=0.992908
H[86]=0.993536
H[87]=0.994102
H[88]=0.994613
H[89]=0.995075
H[90]=0.995493
H[91]=0.995872
H[92]=0.996216
H[93]=0.996528
H[94]=0.996811
H[95]=0.997069
H[96]=0.997304
H[97]=0.997517
H[98]=0.997712
H[99]=0.997890
H[100]=0.998053
Run the program again from Debug-run

Enter order of filter2


Enter the cut off frequency50
Enter the choice for IIR Filter 1.LPF 2.HPF1
The Lowpass filter coefficients are calculated as follows:
UMT Lahore Page 163
H[0]=1.000000
H[1]=1.000000
H[2]=1.000000
H[3]=1.000000
H[4]=1.000000
H[5]=1.000000
H[6]=1.000000
H[7]=1.000000
H[8]=1.000000
H[9]=0.999999
H[10]=0.999999
H[11]=0.999997
H[12]=0.999995
H[13]=0.999990
H[14]=0.999981
H[15]=0.999967
H[16]=0.999945
H[17]=0.999911
H[18]=0.999859
H[19]=0.999783
H[20]=0.999672
H[21]=0.999516
H[22]=0.999298
H[23]=0.998999
H[24]=0.998594
H[25]=0.998053
H[26]=0.997338
H[27]=0.996404
H[28]=0.995199
H[29]=0.993658
H[30]=0.991706
H[31]=0.989259
H[32]=0.986217
H[33]=0.982470
H[34]=0.977897
H[35]=0.972365
H[36]=0.965735
H[37]=0.957862
H[38]=0.948601
H[39]=0.937816
H[40]=0.925382
H[41]=0.911197
H[42]=0.895188
H[43]=0.877322
H[44]=0.857608
H[45]=0.836105
H[46]=0.812922
H[47]=0.788216
H[48]=0.762185
H[49]=0.735063

UMT Lahore Page 164


H[50]=0.707107
H[51]=0.678585
H[52]=0.649766
H[53]=0.620909
H[54]=0.592252
H[55]=0.564010
H[56]=0.536367
H[57]=0.509476
H[58]=0.483458
H[59]=0.458404
H[60]=0.434380
H[61]=0.411425
H[62]=0.389559
H[63]=0.368786
H[64]=0.349093
H[65]=0.330458
H[66]=0.312851
H[67]=0.296235
H[68]=0.280569
H[69]=0.265810
H[70]=0.251913
H[71]=0.238832
H[72]=0.226523
H[73]=0.214940
H[74]=0.204042
H[75]=0.193786
H[76]=0.184135
H[77]=0.175049
H[78]=0.166493
H[79]=0.158435
H[80]=0.150842
H[81]=0.143685
H[82]=0.136935
H[83]=0.130567
H[84]=0.124557
H[85]=0.118881
H[86]=0.113519
H[87]=0.108451
H[88]=0.103658
H[89]=0.099123
H[90]=0.094831
H[91]=0.090765
H[92]=0.086912
H[93]=0.083260
H[94]=0.079796
H[95]=0.076509
H[96]=0.073388
H[97]=0.070423
H[98]=0.067605
H[99]=0.064926

UMT Lahore Page 165


www.jntuworld.com www.

The Lowpass filter response in Code composer studio is as shown below

FIR filter experiments to filter noise from an audio file


UMT Lahore Page 166
Watch the following videos and design LP,HP and BP filters
DSP Kit Tutorial 4A - FIR Filters.mp4
DSP Kit Tutorial 4B - FIR Filters.mp4
DSP Kit Tutorial 4C - FIR Filters.mp4
DSP Kit Tutorial 4D - FIR Filters.mp4
C code for 4 FIR filters (LP,HP,BP,BS)
#include "dsk6713.h"
#include "dsk6713_aic23.h"
#include "dsk6713_dip.h"
#include "tmwtypes.h"

/*
* Filter Coefficients (C Source) generated by the Filter Design and Analysis Tool
*
* Generated by MATLAB(R) 7.12 and the Signal Processing Toolbox 6.15.
*
* Generated on: 29-Dec-2013 12:45:03
*
*/

/*
* Discrete-Time FIR Filter (real)
* -------------------------------
* Filter Structure : Direct-Form FIR
* Filter Length : 51
* Stable : Yes
* Linear Phase : Yes (Type 1)
*/
/*************************LOW-PASS FILTER COEFFICIENTS****************************/
//4KHz Lowpass filter coefficients
const int low = 41;
const real32_T lowpass[41] = {
0.003413982689, -0.04797660932, -0.01539621036,-0.008595237508,-1.524966956e-005,
0.00999723468, 0.01822434552, 0.02121619135, 0.01687069982, 0.005175150465,
-0.01131861564, -0.02771880478, -0.03797810152, -0.03647312522, -0.01977176033,
0.01220615022, 0.0556156598, 0.1033837795, 0.1466035396, 0.1767215133,
0.1875034124, 0.1767215133, 0.1466035396, 0.1033837795, 0.0556156598,
0.01220615022, -0.01977176033, -0.03647312522, -0.03797810152, -0.02771880478,
-0.01131861564, 0.005175150465, 0.01687069982, 0.02121619135, 0.01822434552,
0.00999723468,-1.524966956e-005,-0.008595237508, -0.01539621036, -0.04797660932,
0.003413982689
};

/***********************************************************************************/

/*************************High-PASS FILTER COEFFICIENTS****************************/


//High filter coefficients Fstop=4000 Fpass=5000
const int high = 51;
const real32_T highpass[51] = {
-0.0035854897, -0.03237039223,-0.005130962934, -0.00417484669, 0.002173746238,
0.008399185725, 0.01262090355, 0.01290814392, 0.008431741968,8.705312212e-006,
-0.01002170984, -0.01824956574, -0.02127774991, -0.01693093218,-0.005166633055,
0.01135153137, 0.0277669467, 0.03802761063, 0.03651088849, 0.01979110949,
-0.01220446918, -0.05564640462, -0.1034102291, -0.1466118246, -0.1767069846,
0.8125001788, -0.1767069846, -0.1466118246, -0.1034102291, -0.05564640462,

UMT Lahore Page 167


-0.01220446918, 0.01979110949, 0.03651088849, 0.03802761063, 0.0277669467,
0.01135153137,-0.005166633055, -0.01693093218, -0.02127774991, -0.01824956574,
-0.01002170984,8.705312212e-006, 0.008431741968, 0.01290814392, 0.01262090355,
0.008399185725, 0.002173746238, -0.00417484669,-0.005130962934, -0.03237039223,
-0.0035854897
};

/***********************************************************************************/
/*************************band-PASS FILTER COEFFICIENTS****************************/
//Bandpass filter coefficients

/*******************************************BAND-PASS Filter
coefficients************************/
//[Fstop1 Fpass1 Fpass2 Fstop2 Wstop]=[100 2000 2500 5000 60]
const int band = 51;
const real32_T bandpass[51] = {
0.0009632759611, 0.002002550522, 0.003695710329, 0.00584884733, 0.008191553876,
0.01026241574, 0.01144373138, 0.01104936376, 0.008456530049, 0.003261316568,
-0.004570978228, -0.01459527761, -0.02585300803, -0.03693319112, -0.0461339727,
-0.05171122774, -0.0521716997, -0.04656642303, -0.03472302109, -0.01736706495,
0.003897946095, 0.02676513419, 0.04852762446, 0.06646967679, 0.07827630639,
0.08239423484, 0.07827630639, 0.06646967679, 0.04852762446, 0.02676513419,
0.003897946095, -0.01736706495, -0.03472302109, -0.04656642303, -0.0521716997,
-0.05171122774, -0.0461339727, -0.03693319112, -0.02585300803, -0.01459527761,
-0.004570978228, 0.003261316568, 0.008456530049, 0.01104936376, 0.01144373138,
0.01026241574, 0.008191553876, 0.00584884733, 0.003695710329, 0.002002550522,
0.0009632759611
};

/******************************************************************************************
******/
/*******************************************BAND-STOP Filter
coefficients************************/
//[Fpass1 Fstop1 Fstop22 Fpass2 Wstop] = [100 1000 3500 5000 7]
const int bstop = 51;
const real32_T bandstop[51] = {
0.1176750958, -0.04280536994, -0.02905246243, -0.01399032492, 0.001051147236,
0.01495537348, 0.02547941729, 0.0304671675, 0.02896331251, 0.02110535465,
0.009219906293,-0.002751755528, -0.01036386192, -0.00987265911,0.0001494093158,
0.01788694598, 0.03832666948, 0.05434468761, 0.05854714289, 0.04572274163,
0.01455296483, -0.03134330362, -0.08400481939, -0.1328259408, -0.1673213243,
0.820253551, -0.1673213243, -0.1328259408, -0.08400481939, -0.03134330362,
0.01455296483, 0.04572274163, 0.05854714289, 0.05434468761, 0.03832666948,
0.01788694598,0.0001494093158, -0.00987265911, -0.01036386192,-0.002751755528,
0.009219906293, 0.02110535465, 0.02896331251, 0.0304671675, 0.02547941729,
0.01495537348, 0.001051147236, -0.01399032492, -0.02905246243, -0.04280536994,
0.1176750958
};

/******************************************************************************************
******/
union {
Uint32 combo;
short channel[2];
} temp;
Uint32 Leftchannel,Rightchannel,data;

UMT Lahore Page 168


int a,i;
void main()
{

DSK6713_AIC23_CodecHandle hCodec;
DSK6713_AIC23_Config config=DSK6713_AIC23_DEFAULTCONFIG;

/* Initialize the board support library, must be called first */


DSK6713_init();
DSK6713_DIP_init();

/* Start the codec */


hCodec = DSK6713_AIC23_openCodec(0, &config);
while(1)
{
if (DSK6713_DIP_get(0)==0)// press DIP switch 0 to filter Lowpass frequencies
{
float samples[50];
float result=0.0;
while(!DSK6713_AIC23_read(hCodec,&data))
for( a=low-1;a>=1;a--)
samples[a]=samples[a-1];
temp.combo=data;
samples[0]= (float) temp.channel[0];
for ( a=0;a<low;a++)
result += lowpass[a]*samples[a];
while(!DSK6713_AIC23_write(hCodec,(short) result));
}
else if (DSK6713_DIP_get(1)==0)// press DIP switch 1 to pass HIGH frequencies
{
float samples[50];
float result=0.0;
while(!DSK6713_AIC23_read(hCodec,&data))
for( a=high-1;a>=1;a--)
samples[a]=samples[a-1];
temp.combo=data;
samples[0]= (float) temp.channel[0];
for ( a=0;a<high;a++)
result += highpass[a]*samples[a];
while(!DSK6713_AIC23_write(hCodec,(short) result));
}

else if (DSK6713_DIP_get(2)==0)//press DIP switch 2 to bandpass frequencies


{
float samples[51];
float result=0.0;
while(!DSK6713_AIC23_read(hCodec,&data))
for( a=band-1;a>=1;a--)
samples[a]=samples[a-1];
temp.combo=data;
samples[0]= (float) temp.channel[0];
for ( a=0;a<band;a++)
result += bandpass[a]*samples[a];
while(!DSK6713_AIC23_write(hCodec,(short) result));
}

else if (DSK6713_DIP_get(3)==0)//press DIP switch 3 to bandstop frequencies


{

UMT Lahore Page 169


float samples[51];
float result=0.0;
while(!DSK6713_AIC23_read(hCodec,&data))
for( a=bstop-1;a>=1;a--)
samples[a]=samples[a-1];
temp.combo=data;
samples[0]= (float) temp.channel[0];
for ( a=0;a<bstop;a++)
result += bandstop[a]*samples[a];
while(!DSK6713_AIC23_write(hCodec,(short) result));
}
else
{
while(!DSK6713_AIC23_read(hCodec,&data));
while(!DSK6713_AIC23_write(hCodec,data));
}
}
}

FILTER STRUCTURE: direct form FIR

UMT Lahore Page 170


Using FDATool to design the filter coefficients
Lowpass filter Fpass=4000 Fstop=5000

In code composer window

UMT Lahore Page 171


Highpass FIR filter
Fstop=4000 Fpass=5000

UMT Lahore Page 172


BANDPASS FIR Filter
[Fstop1 Fpass1 Fpass2 Fstop2 Wstop]=[100 2000 2500 5000 60]

UMT Lahore Page 173


Bandstop filter
[Fpass1 Fstop1 Fstop22 Fpass2 Wstop] = [100 1000 3500 5000 7]

UMT Lahore Page 174


SETUP to evaluate the performance of FIR filter
Press DIP switch 0 to lowpass frequencies
Press DIP switch 0 to highpass frequencies
Press DIP switch 0 to bandpass frequencies
Press DIP switch 0 to bndstop frequencies

UMT Lahore Page 175


FIR FILTER DESIGN USING WINDOW functions (Rectangular,
hamming, Hanning, Blackmann)
/*FIR Filter design in Code composer studio*/
// FIR Lowpass Filter program in C language using CC Studio
#include<stdio.h>
#include<math.h>
main()
{
int k,N,n,x,y;
static float h[10],hd[10],w[10];
printf("enter the no of samples N");
scanf("%d",&N);
y=(N-1)/2;
x=-y;
for(n=x;n<=y;n++)
{
if(n!=0)
{
hd[n]=(sin(n*1.57)/3.14*n);
}
else
hd[n]=0.5;
}
printf("select the window: 1.rectangular 2.triangular 3.hanning 4.hamming 5.blackmann");
scanf("%d",&k);
switch(k)
{
case 1:
for(n=x;n<=y;n++)
w[n]=1;
break;
case 2:

UMT Lahore Page 176


for(n=x;n<=y;n++)
w[n]=1-((abs(n)*2)/(N-1));
break;
case 3:
for(n=x;n<=y;n++)
w[n]=0.5+(0.5*cos((6.28*n)/(N-1)));
break;
case 4:
for(n=x;n<=y;n++)
w[n]=0.54+(0.46*cos((6.28*n)/(N-1)));
break;
case 5:
for(n=x;n<=y;n++)
w[n]=0.42+(0.5*cos((6.28*n)/(N-1)))+(0.08*cos((12.56*n)/(N-1)));
break;
default:
printf("wrong choice is entered");
}
for(n=x;n<=y;n++)
{
h[n]=hd[n]*w[n];
printf("output is %f\t",h[n]);
}
}
1.FIR Low Pass Filter impulse response with Rectangular Window
Result:
enter the no of samples N 5
select the window: 1.rectangular 2.triangular 3.hanning 4.hamming 5.blackmann 1
output is 0.001014 output is 0.318471 output is 0.500000 output is 0.318471 output is 0.001014

UMT Lahore Page 177


2.FIR Low pass filter impulse response with Triangular window

UMT Lahore Page 178


FIR Low Pass filter impulse response with Hanning window
enter the no of samples N 5
select the window: 1.rectangular 2.triangular 3.hanning 4.hamming 5.blackmann 3
output is 0.000000 output is 0.159362 output is 0.500000 output is 0.159362 output is 0.000000

FIR Filter Impulse response with Hamming Window


Result:
enter the no of samples N 5
select the window: 1.rectangular 2.triangular 3.hanning 4.hamming 5.blackmann 4
output is 0.000081 output is 0.172091 output is 0.500000 output is 0.172091 output is 0.000081

UMT Lahore Page 179


Result:
enter the no of samples N 5
select the window: 1.rectangular 2.triangular 3.hanning 4.hamming 5.blackmann 5
output is 0.000000 output is 0.108407 output is 0.500000 output is 0.108407 output is 0.000000
FIR Low Pass Filter impulse response with Blackmann Window

UMT Lahore Page 180


FIR Highpass Filter Design
Program:
// FIR High pass Filter program in C language using CC Studio
#include<stdio.h>
#include<math.h>
static float h[20],hd[20],w[20]; // 20 samples
main()
{
int k,n,N,x,y;
printf("Enter the number of samples");
scanf("%d",&N);
y=(N-1)/2;
x=-y;
for(n=x;n<=y;n++)
{
if(n!=0)
{
hd[n]=((sin(n*3.14))-(sin(n*1.57)))/(n*3.14);
}
else
hd[n]=0.5;
}
printf("Select the window");
printf("1.Rectangular Window 2.Triangular window 3.Hanning window 4.Hamming window
5.Blackmann window");
scanf("%d",&k);
switch(k)
{
case 1:
for(n=x;n<=y;n++)
w[n]=1;
break;
case 2:
for(n=x;n<=y;n++)
w[n]=1-((abs(n)*2)/(N-1));
break;
case 3:
for(n=x;n<=y;n++)
w[n]=0.5+(0.5*cos((6.28*n)/(N-1)));
break;
case 4:
for(n=x;n<=y;n++)
w[n]=0.54+(0.46*cos((6.28*n)/(N-1)));
break;
case 5:
for(n=x;n<=y;n++)
w[n]=0.42+(0.5*cos((6.28*n)/(N-1))+(0.08*cos((12.5*n)/(N-1))));
break;
default:

UMT Lahore Page 181


printf("\n Wrong choice is entered,Please Enter the correct choice\n");
break;
}
for(n=x;n<=y;n++)
{
h[n]=hd[n]*w[n];
printf("\n The Output is: %f \t",h[n]);
}
}

Result of running the above code:


Enter the number of samples 5
Select the window 1.Rectangular Window 2.Triangular window 3.Hanning window 4.Hamming
window 5.Blackmann window 5
The Output is: 0.000000
The Output is: -0.108238
The Output is: 0.500000
The Output is: -0.108238
The Output is: 0.000000
FIR High Pass Filter Blackmann Window Graph:

UMT Lahore Page 182


FIR Filters: Generating window coefficients w(n)
// FIR LP/HP Filter program in C language using CC Studio
#include<stdio.h>
#include<math.h>
#define pi 3.1415
int n,N,c;
float wr[64],wt[64];
void main()
{
printf("\n enter no. of samples,N= :");
scanf("%d",&N);
printf("\n enter choice of window function\n 1.rect \n 2. triang \n c= :");
scanf("%d",&c);
printf("\n elements of window function are:");
switch(c)
{
case 1:
for(n=0;n<=N-1;n++)
{
wr[n]=1;
printf(" \n wr[%d]=%f",n,wr[n]);
}
break;
case 2:
for(n=0;n<=N-1;n++)
{
wt[n]=1-(2*(float)n/(N-1));
printf("\n wt[%d]=%f",n,wt[n]);
}
break;
}
}

UMT Lahore Page 183


Result:
enter no. of samples, N= :64
enter choice of window function
1.rect
2.triang
c=:2
elements of window function are:
wt[0]=1.000000 wt[1]=0.968254 wt[2]=0.936508 wt[3]=0.904762
wt[4]=0.873016 wt[5]=0.841270 wt[6]=0.809524 wt[7]=0.777778
wt[8]=0.746032 wt[9]=0.714286 wt[10]=0.682540 wt[11]=0.650794
wt[12]=0.619048 wt[13]=0.587302 wt[14]=0.555556 wt[15]=0.523810
wt[16]=0.492063 wt[17]=0.460317 wt[18]=0.428571 wt[19]=0.396825
wt[20]=0.365079 wt[21]=0.333333 wt[22]=0.301587 wt[23]=0.269841
wt[24]=0.238095 wt[25]=0.206349 wt[26]=0.174603 wt[27]=0.142857
wt[28]=0.111111 wt[29]=0.079365 wt[30]=0.047619 wt[31]=0.015873
wt[32]=-0.015873 wt[33]=-0.047619 wt[34]=-0.079365 wt[35]=-0.111111
wt[36]=-0.142857 wt[37]=-0.174603 wt[38]=-0.206349 wt[39]=-0.238095
wt[40]=-0.269841 wt[41]=-0.301587 wt[42]=-0.333333 wt[43]=-0.365079
wt[44]=-0.396825 wt[45]=-0.428571 wt[46]=-0.460317 wt[47]=-0.492064
wt[48]=-0.523810 wt[49]=-0.555556 wt[50]=-0.587302 wt[51]=-0.619048
wt[52]=-0.650794 wt[53]=-0.682540 wt[54]=-0.714286 wt[55]=-0.746032
wt[56]=-0.777778 wt[57]=-0.809524 wt[58]=-0.841270 wt[59]=-0.873016
wt[60]=-0.904762 wt[61]=-0.936508 wt[62]=-0.968254 wt[63]=-1.000000

UMT Lahore Page 184


Integratig MATLAB/SIMULINK with Code Composer Studio

>> c600lib
>>ccsboardinfo
>>ccsdsp
>> ccsboardinfo

UMT Lahore Page 185


Board Board Proc Processor Processor
Num Name Num Name Type
--- ---------------------------------- --- ---------------------------------- --------------
0 C6713 DSK 0 CPU_1 TMS320C6x1x

>> ticcs
??? Error using ==> compareAndWarnCCSVersions at 53
This version of the Embedded Coder does not support your
version of Code Composer Studio(TM) IDE.
The Code Composer Studio(TM) version supported in this release is 3.3.
Refer to the Embedded Coder data sheet for more information on product requirements.

Error in ==> ticcs>CheckIfIdeVersionIsSupported at 270

UMT Lahore Page 186


ticcsext.Utilities.compareAndWarnCCSVersions(apiver,'warn');

Error in ==> ticcs>Connect2App_CheckIdeVersion at 252


CheckIfIdeVersionIsSupported(hccs);

Error in ==> ticcs at 136


hccs = Connect2App_CheckIdeVersion;

>>simulink
Find in find tab
6713
Under embedded coder you will see Texas Instruments C6000--------C6713 DSK
Double click on it

UMT Lahore Page 187

Potrebbero piacerti anche