0% found this document useful (0 votes)
104 views178 pages

EEE324 Digital Signal Processing V (Latest) 2

Uploaded by

all ofbest
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views178 pages

EEE324 Digital Signal Processing V (Latest) 2

Uploaded by

all ofbest
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 178

EEE 324 Digital Signal Processing Lab.

EEE-324 Digital Signal Processing

Lab Manual

Name

Registration Number

Class

Instructor‘s Name

COMSATS University Islamabad Page 1


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 2


EEE 324 Digital Signal Processing Lab.

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)

July 2015 Dr. Naveed ur Rehman Experiments updated (Version II)


Mr. Khurram Naveed
September Dr. Muhammad Tahir Akhtar
2016 Mr. Khurram Naveed Conversion on OBE based model (Version III)
Ms. Amber Madeeha Zeb
September Dr. Safwan Khalid Experiments updated (Version IV)
2021

COMSATS University Islamabad Page 3


EEE 324 Digital Signal Processing Lab.

Safety Precautions
 Be calm and relaxed, while working in lab.

 First check your measuring equipment.

 When working with voltages over 40 V or current over 10 A , there must be at least two

people in the lab at all time.

 Keep the work area neat and clean.

 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).

Do not wear them near an energized circuit.

 When working with energize circuit use only one hand while keeping rest of your body

away from conducting surfaces.

 Always check your circuit connections before power it ON.

 Always connect connection from load to power supply.

 Never use any faulty or damage equipment and tools.

 If an individual comes in contact with a live electrical conductor.

o Do not touch the equipment, the cord, the person.

o Disconnect the power source from the circuit breaker and pull out the plug using

insulated material.

COMSATS University Islamabad Page 4


EEE 324 Digital Signal Processing Lab.

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

COMSATS University Islamabad Page 5


EEE 324 Digital Signal Processing Lab.

Lab # 06 Z-Transform and Inverse Z-Transform ........................................................................ 79


Objective ................................................................................................................................. 79
Pre-Lab .................................................................................................................................... 79
In-Lab Tasks ............................................................................................................................ 80
Post Lab Task .......................................................................................................................... 86
Lab # 07 Sampling and Multi-rate Signal Processing ................................................................. 88
Objective ................................................................................................................................. 88
Pre-Lab .................................................................................................................................... 88
In-Lab Tasks ............................................................................................................................ 93
Post Lab Task ........................................................................................................................ 121
Lab # 08 Simulation of Non RT AM Tx/Rx on Simulink......................................................... 104
Objective ............................................................................................................................... 104
Pre-Lab .................................................................................................................................. 104
In-Pre Tasks ........................................................................................................................... 120
Post Lab Task ........................................................................................................................ 121
Lab # 09 Filtering through MATLAB (Simulink) and its implementation on hardware
(TMS320C6416 & TMS320C6713) ......................................................................................... 124
Objective ............................................................................................................................... 124
Pre-Lab .................................................................................................................................. 124
In-Lab Tasks .......................................................................................................................... 127
Post Lab Task ........................................................................................................................ 129
Lab # 10 Hardware implementation of AM modulator and demodulator on (TMS320C6713 &
TMS320C6416) ......................................................................................................................... 131
Objective ............................................................................................................................... 131
Pre-Lab .................................................................................................................................. 131
In-Lab Tasks .......................................................................................................................... 133
Post Lab Task ........................................................................................................................ 144
Lab # 11 Implementation of FIR and IIR Filters on DSP kit .................................................... 146
Objective ............................................................................................................................... 146
Pre-Lab .................................................................................................................................. 146
In-Lab Tasks .......................................................................................................................... 147

COMSATS University Islamabad Page 6


EEE 324 Digital Signal Processing Lab.

Post Lab Task ........................................................................................................................ 151


Lab # 12 Audio Signal Processing using DSK6713 & DSK6416 ............................................ 156
Objective ............................................................................................................................... 156
Pre-Lab .................................................................................................................................. 156
In-Lab Tasks .......................................................................................................................... 156
Post Lab Task ........................................................................................................................ 175

COMSATS University Islamabad Page 7


EEE 324 Digital Signal Processing Lab.

Lab # 01 Introduction to Code Composer Studio and DSP Starter


Kits TMS320C6416 and TMS320C6713

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

Pre Lab Tasks:


Code Composer Studio:
Code Composer Studio or CCS is an IDE for developing and building a digital system on a
DSP kit. Code is written in C language in CCS. This code is then converted to assembly
language by Code Composer Studio compiler which is converted to machine language by Code
Composer Studio assembler.

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:

CCS Code Flow

COMSATS University Islamabad Page 8


EEE 324 Digital Signal Processing Lab.

DSP Starter Kit:


A DSK or DSP Starter Kit is a training kit designed for academic and research purposes. It
contains Digital Signal Processor, Memory, Ports, special chips (for carrying out specific tasks.
Following are the two data types handled by DSKs:

 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.

Just for information

1. Video rate: 24 frames per second


2. Ear can detect minute differences in sound waves e.g. Beats

Available DSKs in Lab:

Following table illustrates the equipment available in lab:

1. No SIMULINK block set for this product and it is the only product with whom TI does not give MATLAB trial CD

C6711 DSK Board Layout

COMSATS University Islamabad Page 9


EEE 324 Digital Signal Processing Lab.

C5416 DSK Board Layout

C6416 DSK Board Layout

COMSATS University Islamabad Page 10


EEE 324 Digital Signal Processing Lab.

C6713 DSK Board Layout

DSK Specifications:

C6416 DSK:

 Capacity: 8000 MIPS


 Codec: High quality 24-bit AIC23 stereo codec
 Memory: 16MB SDRAM
 Flash: 512kB (non-volatile)
 Connector: USB
 Expansion port connector to add new modules
 On-board standard IEEE JTAG interface
 Audio Jacks: 4 (Mic-in, Line-in, Line-out, Headphones)
 Power supply: +5V

C6713 DSK:

 Capacity: 1800 MIPS


 Codec: High quality 24-bit stereo codec
 Memory: 16MB SDRAM
 Flash: 512kB (non-volatile)
 Connector: USB
 Expansion port connector to add new modules
 On-board standard IEEE JTAG interface
 Audio Jacks: 4 (Mic-in, Line-in, Line-out, Headphones)
 Power supply: +5V

COMSATS University Islamabad Page 11


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 12


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 13


EEE 324 Digital Signal Processing Lab.

Working with CCS and DSK 6713:


Loading a project in Code Composer Studio:

Follow the following steps to load a project in code composer studio:

Step 1: Open Code Composer Studio from ‗Start‘ Menu:

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:

COMSATS University Islamabad Page 14


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 15


EEE 324 Digital Signal Processing Lab.

Step 3: Right click ‗Projects  Open Project…‘, Navigate to ‗examples dsk6416bslled‘


and open ‗led.pjt‘:

COMSATS University Islamabad Page 16


EEE 324 Digital Signal Processing Lab.

Step 4: Go to ‗File‘ menu and click ‗Load Program…‘:

Step 5: Double click the ‗Debug‘ folder:

COMSATS University Islamabad Page 17


EEE 324 Digital Signal Processing Lab.

Step 6: Double click ‗led.out‘ to load this program:

Step 7: Go to ‗Debug‘ menu and click ‗Run‘:

Step 8: To stop executing a program go to ‗Debug‘ menu and click ‗Halt‘:

COMSATS University Islamabad Page 18


EEE 324 Digital Signal Processing Lab.

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

Example project in Code Composer Studio – led.pjt:

COMSATS University Islamabad Page 19


EEE 324 Digital Signal Processing Lab.

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:

Following are some of the important header files in the project:

 #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

Given below are the contents of the file ‗led.c‘:

Try to understand what these commands mean. Consult your handouts and instructor for any
help.

COMSATS University Islamabad Page 20


EEE 324 Digital Signal Processing Lab.

SIMULINK Based Hardware Implementation – SBHI:


Introduction:

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

Design can be done by following the following steps:

1. Design of a system on SIMULINK


2. Conversion of the design in to C code (Done by SIMULINK)
3. Transfer of the C code to Code Composer Studio
4. Conversion of the C code into assembly language code (Done by CCS)
5. Conversion of the C code into machine language code (Done by CCS)
6. Building the machine language code on the DSP kit (Done by CCS)

Preliminary Settings:

Solver is the same as is being used in previous labs:

Click on ‗Optimization‘ in the pane on the left and uncheck first 2 boxes:

COMSATS University Islamabad Page 21


EEE 324 Digital Signal Processing Lab.

Select ‗TIC Compiler/Linker‘ from the pane on the left and check ‗Symbolic Debugging‘ box:

Some Useful MATLAB commands:

 ccsboardinfo – Displays the information of your DSK if it is installed properly


 ccsdsp – Checks if our MATLAB is compatible with CCS version installed in your
computer

COMSATS University Islamabad Page 22


EEE 324 Digital Signal Processing Lab.

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:

COMSATS University Islamabad Page 23


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 24


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 25


EEE 324 Digital Signal Processing Lab.

Lab # 02 Introduction to Discrete Time Signal Processing on


MATLAB

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.

• View the MATLAB introduction by typing

>> intro

at the MATLAB prompt. This short introduction will demonstrate some basic MATLAB
commands.

• Explore MATLAB‘s help capability by trying the following:

>> help

>> help plot

>> help ops

>> help arith

• Type ‗demo‘ and explore some of the demos of MATLAB commands.

COMSATS University Islamabad Page 26


EEE 324 Digital Signal Processing Lab.

• 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;

>> a^3+sqrt (b*d)-4*c

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.

1. Special characters and functions


Some common special characters used in MATLAB are given below:

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

MATLAB interpreter and is considered as comments


‗ Denotes transpose of a vector or matrix. It‘s also used to define strings, e.g.,str1=‘DSP‘;

2. Handling Complex Numbers in MATLAB


MATLAB also supports complex numbers. The imaginary part of the signal can be
represented with the alphabet j assuming. Try commands given in following:

>> z=3 + 4i % note that you do not need the ‗*‘ after 4

COMSATS University Islamabad Page 27


EEE 324 Digital Signal Processing Lab.

>> conj (z) % computes the conjugate of Signal z

>> angle (z) % computes the phase of Signal z

>> real (z) % computes the real part of Signal z

>> imag (z) % computes the imaginary part of z

>> abs (z) % computes the magnitude of Signal z

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)

3. Handling Arrays/Vectors in MATLAB


3.1. Arithmetic Operations
There are four different arithmetic operators:

+ addition

− subtraction

* multiplication

/ division (for matrices it also means inversion)

There are also three other operators that operate on an element by element basis:

.* multiplication of two vectors, element by element

./ division of two vectors, element-wise

.^ raise all the elements of a vector to a power.

Suppose that we have the vectors x = [x1 , x2 , ..., xn ] and y = [y1 , y2 , ..., yn ]. Then

x. ∗ y = [x1 y1 , x2 y2 , ..., xn yn ]

x./y = [x1/ y1 , x2/ y2 , ..., xn/ yn ]

x.ˆp = [xp , xp , ..., xp ]


1 2 n

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-

COMSATS University Islamabad Page 28


EEE 324 Digital Signal Processing Lab.

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.

3.2. Array Indexing


In MATLAB, all arrays (vectors) are indexed starting with 1, i.e., y(1) is the first element
of the array y.

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]

Alternatively, you can use the : notation,


>> x = -5:5

The : notation above creates a vector starting from 1 to 6, in steps of 1. We can


visualize the array ‗x‘ and its indexes by the following table:

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

COMSATS University Islamabad Page 29


EEE 324 Digital Signal Processing Lab.

If you want to create a vector from 1 to 6 in steps of say 2, then type:


>> x = 1:2:6

ans= 3 5

Try the following code:


>> jj= 2 : 4 : 17

>> jj=20 : -2 : 0

>> ii=2 : (1/10) : 4

Extracting or inserting numbers in a vector can be done very easily. To concatenate an


array, you can use the [ ] operator, as shown in the example below:
>> x=[1:3, 4, 6, 100:110]

To access a subset of the array, try the following:


>> x(3:7)

>> length(x) % gives the size of the array or vector

>> x(2:2:length(x)

3.3. Allocating memory


You can allocate memory for one-dimensional arrays (vectors) using the zeros command.
The following command allocates memory for a 100-dimensional array:
>> Y=zeros (100,1);

>> 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.

COMSATS University Islamabad Page 30


EEE 324 Digital Signal Processing Lab.

4. Conditional Statements and Loops


MATLAB has the following flow control constructs:

 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

str = ‘ Not a real number’;

end

a. What is the value of ‘str‘ after execution of the above code?


WHILE:
x=-10;

while x<0

x=x+1;

end

b. What is the value of x after execution of the above loop?


FOR loop:
X=0;

for i = 1:10

X=X+1;

end

COMSATS University Islamabad Page 31


EEE 324 Digital Signal Processing Lab.

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

MATLAB supports the following relational and logical operators:

Conditional and Logical Operator

Meaning Symbol

Less than equal <=

Less than <

Greater than equal >=

Greater than >

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;

>> plot(x) %see Figure 1

COMSATS University Islamabad Page 32


EEE 324 Digital Signal Processing Lab.

20

18

16

14

12

10

0
0 2 4 6 8 10 12 14 16 18 20

Figure 1: Plot obtained using the plot command.


>> stem(x) % see Figure 2

20

18

16

14

12

10

0
0 2 4 6 8 10 12 14 16 18 20

Figure 2: Plot obtained using the stem function.

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:

r Red + plus −− dashed


g green * star
b blue s square

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)

>> subplot(2,1,2), stem(x)


COMSATS University Islamabad Page 33
EEE 324 Digital Signal Processing Lab.

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

Figure 3: Output of the subplot(2,1,p) command.

To get more help on plotting, type: ‗help plot‘ or ‗ help subplot‘.

6. Programming in MATLAB (M-File):


MATLAB programming is done using M-files, i.e., files that have the extension .m.
These files are created using a text editor. To open the text editor, go to the File pull-
down menu, choose ‗New‘, then ‘M-file‘. After you type in the program, save it, and
then call it from the command window to execute it. Say for instance that you want to
write a program to compute the average (mean) of a vector x. The program should take as
input the vector x and return the average of the vector.

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

sum = sum + x(i);

end

y = sum /L; % the average of x

Remarks:

y — is the output of the function ―average‖

x — is the input array to the function ―average‖


COMSATS University Islamabad Page 34
EEE 324 Digital Signal Processing Lab.

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)

In the command window it has to be invoked as:


>> [y1, y2, y3] = average(x1,x2,x3,x4)

7. Loading and saving data:


You can load or save data using the commands load and save. To save the variable x of
the above code in the file data.mat, type:

>> save data.mat x

Note that MATLAB‘s data files have the extension .mat. To retrieve the data that was
saved in the vector x, type:

>> load data.mat

The vector x is loaded in memory. To see the contents of memory use the command whos:

>> whos

Name Size Bytes Class


X 1x8193 65544 double array
Grand total is 8193 elements using
array65544 bytes

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

COMSATS University Islamabad Page 35


EEE 324 Digital Signal Processing Lab.

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.

1.1. Analog Signals


If either of the independent (Time) or dependent (Signal values) variables are continuous, the
signal is termed as analog. In this lab, we will mostly be dealing with discrete time signals.
MATLAB representation
Output:
In MATLAB, signals are represented by using two
variables i.e. y=sin (t) where variable‗t‘ represents the
time axis and ‗y‘ represents the signal values.
>> t=0:0.01:7;

>> y=sin(t);

>> plot(y)

1.2. Digital signals


If both independent (Time) or dependent (Signal
values) variables are discrete, the signal is termed as Output:
digital. Digital signals uses discrete or discontinuous
values to represent information.

MATLAB representation:
>> n=0:7;

>> y=sin(n);

>> stem(n,y)

2. Some fundamentals sequences


2.1. Impulse Sequence

COMSATS University Islamabad Page 36


EEE 324 Digital Signal Processing Lab.

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.

Initialize a vector ‗n‘ containing value from -10 to 9.

Initialize an input array ‗x‘ containing all zeros of length ‗n‘.

Find the index when ‗n‘ is equal to the 0, and save its value into a variable ‗i‘.

If ‗n0‘ is less than 0

 Replace ‗0‘ by ‗1‘ in an array ‗x‘ at an index ‗i + n0‘.


Else- If ‗n0‘ is greater than 0

 Replace ‗0‘ by ‗1‘ in an array ‗x‘ at an index ‗i - n0‘.


Else

 Insert ‗1‘ in an array ‗x‘ at an index ‗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.

Initialize a vector ‗n‘ containing value from -10 to 9.

Initialize an input array ‗x‘ containing all zeros of length ‗n.‘

Find the index when ‗n‘ is equal to the 0, and save its value into a variable ‗i‘.

If ‗n0‘ is less 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- 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.

COMSATS University Islamabad Page 37


EEE 324 Digital Signal Processing Lab.

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-2: Generate a Discrete time exponential signal and plot it.

COMSATS University Islamabad Page 38


EEE 324 Digital Signal Processing Lab.

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.

Task-5: Can you explain what the following program does:


L = length(x);

for I = 1: L

if x (i) < 0

x (i) = -1;

end

end

COMSATS University Islamabad Page 39


EEE 324 Digital Signal Processing Lab.

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.
[ ] ∑ [ ]

COMSATS University Islamabad Page 40


EEE 324 Digital Signal Processing Lab.

Task-8: Generate the following sequences using step and impulse sequence.

a. x[n] = u[n] – u[n-10]


b. x[n] = an u[n]
c. ∑an δ[n-k] , k = -10 to 10

COMSATS University Islamabad Page 41


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 42


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 43


EEE 324 Digital Signal Processing Lab.

Lab # 03 Basic Operations on Discrete-Time Sequences

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

or just write following in Command Window to open the M-file

>> script

ii. Once the mfile is open write your code and then save it by some name as

COMSATS University Islamabad Page 44


EEE 324 Digital Signal Processing Lab.

iii. After writing the code click the play button on the m-file window to run the
code

b. How to make a function in Matlab

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.

i. function command is used to define a function as

function [output1 output2 output3] = func_name(input1 input2 input3)

Code

end

ii. Each function is defined in a separate M-file

COMSATS University Islamabad Page 45


EEE 324 Digital Signal Processing Lab.

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.

c. How to call a functions in Matlab

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

[avg] = average (n1, n2, n3); % function called

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)

COMSATS University Islamabad Page 46


EEE 324 Digital Signal Processing Lab.

e. Generating a signal in Matlab

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;

>> x = [6, 11, 14, 5, 0]

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‖.

f. Some other type of signals

1. Real-valued exponential Sequence


 The operator ―.^‖ is required to implement a real exponential sequence. For
example, to generate x(n) = (0.9)n, 0<= n<=10, we will need the following script:
 Example tutorial:
>> n = [0:10];

>> x = (0.9).^n;

 Create a function (M-file) to generate an exponential sequence. Use the previous


examples as your guide.
2. Complex-valued exponential Sequence
A matlab function ―exp‖ is used to generate exponential sequences. For example, to
generate x(n) = exp[(2+j3)n], 0<= n<=10, we will need the following script:

>> 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.

COMSATS University Islamabad Page 47


EEE 324 Digital Signal Processing Lab.

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];

>> x = 3*cos(0.1*pi*n+pi/3) + 2*sin(0.5*pi*n);

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:

>> xtilde = [x,x,x,x...,x];

An elegant approach is to use matlab‘s indexing capabilites:

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

>> xtilde = xtilde(:); %long coloumn vector

>> xtilde = xtilde'; %long row vector

In-Lab

Important Signal Operations in Matlab:


1. Signal Scaling
Description:

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 )}

COMSATS University Islamabad Page 48


EEE 324 Digital Signal Processing Lab.

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.

i) Check whether k is positive or negative?


ii) If k is positive it means shift is towards right i.e. x[n-k] then do following
a. As signal is shifting towards right time axes ―n‖ should be extended towards
right side by ―k‖ samples i.e. if n is ending at n2 then it should now end at n2 +
k.
b. Since the signal has now moved towards right meaning initial ―k‖ samples in
―x‖ are empty so concatenate ―k‖ zeroes in the beggining of the sequence x.
iii) If k is negative it means shift is towards left i.e. x[n+k] then do following
c. As signal is shifting towards left time axes ―n‖ should be extended towards left
side by ―k‖ samples i.e. if n is starting at n1 then it should now start at n1 - k.
d. Since the signal has now moved towards left meaning last ―k‖ samples in ―x‖
are empty so concatenate ―k‖ zeroes in the end of the sequence x.
3. Folding
Description: Folding operation is also termed as flipping a signal where each sample is of
x(n) is mirrored around n=0 to obtain a folded sequence y(n) = x[-n].

In Matlab, folding operation can be performed in three steps

i) Flip the magnitude sequence ―x‖


ii) Flip the time index ―n‖
iii) Now multiply the flipped time vector ―n‖ with a minus
Note that in Matlab a built-in function ―fliplr(m) can be used to flip any sequence.

4. Add/Subtract/Multiply two signals


Adding a signal in Matlab is not as easy as on paper. In order to add two sequences x1 and x2
in Matlab, both sequences have to be of same length, same is the case for subtraction,
multiplication and division.

In signal processing signal elements are added/subtracted or multiplied corresponding to their


time index i.e. a signal element at time -1 will be added to the signal element of the other
signal at the same time.

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)

COMSATS University Islamabad Page 49


EEE 324 Digital Signal Processing Lab.

 Concatenate n2(1) – n1(1) number of zeros before x2


 And put n2(1) = n1(1);

Else-If n2(1) is smaller than n1(1)

 Concatenate n1(1) – n2(1) number of zeros before x1


 And put n1(1) = n2(1);
b. Compare the ending points of both signals time index vectors i.e. n1(end) and
n2(end).
If n1(end) is greater than n2(end)

 Concatenate n1(end) – n2(end) number of zeros at the end of x2


 And put n2(end) = n1(end);

Else-If n2(end) is greater than n1(end)

 Concatenate n2(end) – n1(end) number of zeros at the end of x1


 And put n1(1) = n2(1);
c. Now make a universal time index n = n1(1):n2(1)
d. Add the magnitude vectors by as x = x1+x2 or multiply them as x = x1.*x2 etc.

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

COMSATS University Islamabad Page 50


EEE 324 Digital Signal Processing Lab.

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)

COMSATS University Islamabad Page 51


EEE 324 Digital Signal Processing Lab.

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 

COMSATS University Islamabad Page 52


EEE 324 Digital Signal Processing Lab.

Determine and plot the following sequences


a. x1 (n)  2 x(n  5)  3x(n  4)
b. x2 (n)  x(3  n)  x(n) x(n  2)

COMSATS University Islamabad Page 53


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 54


EEE 324 Digital Signal Processing Lab.

Lab # 04 Convolution of Discrete-time Sequences and its implementation on


DSP kits

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.

1. Time Reversal y(t) = x(-t)


2. Time Shifting y(t) = x(t-td)
3. Amplitude Scaling y(t) = Bx(t)
4. Addition y(t) = x1(t) + x2(t)
5. Multiplication y(t) = x1(t)x2(t)
6. Time Scaling y(t) = x(at)
Decomposition of signals
Let us have a look at how to decompose a signal into its even and odd components.

Even and odd synthesis

 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

x(n)  xe (n)  xo (n)


xe (n)  1 [ x(n)  x(n)], xo (n)  1 [ x(n)  x(n)]
2 2
 Try writing a function that decomposes a given signal into its even and odd components.
You can think like the steps given below.
 Input a signal
 Flip the signal
 Calculate its length
 Zero padding
 Calculating even and odd parts.

COMSATS University Islamabad Page 55


EEE 324 Digital Signal Processing Lab.

 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:

Convolution as sum of shifted and scaled impulse response:

• For any given n, one point convolution is evaluated as

– Step 1: time reversal of either signal (e.g., x(k)x(-k) ) or h(k)h(-k)

– Step 2: shift h(-k) by n samples to obtain h(n-k)

– Step 3: multiply x(k) and h(n-k) for each k and then take the summation over k

• Note: You need to change variable n to get the whole sequence

Example:

x(n)=[1 2 3 4] and h(n)=[1 –1]

Step 1: Time reversal

h(k)=[1 -1] h(n-


k)=[-1 1]

COMSATS University Islamabad Page 56


EEE 324 Digital Signal Processing Lab.

Step 2: Time shift

Step 3: Multiply and Add

Final Result:

x(n)

COMSATS University Islamabad Page 57


EEE 324 Digital Signal Processing Lab.

Method 2:

Convolution as sum of shifted and scaled unit impulses.

Y(n) = ∑k x(n)h(n-k)

x(n) = ∑k ak δ(n-k)

y(n)= ∑k (∑k ak δ(n-k)) h(n-k)

y(n)= ∑ (a0 δ(n)+ a1 δ(n-1)+ a2 δ(n-2)+ a3 δ(n-3)+ …….. ) h(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:

Consider the same example we solved in first method of convolution as above.

X(n) = [1 2 3 4], h(n)= [1 -1]

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

COMSATS University Islamabad Page 58


EEE 324 Digital Signal Processing Lab.

𝛿[𝑛 3] [𝑛 3] Y3
4 1 4

X = 3 4 n
3 n 3 4 n
-1 -4

Final Result:

Final result is the summation of y0, y1, y2, y3.

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

[ ] ∑ [ ]

where and define the length of the averaging system.

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.

COMSATS University Islamabad Page 59


EEE 324 Digital Signal Processing Lab.

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‖.

 x[n] = [1 2 1], n=[0 1 2] h[n] = [1 1 1], n= [0 1 2]


 x[n] = [-1 4 -3 -2 1 0 2], n=[-2:4] h[n] = [1 1 1], n= [-1 0 1]

COMSATS University Islamabad Page 60


EEE 324 Digital Signal Processing Lab.

Task 4: Design a five-point Moving-average system on MATLAB Simulink. Pass a sinusoidal


through this system and implement it on DSK, and show the results on Oscilloscope.

COMSATS University Islamabad Page 61


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 62


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 63


EEE 324 Digital Signal Processing Lab.

Lab # 05 Discrete Fourier Transform and its Properties

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

X (k) = ∑ x (n) e-j(2π/N)kn

Where w0 = 2π/N is the fundamental frequency of the signal. Following two conditions must satisfied
for its DFT to be computed

i. x[n] should be of finite length of length N.

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

X (k) = ∑ x (n) e-jwn

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.

COMSATS University Islamabad Page 64


EEE 324 Digital Signal Processing Lab.

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 )  

Then, discrete-time Fourier transforms (DTFT):

X (e jw )  F[ x(n)]   x(n)e  jwn


Inverse discrete-time Fourier transform (IDTFT) of X(e-jwn):

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.

We need only one period of X(ejw)

i.e. w[0,2], or [- , ], ect.

2.3 Symmetry
For real-valued x(n), X(ejw) is conjugate symmetric

X(ejw) = X*(ejw) or

Re[X(e-jw)] = Re[X(ejw)] (even symmetry)

Im[X(e-jw)] = Im[X(ejw)] (odd symmetry)

|X(e-jw)| = |X(ejw)| (even symmetry)

phase(X(e-jw)) = phase(X(ejw)) (odd symmetry)

2.4 Implication:
We need only half period of X(ejw) i.e. w[0,]

3. Shifting and convolving periodic signals

3.1 Periodic or circular Shift


Shifting in periodic sequences is referred to as circular shift, x[n-l] is depicted in the figure
below,

Fig. 2: Depiction of shift in a periodic signal.

COMSATS University Islamabad Page 66


EEE 324 Digital Signal Processing Lab.

If we consider only one period of this sequence then this shifting can be considered as circular
shift, depicted below.

Fig. 3: Interpretation of shift in a periodic signal as a circular shift.

3.2 Periodic Convolution

Convolution of two periodic sequences is referred to as periodic convolution. As the same


sequence is repeating after a N samples, it is sufficient to calculate the convolution for only the
one period and repeat the resulted sequence infinite times to yield the convolved sequence.
Figure below depicts the circular convolution of y[n] = [1 1 1 1 0 0 0 1] and h[n] = [0 0 0 0 1 1
1 1].

COMSATS University Islamabad Page 67


EEE 324 Digital Signal Processing Lab.

4. The Properties of DFT


Let, X[k] denote the DFT of x(n), Then:

4.1. Linearity

DFT {x1 (n)  x2 (n)} X1[k]  X 2 [k]

4.2. Time shifting

DFT{x(n  l )}  X (k )e  j ( 2 / N ) kl

4.3. Frequency shifting

DFT [ x(n)e j ( 2 / N ) nl ]  X (k  l )

4.4. Conjugation

DFT [ x* (n)]  X * (k )


4.5. Duality

DFT [ Nx(n)]  X (k )

4.6. Convolution

DFT {x1 (n) * x2 (n)}  X 1 (k ) X 2 (k )

4.7. Parseval‟s Theorom

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:

COMSATS University Islamabad Page 68


EEE 324 Digital Signal Processing Lab.

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.

If the length of X is greater than n, the sequence X is truncated.

The fft function employs a radix-2 fast Fourier transform algorithm if the length of the sequence is a
power of two.

The frequency axis w, in case of discrete signals goes from w = –π → π.

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

However normalized frequency w/π goes from -1 to 1, defined as follows in Matlab.


>> w = linspace(-1,1,length(y));

>> stem(w,y);

COMSATS University Islamabad Page 69


EEE 324 Digital Signal Processing Lab.

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

Absolute value and complex magnitude Y = abs(X)

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. Verifying the DFT Properties on Matlab

5.1.Linearity property
(Pseudo-code)

i. Take two signals x1[n] and x2[n].


ii. Compute the LHS as
a. Multiply x1[n] with constant α and x2[n] with a constants β
b. Add αx1[n] and βx2[n] using sigadd function
c. Take the DFT of the sum computed in last step using FFT command
iii. Compute the RHS as
a. Take the DFT of x1[n] and x2[n] using FFT command
b. Multiply the constants α and β with DFTs of x1[n] and x2[n] respectively.
c. Add the αDFT{x1[n]} and βDFT{x2[n]} using sigadd function
iv. Subplot both LHS and RHS to compare both sides

MATLAB Code
alpha = 2;

beta = 3;

COMSATS University Islamabad Page 70


EEE 324 Digital Signal Processing Lab.

n = -10:10;

x1 = sinc(2000*pi*n);

x2 = sinc(5000*pi*n);

%% Left Hand Side %%

x = alpha*x1+beta*x2; %use sigadd() if x1&x2 have different lengths

N = length(x);

LHS = fft(x,N);

w = linspace(-1,1,N);

subplot(211)

stem(w,LHS)

%% Right Hand Side %%

f1 = fft(x1,N);

f2 = fft(x2,N);

RHS = alpha*f1 + beta*f2; %use sigadd() if x1&x2 have different


lengths

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)

i. Take a signals x[n].


ii. Compute the LHS as
a. Compute the mod of x[n] using abs() command
b. Take the square of the mod of x[n] (calculated in last step)
c. Compute the sum of squared mod of x[n] (calculated in last step) to obtain
the energy of x[n], use sum() command for computing sum.

COMSATS University Islamabad Page 71


EEE 324 Digital Signal Processing Lab.

iii. Compute the RHS as


a. Compute the DFT of x[n] using fft command
b. Compute the mod of DFT{x[n]} using abs() command
c. Take the square of the mod of DFT{x[n]} (calculated in last step)
d. Compute the sum of squared mod of DFT{x[n]} (calculated in last step)
iv. Compare the result of both LHS and RHS

MATLAB Code
n = -10:10;

x = sinc(2000*pi*n);

%% Left Hand Side %%

xmod = abs(x);

xmodsquared = xmod.^2;

LHS_Energy = sum(xmodsquared)

%% Right Hand Side %%

N = length(x);

f = fft(x,N);

fmod = abs(f);

fmodsquared = fmod.^2;

RHS_Energy = sum(fmodsquared)/N

>> LHS_Energy = 1.0000

>> RHS_Energy = 1.0000

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.

COMSATS University Islamabad Page 72


EEE 324 Digital Signal Processing Lab.

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 )

COMSATS University Islamabad Page 73


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 74


EEE 324 Digital Signal Processing Lab.

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.

DFT {x1 (n) * x2 (n)}  X 1 (k ) X 2 (k )

COMSATS University Islamabad Page 75


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 76


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 77


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 78


EEE 324 Digital Signal Processing Lab.

Lab # 06 Z-Transform and Inverse Z-Transform

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).

The z-transform of a sequence is defined as

X(z) = ∑(x[n] z-n)

COMSATS University Islamabad Page 79


EEE 324 Digital Signal Processing Lab.
 The Z-transform is a variant form of the Fourier transform that is particularly useful for
time-discretized (sampled) functions.
 In sampled systems, Z-transforms are used to represent systems with transfer
functions.
 Things work differently in the z-plane. For a function to decay to zero, the pole must be
inside the unit circle.
 A decaying signal, yk = yoak, has a pole at z = a.
 If a is positive, that pole is in the right half of the z-plane. If a is positive, as long as a <
1, the response settles out. If a > 1, the response grows without limit.
 If a is negative, the pole is in the left half plane, and it is on the negative real axis.

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

COMSATS University Islamabad Page 80


EEE 324 Digital Signal Processing Lab.
response at frequencies designated in vector W, in radians/sample (normally between 0 and
pi).

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

Fs= Sampling Frequency

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:

Y(n) = 0.2x(n) + 0.52y(n-1) – 0.68(y(n-2)

Matlab Code:

b = [0.2];

a= [1, -0.52, 0.68];

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│');

COMSATS University Islamabad Page 81


EEE 324 Digital Signal Processing Lab.
subplot(2,1,2);

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);

 residuez: It can be used to develop the partial-fraction expansion of a rational z-transform


and to convert a z-transform expressed in a partial-fraction form to its rational form. [r,p,k]
= residuez(b,a) finds the residues, poles and direct terms of the partial-fraction expansion of
B(z)/A(z). ‗b‘ and ‗a‘ are the numerator and denominator polynomial coefficients,
respectively, in ascending powers of z^(-1). R and P are column vectors containing the

COMSATS University Islamabad Page 82


EEE 324 Digital Signal Processing Lab.
residues and poles, respectively. K contains the direct terms in a row vector. The number
of poles is

n = length(A)-1 = length(R) = length(P)

z-transform partial-fraction expansion

[r,p,k] = residuez(b,a)

[b,a] = residuez(r,p,k)

Example:

Determine the Inverse z-transform using partial fraction expansion.


X(z) = z / (z3 + 2z2 + 1.25z + 0.25) , |z| > 1

MATLAB Code:

b = [0,0,1];

a = [1,2,1.25,0.25]; [R,P,K] = residuez(b,a);

Result:

R = 4,0,-4

P = -1,-0.5,-0.5
K=[]

X(z) = 4/(1+z-1) + 0(1+0.5z-2) - 4 (1+0.5z- 1) 2

 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.

 zp2tf: It is used as inverse process of above function.

COMSATS University Islamabad Page 83


EEE 324 Digital Signal Processing Lab.
 impz: The inverse of a rational z-transform can be readily calculated using this function.

 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

Task-2: Determine the inverse z-transform of the 11 terms of following equation

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.

x(z) = __1 – z-1 – 4z-2 + 4z-3_______

1 – 2.75z-1 + 1.625z-2 – 0.25z-3

Task-4: A digital filter is described by the difference equation,

Y(n) = x(n) + x(n-1) + 0.9y(n-1) – 0.81y(n-2)


Using the freqz function, plot the magnitude and phase of the frequency response of the
filter.

COMSATS University Islamabad Page 85


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 86


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 87


EEE 324 Digital Signal Processing Lab.

Lab # 07 Sampling and Multi-rate Signal Processing


Objectives:

The purpose of this lab is to acquaint students with the following concepts:

• Sampling

• Rates of sampling

• Up sampling/Interpolation

• Down sampling/Decimation

• Filtering within Sampling - More commonly known as the process of antialiasing

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

Sampling is a process of converting a continuous signal into a discrete signal. Physical


meaning of sampling is ―to measure and store/save a continuous quantity (i.e. temperature
or voice) after a particular interval of time‖. It must be noted that information between two
samples is lost during sampling hence we are loosing more information if the time interval
two samples or sampling time

COMSATS University Islamabad Page 88


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 89


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 90


EEE 324 Digital Signal Processing Lab.

Changing the sampling rate or resolution of the discrete signal

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

COMSATS University Islamabad Page 91


EEE 324 Digital Signal Processing Lab.

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

Plotting FFT of the Sampled signal

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:

COMSATS University Islamabad Page 93


EEE 324 Digital Signal Processing Lab.

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); fax = [f ax1 f ax2];


stem(f ax,2*abs(y));

Example-1: Perfect Reconstruction (No Aliasing)

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);

fax = [f ax1 f ax2];

stem(f ax,2*abs(y))

xlabel('Hz');

ylabel('Amplitude');

COMSATS University Islamabad Page 94


EEE 324 Digital Signal Processing Lab.

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.

Example-2: Aiasing while due to sampling

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);

f ax1 = fs/2*linspace(0,1,NFFT/2+1); f ax2 = fs/2*linspace(-1,0,NFFT/2-1); fax = [f ax1 f ax2];

COMSATS University Islamabad Page 95


EEE 324 Digital Signal Processing Lab.

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.

Changing Sampling rate in a Discrete Signal

• 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

Aliasing In a Speech Signal

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?

COMSATS University Islamabad Page 96


EEE 324 Digital Signal Processing Lab.

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

ii. Take its fft and plot it

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:

Step-1: Process of Recording audio signal

recObj = audiorecorder(44100, 16, 2); % Create a recording object with 16 bit, 2


channel and sampling frequency fs=44100
get(recObj) % To Check details of the created recording object
recObj = audiorecorder; % Start recording

disp( 'Start speaking.')


recordblocking(recObj, 10); % Set the time of recording, 10 sec in this case
disp('End of Recording.');
myRecording = getaudiodata(recObj); % Get audio data out of the recording object

% Plot the waveform.

stem(myRecording); % Plot the audio data


play (myRecording) ; % Play the audio data
% sound(myRecording); % Another way to Play the audio data

Or load an existing audio signal load handel.mat

hfile = 'handel.au'; auwrite(x, fs, hfile); clear y Fs

% 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.

Step-2: Taking FFT and ploting

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); fax = [f ax1 f ax2];


stem(f ax,2*abs(y));

Step-3: Decimation

x = decimate(x,2); x = decimate(x,3);

now follow the step-4 to take and plot its fft.

Step-4: Interpolation

x = interp(x,3); x = decimate(x,2);

Now follow the step-4 to take and plot its fft

Figure: The above spectrum is DFT of a sound signal while below is it’s the spectrum of its
decimated version

COMSATS University Islamabad Page 98


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 99


EEE 324 Digital Signal Processing Lab.

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.

Task-4: Take a speech signal

i. Plot fft of the signal

ii. Downsample (decimate) the signal in part-(ii) by 2 and plot its fft. Comment if there is
aliasing or not?

COMSATS University Islamabad Page 100


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 101


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 102


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 103


EEE 324 Digital Signal Processing Lab.

Lab # 08 Simulation of Non RT AM Tx/Rx on Simulink

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.

Pre Lab Task:


We start with acquainting ourselves with SIMULINK and understanding its significance in
design of digital system. We will then try to implement signal generator in SIMULINK.

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:

Simulink may be accessed in MATLAB by using the following methods:

1. Type ‗simulink‘ in command window


2. Click on ‗simulink‘ icon in the top
3. Click on the ―MATLAB Start‖, point to ―Simulink‖ and click on ―Library Browser‖. As a
result ‗SIMULINK Library Browser‘ will open. Click on the ‗new‘ icon at top left and save
the file on your hard drive.

COMSATS University Islamabad Page 104


EEE 324 Digital Signal Processing Lab.

Given below is the interface of SIMULINK library browser:

SIMULINK Library Browser - Interface

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:

Setting up simulation configuration parameters BEFORE beginning to model

COMSATS University Islamabad Page 105


EEE 324 Digital Signal Processing Lab.

Configuration Parameters Setting Window

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.

Some Useful Toolboxes

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:

COMSATS University Islamabad Page 106


EEE 324 Digital Signal Processing Lab.

Example „.mdl‟ file

Setting of Sine Wave Block

COMSATS University Islamabad Page 107


EEE 324 Digital Signal Processing Lab.

Settings of Spectrum Scope

Display Settings of Spectrum Scope

COMSATS University Islamabad Page 108


EEE 324 Digital Signal Processing Lab.

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

Figure 1- Simulation Environment

The Procedure

Building the Transmitter

The basic modulation mathematical description is given by:

y(t )  [1  m(t )] cos(2f c t )

Where:

COMSATS University Islamabad Page 109


EEE 324 Digital Signal Processing Lab.

cos(2f c t ) - The carrier signal

m(t ) - The modulation index

Figure 2- AM Transmission Principle

1. Start by creating a new model in Simulink ®

2. Open the Simulink library browser and add the DSP sine-wave to your model. This

blocks will represent the information signal m(t).

Figure 3 – The Sine Wave Generator Block

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‖.

COMSATS University Islamabad Page 110


EEE 324 Digital Signal Processing Lab.

Figure 4 – Information Signal Configuration Parameters

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‖

5. Add new DSP-constant to your model:

Figure 5 - Adding a DSP constant

COMSATS University Islamabad Page 111


EEE 324 Digital Signal Processing Lab.

6. Double-click on the constant object and set its constant value to 1.5:

Figure 6 - Set a constant value

7. Add a new adder object from:

Figure 7- Adder

COMSATS University Islamabad Page 112


EEE 324 Digital Signal Processing Lab.

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.

Figure 9 – Vector Scope Configuration

COMSATS University Islamabad Page 113


EEE 324 Digital Signal Processing Lab.

11. Place the objects in the following way:

Figure 10- The Transmitter Model

12. Run the model, pause the simulation and activate the scope window. The modulated

signal should be displayed as follows:

Figure 11 - AM Modulation Signal

The AM Receiver (Square Root Demodulator)

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.

COMSATS University Islamabad Page 114


EEE 324 Digital Signal Processing Lab.

Figure 12 – SQRT Demodulation Principle of Operation

13. Add the new math function block to your model. This block can be configured to

implement various mathematical functions.

Figure 13 –Square Function

14. Configure the block to calculate the square:

COMSATS University Islamabad Page 115


EEE 324 Digital Signal Processing Lab.

Figure 14 – Select Math Function

15. Use the math function block to create the Square root function. You may retrieve it

from the library or copy the ―square‖ block.

16. Add a digital filter design block. This block enables you to design filters using the

MATLAB® FDATool.

Figure 15- Digital Filter Design

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

COMSATS University Islamabad Page 116


EEE 324 Digital Signal Processing Lab.

pass frequencies below 5 KHz, and rejects frequencies higher than 10 KHz (please refer
to Figure 16).

Figure 16 –LPF Design Window


1
18. Add a "Multiplier" and a "Subtract" block.

19. Add two "DSP Constant" blocks.

20. Add the matrices concatenation object. This object will enable the modulated and the

de-modulated signals to be displayed simultaneously in the scope:

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.

Figure 17- Matrix Concatenate

21. The blocks should be connected as shown in Figure 18.

Figure 18 -AM Simulation Model

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).

COMSATS University Islamabad Page 118


EEE 324 Digital Signal Processing Lab.

Figure 19 -Displaying the Modulated and Demodulated Signals

You should get the signals presented bellow:

Figure 20 - The Video Viewer Display

 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

COMSATS University Islamabad Page 119


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 120


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 121


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 122


EEE 324 Digital Signal Processing Lab.

COMSATS University Islamabad Page 123


EEE 324 Digital Signal Processing Lab.

Lab # 09 Filtering through MATLAB (Simulink) and its


implementation on hardware (TMS320C6416 & TMS320C6713)

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.

Pre Lab Task:


The filters may be broadly classified as follows:

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:

Magnitude Response (dB)

-10

-20
Magnitude (dB)

-30

-40

-50

-60

0 5 10 15 20
Frequency (kHz)

Low Pass Filter (Cutoff = 4kHz)


Magnitude Response (dB)

-10

-20
Magnitude (dB)

-30

-40

-50

-60

-70

0 5 10 15 20
Frequency (kHz)

High Pass Filter (Cutoff = 6kHz)


COMSATS University Islamabad Page 124
EEE 324 Digital Signal Processing Lab.

Magnitude Response (dB)

-10

-20
Magnitude (dB)

-30

-40

-50

-60

0 5 10 15 20 25 30
Frequency (kHz)

Band Pass Filter (24 – 28 kHz)


Magnitude Response (dB)

-10

-20
Magnitude (dB)

-30

-40

-50

-60

-70

0 5 10 15 20 25 30
Frequency (kHz)

Band Stop Filter (24 – 28 kHz)

In Lab Task:
Alternatively, filters may also be classified according to their response type as:

1. FIR – Response is time limited


2. IIR – Response is not limited in time

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

Alternatively, it may also be opened by following the method given below:

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)

COMSATS University Islamabad Page 125


EEE 324 Digital Signal Processing Lab.

Following is the self-explanatory diagram of FDA tool interface:

Filter Design and Analysis Tool - Interface

Following are some of the parameters considered during filter design process in FDA tool:

• fstop – Start of stop band


• fpass – End of pass band
• Apass – Magnitude (dB) by which pass band frequencies will be attenuated
• Astop – Magnitude (dB) by which stop band frequencies will be attenuated
• fs – Sampling frequency of the filter
– Must be greater than twice the max filter frequency
• Order – Order of the filter

Think of order as the measure of how much processing power our digital filter will require to
be implemented. Hence,

1. Sharper the cutoff, higher the order


2. Higher the fs (not fstop), higher the order

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 ‗ViewFilter Visualization Tool‘. The interface of this tool is shown
below:

COMSATS University Islamabad Page 126


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 127


EEE 324 Digital Signal Processing Lab.

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.

COMSATS University Islamabad Page 128


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 129


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 130


EEE 324 Digital Signal Processing Lab.

Lab # 10 Hardware implementation of AM modulator and


demodulator on (TMS320C6713 & TMS320C6416)

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:

 Creating a simulation model (not R-T) for the AM transmitter/receiver


(Lab 9)

 Migration to Real-time of the Simulation Model

Pre-Lab Task

1. Real Time Implementation


1.1. The Environment
The real-time implementation model will be created upon the simulation model, after the
following changes:

 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.

COMSATS University Islamabad Page 131


EEE 324 Digital Signal Processing Lab.

Figure 21- Real Time Implementation Environment

Equipment Used (shown in Figure 22):

 DSK6713/DSK6416
 Dual Channel Oscilloscope
 Signal Generator

Modulated
Signal Demodulated
Signal
Information

Figure 22- Equipment Used

We have 4 signals (4 cables):

1. Information- the signal to be modulated

2. Modulated- the DSK creates a modulation of the given information

COMSATS University Islamabad Page 132


EEE 324 Digital Signal Processing Lab.

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.

Figure 2 - The C6713DSK Block

4. Add the ―Analog to Digital‖ and ―Digital to Analog‖ converters (ADC and DAC) to

your model as shown in Figure 3.

COMSATS University Islamabad Page 133


EEE 324 Digital Signal Processing Lab.

Figure 3 – A/D and D/A converters

5. Add the multi-port selector, in order to split the stereo input, as shown in Figure 4.

Figure 4 – Multiport Selector

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.

COMSATS University Islamabad Page 134


EEE 324 Digital Signal Processing Lab.

Figure 5 – Multiport Configuration

7. Configure the ADC and DAC blocks to a sampling rate to 96 KHZ and 16-bit samples.

Figure 6 – DAC and ADC Configuration

8. The final model should look as follows:

Figure 7- AM (SQRT) Real Time Model

9. You should configure the DSP constants as shown in Figure . The frame period for all

constants should be -1

COMSATS University Islamabad Page 135


EEE 324 Digital Signal Processing Lab.

Figure 8- Constant Value Parameters

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.

12. Display the modulated and demodulated signals in the scope.

Model Extensions
In this section following extensions to the model are introduced. Adding two more features:

 A variable frequency carrier generator


 An additional model for AM detection
The modulation index and carrier frequency will be changed through RTDX.

1. Open the model created in the previous section

2. Replace the constant modulation index by an RTDX input (Please refer to Figure ), and

name it Input Modulation.

COMSATS University Islamabad Page 136


EEE 324 Digital Signal Processing Lab.

Figure 9 - RTDX input

3. Configure the RTDX input object to the values described bellow:

COMSATS University Islamabad Page 137


EEE 324 Digital Signal Processing Lab.

Figure 10 - RTDX Input Configuration

4. Replace the sine wave block used for the carrier by the configurable carrier blocks and

create a subsystem for the carrier generator as shown in Figure

Your model should look as shown in Figure

COMSATS University Islamabad Page 138


EEE 324 Digital Signal Processing Lab.

Figure 11 – Inserting a Configurable Carrier

COMSATS University Islamabad Page 139


EEE 324 Digital Signal Processing Lab.

Figure 12 - AM (SQRT) Model with Configurable Carrier

5. Enter the Configuration Parameters menu (ctrl+E). Choose Real-Time

Workshop=>TIC6000 Code-Generator, In The Run-Time box change the Build Action


to ―Build‖2:

Figure 13 – Simulation Parameters

COMSATS University Islamabad Page 140


EEE 324 Digital Signal Processing Lab.

Push the OK button and close the ―Configuration Parameters‖ window.

Rebuild *.out file using ctrl+B.

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.

A Configurable Carrier Wave Generator


The Simulink sine wave block cannot be configured during run-time; its frequency is a
parameter that should be set in advance. We will introduce the implementation of a block
where the frequency is a variable that can be set in real-time (In this case using RTDX). The
block is based on the following relationship:

cosct  Re e jct  

In the discrete case the following relationship applies:

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

COMSATS University Islamabad Page 141


EEE 324 Digital Signal Processing Lab.

Figure 23 – Carrier Wave Generator

COMSATS University Islamabad Page 142


EEE 324 Digital Signal Processing Lab.

The Coherent Detector (in brief)


The coherent detector principle of operation is in Figure 24 The AM example model
(AM_Coherent.mdl) is shown in Figure 4.0

Figure 24 – Coherent SQRT Demodulation Principle of


Operation

Figure 25 – Amplitude Modulation Example with Coherent Detection

COMSATS University Islamabad Page 143


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 144


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 145


EEE 324 Digital Signal Processing Lab.

Lab # 11 Implementation of FIR and IIR Filters on DSP kit

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

IIR vs FIR Filters:


IIR filters are difficult to control and have no particular phase, whereas FIR filters make a
linear phase always possible. IIR can be unstable, whereas FIR is always stable. IIR, when
compared to FIR, can have limited cycles, but FIR has no limited cycles. IIR is derived from
analog, whereas FIR has no analog history. IIR filters make poly phase implementation
possible, whereas FIR can always be made casual. FIR filters are helpful to achieve fractional
constant delays. #MAD stands for a number of multiplications and additions, and is used as a
criterion for an IIR and FIR filter comparison. IIR filters require more #MAD when compared
to FIR, because FIR is of a higher order in comparison to IIR, which is of lower order, and uses
poly phase structures.

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.

COMSATS University Islamabad Page 146


EEE 324 Digital Signal Processing Lab.

In-Lab Task

Types of IIR filters:


Common types of IIR filters are as follows:

 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

COMSATS University Islamabad Page 147


EEE 324 Digital Signal Processing Lab.

honor of Pafnuty Chebyshev because its mathematical characteristics are derived from
Chebyshev polynomials.

Type I Chebyshev filters:

The frequency response of a fourth-order type I Chebyshev low-pass filter with

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 =

so that a ripple amplitude of 3 dB results from


COMSATS University Islamabad Page 148
EEE 324 Digital Signal Processing Lab.

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.

Type II Chebyshev filters:

The frequency response of a fifth-order type II Chebyshev low-pass filter with

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:

COMSATS University Islamabad Page 149


EEE 324 Digital Signal Processing Lab.

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

is the ripple factor

is the selectivity factor

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

COMSATS University Islamabad Page 150


EEE 324 Digital Signal Processing Lab.

Lab Tasks
Task-1: Make a filter using following specifications:

Filter type: Low-pass

fpass = 4kHz

fstop= 6kHz

fs= 44.1kHz

Order: Minimum Order

Match exactly = Pass-band (if applicable)

Apass= 1dB

Astop= 60dB

COMSATS University Islamabad Page 151


EEE 324 Digital Signal Processing Lab.

• Task-2: Design following high-pass filters:


1. Kaiser Window
2. Butterworth
3. Chebyshev Type-I
4. Chebyshev Type-II
5. Elliptic
With following specifications:

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

COMSATS University Islamabad Page 152


EEE 324 Digital Signal Processing Lab.

COMSATS University Islamabad Page 153


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 154


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 155


EEE 324 Digital Signal Processing Lab.

Lab # 12 Audio Signal Processing using DSK6713 & DSK6416

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:

Hardware and Software Requirements

This laboratory will be developed using the following hardware and software:

 MATLAB 7.0.0.19920 (R14) with Embedded Target for TI C6000.


 Code Composer Studio (CCS) v3.3
 Texas Instruments C6713 DSK hardware
 Microphone and computer loudspeakers/headphones

Simulation

Start by running the Echo and Reverberation Simulink models. These use .wav files as the inputs.

Echo using Wave File

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.

Opening the Echo Simulink Model

From MATLAB, open EchoUsingWav.mdl


COMSATS University Islamabad Page 156
EEE 324 Digital Signal Processing Lab.

Figure 26 – Echo using .wav File

Run the model and listen to the effect of the delay.

Changing the Delay Time

Double-click on the ―Delay‖ block and change the ―Delay (samples)‖ to a different value.

Figure 27 – Changing the Delay Time

Run the model and hear how the effect has changed. Try a few different settings between 100
and 20000 ―Delay (samples)‖.

Reverberation using Wave File

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.

COMSATS University Islamabad Page 157


EEE 324 Digital Signal Processing Lab.

Opening the Reverberation Simulink Model

From MATLAB, open ReverberationUsingWav.mdl

Figure 28 – Reverberaton Using .wav File

Changing the Delay Time

Double-click on the ―Delay‖ block. Change the ―Delay (samples)‖ to a different value then run
the model and listen to the effect.

Changing the Gain

Double-click on the ―Gain‖ block. Change the ―Gain‖ to 0.95 then run the model. Listen to the
effect.

Figure 29 – Changing the Reverberation Gain

COMSATS University Islamabad Page 158


EEE 324 Digital Signal Processing Lab.

Questions

 Why does Reverberation require a shorter delay time than echo?


 What effect does the ―Gain‖ block have on the stability of the reverberation system?
 Is Reverberation system an IIR or FIR system? What are the choices for ‗a‘ & ‗b‘
which makes a second order reverberation model stable?

Real-Time Model for TI C6713 DSK

Texas Instruments C6713 DSK Setup

Figure 30 – Texas Instruments C6713 DSK Setup


Alternatively, you can use computer loudspeakers.

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.

Starting Code Composer Studio

The stages required to implement Echo and Reverberation are now described.

Starting Code Composer Studio

Start Code Composer Studio for C6713 DSK and use Debug -> Connect

COMSATS University Islamabad Page 159


EEE 324 Digital Signal Processing Lab.

Figure 31 – Startup Screen for Code Composer Studio (CCS)

Opening an Existing Model

Start MATLAB 7.3.0 R2006b

In the top left hand corner of the MATLAB screen, select File -> Open.

Figure 32 – Opening an Existing Model

The following screen will appear.

COMSATS University Islamabad Page 160


EEE 324 Digital Signal Processing Lab.

Figure 33 – Selecting an Existing Model

Highlight ―C6713_Audio_Template‖ then click on ―Open‖.

Viewing the “C6713 Audio Template”

The ―C6713_Audio_Template‖ is now displayed.

Figure 34 – The C6713 DSK Audio Template

Overview of the Complete Echo Subsystem

You are now going to implement the Echo Subsystem shown below.

COMSATS University Islamabad Page 161


EEE 324 Digital Signal Processing Lab.

Figure 35 – The Complete Echo Subsytem

Implementing the Echo Subsystem

Double click on the ―Effect 1‖ subsystem block. An empty model will appear.

Figure 36 – The Blank “Effect 1” Subsystem

You will now drag-and-drop some library components onto the model.

The Simulink Library Browser – Commonly Used Blocks

Select View -> Library Browser. Expand the ―Simulink‖ section.

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.

Figure 37 – Commonly Used Blocks

From ―Commonly Used Blocks‖, drag-and-drop a ‖Gain‖ block, a ―Sum‖ block and two ―Data
Type Conversion‖ blocks onto the model.

The Simulink Library Browser - Discrete

From the Simulink Library Browser, select ―Discrete‖. Highlight ―Integer Delay‖ and drag-
and-drop this block onto the model.

COMSATS University Islamabad Page 163


EEE 324 Digital Signal Processing Lab.

Figure 38 – Discrete Blocks

Setting the Integer Delay Time

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‖.

COMSATS University Islamabad Page 164


EEE 324 Digital Signal Processing Lab.

Figure 39 – Setting the Integer Delay Time

Setting the Output Data Conversion to Single

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‖.

Figure 40 – Setting the Data Conversion to Single

Setting the Delay Gain

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‖.

COMSATS University Islamabad Page 165


EEE 324 Digital Signal Processing Lab.

Figure 41 – Setting the Echo Delay Gain

Setting the Output Data Conversion to int16

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.

Figure 42 – Data Type Conversion to 16-bit Integer

The Completed Echo Subsystem

Join the blocks as shown and add a title.

COMSATS University Islamabad Page 166


EEE 324 Digital Signal Processing Lab.

Figure 43 – Joining the Blocks

Returning to the Parent System

From the Toolbar, select the ―Up Arrow‖ icon. This returns you to the next higher level.

Figure 44 – Returning to the Parent System

The Reverberation Subsystem

The next subsystem to be implemented will be Reverberation.

Overview of the Completed Reverberation Subsystem

We are now going to implement the Reverberation System shown below.

COMSATS University Islamabad Page 167


EEE 324 Digital Signal Processing Lab.

Figure 45 – Overview of the Reverberation Subsystem

Note that the reverberation subsystem is very similar to that of echo. We will cut-and-paste
from the Echo Subsystem

Opening the Effects 2 Subsystem

From the ―C6713 Audio Template‖ top level, double-click on the ―Effect 2‖ subsystem.

Figure 46 – The Blank “Effect 2” Subsystem

Copying a Block from the Echo 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.

COMSATS University Islamabad Page 168


EEE 324 Digital Signal Processing Lab.

Figure 47 – Outlining the Block to be Copied

Release the left button on the mouse.

Figure 48 – Block to be Copied is Marked

From pull-down menu, select Edit -> Copy (or Ctrl + C)

Blocks Dropped onto Effect 2 Subsystem

Return to the ―Effect 2‖ subsystem and Edit -> Paste (Ctrl + V) into the model.

COMSATS University Islamabad Page 169


EEE 324 Digital Signal Processing Lab.

Figure 49 – Blocks Dropped onto Subsystem

Flipping the Blocks

The blocks are facing the wrong way. Turn them round using Format -> Flip Block.

Figure 50 – Flipping the Blocks

Changing the Integer Delay for Reverberation.

Because the sound goes round several times with reverberation, a shorter delay time can be
used. Here the delay time is 0.1 seconds.

COMSATS University Islamabad Page 170


EEE 324 Digital Signal Processing Lab.

Figure 51 – Delay Time for Reverberation

Set the ―Number of delays‖ to 800 then click on ―OK‖.

Completing the Reverberation Subsystem

Connect the blocks as shown below. Change the title to ―Reverberation Subsystem‖.

Figure 52 – The Completed Reverberation Subsystem

Returning to the Parent System

From the Toolbar, select the ―Up Arrow‖ icon. This returns you to the next higher level.

Figure 53 – Returning to the Parent System

COMSATS University Islamabad Page 171


EEE 324 Digital Signal Processing Lab.

The Improved Echo Subsystem

The final subsystem to be implemented will be ―Improved Echo‖. This is based on the ―Echo‖
subsystem, but with several delay paths.

The Complete Improved Echo Subsystem

Double click on the ―Effect 3‖ subsystem box. The required components are shown below.

Figure 54 – The Improved Echo Subsystem

Implementing the Improved Echo Subsystem

You should now have enough knowledge to implement this subsystem block without further
assistance. This time you are on your own!

Building the Model

Select Tools -> Real-Time Workshop -> Build Model.

COMSATS University Islamabad Page 172


EEE 324 Digital Signal Processing Lab.

Figure 55 – Building the Model

Running the Model

Microphone Straight Through to Loudspeakers

To check out the microphone and loudspeakers, set the DIP switches on the C6713 DSK as
follows:

Figure 56 – Switch Position 0

The microphone is fed directly to the loudspeakers without any digital signal processing.

Switch Position for Echo

To run the ―Echo‖ subsystem, set the DIP switch to 1.

Figure 57 – Switch Position 1 for Echo

COMSATS University Islamabad Page 173


EEE 324 Digital Signal Processing Lab.

Switch Position for Reverberation

To run the ―Reverberation‖ subsystem, set the DIP switch to 2.

Figure 58 – Switch Position 2 for Reverberation

Switch Position for Improved Echo

To run the ―Improved Echo‖ subsystem, set the DIP switch to 3.

Figure 59 – Switch Position 3 for Improved Echo

COMSATS University Islamabad Page 174


EEE 324 Digital Signal Processing Lab.

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.

Task-4: Development of Real time audio flange model

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

on the model toolbar).

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

In connector of the DSK and a pair of headphones connected to the Headphone

connector.

COMSATS University Islamabad Page 175


EEE 324 Digital Signal Processing Lab.

Figure 35: Real Time Flange Filter

COMSATS University Islamabad Page 176


EEE 324 Digital Signal Processing Lab.

Post Lab Task

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad Page 177


EEE 324 Digital Signal Processing Lab.

Lab Assessment

Pre Lab /5

Performance /5

Results /5 /25

Viva /5

Critical Analysis /5

Instructor Signature and Comments

COMSATS University Islamabad Page 178

You might also like