DSP Manual Hamdard
DSP Manual Hamdard
IR Rao
Lab Manual
Digital Signal Processing
TABLE OF CONTENTS
LAB
PAGE
11
14
17
22
24
32
42
49
50
51
Page 1
LAB#01
Introduction to MATLAB and Basic Signals
MATLAB is the most popular tool used for Digital Signal Processing. It provides one of the strongest environments for
study and simulation of the real-world problems and their solutions, especially in the field of engineering.
MATLAB (abbreviation for Matrix Laboratory) is a matrix based system which is used for Engineering and Mathematical
calculations. It integrates computation, visualization, programming to use environment where problems and solutions are
expressed in familiar mathematical notation. It is a kind of language which is designed to do matrix manipulations. All
variables used in MATLAB are matrices. It means that MATLAB contains only one data type and a matrix or a rectangular
array of numbers. MATLAB contains a large set of routines to obtain graphical outputs. There are many predefined
functions in MATLAB which are called by the user to solve many different types of problems.
Definition of variables
Variables are assigned numerical values by typing the expression directly, for example, typing
a = 1+2; yields: a = 3;
The answer will not be displayed when a semicolon is put at the end of an expression, for example type
a = 1+2;
MATLAB utilizes the following arithmetic operators:
+
*
/
^
'
addition
subtraction
multiplication
division
power operator
transpose
If your expression does not fit on one line, use an ellipsis (three or more periods at the end of the line) and continue on the
next line.
c = 1+2+3+...
5+6+7;
Page 2
abs
sin
exp
exponential function
Definition of Matrices
MATLAB is based on matrix and vector algebra; even scalars are treated as 11 matrices. Therefore, vector and matrix
operations are as simple as common calculator operations.
M=[1 2 4; 3 6 8];
nm matrix of ones:
M=ones(n,m);
nn identity matrix:
M=eye(n);
Operations that need to be performed element-by-element can be accomplished by preceding the operation by a ".".
M-FILES
M-files are macros of MATLAB commands that are stored as ordinary text files with the extension "m", that is
filename.m. An M-file can be either a function with input and output variables or a list of commands. MATLAB requires
that the M-file must be stored either in the working directory or in a directory that is specified in the MATLAB path list.
All variables used in a MATLAB function are local to that function only. Variables which are used in a script m-file which
is not a function are all global variables.
Page 3
PLOTTING GRAPHS
Commands:
plot, xlabel, ylabel, title, grid, axis, axes, stem, subplot, zoom, hold
BASIC SIGNALS
UNIT IMPULSE
1
1; n = 0
0; else
d [ n] =
0.5
0
-10
1; n = n0
d [ n - n0 ] =
0; else
-5
10
1
0.5
0
-10
-5
10
UNIT STEP
1; n 0
u[n] =
0; else
1; n n0
u[n - n0 ] =
0; else
HOME TASKS:
PROBLEM 1:
Implement a function for generating and plotting
x[n] = md [n - n0 ]
anb
Try it for
(i)
(ii)
n0 = 5,
n0 = -7,
m = 0.9,
m = 4.5,
a = 1,
a = -10,
b = 20
b=0
Page 4
PROBLEM 2:
Implement a function for generating and plotting
anb
x[n] = mu[n - n0 ]
m = 1.9,
m = 1.8,
a = 1,
b = 20
a = -20, b = 20
PROBLEM 3:
Generate and plot
PROBLEM 4:
Consider a continuous time signal x(t ) = ACos (wt + q ) . We can sample a continuous time signal at equally spaced time
instants T = nTs and get a discrete time signal x[ n ] = x( nTs ) . The individual values of x[n] are called samples of
continuous time signal. The fixed time interval between samples, Ts, can also be expressed as a fixed sampling rate, Fs, in
samples per second.
Fs =
If
1
;
Ts
we
samples / second
sample
using
this
approach,
then
by
using t
= nTs ;
we
get
w
Fs
.
^
The signal x[n] is a discrete time cosine signal, and w is its discrete time frequency. We use hat over w to denote that this is
a new frequency variable. It is a normalized version of the continuous time radian frequency with respect to the sampling
frequency.
a.
Generate and plot the signal x(t ) = ACos (wt + q ) with the following values A=3, Frequency=100 Hz, t = 0.01: 0.00001: 0.02 and q= 0.
b.
Generate and plot the Discrete time signal x[n] from the Continuous time signal x(t) using values in part (A) .Use
the sampling frequency Fs=2000.
c.
NOTE: All the plots should be in the same window (use subplot command for this purpose)
Page 5
PROBLEM 5:
Implement and plot the following equation.
4
A l d [ n - 3l ]
l= 0
- 5 n 15 .
PROBLEM 6:
Write MATLAB coding for plotting the following Continuous Time Signals in same window. Use the value of
t s = 0.001 and t = -2 : t s: : 2 - t s .
Page 6
LAB#02
Time Domain Analysis of LTI Systems
Introduction
Mathematically, a discrete-time system is described as an operator T[.] that takes a sequence
x(n) called excitation and transforms it into another sequence y(n) (called response). Discrete
time systems can be classified into two categories i) LTI systems ii) NON-LTI systems. A
discrete system T[.] is a linear operator L[.] if and only if L[.] satisfies the principle of
superposition, namely
L[a1x1(n) + a2x2(n)] = a1L[x1(n)] + a2Lx2(n)] and
A discrete system is time-invariant if
Shifting the input only causes the same shift in the output
A system is said to be bounded-input bounded-output(BIBO) stable if every bounded input
produces a bounded output.
An LTI system is BIBO stable if and only if its impulse response is absolutely summable.
A system is said to be causal if the ouput at index n0 depends only on the input up to and
including the index no; that is output does not depend on the future values of the input. An
LTI system is causal if and only if the impulse response is
Page 7
subplot (3,1,1)
stem(n ,y);
ylabel('Amplitude');
title('Output Due to Weighted Input');
subplot(3,1,2)
stem(n,yt);
ylabel('Amplitude');
title('Weighted Output');
subplot(3,1,3)
stem(n,d);
xlabel('Time index n');
ylabel('Amplitude');
title('Difference Signal');
Question 1: Run above program and compare y[n] obtained with weighted input with
yt[n] obtained by combining the two outputs y1[n] and y2[n] with the same weights. Are
these two sequences equal? Is this system linear?
Exercise 1: Consider another system described by y[n] = x[n] x[n 1]. Modify given
program to compute the output sequences y1[n], y2[n], and y[n] of the above system.
Compare y[n] with yt[n]. Are these two sequences equal? Is this system linear?
Page 8
stem(n,d);
xlabel('Time index n'); ylabel('Amplitude');
title('Difference Signal');grid;
Exercise 2: Consider another system described by:
y[n] = nx[n] + x[n 1]
Modify Program to simulate the above system and determine whether this system is
time-invariant or not.
Page 9
Page 10
LAB#03
Frequency Domain Analysis of LTI System
Introduction
If x(n) is absolutely summable, that is
transform is given by
Page 11
figure
subplot(2,1,1), freqz(b,a)
subplot(2,1,2), zplane(b,a)
2. Properties of DTFT
In this part fft(x,n) function will be used to prove some of the Fourier transform
properties.
a. Linearity
The discrete-time Fourier transform is a linear transformation; that is,
Page 12
Page 13
LAB#04
System Analysis using Z-Transform
Introduction
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:
The z-transform maps a signal in the time domain to a power series in the complex
(frequency) domain: x[n] X(z).
There are many advantages to working with z-transformed signals:
linearity and superposition are preserved
x[n k] zkX(z)
x[n] X(1/z)
anx[n] X(z/a)
x[n] y[n] X(z)Y (z)
The overall result is that the algebra of system analysis becomes greatly simplified in the z
domain. The only tradeoff is the necessity of taking an inverse transform to obtain time
domain responses.
Since the response y[n] of an LTI system to input x[n] is given by the convolution x[n] h[n],
where h[n] is the impulse reponse, we have
The ratio H(z) = Y (z)/X(z) defines the impulse response (and so the system response), and is
called the transfer function of the system.
1. Convolution property
a. If X1(Z) = 2 + 3z-1 + 4z-2 and X2(z) = 3 + 4z-1 + 5z-2 + 6z-3. Determine X3(z) = X1(z)X2(z).
clear all, close all
x1 = [2,3,4]; x2 = [3 4 5 6];
x3 = conv(x1,x2)
x3 =6 17 34 43 38 24
Hence,
X3(z) = 6 + 17z-1 + 34z-2 + 43z-3 + 38z-4 + 24z-5
b. If we are given X3(z) and want to compute X2(z) then we need to divide X3(z) by X1(Z).
In MATLAB this can be done using deconv function.
x3 = [ 6 17 34 43 38 24];
x1 = [2,3,4];
x2 = deconv(x3,x1)
x2 =3 4 5 6
Hence,
Page 14
The location of the zeros and poles of the transfer function determines the response of
an LTI system.
Example: H(z) = (z2 + 2z) / ( z2 + 0.2)
Zeros : z=0, -2
Poles: z=0.2 j
Gain: k =1
b = [1 2];
a = [1 0 0.2];
[z,p,k] = tf2zpk(b,a)
zplane(z,p)
Page 15
Run:
Sptool
To acces the Pole/Zero Editor in SPTool, do the following:
1. Click the New button under the Filters list in SPTool.
2. Select the Pole/Zero Editor in the Algorithm list.
3. View system characteristics as you position poles and zeros.
Exercise 4: Provide examples of all seven properties mentioned above by placing
zero/poles as outlined.
z = [ .5 -.5];
p = [1 0.3333];
k = [];
[b,a] = residuez(z,p,k)
b=
0 0.3334
a=
Page 16
LAB#05
Conversion from Continuous to Discrete Time Signal
(Sampling) and effects of under Sampling (Aliasing)
PERIODIC SIGNALS
A sequence X [n ] is said to be periodic when it satisfies the following relation
X [n] = X [n + N ]
The fundamental period of the signal is defined as the smallest positive value of N for which above equation holds true.
Now consider a signal Y [n ] which is formed by the addition of the two signals X 1[n] and X 2 [n] .
Y [ n] = X 1 [ n] + X 2 [ n]
If the signal X 1[n] is periodic with the fundamental period N1 and X 2 [n] is periodic with the fundamental period N 2 ,
then the signal Y [n ] will be periodic with the period N given by the following relation:
N1 N 2
N=
GCD ( N1 , N 2 )
THE SAMPLING THEORM
A continuous time signal X [t ] with frequencies no higher than Fmax can be reconstructed exactly from its samples
1
that is greater than 2Fmax
Ts
The minimum sampling rate of 2Fmax is called the Nyquist Rate .From Sampling theorem it follows that the reconstruction
of a signal is possible if we have at least 2 samples per period. If we do not sample at a rate that satisfies the sampling
theorem then aliasing occurs.
SAMPLING A CONTINUOUS TIME SIGNAL
For example we want to sample continuous time signal X (t ) = Cos (100pt ) . The frequency of this signal is 50 Hz and
according to sampling theorem the minimum sampling frequency should be 100 samples/sec. But we sample it at a rate
much higher than the Nyquist rate so that it has many samples over one cycle giving an accurate representation of the
sampled discrete time signal.
Page 17
In the figure below the continuous time signal X (t ) = Cos (100pt ) is sampled at Fs=1000 samples/second).Therefore it
will have
Fs 1000
=
= 20 samples per cycle.
f
50
1
0.5
0
-0.5
-1
0
5
10
15
20
25
30
35
x=cos(100*pi*t) sampled with Fs=1000 (samples / sec)
40
CONCEPT OF ALIASING
T=0.03;
N=1024;
fs=1000;
n=[0:1/fs:T];
F=[-N/2+1:N/2]*fs/N;
f=125;
x1=cos(2*pi*f*n);
X1=abs(fftshift(fft(x1,N)));
f=500;
x2=cos(2*pi*f*n);
X2=abs(fftshift(fft(x2,N)));
f=625;
x3=cos(2*pi*f*n);
X3=abs(fftshift(fft(x3,N)));
f=875;
x4=cos(2*pi*f*n);
X4=abs(fftshift(fft(x4,N)));
subplot(421);stem(n,x1);grid on;title('sinusoidal signal of f=125 Hz');
subplot(422);plot(F,X1);grid on;title('fft of sinusoidal signal of f=125 Hz');
subplot(423);stem(n,x2);grid on;title('sinusoidal signal of f=500 Hz');
subplot(424);plot(F,X2);grid on;title('fft of sinusoidal signal of f=500 Hz');
subplot(425);stem(n,x3);grid on;title('sinusoidal signal of f=625 Hz');
subplot(426);plot(F,X3);grid on;title('fft of sinusoidal signal of f=625 Hz');
subplot(427);stem(n,x4);grid on;title('sinusoidal signal of f=825 Hz');
subplot(428);plot(F,X4);grid on;title('fft of sinusoidal signal of f=825 Hz');
Page 18
20
10
-1
0.005
0.01
0.015
0.02
0.025
0.03
0
-500
40
20
-1
0.005
0.01
0.015
0.02
0.025
0.03
0
-500
10
0.005
0.01
0.015
0.02
0.025
0.03
0
-500
10
0.005
0.01
0.015
0.02
500
500
-1
500
-1
0
fft of sinusoidal signal of f=500 Hz
0.025
0.03
0
-500
500
Page 19
y=filter(Num,Den,xs);
wavplay(x,fs)
wavplay(xs,fs)
wavplay(y,fs)
[x,fs,nbits]=wavread('chimes.wav');
ts=1/fs;
N=length(x);
t=[0:N-1]*ts;
tind=find(t>=2.4 & t<=3.7);
xpart=x(tind);
tpart=t(tind);
subplot(211),plot(t,x);grid on;title('Time Plot of Chimes.wav');
subplot(212),plot(tpart,xpart,'r');grid on;title('extracted signal');
axis([0 8 -1 1]);
PROBLEM 1:
Consider the signal
Y [ n] = X 1 [ n] + X 2 [ n]
where
np
X 1 [n] = Cos
12
a.
np
X 2 [n] = Cos
18
and
X 1[n] over the range n=0:(2*N1) . Verify from graph that there
X 2 [n] over the range n=0:(2*N2). Verify from graph that there
b.
c.
X 1[n] repeats itself after N1, X 2 [n] repeats itself after N2 and Y [n] repeats itself after N
PROBLEM 2:
Consider the signals:
g1t = Cos(w1t )
g 2 t = Cos(w 2 t )
g 3t = Cos(w 3t )
Fs=10
Fs=13
Fs=26
Fs=52
Fs=80
Page 20
Fs=130
PROBLEM 3:
Consider a signal X = Cos (0.25pn ) over the range n=0:40. What will be the aliases of the signal X. Plot the signal X
and its two aliases all in the same window. (Actually a signal can have infinite number of aliases)
PROBLEM 4:
Sample the signal Xt = 5 Sin (150pt ) to get sampled signal Xn = 5Sin (150pnTs ) such that there is no aliasing. Choose
an appropriate value of sampling frequency and choose time such that the graph contains 4 cycles of the signal and each
cycle has 22 samples. Plot both signals Xt and Xn in the same window.
Page 21
LAB#06
Study of Digital Filters (IIR and FIR)
Introduction
Filters shape the frequency spectrum of a sound signal.
Filters generally do not add frequency components to a signal that are not there
to begin with.
Boost or attenuate selected frequency regions
The Basic on Filters
Filters work by using one or both of the following methods:
Delay a copy of the input signal (by x number of samples), and combine the
delayed input signal with the new input signal.
(Finite Impulse Response, FIR, or feedforward filter)
Delay a copy of the output signal (by x number of samples), and combine it with
the new input signal.
(Infinite Impulse Response, IIR, feedback filter)
Digital Filtering:
In signal processing, the function of a filter is to remove unwanted parts of the signal,
such as random noise, or to extract useful parts of the signal, such as the components
lying within a certain frequency range
Analog Filter:
Input: electrical voltage or current which is the direct analogue of a physical
quantity (sensor output)
Components: resistors, capacitors and op amps
Output: Filtered electrical voltage or current
Applications: noise reduction, video signal enhancement, graphic equalisers
Digital Filter:
Input: Digitized samples of analog input (requires ADC)
Components: Digital processor (PC/DSP/ASIC/FPGA)
Output: Filtered samples (requires DAC)
Types: lowpass, highpass, bandpass, bandreject (notch).
First, how we label things:
x is the input signal
y is the output signal
n is the sample index (all samples are numbered, or indexed)
Hamdard University, Islamabad Campus
Waris
Page 22
n x[0] is the first sample of input; y[0] is the first sample of output. x[n] is the current
sample; x[n - 1] is the previous sample.
FIR filtering
Finite Impulse Response (FIR) filters use past input samples only
Example:
y(n)=0.1x(n)+0.25x(n-1)+0.2x(n-2)
Z-transform: Y(z)=0.1X(z)+0.25X(z)z-1+0.2X(z)z-2
Transfer function: H(z)=Y(z)/X(z)=0.1+0.25z-1+0.2z-2
No poles, just zeroes. FIR is stable
Home Task:
A filter is described by the following equation:
y(n)=0.5x(n) + 1x(n-1) + 0.5x(n-2), with initial condition y(-1) = 0
What kind of filter is it?
Plot the filters transfer function on the z plane
Is the filter stable?
Plot the filters unit step response
Plot the filters unit impulse response
IIR Filtering
Infinite Impulse Response (IIR) filters use past outputs together with past inputs
IIR Filter Implementation
y(n)=b(0)x(n)+b(1)x(n-1)+b(2)x(n-2)+b(3)x(n-3) + a(0)y(n)+
a(1)y(n-1)+a(2)y(n-2)+a(3)y(n-3)
Home Task
A filter is described by the following equation:
y(n)=0.5x(n) + 0.2x(n-1) + 0.5y(n-1) + 0.2y(n-2), with initial condition y(-1)=y(-2) = 0
What kind of filter is it?
Plot the filters transfer function on the z plane
Is the filter stable?
Plot the filters unit step response
Plot the filters unit impulse response
Page 23
LAB#07
IIR Filter Design and Analysis using FDATool and script
writing Techniques of MATLAB
Filter Design:
The goal of Filtering is to perform frequency-dependent alteration of a signal. A simple design specification for a Filter
might be to remove noise above a certain cutoff frequency. A more complete specification might call for a specific amount
of passband ripple (Rp, in decibels), stopband attenuation (Rs, in decibels), or transition width (Wp - Ws, in hertz). A
precise specification might ask to achieve the performance goals with the minimum Filter order, call for an arbitrary
magnitude response, or require an FIR Filter.
IIR Filter design methods differ from FIR primarily in how performance is specified. For loosely specified requirements, as
in the previous paragraph, a Butterworth Filter is often sufficient. More rigorous Filter requirements can be met with socalled Chebyshev and elliptic Filters. The Signal Processing Toolbox order selection functions estimate the minimum Flter
order that meets a given set of requirements.
Filter Configurations
First, recall that when dealing with sampled signals, we can normalize the frequencies to the Nyquist frequency (defined as
one-half the sampling frequency). All the filter design functions in the Signal Processing Toolbox operate with normalized
frequencies,
v
v
v
v
FDA Tool:
Introduction to the Filter Design and Analysis Tool (FDATool):
Page 24
The Filter Design and Analysis Tool (FDATool) is a powerful graphical user interface (GUI) in the Signal Processing
Toolbox 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 adding, moving or deleting
poles and zeros. FDATool also provides tools for analyzing filters, such as magnitude and phase response plots and polezero plots. You can use FDATool as a convenient alternative to the command line filter design functions.
Getting Started
Type fdatool at the MATLAB command prompt:
>>fdatool
in command window, FDAtool will be opened. There you can select FIR or IIR filter,order of filter and cutoff frequency of
a filter (either HPF, LPF or BPF). That code will automatically generate .m file for you. Record your voice. Analyze the
effect of lowpass filtering on speech signal. Use the Filter Design and Analysis Tool (FDATool) of MATLAB for the
purpose of designing LPF filter. Consider separately FIR and IIR filter. A detail demo of the FDATool is available in the
website of The Mathworks which I recommend you to visit for acquiring more knowledge in Matlab.
Page 25
We will design a low pass filter that passes all frequencies less than or equal to 20% of the Nyquist frequency (half the
sampling frequency) and attenuates frequencies greater than or equal to 50% of the Nyquist frequency.We will use an FIR
Equiripple filter with these specifications:
v
v
v
v
Passband attenuation 1 dB
Stopband attenuation 80 dB
A passband frequency 0.4 [Normalized (0 to 1)]
A stopband frequency 0.5 [Normalized (0 to 1)]
Page 26
v
v
v
v
v
v
v
v
v
v
Magnitude response
Phase response
Magnitude and Phase responses
Group delay response
Phase delay response
Impulse response
Step response
Pole-zero plot
Filter Coefficients
Filter Information
Page 27
rs=80;
[n,wn]=buttord(wp,ws,rp,rs)
[b,a]=butter(n,wn,'low');
freqz(b,a)
N=1024;
fs=100;
n=[0:1:100];
F=[-N/2+1:N/2]*fs/N;
x1=cos(2*pi*(10/fs)*n)+cos(2*pi*(20/fs)*n)+cos(2*pi*(30/fs)*n);
X1=abs(fftshift(fft(x1,N)));
y=filter(b,a,x1);
Y=abs(fftshift(fft(y,N)));
figure;
subplot(411);stem(n,x1);grid on;title('sinusoidal signal Xn');
subplot(412);plot(F,X1);grid on;title('fft of sinusoidal signal Xn');
subplot(413);stem(n,y);grid on;title('sinusoidal signal Xn');
subplot(414);plot(F,Y);grid on;title('fft of sinusoidal signal Xn');
IIR filter types
v
v
v
v
BUTTERWORTH FILTER
CHEBYSHEV TYPE I FILTER
CHEBYSHEV TYPE II FILTER
ELLIPTIC FILTER
BUTTERWORTH FILTER
Butterworth filters are defined by the property that the magnitude response is maximally flat in the pass band. Another
property is that the approximation is monotonic in the pass band and the stop band.
Page 28
PROBLEM 1
Design a Low pass Filter for the following IIR types
v
v
v
v
BUTTERWORTH FILTER
CHEBYSHEV TYPE I FILTER
CHEBYSHEV TYPE II FILTER
ELLIPTIC FILTER
Page 29
PROBLEM 2
Design a High pass Filter for the following IIR types
v
v
v
v
BUTTERWORTH FILTER
CHEBYSHEV TYPE I FILTER
CHEBYSHEV TYPE II FILTER
ELLIPTIC FILTER
PROBLEM 3
Design a Bandpass for the following IIR types
v
v
v
v
BUTTERWORTH FILTER
CHEBYSHEV TYPE I FILTER
CHEBYSHEV TYPE II FILTER
ELLIPTIC FILTER
Page 30
PROBLEM 4
Design a Band Stop for the following IIR types
v
v
v
v
BUTTERWORTH FILTER
CHEBYSHEV TYPE I FILTER
CHEBYSHEV TYPE II FILTER
ELLIPTIC FILTER
2.
Generate the following signal with 100 samples and then plot it against time.
Fs=100Hz,F1=10Hz,F2=20Hz,F3=30Hz
3.
Plot the DFT of the above signal versus frequency. Choose an appropriate value of N .
4.
Remove the highest frequency component of the signal using Butterworth, Chebyshev Type I, Chebyshev Type II
and Elliptic filters. Use freqz to plot the frequency response for each of the filters used. Plot DFT of the filtered
signal for each case.
5.
6.
7.
8.
Page 31
LAB#08
FIR Filter Design and Analysis using FDATool and script
writing Techniques of MATLAB
Filter Design Using Fir1 Command:
Design of FIR filters are based on directly approximating the desired frequency response of the discrete time system. Most
techniques used to design FIR filters use linear phase constraint. The simplest method of FIR filter design is called window
method. To obtain a casual FIR filter a window truncates frequency response of the ideal filter. According to the type of
window that is selected different approximation of the filter will be obtained.
In order to design a FIR filter using Matlab we can use fir1 and Filter commands.
The format of fir1 is as follows:
LOW PASS:B = FIR1(N,Wn) designs an N' th order low pass FIR digital filter and returns the filter coefficients in length
N+1 vector B.
For example in order to design a FIR filter assuming a sampling rate of 48khz and having a low pass filter with the cut off
frequency of 10khz by windowing method:
B=fir1(40,10.0/(48.0/2))=fir1( N, fc/(fs/2) )
HIGH PASS: B = FIR1(N,Wn,'high')=FIR1(N,fc/(fs/2),high) designs an N'th order high pass filter.
BAND PASS:If Wn is a two-element vector, Wn = [W1 W2], FIR1 returns an order N band pass filter with pass band W1
< W < W2. Example: FIR1( N , [f1/(fs/2) f2/(fs/2)] )
BAND STOP:If Wn = [W1 W2], B = FIR1(N,Wn,'stop') will design a band stop filter.
FIR1( N , [ f1/(fs/2) f2/(fs/2) ], stop )
FILTER command (One-dimensional digital filter) :
Y = FILTER(B,A,X) filters the data in vector X with the filter described by vectors A and B to create the filtered data Y.
For FIR filters A=1 because they do not contain any poles.
FREQZ(b,1,f,fs) will plot frequency response of the filter designed above for the designated f vector.
Example 1: Design a 48th-order FIR low filter with ws=0.6,
b = fir1(48,0.6,low);
Page 32
freqz(b,1,512)
Magnitude (dB)
50
-50
-100
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
Normalized Frequency (p rad/sample)
0.9
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
Normalized Frequency (p rad/sample)
0.9
Phase (degrees)
-1000
-2000
-3000
Example 2:Design a 48th-order FIR bandpass filter with passband 0.35 0.65:
b = fir1(48,[0.35 0.65]);
freqz(b,1,512)
Magnitude (dB)
50
-50
-100
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
Normalized Frequency (p rad/sample)
0.9
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
Normalized Frequency (p rad/sample)
0.9
Phase (degrees)
1000
-1000
-2000
Page 33
Magnitude (dB)
B = FIR1(30,0.2,'high')
freqz(B,1,512)
50
-50
Phase (degrees)
-100
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
Normalized Frequency (p rad/sample)
0.9
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
Normalized Frequency (p rad/sample)
0.9
1000
0
-1000
-2000
-3000
Page 34
clc
fsamp = 8000;
fcuts = [1000 1500];
mags = [0 1];
devs = [0.01 0.05];
[n,Wn,beta,ftype] = kaiserord(fcuts,mags,devs,fsamp);
hh = fir1(n,Wn,ftype,kaiser(n+1,beta),'noscale');
[H,f] = freqz(hh,1,1024,fsamp);
figure;
plot(f,abs(H)), grid on,ylabel('Magnitude');xlabel('Frequencies in Hz');title('High Pass Filter');
Page 35
fsamp = 8000;
fcuts = [1000 1500 2500 3000];
mags = [0 1 0];
devs = [0.01 0.05 0.01];
[n,Wn,beta,ftype] = kaiserord(fcuts,mags,devs,fsamp);
hh = fir1(n,Wn,ftype,kaiser(n+1,beta),'noscale');
[H,f] = freqz(hh,1,1024,fsamp);
figure;
plot(f,abs(H)), grid on,ylabel('Magnitude');xlabel('Frequencies in Hz');title('Band Pass Filter');
Page 36
fsamp = 8000;
fcuts = [1000 1500 2500 3000];
mags = [1 0 1];
devs = [0.05 0.01 0.05];
[n,Wn,beta,ftype] = kaiserord(fcuts,mags,devs,fsamp);
hh = fir1(n,Wn,ftype,kaiser(n+1,beta),'noscale');
[H,f] = freqz(hh,1,1024,fsamp);
figure;
plot(f,abs(H)), grid on,ylabel('Magnitude');
Page 37
Kaiser
Hamming
Hanning
Rectangular
Blackman
Bartlett
PROBLEM 2
Design a High pass FIR Filter for the following Windows types.
Page 38
Kaiser
Hamming
Hanning
Rectangular
Blackman
Bartlett
Fs=8000hz
Fc=-2000hz
Rp = 1dB,Rs = 80dB
PROBLEM 3
Design a Band pass FIR Filter for the following Windows types.
v
v
v
v
v
v
Kaiser
Hamming
Hanning
Rectangular
Blackman
Bartlett
Kaiser
Hamming
Hanning
Rectangular
Black an
Bartlett
PROBLEM 5
Page 39
Page 40
LAB#09
INTRODUCTION TO TEXAS
INSTRUMENTS TMS320C6713 DSP
STARTER KIT (DSK) DIGITAL SIGNAL
PROCESSING BOARD
Introduction
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
The C programming language
Page 41
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.
1.4. 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.
In this lab, we will go over the basic components of the DSK and show how software
may be downloaded onto the DSK.
2. 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.
3. 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 8KHz to 96KHz and support data word lengths of 16b, 20b, 24b, and
Page 42
Page 43
u:\ drive.
1. u:\DSP\Support
c6713dskinit.c,...
2. u:\DSP\Lab 08
led.c
Page 44
In addition to the support files that you have been given, there are pre-compiled files
from TI that need to be included with your project. For this project, we need run-time
support libraries. For the C6713 DSK, there are three support libraries needed:
csl6713.lib, dsk6713bsl.lib, and rts6700.lib. The first is a chip support library, the
second a board support library, and the third is a real-time support library.
Besides the above support libraries, there is a GEL (general extension language) file
(dsk6211 6713.gel) used to initialize the DSK. The GEL file was automatically added
when the project file Lab07.pjt was created, but the other libraries must be explicitly
included in the same manner as the pre-vious files. Go to Project and then Add Files
to Project. For Files of type, select Ob-ject and Library Files (*.o*,*.l*). Navigate to
the path u:\DSP\Support and select the files csl6713.lib,. . . . In the left sub-window of
the CCS main window, double-click on the folder Libraries to make sure the file was
added correctly.
These files, along with our other support files, form the black box that will be required
for every project created in this class. The only files that change are the source code
files that code a DSP algorithm and possibly a vectors file.
7.4 Adding Source Code Files to a Project
The last file that you need to add to led.pjt is your C source code file. This file will
contain the code needed to control the leds through the DIP switch. Go back to Project
and then Add Files to Project . . ., but this time browse to the path u:\DSP\Lab 08.
Click on the file led.c and add it to your project by clicking on Open. You may have
noticed that the .h files cannot be added there is no Files of type entry for .h files.
Instead, they are added in the following manner: go to Project and select Scan All
Dependencies. In CCS, double-click on led.ct and then double-click on Include. You
should see any header files on an #include line in your source files (including
c6713dskinit.c) plus approximately 14 other header files found by the scan step. The
latter files are supplied with the Code Composer Studio software and are used to
configure the DSP chip and board. CCS automatically found and included all needed
header files starting from the header files included in the source files. Open
c6713dskinit.c and observe that it includes c6713dskinit.h; this header and dsk6713
aic23.h (included in led.c) include other header files which in turn include others,
leading to the list observed. Note that some include files are prefixed csl ; these are chipsupport
header files supplied by TI. The file dsk6713.h is a top level header file supplied
by the DSK board manufacturer, Spectrum Digital, Inc.
The project file Lab08.pjt has now been charged with all of the files required to build the
first executable .out file.
7.5. Build Options
The next objective is to customize the compiler and linker options so that the
executable file gets built correctly. Also, the compiler will first convert the C coded
programs into DSP assembly programs before it compiles them into machine code. By
selecting the appropriate options, we can keep these intermediate assembly files. For
your own amusement, you can open these files in word processing program to see how
the DSP assembly is coded.
To make these customizations, click on the Project pull-down menu, go to Build
Options. This will open up a new window. In this window, click on the Compiler tab.
In the Category column, click on Basic and select the following:
Target Version: 671x
Generate Debug Info: Full Symbolic Debug (-g)
Opt Speed vs. Size: Speed Most Critical (no ms)
Opt Level: None
Program Level Opt: None
Then click on the Advanced entry in the Category column and select:
Memory Models: Far
and click on the Preprocessor entry in the Category column and type into the boxes
the following text:
Include Search Path (-i): u:\DSP\Support
Page 45
Now click on the Linker tab on the top of the current window and make sure the
following command appears in the top-most window (See Figur below):
-q -c -o".\Debug\sine gen.out" -x
The options -g, -k, -s in the compiler options and -g, -c, -o in the linker options do serve
apurpose, but we will not be concerned with them just yet.
Your project and project file Lab07.prj has now been created. This process is
cumbersome, but it only needs to be done once. In future projects, you will be able to
copy this project file into another folder and make a few simple modifications. These
modifications include altering the C code and editing one linker option.
Page 46
Page 47
CPU. To reset the CPU, click on the Debug pull-down menu and select Reset CPU.
Then, to load the program onto the DSK, click on the File pull-down menu and select
Load Program. In the new window that appears, double-click on the folder Debug,
click on the file led.out, and click on Open. This will download the executable file
led.out onto the DSK. A new window will appear within CCS entitled Disassembly,
which contains the assembled version of your program. Ignore this window for now.
In CCS, select the Debug pull down menu and then select Run, or just simply click on
the top running man on the left side toolbar. Verify by pressing down the DIP
switches that which led turns on. After you have completed both of these tasks, either
click on the icon of the blue running man with a red X on it or go to the Debug pulldown
menu to select Halt.
Page 48
LAB 10
SAMPLING IN CCS AND C6713
Introduction
In this laboratory you will learn to configure sampling rate in CCS. Lab will also go
through signal generation using lookup tables. A table is created via MATLAB with
the values of sine wave. The sampling frequency that is set in CCS is used to
generate the table in MATLAB.
1. Open and run the tone.pjt project located at
C:\CCStudio_v3.1\examples\dsk6713\bsl\tone
2. The frequency of the signal is 1KHz. Change this frequency to 2KHz.
Hint: Use MATLAB to get a signal of 2 KHz and use its value.
3. Now, change the frequency to 3 KHz.
4. This time change the frequency to 4 KHz. What do you notice?
5. Change the sampling frequency to 48 KHz. The following instruction can be
used to change the frequency of the codec.
DSK6713_AIC23_setFreq(hAIC23_handle, DSK6713_AIC23_FREQ_48KHZ);
You will have to obtain a new lookup table for 1 KHz signal from MATLAB.
Page 49
Introduction
In this laboratory you will design FIR filters and will learn more about the capabilities of the
C6713. Filtering is one of the most useful signal processing operations. DSPs are now
available to implement digital filters in real time. A FIR filter operates on discrete-time
signals and can be implemented on a DSP such as the TMS320C6x. This process involves the
use of an ADC to acquire an external input signal, processing of the samples, and sending
the result through a DAC. Filter characteristics such as center frequency, bandwidth, and
filter type can be readily implemented and modified.
Lab Excercises:
1. Open and run the FIR project
2. There are four different filter coefficients saved in four *.dat files. Provide
the time and frequency plots for each.
3. Apply a signal from MATLAB and show the effect on the signal after it
passes through the filter(s).
Page 50
or equivalently,
This recursive equation represents an IIR. The z-domain representation of the
input-output equation described above can be implemented using different
structures: namely Direct Forms I & II. The Direct Form I structure requires 2N
delay elements for an Nth order filter. Direct Form II is one of the most commonly
used structures as it requires half as many delays. A Direct Form II implementation
would require the use of an intermediate variable w(n),
Thus
It is possible to implement higher order systems, i.e. fourth order IIR structures, as
a cascade of Direct Form II second sections.
Digital Signal Processing
Lab Manual Fall 2010
52
Lab Excercises:
1. Open and run the IIR project
2. There are four different filter coefficients saved in four *.dat files. Provide
the time and frequency plots for each.
3. Apply a signal from MATLAB and show the effect on the signal after it
passes through the filter(s).
Page 51