EEE324 Digital Signal Processing V (Latest) 2
EEE324 Digital Signal Processing V (Latest) 2
Lab Manual
Name
Registration Number
Class
Instructor‘s Name
Introduction
This is the Lab Manual for EEE – 324 Digital Signal Processing. The labs
constitute 25 % of the total marks for this course.
During the labs you will work in groups (no more than three students per group).
You are required to complete the ‘Pre-Lab’ section of the lab before coming to the
lab. You will be graded for this and the ‘In-Lab’ tasks during the in-lab viva. You
will complete the ‘Post-Lab’ section of each lab before coming to the next week’s
lab.
You are not allowed to wander in the lab or consult other groups when performing
experiments. Similarly the lab reports must contain original efforts. CUI has a zero
tolerance anti-plagiarism policy.
Apart from these weekly labs you will complete project. The grading policy is
already discussed in the Course Description File.
Acknowledgement
The The lab manual has gone through a series of changes over the years with
several faculty members and lab engineers contributing towards its improvement.
The experiments were initially designed by Dr. Fasih ud Din Butt and Mr. Fahad
Ali Shifa. The second round of changes was introduced by Dr. Naveed ur Rehman
and Mr. Khuram Naveed. With the aim to follow the Outcome-based education
(OBE) model, the current set of changes have been designed and implemented by
Dr. Muhammad Tahir Akhtar along with his following team members: Mr.
Khurram Naveed and Ms. Amber Madeeha Zeb. In the fourth iteration, DSP kit
related experiments are introduced and updated by Dr. Safwan Khalid.
History of Revision
Date of Issue Team Comments
March 2013 Dr. Fasih ud Din Butt This is the first editable draft of EEE324 lab
Mr. Fahad Ali Shifa manual. (Version I)
Safety Precautions
Be calm and relaxed, while working in lab.
When working with voltages over 40 V or current over 10 A , there must be at least two
Be sure about the locations of fire extinguishers and first aid kit.
No loose wires or metals pieces should be lying on the table or neat the circuit.
Avoid using long wires, that may get in your way while making adjustments or changing
leads.
Be aware of bracelets, rings, and metal watch bands (if you are wearing any of them).
When working with energize circuit use only one hand while keeping rest of your body
o Disconnect the power source from the circuit breaker and pull out the plug using
insulated material.
Table of Contents
Introduction ................................................................................................................................... 2
Acknowledgement ....................................................................................................................... 3
History of Revision ...................................................................................................................... 3
Safety Precautions ......................................................................................................................... 4
Lab # 01 Introduction to Code Composer Studio and DSP Starter Kits TMS320C6416 and
TMS320C6713 .............................................................................................................................. 8
Objective ................................................................................................................................... 8
Pre-Lab ...................................................................................................................................... 8
In-Lab Tasks: ........................................................................................................................... 12
Post Lab Task .......................................................................................................................... 24
Lab # 02 Introduction to discrete-time Signal Processing on MATLAB.................................... 26
Objective ................................................................................................................................. 26
Pre-Lab .................................................................................................................................... 26
In-Lab Tasks ............................................................................................................................ 36
Post Lab Task .......................................................................................................................... 42
Lab # 03 Basic operations on discrete-time sequences .............................................................. 44
Objective ................................................................................................................................. 44
Pre-Lab .................................................................................................................................... 44
In-Lab Tasks ............................................................................................................................ 48
Post Lab Task .......................................................................................................................... 54
Lab # 04 Convolution of discrete-time sequences and its implementation on DSP kits ............. 55
Objective ................................................................................................................................. 55
Pre-Lab .................................................................................................................................... 55
In-Lab Tasks ............................................................................................................................ 59
Post Lab Task .......................................................................................................................... 62
Lab # 05 Discrete Fourier Transform and its Properties ............................................................. 64
Objective ................................................................................................................................. 64
Pre-Lab .................................................................................................................................... 64
In-Lab Tasks ............................................................................................................................ 68
Post Lab Task .......................................................................................................................... 77
Objective:
To get acquainted with Code Composer Studio
How to run codes in Code Composer Studio
To get acquainted with C6711, C5416, C6416, C6713 DSP Starter Kits
To get acquainted with the process of designing a system using SIMULINK and
implementing it on DSK6713
Understanding the C codes is important for an Engineer since it enables him/her to modify the
codes even generated by SIMULINK for optimization and to suit his/her needs. CCS code flow
is shown in diagram below:
Fixed – Contains fixed numbers before and/or after the decimal point
Floating - Numbers are not fixed
Keep in mind that the eye is easier to deceive as compared to ear. This fact is exploited in
the voice and video data communication systems to send the respective signals.
1. No SIMULINK block set for this product and it is the only product with whom TI does not give MATLAB trial CD
DSK Specifications:
C6416 DSK:
C6713 DSK:
In-Lab Task :
Introduction:
The hardware experiments in the DSP lab are carried out on the Texas Instruments
TMS320C6713 DSP
Starter Kit (DSK), based on the TMS320C6713 floating point DSP running at 225 MHz. The
basic clock cycle instruction time is 1 /( 225 MHz)=4.44 nanoseconds. During each clock
cycle, up to eight instructions can be carried out in parallel, achieving up to 8 × 225= 1800
million instructions per second (MIPS).
The C6713 processor has 256KB of internal memory, and can potentially address 4GB of
external
memory. The DSK board includes a 16MB SDRAM memory and a 512KB Flash ROM. It has
an on-board 16-bit audio stereo codec (the Texas Instruments AIC23B) that serves both as an
A/D and a D/A converter. There are four 3.5 mm audio jacks for microphone and stereo line
input, and speaker and head-phone outputs. The AIC23 codec can be programmed to sample
audio inputs at the following sampling rates:
fs = 8,16,24,32,44.1,48,96 kHz
The ADC part of the codec is implemented as a multi-bit third-order noise-shaping delta-sigma
converter that allows a variety of oversampling ratios that can realize the above choices of fs.
The corresponding oversampling decimation filters act as anti-aliasing prefilters that limit the
spectrum of the input analog signals effectively to the Nyquist interval [−fs/2,fs/2]. The DAC
part is similarly implemented as a multi-bit second-order noise-shaping delta-sigma converter
whose oversampling interpolation filters act as almost ideal reconstruction filters with the
Nyquist interval as their passband.
The DSK also has four user-programmable DIP switches and four LEDs that can be used to
control and monitor programs running on the DSP. All features of the DSK are managed by the
CCS, which is a complete integrated development environment (IDE) that includes an
optimizing C/C++ compiler, assembler, linker, debugger, and program loader. The CCS
communicates with the DSK via a USB connection to a PC. In addition to facilitating all
programming aspects of the C6713 DSP, the CCS can also read signals stored on the DSP‘s
memory, or the SDRAM, and plot them in the time or frequency domains. The following block
diagram depicts the overall operations involved in all of the hardware experiments in the DSP
lab. Processing is interrupt-driven at the sampling rate fs, as explained below.
The AIC23 codec is configured (through CCS) to operate at one of the above sampling rates fs.
Each collected sample is converted to a 16-bit two‘s complement integer (a short data type in
C). The codec actually samples the audio input in stereo, that is, it collects two samples for the
left and right channels.
At each sampling instant, the codec combines the two 16-bit left/right samples into a single 32-
bit unsigned integer word (an unsigned int ,or Uint32 data type in C), and ships it over to a 32-
bit receive- register of the multichannel buffered serial port (McBSP) of the C6713 processor,
and then issues an interrupt to the processor.
Upon receiving the interrupt, the processor executes an interrupt service routine (ISR) that
implements a desired sample processing algorithm programmed with the CCS (e.g., filtering,
audio effects, etc.). During the ISR, the following actions take place: the 32-bit input sample
(denoted by x in the diagram) is read from the McBSP, and sent into the sample processing
algorithm that computes the corresponding 32-bit output word (denoted by y), which is then
written back into a 32-bit transmit-register of the McBSP, from where it is transferred to the
codec and reconstructed into analog format, and finally the ISR returns from interrupt, and the
processor begins waiting for the next interrupt, which will come at the next sampling instant.
Clearly, all processing operations during the execution of the ISR must be completed in the
time interval between samples, that is,T=1/fs. For example, if fs=44.1 kHz,
then,T=1/fs=22.68μsec.
With an instruction cycle time of Tc=4.44 nsec, this allowsT/Tc=5108 cycles to be executed
during each sampling instant, or, up to 8×5108=40864 instructions, or half of that per channel.
Block diagrams of DSK 6713 board and its Codec are shown below for understanding.
When you initially start CCS, the DSK is not connected to it as shown below:
Step 2: Go to ‗Debug‘ menu and click ‗Connect‘ or Press ‗Alt+Ctrl+C‘ from your keyboard:
As a result, the DSK will get connected. If not, then check cables and run the diagnostic utility
located at your Desktop. The diagnostic utility for DSK 6713 is shown below.
The test is run by pressing ‗start‘, tests each module of DSK 6713 till all tests are passed. Now
in code composer studio go to Debug and click connect.
Note: To view the C code go to ‗Projects led.pjt Source‘ and double click ‗led.c‘:
Note: To view the header files go to ‗Projects led.pjt Include‘ and double click the file
you want to see
Behavior:
Blinks LED #0 at a rate of about 2.5 Hz (s-1) using the LED module of the 6416 DSK
Board Support Library
Reads the state of DIP switch #3
o Lights LED #3 if the switch is pressed
o Turns it off if the switch is not pressed
Header Files:
#include "ledcfg.h" – Header file for DSP/BIOS configuration of DSK6416 for the said
example
#include "dsk6416.h― – Tells CCS about the connected board
#include "dsk6416_led.h― – For LED module of DSK6416
#include "dsk6416_dip.h― – For DIP switches module of DSK6416
Try to understand what these commands mean. Consult your handouts and instructor for any
help.
Any SIMULINK file may be built on to DSP kit. DSP kit will then perform the function of the
system which was designed in SIMULINK. One may ask about the Significance of this
implementation. The answer is ‗HUGE significance‘ because you may build any system in
SIMULINK and then ‗test drive‘ that system on your DSP processor to see its behavior in real
life.
Important Note: Being a telecom/computer engineer, you can implement various encoding
schemes and propose modifications in them or you can design new encoding schemes
Preliminary Settings:
Click on ‗Optimization‘ in the pane on the left and uncheck first 2 boxes:
Select ‗TIC Compiler/Linker‘ from the pane on the left and check ‗Symbolic Debugging‘ box:
In Lab Tasks:
Task 1:
The model shown below simply takes input from user via Microphone and then sends it to an
output device e.g. Headphones or Speakers. Make, build and run the following model using
SIMULINK and CCS v3.1:
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
Objective
This introductory lab allows students to understand the basic concept of the discrete-time
signals and their representation on MATLAB. Furthermore, it demonstrates some basic
MATLAB codes in order to achieve hands-on it.
Pre-Lab
MATLAB is a high-level programming language that has been used extensively to solve
complex engineering problems. The language itself bears some similarities with ANSIC
and FORTRAN.
MATLAB works with three types of windows on your computer screen. These are the
‗Command window‘, the Figure window and the Editor window. The Figure window only
pops up whenever you plot something. The Editor window is used for writing and
editing MATLAB programs (called M-files) and can be invoked in Windows from the pull-
down menu after selecting File |New| M-file. In UNIX, the Editor window pops up when
you type in the command window: edit filename (‗filename‘ is the name of the file you
want to create).
The ‗ Command window‘ is the main window in which you communicate with the
MATLAB interpreter. The MATLAB interpreter displays a command >> indicating
that i t is ready to accept commands from you.
>> intro
at the MATLAB prompt. This short introduction will demonstrate some basic MATLAB
commands.
>> help
• You can use the ‗command‘ window as a calculator, or you can use it to call
other MATLAB programs (M-files).
Say you want to evaluate the expression a3 + √bd-4c, where a=1.2, b=2.3, c=4.5 and d=4.
Then in the ‗command‘ window, type:
>> a = 1.2;
>> b=2.3;
>> c=4.5;
>> d=4;
ans=
-13.2388
Note the semicolon after each variable assignment. If you omit the semicolon, then
MATLAB echoes back on the screen the variable value.
Symbol Meaning
Pi π (3.14...)
Sqrt indicates square root e.g., sqrt(4)=2
ˆ indicates power(e.g., 3ˆ2=9)
Abs Absolute value | .| e.g., abs(-3)=3
NaN Not-a-number, obtained when comparing mathematically undefined op-ererations, such
as 0/0
inf Represents +∞
; Indicates the end of a row in a matrix. It is also used to suppress printing on the
screen (echo off )
% Denotes a comment. Anything to the right of % is ignored by the
>> z=3 + 4i % note that you do not need the ‗*‘ after 4
You can also define the imaginary number with any other variables you like. Try the
following:
>> img = sqrt (-1)
>> z = 3+4*img
>> exp(pi*img)
+ addition
− subtraction
* multiplication
There are also three other operators that operate on an element by element basis:
Suppose that we have the vectors x = [x1 , x2 , ..., xn ] and y = [y1 , y2 , ..., yn ]. Then
x. ∗ y = [x1 y1 , x2 y2 , ..., xn yn ]
The arithmetic operators + and — can be used to add or subtract matrices, scalars or
vectors. By vectors we mean one-dimensional arrays and by matrices we mean multi-
dimensional arrays. This terminology of vectors and matrices comes from Linear Algebra.
Example:
>> X=[1,3,4]
>> Y=[4,5,6]
>> X+Y
ans = 5 8 10
To compute the dot product of two vectors, you can use the multiplication operator *. For the
above example, it is:
>> X*Y’
ans= 43
Note the single quote after Y. The single quote denotes the transpose of the matrix or a vector.
To compute an element by element multiplication of two vectors (or two arrays) you can
use the .* operator:
>> X .* Y
ans = 4 15 24
That is, X.*Y means [1×4, 3×5, 4×6] = [4 15 24]. The ‗.*‘ operator is used very often
(and is highly recommended) because it is executed much faster compared to the code
that uses for loops.
Note that the arrays are indexed using parenthesis (.) and not square brackets [.] as in
C/C++. To create an array having as elements the integers -5 through 5, just enter:
>> x= [-5,-4,-3,-2,-1,0,1,2,3,4,5]
array ‗x‘ -5 -4 -3 -2 -1 0 1 2 3 4 5
indexes of ‗x‘ 1 2 3 4 5 6 7 8 9 10 11
ans= 3 5
>> jj=20 : -2 : 0
>> x(2:2:length(x)
>> Y (30)
ans = 0
Similarly, you can allocate memory for two-dimensional arrays (matrices). The command
>> Y=zeros (4,5)
defines a 4 by 5 matrix. Similar to the zeros command, you can use the command ones to
define a vector containing all ones,
>> Y=ones (1,5)
ans= 1 1 1 1 1
Note: Memory allocation is needed when in your code you have to refer to some variable
which has not been created yet. If in such cases you proceed with referring the variable without
first allocating memory for it the MATLAB will generate an error saying ‗unknown variable‘.
So the commands zeros, ones and randn may be used to allocate this space.
if statements
switch statements
for loops
while loops
break statement
The if, for, switch and while statements need to terminate with an end statement.
Examples:
IF:
x=-3;
if x>0
str = ‘positive’;
elseif x<0
str = ‘negstive’;
elseif x = = 0
str = ‘zero’;
else
end
while x<0
x=x+1;
end
for i = 1:10
X=X+1;
end
The above code computes the sum of all numbers from 1 to 10.
BREAK:
The break statement lets you exit early from a for or a while loop:
x = -10;
while x < 0
x = x + 2;
if x = = -2
break;
end
Meaning Symbol
Equal ==
Not equal ˜=
AND &
OR |
NOT ˜
Write a code that prints your name five times using FOR loop and WHILE loop.
5. Plotting:
You can plot arrays using MATLAB‘s function plot. The function plot(.) is used to
generate line plots. The function stem(.) is used to generate ―picket-fence‖ type of
plots. Example:
>> x=1:20;
20
18
16
14
12
10
0
0 2 4 6 8 10 12 14 16 18 20
20
18
16
14
12
10
0
0 2 4 6 8 10 12 14 16 18 20
Example of a plot generated using the plot command is shown in Figure 1, and
example of a plot generated using the stem function is shown in Figure 2. More
generally, plot(X,Y) plots vector Y versus vector X. Various line types, plot symbols
and colors may be obtained.
using plot(X,Y,S) where S is a character string indicating the color of the line, and
the type of line (e.g., dashed, solid, dotted, etc.). Examples for the string S include:
You can insert x-labels, y-labels and title to the plots, using the functions
xlabel(.), ylabel (.) and title (.) respectively. To plot two or more graphs on the same
figure, use the command subplot.
The subplot (m, n, p) argument in the subplot command indicates that the figure will be
split in ‗m‘ rows and ‗ n‘ columns. The ‗p‘ argument takes the values 1, 2, . . . , m × n.
In the example above, m = 2, n = 1,and, p = 1 for the top figure and p = 2 for the
bottom figure. For instance, to show the above two plots in the same figure, type:
>> subplot(2,1,1), plot(x)
20
15
10
0
0 2 4 6 8 10 12 14 16 18 20
20
15
10
0
0 2 4 6 8 10 12 14 16 18 20
You need to create a new file, called ―average.m‖. If you are in Windows, open the
text editor by going to the File pull-down menu, choose New, then M-file. If you are in
UNIX, then type in the command window: edit average.m. Type the following in the
empty file:
function y = average (x)
L=length(x);
sum = 0;
for i = 1:L
end
Remarks:
average — is the name of the function. It‘s best if it has the same name
as the filename. MATLAB files always need to have the extension .m
1. From the Editor pull-down menu, go to File|Save, and enter: average.m for the
filename.
2. Go to the Command window to execute the program by typing:
>> x=1:100;
>> y=average(x)
ans =
50.500
Note that the function average takes as input the array x and returns one number, the
average of the array. In general, you can pass more than one input argument and can
have the function return multiple values. You can declare the function average, for
instance, to return 3 variables while taking 4 variables as input with the following
statement:
function [y1, y2, y3] = average(x1,x2,x3,x4)
Note that MATLAB‘s data files have the extension .mat. To retrieve the data that was
saved in the vector x, type:
The vector x is loaded in memory. To see the contents of memory use the command whos:
>> whos
The command whos gives a list of all the variables currently in memory, along with their
dimension. In our case, x contained 8193 samples.
To clear up memory after loading a file, you may type clear all when done.That is very
important, because if you do not clear all the variables in memory, you may run into
problems with other programs that you will write that use the same variables.
In-Lab Tasks:
A signal is a function that conveys some useful information about the behavior or attributes of
some phenomenon. Signals are mathematically represented as a function of one or more
independent variables i.e. y =ƒ( .., ) where .., are the independent variables
that could be time or space and ‗y‘ is the independent variable that in this case represent the
signal values. In this lab, we will mostly be dealing with signals which are the function of time
only and in case of discrete signals, we will replace time with the variable ‗n‘ which will only
take discrete values.
1. Signals in MATLAB
Signals are divided into two major types.
>> y=sin(t);
>> plot(y)
MATLAB representation:
>> n=0:7;
>> y=sin(n);
>> stem(n,y)
How to generate an impulse sequence δ [n- n0] for a finite length [-10 to 9], where ‗n‘
represents the discrete-time axis and ‗n0‘ is the delay.
Find the index when ‗n‘ is equal to the 0, and save its value into a variable ‗i‘.
Plot the array ‗x‘ w.r.t ‗n‘ and label its axis.
2.2. Step Sequence
How to generate a step sequence u [n- n0] for a finite length [-10 to 9], where ‗n‘ is a discrete-
time axis and ‗n0‘ is the delay.
Find the index when ‗n‘ is equal to the 0, and save its value into a variable ‗i‘.
Replace ‗0‘s by ‗1‘s in an array ‗x‘ starting from the index ‗i + n0‘ upto the last
index of the array.
Else- If ‗n0‘ is greater than 0
Replace ‗0‘s by ‗1‘s in an array ‗x‘ starting from the index ‗i - n0‘ upto the last
index of the array.
Else
Replace ‗0‘s by ‗1‘s in an array ‗x‘ starting from the index ‗i‘ upto the last index
of the array.
Plot the array ‗x‘ w.r.t ‗n‘ and label its axis.
Note: The value of the delay ‗n0‘ must not exceed the maximum or minimum value of the
vector ‗n‘ i.e from above mentioned cases ‗n0‘ should lie exceed 9 or 10 (ignoring the negative
sign of the negative values).
Lab Tasks
Task-1: Generate a Continuous time cosine signal and plot it.
Task-3: Write a MATLAB program for the ‗running average‟, a running total is a
sequence of partial sum of a given sequence/signal. For example, the running totals of the
signal {a, b, c, …}are a, a+b, a+b+c, ... Use that program to find the running total of the
discrete time signal of length N=100. Write your program so that it is flexible. That is,
you should be able to invoke your program from the command window as follows:
>> y=running_averagel(x)
where x is the input signal, and y is the running total of that signal.
Task-4: Write a program to compute the variance and mean of a signal x. The variance
is defined to be:
∑ ̅
where ̅ denotes the mean of the signal x. For signal x, use all the integers from 1 to
1000.
for I = 1: L
if x (i) < 0
x (i) = -1;
end
end
Task-6: Generate a step sequence u [n] as described in In-Lab section, use it to generate an
impulse as δ [n] = u[n] – u[n-1].
Task-7: Generate an impulse sequence δ [n] as described in In-Lab section, use it to generate
step sequence.
[ ] ∑ [ ]
Task-8: Generate the following sequences using step and impulse sequence.
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
Objective:
By the end of this lab students will be able to perform signal shifting and folding operations in
MATLAB, in addition students will be able to perform arithmetic operations like adding,
subtracting or multiplying signals of different lengths.
Pre-Lab:
a. How to write script in M-file
i. Click on File drop down menu and go to New tab and select Script/M-file
>> script
ii. Once the mfile is open write your code and then save it by some name as
iii. After writing the code click the play button on the m-file window to run the
code
A function in Matlab is similar to a function in C/C++. Once a function is made it can be called
in any other function/script just like C/C++. Note that script is just a code but function is more
like a separate object or entity. Just like C/C++ there is a particular syntax for making a
function as given below.
Code
end
iii. Each function has a distinct name and file is also saved with the same name as
function. If an M-file having the function with a name ―average‖ is saved by the name of
―avg‖, then this function cannot be called in another file.
i. In order to call a function in another file the directory of both file must be same.
ii. Before calling the function inputs needs to be defined in the script or command
window.
iii. Suppose we have a function by the name of ―average‖ that takes the average of
three numbers n1, n2 and n3 and returns average avg, then following code must be written
in command window or script to call this function
n1 = 10; % defined n1
n2 = -5; % defined n2
n3 = 20; % defined n3
or simply,
[avg] = average (10,-5, 20); % function called directly
iv. If the inputs are not defined the function call will produce an error and also function
cannot be run using the play button in m-file unlike scripts.
d. Some relevant MATLAB commands to generate different type of signals
(See help of following)
A signal x[n] in Matlab in matlab is defined using two arrays or sequences, one array
representing the magnitudes ―x‖ and the other array defining the time indexes i.e. the signal
given in the figure (on right side) will be defined as
>> n = 0:4;
It is of particular importance to mention that any operation performed on this signal i.e.
shifting, folding etc. will be performed on both the magnitudes ―x‖ and time index ―n‖.
>> x = (0.9).^n;
>> n = [0:10];
>> x = exp((2+3j)*n);
Note that you need different plot commands for plotting real and imaginary
components.
3. Sinusoidal sequence
A matlab function ―cos‖ (or sin) is used to generate sinusoidal sequences.
To generate x(n) = 3cos(0.1πn + π/3) + 2sin(0.5 πn), 0<= n<=10, we will need the
following script:
>> n = [0:10];
4. Random Sequences
A random or stochastic sequences are characterised by parameters of the associated
probability density functions or their statistical moments. In matlab, 2 types of (psuedo
) random sequences are avalable: ―rand(1,N)‖ generates a length N random sequence
whos elements are uniformly distributed between 0 and 1. ―randn(1,N) generates a
length N gaussian random sequence with mean 0 and variance 1. Other random
sequences can be generated using transformation of the above functions.
5. Periodic sequence
A sequence is periodic if x(n) = x(n +N). To generate P periods of x(n) from one
period, we can copy x(n) P times:
Generate a matrix containing P rows of x(n) values. Concatenate P rows into a long row
vector using the construct (:).
Have to use matrix transposition operator (‗) to provide the same effect on rows:
>> xtilde = x' * ones(1,P); %P columns of x; x is a row vector
In-Lab
In this Operation each sample is multiplied by a scalar. Use the command ―*‖ for scaling.
2. Signal Shifting
Description: During a shift operation a signal changes its position in time where each sample
of x(n) is shifted by an amount k to obtain a shifted sequence y[n].
y (n) {x(n k )}
In Matlab, this operation is not so simple, both ―x‖ and ―n‖ need to be processed separately in
order to get the shifted signal x[n-k]. Perform following steps to in Matlab to perform the
signal shift.
We know that signals can have different starting and ending times, here we want to modify
time indexes such that both signals start from the lowest time index and end at highest time
index and accordingly concatenate zeros or at the start or end of the signal. Suppose we want
to add/multiply two signals x1[n] specified by x1 and n1 in Matlab and and x2[n] specified by
x2 and n2 in Matlab. Following two steps can be followed to make the lengths of x1 & x2 and
making n1 and n2 same as well.
a. Compare the starting points of both signals time index vectors i.e. n1(1) and n2(1).
If n1(1) is smaller than n2(1)
Lab Tasks
Task-1: Take an exponential signal and perform scaling operation with a negative integer as
given in In-Lab Work section and plot the result
Task-2: Write a Matlab function ―sigshift‖ for producing a delay of ‗k‘ in a given sequence
‗x[n]‘ defined by arrays ―x‖ and ―n‖ by using the pseudo code given in In-Lab Work section.
Your function should yield y[n] = x[n-k].
Function [y,n]=sigshift(x,n,k)
Task-3: Write a Matlab function ―sigfold‖ for folding a given sequence ‗x[n]‘ defined by
arrays ―x‖ and ―n‖ by using the pseudo code given in In-Lab Work section.
Function [y,n]=sigfold(x,n)
Task-4: Write a Matlab function ―sigadd‖ for adding two sequences x1[n] and x2[n] by using
the pseudo code given in In-Lab Work section.
Function [y,n]=sigadd(x1,n1,x2,n2)
Task-5:
x(n) {1, 2,3, 4,5, 6, 7, 6,5, 4,3, 2,1}
Let
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
Objective
By the end of this lab students will learn about decomposition of signals into even and odd
components, how to take output from LTI system by convolving input signal [ ] with impulse
response [ ]? This will add to their understanding of LTI system and its operation.
Pre Lab
Before performing convolution, you should be familiar with the basic operations on continuous
time signals.
if xe (n) xe (n)
if xo (n) xo (n)
then xe (n) is called even( symmetric)
then xo (n) is called odd (antisymmetric)
Any arbitrary real-valued sequence x(n) can be decomposed into its even and odd component
Recall the ―conv‖ command you have used in Signals & Systems course. Try
performing convolution using ―conv‖ command.
>> y = conv(x,h)
You will see there is a limitation in ―conv‖ command. Can you find a solution to it?
There are two widely used methods to compute convolution. We will discuss both methods
before performing this lab
Method 1:
– Step 3: multiply x(k) and h(n-k) for each k and then take the summation over k
Example:
Final Result:
x(n)
Method 2:
Y(n) = ∑k x(n)h(n-k)
x(n) = ∑k ak δ(n-k)
y(n)= ∑ a0 δ(n) h(n)+ ∑a1 δ(n-1) h(n-1)+ ∑ a2 δ(n-2) h(n-2)+ ∑a3 δ(n-3) h(n-3)+ ……..
Example:
y(n)= ∑ (a0 δ(n) h(n)+ a1 δ(n-1) h(n-1)+ a2 δ(n-2) h(n-2)+ a3 δ(n-3) h(n-3)
δ[ ] [𝑛] y0
1 1 1
X =
0 n 0 1 n 0 1 n
-1 -1
[𝑛 ]
𝛿[𝑛 ] y1
1 2
2
X 2 =
1 n 1 n 1 2 n
-1 -2
[𝑛 ] Y2
𝛿[𝑛 ]
1 3
3
X = 2 3
n 2 3 n n
2
-1 -3
𝛿[𝑛 3] [𝑛 3] Y3
4 1 4
X = 3 4 n
3 n 3 4 n
-1 -4
Final Result:
y(n)
1 1 1 1
0 1 2 3 4 n
-4
Moving-average system
Moving-average system computes the nth sample of the output sequence as the average
of ) samples of the input sequence around the nth sample. Mathematically it is
[ ] ∑ [ ]
In Lab Tasks
Task 1: Write a MATLAB code to decompose a sequence into its even and odd components.
Take help from Pre-Lab work.
Task 2: You should have noticed that ―conv‖ command calculates convolution assuming both
input sequences starting from origin. This is not always the case because we do have sequences
that can have values for . Write a MATLAB function ―conv_m‖ that would remove this
limitation.
Task 3: Convolve following sequences using MATLAB function ―conv‖ and ―conv_m‖ and
show input signal, impulse response and output in one figure using ―subplot‖.
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
Objective:
By the end of this lab students will be able to compute and plot the DFT of a discrete signal on
MATLAB using FFT command, and perform periodic convolution on MATLAB, in-addition
students will verify the properties of DFT.
Pre-Lab:
1. DFT
For a periodic signal x[n] with a period N, discrete Fourier transform (DFT) is computed as
Where w0 = 2π/N is the fundamental frequency of the signal. Following two conditions must satisfied
for its DFT to be computed
ii. x[n] should be made periodic by repeating the system infinite times
Since x[n] is periodic the FT of its one period will completely characterize the system, hence the
summation will go from 0 to N-1.
2. DTFT
DFT is the computable version of discrete time Fourier transform. Despite being the Fourier transform
of a discrete signal x[n], DTFT X(ejw) is function of a continuous variable w, given by
In order to compute DTFT, infinite summations are required, which is not possible, hence DFT is
computed for the knowledge of frequency response. Figure below presents DFT as the discretized
version of discrete time Fourier transform (DTFT) in frequency domain.
Fig. 1: Stems represent DFT and the envelope over them is DTFT
The DTFT is a transformation that maps Discrete-time (DT) signal x[n] into a complex valued function
of the real variable, if x (n) is absolutely sum able i.e.
x(k )
1
x(n) F 1[ X (e jw )] X (e
jw
)e jwn dw
2
2.1 Periodicity
The DTFT X(ejw) is periodic in w with period 2:
2.2 Implication
COMSATS University Islamabad Page 65
EEE 324 Digital Signal Processing Lab.
2.3 Symmetry
For real-valued x(n), X(ejw) is conjugate symmetric
X(ejw) = X*(ejw) or
2.4 Implication:
We need only half period of X(ejw) i.e. w[0,]
If we consider only one period of this sequence then this shifting can be considered as circular
shift, depicted below.
4.1. Linearity
DFT{x(n l )} X (k )e j ( 2 / N ) kl
DFT [ x(n)e j ( 2 / N ) nl ] X (k l )
4.4. Conjugation
DFT [ Nx(n)] X (k )
4.6. Convolution
In-Lab Tasks
1. FFT Command in MATLAB
FFT command is used to compute Discrete Fourier Transform (DFT), it uses one-dimensional fast
algorithm namely Fast Fourier transform to compute DFT.
Y = fft(X)
Y = fft(X, n)
The functions X = fft(x) implement the transform for vectors of length N by:
Y = fft(X) returns the discrete Fourier transform of vector X, computed with a fast Fourier transform
(FFT) algorithm.
If X is a matrix, fft returns the Fourier transform of each column of the matrix.
πIf the length of X is less than n, X is padded with trailing zeros to length n.
The fft function employs a radix-2 fast Fourier transform algorithm if the length of the sequence is a
power of two.
Example:
>> x = cos(1:100);
>> y = fft(x);
>> w = linspace(-pi,pi,length(Y));
>> stem(w,Y);
40
35
30
25
Amplitude
20
15
10
-5
-4 -3 -2 -1 0 1 2 3 4
Frequency w
>> stem(w,y);
40
35
30
25
Amplitude
20
15
10
-5
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
Normalized Frequency w
Abs
Abs(X) returns an array Y such that each element of Y is the absolute value of the corresponding
element of X.
Angle:
Phase angle P = angle (Z) returns the phase angles, in radians, for each element of complex
array Z. The angles lie between . For complex Z, the magnitude R and phase angle theta are
given by:
5.1.Linearity property
(Pseudo-code)
MATLAB Code
alpha = 2;
beta = 3;
n = -10:10;
x1 = sinc(2000*pi*n);
x2 = sinc(5000*pi*n);
N = length(x);
LHS = fft(x,N);
w = linspace(-1,1,N);
subplot(211)
stem(w,LHS)
f1 = fft(x1,N);
f2 = fft(x2,N);
subplot(212)
stem(w,RHS)
-5
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
-5
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
5.2.Parsevals theorem
(Pseudo-code)
MATLAB Code
n = -10:10;
x = sinc(2000*pi*n);
xmod = abs(x);
xmodsquared = xmod.^2;
LHS_Energy = sum(xmodsquared)
N = length(x);
f = fft(x,N);
fmod = abs(f);
fmodsquared = fmod.^2;
RHS_Energy = sum(fmodsquared)/N
Lab Tasks
Task-1: Write Matlab function for circular shift by first writing its pseudo-code of the
procedure explained in the In-Lab section and then writing its code.
Task-2: Verify the time shifting property of DFT by first writing a pseudo code of the RHS
and LHS followed by the MATLAB code. Use the circular shift function designed above for
shifting in time domain. Compare the result by sub-plotting LHS and RHS of the following
equation.
DFT{x(n l )} X (k )e j ( 2 / N ) kl
Task-3: Verify the duality property of DFT by first writing a pseudo code of the RHS and LHS
followed by the MATLAB code. Compare the result by sub-plotting LHS and RHS of the
following equation.
DFT [ Nx(n)] X (k )
Task-4: Write Matlab function for circular convolution by first writing its pseudo-code of the
procedure explained in the In-Lab section and then writing its code.
Task-5: Verify the convolution property of DFT by first writing a pseudo code of the RHS
and LHS followed by the MATLAB code. Use the circular convolution function developed in
task-4 to compute convolution in time domain. Compare the result by sub-plotting LHS and
RHS of the following equation.
Task-6: Verify the duality property of DFT by first writing a pseudo code of the RHS and LHS
followed by the MATLAB code. Compare the result by sub-plotting LHS and RHS of the
following equation.
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
Objective
By the end of this lab students will be able to:
Become familiar with the computation of the z-transform of various signals and with
the determination of ROC.
Learn and understand the properties of the z-transform and how these properties can be
used to simplify computations.
Learn the process of inverting the z-transform by using method of partial fraction
expansion.
Understand how LTI systems are represented in the z-domain and the relationship to
the frequency response.
Learn how to solve difference equations that describe LTI systems with initial
conditions.
Understand the difference between bilateral and unilateral z-transform.
Pre-Lab Tasks
The z-Transform for the discrete time signals is the counter part of Laplace transform for
continuous time signals and they each have similar relationship to the corresponding Fourier
transform.
One motivation for introducing this generalization is that the Fourier transform does not
converge for all sequences and it is useful to have a generalization of the Fourier transform that
encompasses a broad class of signals.
The analysis and synthesis equation of the z-transform has been shown to the students in
lecture. The two sided z-transform is also known as Bilateral z-transform and the one sided z-
transform is known uni-lateral z-transform.
Also we will see in this lab session that how we can calculate the inverse z-transform
analytically and by using one of the simple command of Matlab.(Particularly to solve partial
expansion).
1. Region of convergence
The region of convergence, known as the ROC, is important to understand because it defines
the region where the z-transform exists. For a given sequence, the set of values of z for which
the z-transform converges is called the Region of Convergence (ROC). The ROC for a given
x[n], is defined as the range of z for which the z-transform converges. Since the z-transform is
a power series, it converges when x[n] z−n is absolutely summable. Further, the convergence is
dependent only on the magnitude of z i.e |z|. Thus, if z = z1 is in the ROC, then all values of z
on the circle defined by |z| = |z1| will also be in the ROC. As a result, the ROC will consist of
a ring in the z-plane centered about the origin. The ROC might extend outward to ∞ or inward
to origin depending on the sequence. If the ROC includes the Unit circle, this implies
convergence of z-transform for |z| = 1 or, equivalently, the Fourier transform converges. The
ROC cannot contain a Pole, since at a pole H(z) is infinite by definition and hence does not
converge. A causal LTI system with a rational system function H(z) is stable if and only if all
of the poles of H(z) lie inside the unit circle.i.e., the magnitude of poles must be less than 1.
2. Pole-Zero Plot
Pole-Zero plot is an important tool, which helps us to relate the Frequency domain and Z-
domain representation of a system. A plot of Pole and Zeros of a system on the z-plane is
called a Pole-Zero plot. Usually, a Zero is represented by a 'o'(small-circle) and a pole by a
'x'(cross). Since H(z) evaluated on the unit-circle gives the frequency response of a system, it is
also shown for reference in a pole-zero plot. It also helps in determining stability of a system,
given its transfer function H(z).
In-Lab Task:
1. Some Useful MATLAB Commands
freqz: can be used to plot the magnitude and phase of system response. Also it is used to
find Frequency response of any system. The function freqz(b,a,w) returns the frequency
Examples:
1. The Freqz function computes and display the frequency response of given Z-
Transform
of the function
freqz(b,a,Fs)
b= Coeff. Of Numerator
a= Coeff. Of Denominator
Matlab Code:
b=[2 5 9 5 3]
a= [5 45 2 1 1]
freqz(b,a);
2. Plot the magnitude and phase of the frequency response of the given digital filter
Using freqz function:
Matlab Code:
b = [0.2];
w = [0:1:500]*pi/500;
H=freqz(b,a,w);
magH = abs(H);
phaH = angle(H)*180/pi;
subplot(2,1,1);
plot(w/pi,magH);
title('Magnitude Response');
xlabel('frequency in pi units');
ylabel('│H│');
plot(w/pi,phaH);
title('Phase Response');
xlabel('frequency in pi units');
ylabel('Degrees');
zplane: This function plots zeros and poles of discrete time systems.
zplane(b,a)
[hz,hp,ht] = zplane(z,p)
o zplane(b,a) where b and a are row vectors, first uses roots to find the
zeros and poles of the transfer function represented by numerator coefficients b
and denominator coefficients a.
o [hz,hp,ht] = zplane(z,p) returns vectors of handles to the zero lines,
hz, and the pole lines, hp. ht is a vector of handles to the axes/unit circle line
and to text objects, which are present when there are multiple zeros or poles.
Example:
Matlab Code:
b=[0 1 1 ]
a= [1 -2 +3]
roots(a)
roots(b)
zplane(b,a);
[r,p,k] = residuez(b,a)
[b,a] = residuez(r,p,k)
Example:
MATLAB Code:
b = [0,0,1];
Result:
R = 4,0,-4
P = -1,-0.5,-0.5
K=[]
tf2zp: This function is used to find poles and zeros of a rational z-transform expressed as
ratios of polynomials in descending powers of z.
filter: This command can also be used for calculating inverse of z-transform.
sptool: Signal Processing Tool - Graphical User Interface. sptool opens the sptool window
which allows you to import, analyze, and manipulate signals, filters, and spectra.
Lab Tasks
Task-1: Using MATLAB we determine the partial-fraction expansion of the z-transform X(z)
given by
18z3
X(z) =
18z3 + 3z2 – 4z -1
1- 2z-1
H(z) =
(1-0.2z-1)(1+0.6z-1)
COMSATS University Islamabad Page 84
EEE 324 Digital Signal Processing Lab.
Task-3: Determine the Inverse z-transform of the following sequences, using partial fraction
expansion method.
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
The purpose of this lab is to acquaint students with the following concepts:
• Sampling
• Rates of sampling
• Up sampling/Interpolation
• Down sampling/Decimation
Pre-Lab Work:
Introduction: The signals we use in the real world, such as our voices, are called "analog"
signals. To process these signals in computers, we need to convert the signals to "digital"
form. While an analog signal is continuous in both time and amplitude, a digital signal is
discrete in both time and amplitude. To convert a signal from continuous time to discrete
time, a process called sampling is used. The value of the signal is measured at certain
intervals in time. Each measurement is referred to as a sample. (The analog signal is also
quantized in amplitude, but that process is ignored in this demonstration.
Sampling
is large and less information if the it is small. Theoretically, this measuring and storing of samples
of continuous signal, can be thought of as the multiplication of impulse train with the continuous
signal as
While we sampling a signal there is limit to which we can increase the sampling time Ts or
decrease the sampling rate (fs= 1/TS) in order to full reconstruct the continuous signal back from
the discrete signal. This limit is defined by the Nyquiste criteria.
Sampling process (decpicted in the figure above) in frequency domain becomes convolution of the
impulse train with the X(jm), which creates a repetition of X(jm) on the multiples of m s As
depicted below.
Nyquist Criterion:
The Nyquist criterion states that for the digital signal to be correctly reconstructed it must be sampled at
twice the frequency of the maximum frequency signal in the original analog signal. It is named after the
Swedish-American engineer Harry Nyquist.
or
When the continuous function being sampled contains no frequencies equal or higher than the
half of the sampling rate, there is no loss of the information i.e. Nyquiste criteria is fulfilled.
But if the continuous signal is contains a frequency component higher than half the sampling
rate then aliasing occurs and exact reconstruction is not possible.
Aliasing
Aliasing is caused by the repetition of X(jm) on the multiples of m s i.e. X(jm- kms) if ms < 2mM. It
means that the repeated spectrums overlap with each in frequency domain hence making it
impossible to recover the complete information i.e. some information is lost forever. This
phenomena is explained in the figure below.
In signal processing, oversampling is the process of sampling a signal with a sampling frequency
significantly higher than twice the bandwidth or highest frequency of the signal being sampled.
Oversampling helps avoid aliasing, improves resolution and reduces noise. Oversampling can make it
easier to realize analog anti-aliasing filters. Without oversampling, is very difficult to implement filters
with the sharp cutoff necessary to maximize use of the available bandwidth without exceeding the
Nyquist limit. By increasing the bandwidth of the sampled signal, design constraints for the antialiasing
filter may be relaxed. Once sampled, the signal can be digitally filtered and downsampled to the desired
sampling frequency. In modern integrated circuit technology, digital filters are easier to implement than
comparable analog filters.
In signal processing, downsampling (or "subsampling") is the process of reducing the sampling
rate of a signal. This is usually done to reduce the data rate or the size of the data. The
downsampling factor (commonly denoted by M) is usually an integer or a rational fraction
greater than unity. This factor multiplies the sampling time or, equivalently, divides the
sampling rate. For example, if compact disc audio at 44,100 Hz is downsampled to 22,050 Hz before
broadcasting over FM radio, the bit rate is reduced in half, from 1,411,200 bit/s to 705,600 bit/s,
assuming that each sample retains its bit depth of 16 bits. The audio was therefore downsampled by a
factor of 2.
Since downsampling reduces the sampling rate, we must be careful to make sure the
Shannon-Nyquist sampling theorem criterion is maintained. If the sampling theorem is
not satisfied then the resulting digital signal will have aliasing. To ensure that the
sampling theorem is satisfied, a low-pass filter is used as an anti-aliasing filter to reduce
the bandwidth of the signal before the signal is downsampled; the overall process (low-
pass filter, then downsample) is called Decimation. Note that if the original signal had
been bandwidth limited, and then first sampled at a rate higher than the Nyquist
minimum, then the downsampled signal may already be Nyquist compliant, so the
COMSATS University Islamabad Page 92
EEE 324 Digital Signal Processing Lab.
downsampling can be done directly without any additional filtering. Downsampling only
changes the sample rate not the bandwidth of the signal. The only reason to filter the
bandwidth is to avoid the case where the new sample rate would become lower than the Nyquist
requirement and then cause the aliasing by being below the Nyquist minimum.
In-Lab Tasks
In order to plot DFT of a finite signal, one period of a periodic signal of length N is considered. In order
for DFT to be without loss of information NFFT (Number of elements in DFT) must be greater then or
equal to N (Nyquist Criteria). The DFT of the sampled signal will always be between f/2 andf/2 if
above condition is fulfilled
Code:
NFFT = 2Anextpow2(L); y =
fft(x,NFFT);
Use your ‗sin‘ function to generate a sine wave with f = 3kHz and sample it with fs = 8kHz.
Calculate its fft with zero frequency component in the middle. Plot it on a properly scaled w-
axis. Specify if there is aliasing or not?
Code:
n = -50:50; f =
3000; fs = 8000;
x = sin(2*pi*(f/fs)*n)
L = length(x);
NFFT = 2Anextpow2(L); y =
fft(x,NFFT);
f ax1 = fs/2*linspace(0,1,NFFT/2+1);
f ax2 = fs/2*linspace(-1,0,NFFT/2-1);
stem(f ax,2*abs(y))
xlabel('Hz');
ylabel('Amplitude');
As can be seen from the DFT, there is an impulse on f = 3000 Hz and f = -3000 Hz, hence there is no
aliasing due to the sampling sin(2n(3000)t) should have an impulse on ±3000 Hz and sampled signal
shows precisely the same spectrum. While little impulses in the DFT represent the energy leakage due
to the finite length of the signal.
Use your ‗sin‘ function to generate a sine wave with f = 3kHz and sample it with fs = 5kHz. Calculate
its fft with zero frequency component in the middle. Plot it on a properly scaled w-axis. Specify if there
is aliasing or not?
Code:
n = -50:50; f =
3000; fs = 5000;
x = sin(2*pi*(f/fs)*n)
% subplot(2,1,1)
% stem(n,x);
L = length(x);
NFFT = 2Anextpow2(L); y =
fft(x,NFFT);
stem(f ax,2*abs(y))
xlabel('Hz');
ylabel('Amplitude');
As the figure above shows the DFT of sin(2n(3000)t) at fs = 5000 Hz, which originally, should have
two impulses at ±3000 Hz. But the spectrum has changed (as shown in the figure above) because the
signal has lost enough information that its not sin(2n(3000)t) anymore. In fact the DFT in figure above
shows a signal sin(2n(2000)t) as both impulses are at ±2000 Hz, hence there is aliasing.
• y = decimate(x,R) - To downsample a signal. Here ‗x‘ is the array containing the signal to be
downsampled and ‗R‘ is the downsampling factor/ratio
• y = interp(x,R) - To upsample a signal. Here ‗x‘ is the array containing the signal to be upsampled
and ‗R‘ is the upsampling factor/ratio
Up till now you have studied and performed theoretical concepts, whether these theoretical tool
you have studied in the DSP theory and simulated in DSP lab have any practical significance?
How a signal is processed in reality, in this section we are going to perform an example of
aliasing on a speech signal. We are going to perform following steps for this purpose.
i. Record your voice in matlab or use a recorded audio file and play the audio using play, sound
or audioplayer
iii. Decimate the speech signal first by 2 and later by 3 and then perform step ii. Now compare the
fft of original and decimated signals and deduce your opinion about the effect of aliasing by
listening the reconstructed signal and their fft plots.
iv. Now take the interpolated signal by 3 and perform step ii, afterwards decimate it by 2. Play the
signal listen to it check whether its quality has deteriorated or not due to aliasing. Decimate the
signal further by 2 until aliasing has appeared and voice quality of the signal has deteriorated.
Also observe how fft plot is effected due decimation and interpolation.
Required code:
% Read the data back into MATLAB, and listen to audio. [x,
fs, nbits] = auread(hfile) sound(myRecording,fs);
COMSATS University Islamabad Page 97
EEE 324 Digital Signal Processing Lab.
L = length(x);
Step-3: Decimation
x = decimate(x,2); x = decimate(x,3);
Step-4: Interpolation
x = interp(x,3); x = decimate(x,2);
Figure: The above spectrum is DFT of a sound signal while below is it’s the spectrum of its
decimated version
Lab Tasks
Lab Tasks
Task-1: Use your ‗sin‘ or ‗cos‘ function to generate a sinusoid wave having two components
as f1 = 3kHz and f2 = 5kHz and then sample it with fs = 10kHz. Calculate its fft with zero
frequency component in the middle. Plot it on a properly scaled w-axis. Specify if there is
aliasing or not? If there is aliasing specify which component is casing the aliasing.
Task-2: Use your ‗sin‘ or ‗cos‘ function to generate a sinusoid wave having two components
as f1 = 3kHz and f2 = 5kHz and then sample it with fs = 8kHz. Calculate its fft with zero
frequency component in the middle. Plot it on a properly scaled w-axis. Specify if there is
aliasing or not? If there is aliasing specify which component is casing the aliasing.
Task-3: Use your ‗sin‘ or ‗cos‘ function to generate a sinusoid wave having two components
as f1 = 1.5kHz and f2 = 4kHz and f3 = 7kHz and then (a) sample it with an fs such that there is
no aliasing (b) sample it with an fs which produces aliasing. Show the result in both cases by
plotting fft of the discretized signal.
ii. Downsample (decimate) the signal in part-(ii) by 2 and plot its fft. Comment if there is
aliasing or not?
iii. Now upsample (interpolate) the signal in part-(ii) by 2 and plot its fft. Comment on the
outcome?
iv. Compare the fft of in part-(i) and in part-(iii) and comment on whether or not the
interpolation operation recovers the information lost during decimation operation?
Task-5: Take a speech signal, plot its fft, now decimate by 2,3,4 … until the spectrum goes
outsidethe range {-fs/2, fs/2} (That‘s when aliasing appears). Now do the reverse process i.e.
interpolate by … 4,3,2 and see whether the original signal has recovered or not listening the
reconstructed signal. Note that you are required to plot fft at all stages.
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
Objective:
By the end of this lab students will be able to model and simulate any type of
communications/control / DSP model on Simulink and analyze its performance.
Introduction:
Simulink, developed by MathWorks©, is a commercial tool for modeling, simulating and
analyzing multi-domain dynamic systems. Its primary interface is a graphical block
diagramming tool and a customizable set of block libraries. It offers tight integration with the
rest of the MATLAB environment and can either drive MATLAB or be scripted from it.
Simulink is widely used in control theory and digital signal processing for multi-domain
simulation and Model-Based Design.
Running SIMULINK:
Click on the new file icon shown at the top left corner of the above figure and set the
configuration parameters of your simulation as shown below:
Library Browser:
A toolbox is a collection of tools designated to perform a specific task or set of tasks. All the
toolboxes are in this window. However, we are concerned with Digital Signal Processing so we
will use the ‗Signal Processing Toolbox‘. Navigate inside the blocks and right click on any
component and click on ―add to <filename>‖ where filename is the name of your simulink
model file.
Following are some of the important toolboxes we will use in our labs:
SIMULINK
o Commonly Used Blocks
o Discontinuities
o Discrete
o Math Operations, Signal Attributes, Signal Routing, Sources, Sinks etc
Signal Processing Blockset
Embedded Target for TI C6000 DSP (for DSKs)
o DSK DSP Starter Kits (6414, 6711, 6713 etc)
Acquaint yourselves with these toolboxes as they will be used in your subsequent labs. Consult
Google and ask your instructor in case of any queries. Build the following example model in
SIMULINK:
In-Lab Task :
In this lab non R-T model for the AM transmitter/receiver is to be developed to demonstrate
the features of Amplitude Modulation (AM) transmission and reception. Amplitude
Modulation is a process where the amplitude of a carrier signal (high frequency sinusoid) is
altered according to information in a message signal. The model runs in SIMULINK and
enables the user to select:
1. The AM algorithm
2. The transmission and reception parameters (modulation index and carrier frequency).
Simulation
The Environment
Figure 1 shows the data flow for the AM modulation simulation. The AM modulation model
receives an input signal from an external signal generator, modulates it and displays the
modulation on the scope.
Information Demodulated
Modulator Demodulator
Signal Signal
Virtual
Scope
The Procedure
Where:
2. Open the Simulink library browser and add the DSP sine-wave to your model. This
3. Configure the Sine Wave Generator Block (Double click on the DSP sine object). Set
the sine frequency to 1000 Hz, sample time to 1/96000, samples per frame to 64 and
close the box, and change its label to ―information‖.
4. Use the same block to create the carrier signal. You may copy the block already created
or select it form the Simulink library. Set the carrier frequency to 15,000 Hz. The
remaining parameters are identical to the ones of the information signal. Change its
label to ―carrier‖
6. Double-click on the constant object and set its constant value to 1.5:
Figure 7- Adder
8. Add a new multiplexer from the same directory as the adder (choose ―product‖).
9. Add a new scope object:
Figure 8 - Scope
10. Set the number of frames parameter to 5. This parameter determines the horizontal scaling of
the presented signal.
12. Run the model, pause the simulation and activate the scope window. The modulated
In this section you will create the model for an AM receiver based on Square Root (SQRT)
demodulation. The principle of operation is shown Figure 1.
13. Add the new math function block to your model. This block can be configured to
15. Use the math function block to create the Square root function. You may retrieve it
16. Add a digital filter design block. This block enables you to design filters using the
MATLAB® FDATool.
17. Configure the filter to be Low-Pass Filter. Since the carrier frequency (fc) is 15 KHz
and the maximal frequency of the information is 1 KHz, the filter will be designed to
pass frequencies below 5 KHz, and rejects frequencies higher than 10 KHz (please refer
to Figure 16).
20. Add the matrices concatenation object. This object will enable the modulated and the
1
The subtraction is created by reconfiguring the adder block, and choosing “+-
“ instead of: “++”
COMSATS University Islamabad Page 117
EEE 324 Digital Signal Processing Lab.
22. Run the simulation (push the ―play‖ button). Double click on the scope. Scale the
display to fit the scope window (Choose from the menus: Axes=>Autoscale). Choose a
different color for each signal (Please refer to Figure 19).
Try to change the modulation index to 50%, 100% and 150% and comment on the
influence of changing ‗mu‘ on the modulated and demodulated signals. Keep the
carrier signal frequency same as before
In Lab Tasks:
Task 1:
Generate a sinusoid containing 5 frequency components and display these components in the
FFT-scope.
Task 2:
Generate DSB SC and use coherent detection to recover the message signal. Analyze the
spectra of AM and DSB-SC signals and comment on the bandwidth and transmission of both
schemes.
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
Objective:
In this lab students will design different types of filters using MATLAB (Simulink).
Their testing will be performed through DSK kit and results of filtering will be displayed on
Oscilloscope.
1. Low-pass filters
2. High-pass filters
3. Band-pass filters
4. Band-stop filters
The typical responses of these filters are shown below:
-10
-20
Magnitude (dB)
-30
-40
-50
-60
0 5 10 15 20
Frequency (kHz)
-10
-20
Magnitude (dB)
-30
-40
-50
-60
-70
0 5 10 15 20
Frequency (kHz)
-10
-20
Magnitude (dB)
-30
-40
-50
-60
0 5 10 15 20 25 30
Frequency (kHz)
-10
-20
Magnitude (dB)
-30
-40
-50
-60
-70
0 5 10 15 20 25 30
Frequency (kHz)
In Lab Task:
Alternatively, filters may also be classified according to their response type as:
FDA tool is the filter design and analysis tool in MATLAB which is used for the design and
analysis of FIR or IIR filters. It may be opened by simply typing the following command in
MATLAB command window:
>>fdatool
1. Go to MATLAB ‗Start‘
2. Point to Toolboxes
3. Point to Filter Design in the sub menu
4. Click on Filter Design & Analysis Tool (fdatool)
Following are some of the parameters considered during filter design process in FDA tool:
Think of order as the measure of how much processing power our digital filter will require to
be implemented. Hence,
FV tool is the Filter Visualization tool in MATLAB and you can use it to analyze your filter
response in details. It may be opened from FDA tool by first designing a filter and then
opening this tool from ‗ViewFilter Visualization Tool‘. The interface of this tool is shown
below:
FV Tool – Interface
In Lab Tasks:
Task 1:
Design a low pass filter to suppress all frequencies above 4 kHz. Implement it on DSP kit
and show filtered signal on Oscilloscope.
Task 2:
Design a high pass filter to pass frequencies above 6 kHz. Implement it on DSP kit and
show filtered signal on Oscilloscope.
Task 3:
For a frequency range of ‗24kHz – 28kHz‘, design a band pass filter and a band stop filter.
Implement on DSP kit and show filtered signals on Oscilloscope.
Task 4:
Observe that there is a guard band of 2 kHz between 4 kHz and 6 kHz. Implement it on DSP
kit and show filtered signal on Oscilloscope.
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
Objective
In this lab DSK6713 and DSK6416 will be used to demonstrate the features of Amplitude
Modulation (AM) transmission and reception. The model run is in real-time and enables the
user to select:
The AM algorithm
The transmission and reception parameters (modulation index and carrier frequency).
The process comprises:
Pre-Lab Task
The signal generator block will be replaced by the CODEC of the DSK6713
The virtual scope will be replaced also by the CODEC
A target definition block (DSK6713) will be added.
Figure 21 shows the block-diagram for the real time implementation.
DSK6713/DSK6416
Dual Channel Oscilloscope
Signal Generator
Modulated
Signal Demodulated
Signal
Information
3. Feedback- since the transmitter and the receiver are running on the same platform, we
need to perform a loopback from the transmitter to the receiver and this is exactly the
feedback signal, the modulated signal that is broadcasted by the transmitter and used as
input for the receiver.
Demodulated- the signal that the receiver outputs after the demodulation process.
In-Lab Task
Lab Task
1. Open the model created in the previous lab
2. Remove the scope and the ―information‖ signal (the 1,000 Hz).
3. Open the Simulink library browser and add the "C6713DSK" as shown in Figure 2.
4. Add the ―Analog to Digital‖ and ―Digital to Analog‖ converters (ADC and DAC) to
5. Add the multi-port selector, in order to split the stereo input, as shown in Figure 4.
6. After placing the selector, double-click to open the dialog box and choose ―columns‖
in the ―select‖ label and ―{1,2}‖ in the ―indices to output label.
7. Configure the ADC and DAC blocks to a sampling rate to 96 KHZ and 16-bit samples.
9. You should configure the DSP constants as shown in Figure . The frame period for all
constants should be -1
10. Build the project and load the program to the DSK memory using ctrl+B.
11. Make sure that the signals generator amplitude is set to 1 Volt and frequency of [0.1,5]
kHz.
Model Extensions
In this section following extensions to the model are introduced. Adding two more features:
2. Replace the constant modulation index by an RTDX input (Please refer to Figure ), and
4. Replace the sine wave block used for the carrier by the configurable carrier blocks and
6. Open the ―AM_Coherent.mdl‖ file, and repeat step 0 for this file.
You now have two load files each one corresponding to a different AM scheme.
cosct Re e jct
fc j 2 ffc n
cos c nTs cos 2 n Re e s
fs
The following model implements the last equation. Please note that a feedback path was
included for phase continuity
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
Objective:
In this lab we will learn how to implement FIR and IIR filters on different DSP kits. The
basics of FIR and IIR filters and the design and analysis of FIR and IIR filter(s) in FDA tool
will also be carried out.
Pre-Lab
FIR filters are dependent upon linear-phase characteristics, whereas IIR filters are used for
applications which are not linear. FIR‘s delay characteristics are much better, but they require
more memory. On the other hand, IIR filters are dependent on both i/p and o/p, but FIR is
dependent upon i/p only. IIR filters consist of zeros and poles, and require less memory than
FIR filters, whereas FIR only consists of zeros. IIR filters can become difficult to implement,
and also delay and distort adjustments can alter the poles & zeroes, which make the filters
unstable, whereas FIR filters remain stable. FIR filters are used for tapping of a higher-order,
and IIR filters are better for tapping of lower-orders, since IIR filters may become unstable
with tapping higher-orders. FIR stands for Finite IR filters, whereas IIR stands for Infinite IR
filters. IIR and FIR filters are utilized for filtration in digital systems. FIR filters are more
widely in use, because they differ in response. FIR filters have only numerators when
compared to IIR filters, which have both numerators and denominators.
Where the system response is infinite, we use IIR filters, and where the system response is
zero, we use FIR filters. FIR filters are also preferred over IIR filters because they have a linear
phase response and are non recursive, whereas IIR filters are recursive, and feedback is also
involved. FIR cannot simulate analog filter responses, but IIR is designed to do that accurately.
IIR‘s impulse response when compared to FIR is infinite.
In-Lab Task
Butterworth
Chebyshev type I
Chebyshevtype II
Elliptic
Butterworth filter:
The Butterworth filter is a type of signal processing filter designed to have as flat a frequency
response as possible in the passband. It is also referred to as a maximally flat magnitude
filter. It was first described in 1930 by the British engineer Stephen Butterworth in his paper
entitled "On the Theory of Filter Amplifiers"
Butterworth had a reputation for solving "impossible" mathematical problems. At the time,
filter design required a considerable amount of designer experience due to limitations of the
theory then in use. The filter was not in common use for over 30 years after its publication.
Butterworth stated that:
"An ideal electrical filter should not only completely reject the unwanted frequencies but
should also have uniform sensitivity for the wanted frequencies".
Such an ideal filter cannot be achieved but Butterworth showed that successively closer
approximations were obtained with increasing numbers of filter elements of the right values.
At the time, filters generated substantial ripple in the passband, and the choice of component
values was highly interactive. Butterworth showed that a low pass filter could be designed
whose cutoff frequency was normalized to 1 radian per second and whose frequency response
(gain) was
where ω is the angular frequency in radians per second and n is the number of reactive
elements (poles) in the filter. If ω = 1, the amplitude response of this type of filter in the
passband is 1/√2 ≈ 0.707, which is half power or −3 dB. Butterworth only dealt with filters
with an even number of poles in his paper
Chebyshev filter:
chebyshev filters are analog or digital filters having a steeper roll-off and more passband
ripple (type I) or stopband ripple (type II) than Butterworth filters. Chebyshev filters have the
property that they minimize the error between the idealized and the actual filter characteristic
over the range of the filter, but with ripples in the passband. This type of filter is named in
honor of Pafnuty Chebyshev because its mathematical characteristics are derived from
Chebyshev polynomials.
These are the most common Chebyshev filters. The gain (or amplitude) response as a function
of angular frequency of the nth-order low-pass filter is
where is the ripple factor, is the cutoff frequency and is a Chebyshev polynomial of
the th order.
The passband exhibits equiripple behavior, with the ripple determined by the ripple factor . In
the passband, the Chebyshev polynomial alternates between 0 and 1 so the filter gain will
alternate between maxima at G = 1 and minima at . At the cutoff frequency
the gain again has the value but continues to drop into the stop band as the
frequency increases. This behavior is shown in the diagram on the right. The common practice
of defining the cutoff frequency at −3 dB is usually not applied to Chebyshev filters; instead
the cutoff is taken as the point at which the gain falls to the value of the ripple for the final
time.
The order of a Chebyshev filter is equal to the number of reactive components (for example,
inductors) needed to realize the filter using analog electronics.
The ripple is often given in dB:
Ripple in dB =
An even steeper roll-off can be obtained if we allow for ripple in the stop band, by allowing
zeroes on the -axis in the complex plane. This will however result in less suppression in the
stop band. The result is called an elliptic filter, also known as Cauer filter.
Also known as inverse Chebyshev, this type is less common because it does not roll off as fast
as type I, and requires more components. It has no ripple in the passband, but does have
equiripple in the stopband. The gain is:
In the stopband, the Chebyshev polynomial will oscillate between 0 and 1 so that the gain will
oscillate between zero and
and the smallest frequency at which this maximum is attained will be the cutoff frequency .
The parameter ε is thus related to the stopband attenuation γ in decibels by:
For a stopband attenuation of 5dB, ε = 0.6801; for an attenuation of 10dB, ε = 0.3333. The
frequency fC = ωC/2π is the cutoff frequency. The 3dB frequency fH is related to fC by:
Elliptic filter:
An elliptic filter (also known as a Cauer filter, named after Wilhelm Cauer) is a signal
processing filter with equalized ripple (equiripple) behavior in both the passband and the
stopband. The amount of ripple in each band is independently adjustable, and no other filter of
equal order can have a faster transition in gain between the passband and the stopband, for the
given values of ripple (whether the ripple is equalized or not). Alternatively, one may give up
the ability to independently adjust the passband and stopband ripple, and instead design a filter
which is maximally insensitive to component variations.
As the ripple in the stopband approaches zero, the filter becomes a type I Chebyshev filter. As
the ripple in the passband approaches zero, the filter becomes a type II Chebyshev filter and
finally, as both ripple values approach zero, the filter becomes a Butterworth filter.
The gain of a lowpass elliptic filter as a function of angular frequency ω is given by:
where Rn is the nth-order elliptic rational function (sometimes known as a Chebyshev rational
function) and
is the cutoff frequency
The value of the ripple factor specifies the passband ripple, while the combination of the ripple
factor and the selectivity factor specify the stopband ripple
Lab Tasks
Task-1: Make a filter using following specifications:
fpass = 4kHz
fstop= 6kHz
fs= 44.1kHz
Apass= 1dB
Astop= 60dB
1. fpass = 6kHz
2. fstop = 4kHz
3. fs = 44.1kHz
4. Order: Minimum Order
5. Match exactly = Pass-band (if applicable)
6. Apass = 1dB
7. Astop = 60dB
• Create a simulink model which generates the following sinusoids:
a) Frequency = 3kHz
b) Frequency = 8kHz
And passes them through your filter (one at a time) and sends the output to headphones
jack of the DSP kits DSK6713 or DSK6416
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5
Objectives:
In this lab students will be able to perform audio signal Processing application such as Echo
and Reverberation on DSK6713. Echo and Reverberation are two of the simplest applications
of Digital Signal Processing (DSP). In this lab, an audio effects processor is created to echo
and reverberate using SIMULINK. The model of audio effect processor will be realized on the
Texas Instruments C6000 DSPs in following three steps.
Design models of Echo and Reverberation for the Texas Instruments C6000 family of
DSP devices using MATLAB® and Simulink®.
Modify an existing Simulink model (.mdl will be provided)
Run the model in real-time on the Texas Instruments C6713 DSK.
In-Lab Task:
This laboratory will be developed using the following hardware and software:
Simulation
Start by running the Echo and Reverberation Simulink models. These use .wav files as the inputs.
In this section, an echo filter is designed. An echo is a delayed, attenuated version of the
original signal. The difference equation describing a system with a single echo is defined as
y[n] = x[n] + ax[n − D], where a is the gain and D is the delay.
Double-click on the ―Delay‖ block and change the ―Delay (samples)‖ to a different value.
Run the model and hear how the effect has changed. Try a few different settings between 100
and 20000 ―Delay (samples)‖.
In this section a model that simulates audio reverberation is created and built. Reverberation is
the result of an infinite number of echoes added together, and can be represented
mathematically as y[n] = x[n]+ax[n−D]−by[n−D], where ‗a‘ and ‗b‘ are the gains and D is the
delay.
Double-click on the ―Delay‖ block. Change the ―Delay (samples)‖ to a different value then run
the model and listen to the effect.
Double-click on the ―Gain‖ block. Change the ―Gain‖ to 0.95 then run the model. Listen to the
effect.
Questions
Connect the C6713 hardware to a USB port of the computer and turn on the supply to the
board.
If the board is powered, then the green LED lights on the board will come on during self-test.
The stages required to implement Echo and Reverberation are now described.
Start Code Composer Studio for C6713 DSK and use Debug -> Connect
In the top left hand corner of the MATLAB screen, select File -> Open.
You are now going to implement the Echo Subsystem shown below.
Double click on the ―Effect 1‖ subsystem block. An empty model will appear.
You will now drag-and-drop some library components onto the model.
A list of available blocks will appear. We are initially interested in the ―Commonly Used
Blocks‖.
COMSATS University Islamabad Page 162
EEE 324 Digital Signal Processing Lab.
From ―Commonly Used Blocks‖, drag-and-drop a ‖Gain‖ block, a ―Sum‖ block and two ―Data
Type Conversion‖ blocks onto the model.
From the Simulink Library Browser, select ―Discrete‖. Highlight ―Integer Delay‖ and drag-
and-drop this block onto the model.
The delay time will be 0.5 seconds. Using a sampling rate of 8000 Hz, this requires 8000 x 0.5
= 4000 samples. In the equation given in the lecture, this would make N = 4000.
Double click on the ―Integer Delay‖ block. Change the ―Number of delays‖ field to 4000, then
click on ―OK‖.
We want to set the gain to 0.9. If you multiply an integer value by 0.9, then the value 0.9 will
be rounded-down to zero. Instead, you need to convert the integer value to a floating-point
value such as ―single‖, and then convert it back later. Click on ―OK‖.
We required that 0.9 of the delayed input is added to the normal input. Therefore, set the
―Gain‖ to 0.9 then click on ―OK‖.
Double click on the second ―Data Type Conversion‖ block. Set the ―Output data type mode‖ to
int16. This is compatible with the DAC on the C6713 DSK.
From the Toolbar, select the ―Up Arrow‖ icon. This returns you to the next higher level.
Note that the reverberation subsystem is very similar to that of echo. We will cut-and-paste
from the Echo Subsystem
From the ―C6713 Audio Template‖ top level, double-click on the ―Effect 2‖ subsystem.
Double click on the ― Effect 1‖ subsystem. Cut-and-paste a copy of the echo block as follows:
while left-clicking the mouse, mark the area to be copied.
Return to the ―Effect 2‖ subsystem and Edit -> Paste (Ctrl + V) into the model.
The blocks are facing the wrong way. Turn them round using Format -> Flip Block.
Because the sound goes round several times with reverberation, a shorter delay time can be
used. Here the delay time is 0.1 seconds.
Connect the blocks as shown below. Change the title to ―Reverberation Subsystem‖.
From the Toolbar, select the ―Up Arrow‖ icon. This returns you to the next higher level.
The final subsystem to be implemented will be ―Improved Echo‖. This is based on the ―Echo‖
subsystem, but with several delay paths.
Double click on the ―Effect 3‖ subsystem box. The required components are shown below.
You should now have enough knowledge to implement this subsystem block without further
assistance. This time you are on your own!
To check out the microphone and loudspeakers, set the DIP switches on the C6713 DSK as
follows:
The microphone is fed directly to the loudspeakers without any digital signal processing.
Lab Tasks
Task-1: Change the value of the ―Integer Delay‖ block for echo. Listen to the effect of using
short and long delays.
Task-2: In the ―Reverberation Subsystem‖ block, change the ―Gain‖ from 0.8 to higher and
lower values. Notice how the system can become unstable if the gain is too large.
Task-3: In the ―Improved Echo Subsystem‖, you may wish to experiment with the number of
delay elements, the delay times and the amounts of gain. Try to make the echo as realistic as
possible.
A flange effect is a(time domain) audio effect, which is achieved by combining two identical
signal with each other, with one signal delayed by a gradually changing amount. The
difference equation for the flange effect is given by, y[n] = x[n] + ax[n − d(n)], where the time
varying delay is given by, d(n) = D + D/2 (1 − sin( 2 nfd/ fs )) where D is a fixed delay, fd is
the flanging frequency, and fs is the sampling rate. Figure 35 shows the Simulink block
diagram that implements this system.
1. Build and run the model in figure 35 (using the Incremental Build button
2. Add the C6713DSK target preferences block from the TI C6000 Target
Preferences block library. This block is not connected to any other block
in the model.
3. Test the system using recorded music or speech(wav) played through the Line
connector.
Lab Assessment
Pre Lab /5
Performance /5
Results /5 /25
Viva /5
Critical Analysis /5