0% found this document useful (0 votes)
310 views117 pages

DSP Practical Workbook PDF

This lab session introduces MATLAB fundamentals and demonstrates how to synthesize and analyze signals using the MATLAB DSP toolbox. It covers plotting signals using script and function files, getting help in MATLAB, variables, expressions, and elementary operations. The session also explains the difference between script and function files and how to use the MATLAB workspace to store and manage variables. Students will learn how to generate and examine common signals using MATLAB commands.

Uploaded by

Esha khan
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)
310 views117 pages

DSP Practical Workbook PDF

This lab session introduces MATLAB fundamentals and demonstrates how to synthesize and analyze signals using the MATLAB DSP toolbox. It covers plotting signals using script and function files, getting help in MATLAB, variables, expressions, and elementary operations. The session also explains the difference between script and function files and how to use the MATLAB workspace to store and manage variables. Students will learn how to generate and examine common signals using MATLAB commands.

Uploaded by

Esha khan
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/ 117

Practical Workbook

CS-419
Digital Signal Processing

Name : _____________________________

Year : _____________________________

Batch : _____________________________

Roll No : _____________________________

Department: _______________________________

Department of Computer & Information Systems Engineering


NED University of Engineering & Technology
Practical Workbook
CS-419
Digital Signal Processing

Prepared by:

Dr. Majida Kazmi

Revised in:

October 2019

Department of Computer & Information Systems Engineering


NED University of Engineering & Technology
INTRODUCTION

This workbook has been compiled to assist the conduct of practical classes for CS-419 Digital
Signal Processing. The area of digital signal processing has advanced rapidly over the last four
decades. This advancement is attributed to the progress in digital computer technology and
integrated circuit fabrications. There are many reasons why the digital processing of an analog
signal is preferred over the signal processing directly in analog domain. The advantages of DSP
are common to many digital systems and include: Versatility, Repeatability, and Accuracy. DSP
is used in a very wide variety of applications.

The Course Profile of CS-419 Digital Signal Processing lays down the following Course
Learning Outcomes:

“Explore contemporary digital signal processing techniques (C3, PLO-2)”

“Investigate digital filters (C4, PLO-3)”

“Demonstrate the use of modern tools and techniques for digital signal processing (P4, PLO-5)”

All lab sessions of this workbook have been designed to assist the achievement of the above
CLOs. A rubric to evaluate student performance has been provided at the end of the workbook.

The DSP Labs introduce students to DSP design and analysis techniques that are core knowledge
for DSP engineers, and which serve as solid grounding for advanced level work in DSP. Lab 1-6,
9-11 emphasize on the key DSP concepts, such as overview of discrete time signal and systems in
time domain, and frequency domain, sampling and reconstruction of analog signals, signal and
systems representation in complex frequency domain, solution of differential equations using z
transform, computation of Fourier transform and its efficient implementation, Discrete Fourier
transform and Fast Fourier transform, Structure for the implementation of digital filters, FIR
Filter design and IIR Filter Design. All of these Labs will be performed using MATLAB that
provides an understanding of how to design signal processing systems and process data in a
practical way, using software and analyze output by simulations.

Lab 7, 8, 12-14 gives students an introduction to real-time DSP requirements by


introducing them with some educational DSP kits and FPGA board with real-time
capability, which will help them get acquainted with the programming of these devices
and some typical hardware and functions found in practical applications. It heightens
students' awareness of the diverse practical DSP applications by exposing them to some
practical DSP demos, hardware and operations involved in this area and also to provide
students with a learning platform on which to further experiment with DSP.
CONTENTS
Lab Session Title Page No.
No.

1 Demonstrate DSP toolbox to synthesize and analyze signals 1

2 Examine effects of sampling on analog signals 11

3 Examine effects of quantization on discrete time continuous signals 15

4 Examine discrete fourier transform using butterfly method 19

5 Computation of z – transform 23

6 Design and analyze digital FIR filter using matlab tools 27

7 Demonstrate DSP design on FPGA using Xilinx system generator 31

8 Demonstarte FIR filter using FIR complier on Xilinx FPGA 41

9 Examine aliasing effect in analog signals 53

10 Examine audio processing 60

11 Explore time parameter and classify discrerte time system 64

12 Demonstrate TMS320C6713DSK processor and related software 68

13 Audio processing using DSK-6713 board 72

14 Execute LED blinking program for DSK-6713 and 6416 board 82


Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 01
Demonstrate DSP toolbox to synthesize and analyze signals

MATLAB FUNDAMENTALS

a. MATLAB software will be used to implement and simulate digital signal processing
algorithms. The name MATLAB stands for MATrixLABoratory. Originally MATLAB was
developed to deal with only one single but universal data type: the matrix. A matrix is defined by
 Its associated name
 The number of rows
 The number of columns
 The value of all matrix elements

The matrix data type includes vectors, for the case when either of the number of rows or the
number of column equals to 1; and it includes scalars when both the number of rows and columns
equal 1. Furthermore, matrices can be either real‐valued or complex valued, which is the most
general case. This Lab will cover MATLAB fundamentals. It is recommended to try out
introduced methods while solving the described tasks.

b. This Lab also covers the difference between a script file and a function file by plotting
several signals. So, basically we would learn two things. First, plotting of signals and second,
difference between script and function file. The command window environment now shift to the
script or function file environment. The main objective of making script or function file is to store
data for future usage as command window do not have the facility of data storage after exit. As
the MATLAB starts the command window initializes and as soon as the MATLAB terminates i.e.
closed, the data on command window screen is cleared. While a script file or function file can be
stored for future reference.

HOW TO GET HELP?


There are several methods in MATLAB to access texts, which explain the usage and behavior of
given functions:

 The HELP command is the basic help feature to get help of a function. For example, to
get help on the SUM function, type at the command prompt:
help sum
 HELPWIN is used in the same manner as help, but it opens a separate window with
advance search facilities and links to related topics.
 HELPDESK uses a window of an installed web browser to display the help texts.
 If the name of a command is not exactly known, the LOOKFOR function helps by
seeking through the first comment line of all available functions and listing all functions where a
desired expression is found.

STATEMENT, EXPRESSIONS AND VARIABLES:


MATLAB is an expression language. The expressions you type are interpreted and evaluated.
MATLAB statements are usually of the form
variable = expression, or simply expression
Expressions are usually composed from operators, functions and variable names. Evaluation of
1
Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

the expression produces a matrix, which is then displayed on the screen and assigned to the
variable for future use.
A statement is normally terminated with the carriage return. However, a statement can be
continued to the next line with three or more periods followed by a carriage return. On the other
hand, several statements can be placed on a single line if separated by commas or semicolon.

 The variable ANS:


If the variable name and = sign are omitted, a variable ANS (for answer) is automatically created
to which the result is assigned.

 Suppressing Screen Output:


If the last character of a statement is a semicolon, the printing is suppressed, but the assignment is
carried out. This is essential in suppressing unwanted printing of intermediate results.

 Colon Notation:
Colon notation is used to generate vectors, and reference submatrices, known as subscripting.
Creative use of this feature makes MATLAB programming code simple, readable and
minimizes the use of loop, which slows MATLAB.

 An index vector is created by using the colon notation


first : last
For example, [1:5] creates the vector [12345]
 An spacing can be introduced between two elements of a vector by using the colon
notation
first : spacing : last
For example, [1: 2 : 5] creates the vector [1 3 5].

WORKSPACE:
The contents of all the variables are stored in the MATLAB workspace. This is the memory
region allocated for variable.
 The command WHO lists all variable which currently exist in the workspace.
 WHOS additionally lists the size and amount of allocated memory.
 The entire workspace or single variable can be cleared by using the CLEAR command.

ELEMENTARY OPERATIONS:
Algebraic expressions can be formed by the following basic operations:

 Transpose of a vector/matrix can be produced by .*


e.g. B.*

 + is used to add two vectors/matrices of identical size, or a vector/matrix and a scalar, e.g.
[3 2; 4 5] + [7 4; 9 6]
 ‐ subtracts two vectors/matrices of identical size, or a vector/matrix and a scalar, e.g.
2-B
 .* performs element‐wise multiplication of two vectors/matrices of identical size, or a
vector/matrix and a scalar. For example, to square all elements of B, we may write
B.*B
 ./ performs element‐wise division of two vectors/matrices of identical size, or a
vector/matrix and a scalar. For example, the reciprocal of all elements in B is computed
through
2
Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

1./B
 * performs vector/matrix multiplication. The number of columns in the first
vector/matrix must equal to the number of rows in the second. Example:
B*B

REAL AND COMPLEX MATRICES:


In general, any matrix within the MATLAB can be complex‐valued. However, for efficient
storage, MATLAB distinguishes between real‐valued and complex‐valued matrices. Real valued
matrices are matrices where the imaginary parts of all matrix elements are zero. The following
essentials must be known to deal with complex‐valued matrices:
 The variables i and j are assigned, by default, the value i= √ −1. This is used to define the
complex values. For example,
5 + j * 10
Generates a complex‐valued variable.
 The real part of a complex‐valued matrix can be extracted by using the function REAL and
imaginary part can be extracted by using the function IMAG. Both functions deliver the real‐
valued matrices as outputs.
 The function CONJ is used to produce the complex conjugate of a matrix.
 The special character ’ generates the complex conjugate transpose of a matrix, the hermitian
matrix. This character is written after an expression or variable.
For example, the hermitian of a matrix A can be obtained through: A'

M-FILES:
MATLAB can execute a sequence of statements stored in a file. Such files are called M‐files
because they have “.m” extension as the last part of their file name. There are two types of M‐
types:
 Script files
 Function files

SCRIPT FILE:
In a script file, script is a sequence of commands as they could be entered at the prompt. The
script allows to execute the entire sequence multiple times in a comfortable way, or to test
modified versions.

FUNCTION FILE:
In a function file, function has the additional feature of passing parameters. On calling a function,
it may read input arguments and after execution it may return output values. The “FUNCTION”
command specifies the input and output parameters of a function. It must be very first command
in a function file. Only comment may be written before the FUNCTION command. Any text
after a % sign inside an m‐file is comment.

FLOW CONTROL:
In MATLAB flow control means that a program may not only be executed straight down from
top to bottom but with branches and repetitions.

 The FOR function allows to create a loop which is controlled by a counter.

3
Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

 More general exit conditions can be implemented in a WHILE loop.


 The IF command allows for conditional programming, together with ELSE.
 All these commands come along with an END command which acts as a closing brace,
together with the opening brace, i.e. the introducing FOR, WHILE or IF command.

PLOTTING OF SIGNALS:
A plot is any graphic display you can create within a figure window. A figure is a MATLAB
window that contains graphic displays (usually data plots). You create figures explicitly with the
figure function, and implicitly whenever you plot graphics and no figure is active. By default,
figure windows are resizable and include pull-down menus and toolbars. Plots can display tabular
data, geometric objects, surface and image objects, and annotations such as titles, legends, and
color bars. Figures can contain any number of plots. Each plot is created within a 2-D or a 3-D
data space called axes. You can explicitly create axes with the axes or subplot functions.

A graph is a plot of data within a 2-D or 3-D axes. Most plots made with MATLAB functions and
GUIs are therefore graphs. In MATLAB we can visualize the results on graphs by using several
commands. Plot command is generally used to generate 2-D graph of continuous time signal
while stem command is used to generate 2-D graph of discrete time signal. Subplot command can
be used to divide the graphical screen in to number of columns and number of rows. The plot,
stem, subplot commands are very helpful in analysis which we would discover in this lab as well.

PLOT COMMAND:
MATLAB plotting functions and tools direct their output to a figure window. Each figure is a
separate window that you can dock in the desktop, and collect together with other plots in a
Figure Group. To illustrate the basic components of a graph, execute the following code to create
a plot of a family of sine curves:
x = 0:.2:20;
y = sin(x)./sqrt(x+1); y(2,:)
= sin(x/2)./sqrt(x+1); y(3,:)
= sin(x/3)./sqrt(x+1);
plot(x,y)

The resulting figure contains a 2-D set of axes. This graphic identifies the components and tools
of a figure window.

4
Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Fig. 1.1: Generation of Continuous time signal using Plot command

The plot function uses a default line style and color to distinguish the data sets plotted in the
graph. You can change the appearance of these graphic components or add annotations to the
graph to present your data in a particular way.
This command is used to generate two-dimensional graph on screen. The syntax used for plot
command is
Plot(x,y)
Where x defines the x-axis and y defines the y-axis. Labeling on a graph is possible with the
help of following commands
 xlabel: It defines the label on x-axis
 ylabel: It defines the label on y-axis
 title: It is used to give a title to a graph

The plot command can generate more than one signal on a single graph with different color. For
detailed information of plot command, use help on MATLAB.

STEM COMMAND:
The stem command shares all the features of a plot command, but the only difference is the type
of signal which is generated on the graph. The stem command is used for the discrete time signals
while the plot command is used for the continuous time signals. Following figure is an example
of stem command:

5
Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Fig. 1.2: Generation of Discrete time signal using Stem command

SUBPLOT:
A graphical screen can be divided in to multiple sub-screens by subplot command. The screen is
divided in to m by n matrix by using following syntax
Subplot(m,n,p)
Where m and n are the dimensions in which the figure screen would be divided and p defines the
position.
Following figure illustrate the example of subplot command.

Fig. 1.3: Generation of 4 plots on a single figure using subplot command

HARMONICS:
Harmonics are integral multiples of a signal. Consider the signal cos (wot). Its harmonics are cos
(2 wot), cos (3 wot) is the fundamental harmonic

6
Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

EVEN & ODD HARMONICS:


If the harmonic of a signal function has an even co – efficient it is called an even harmonic.
Otherwise if the co – efficient is odd it is called an odd harmonic.

For X(t) = Cos (wot) Cos (2 wot), Cos (4 wot), Cos (6 wot) ………………Even Harmonics
 Cos (3 wot), Cos (5 wot), Cos (7 wot) ………………Odd Harmonics

Even, odd harmonic play an important role in signal construction. Different waveforms can be
obtained by adding one type of harmonic e.g. adding infinite odd harmonics of sine/cosine where
generates a square wave. Both will have a 90 degree phase shift from each other.

Exercises:
Task # 1: Generate a script file which produces a sine wave with 2 Hz frequency.

Task # 2: Generate a script file which produces a sine wave by taking frequency as an input
at run time.

Task # 3: Generate a script file which produces a sine wave with 2Hz, 5Hz, 10Hz and 20Hz
frequencies on a single figure by using subplot command. Label the subplots with the relevant
frequency to distinguish the signals clearly.

Task # 4: Implement a function as defined below, which produces a sine wave of 1001
samples with spacing of 1 ms.
[x]=sinewave(t)

Task # 5: Generate a function which produces a sine wave by accepting frequency and
amplitude as input arguments and return a plot of sine wave for the inputted parameters.

Task # 6: Repeat all above tasks by using stem command rather than plot command.

Task # 7: Write MATLAB function for plotting the 5 harmonics of a signal x(t)=cos(wt)
with a fundamental frequency of f = 0.5 Hz. Take t = 0:0.01:2
What are the frequencies and Time periods at the all 5 harmonics?

Task # 8: Try all help methods to get help of any function.

Task # 9: (a) Assign 10 samples, from 0 to 9, of time to the vector t.


(b) Assign a vector of samples without assigning it to a variable.
(c) Assign 10 samples, from 0 to 9, of time to any vector without printing it to
screen.

Task # 10: Investigate the difference between multiplication*and element‐wise


multiplication.* of vectors/matrices.

Task # 11: Generate a complex‐valued matrix


a = ones (1,10)+ i* (1 : 10)
and calculate the absolute square of all elements of this matrix.

Task # 12: Implement a function


[x]=sinewave(t)
7
Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Which produces a sine wave of 1001 samples with spacing of ∆t= 1ms.

Task # 13: Use MATLAB help to get familiar with the syntax of FOR, WHILE and IF‐
ELSE statement.

Task # 14: Use FOR loop to generate a single vector y, which is a digitized unit sine wave
with ten samples per cycles, with 100 elements.

8
Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

9
Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

10
Digital Signal Processing Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 02
Examine effects of sampling on analog signals

ANALOG TO DIGITAL CONVERSION:


Most signals of practical interest, such as speech, biological signals, seismic signals, radar
signals, sonar signals, and various communications signals such as audio and video signals, are
analog. To process analog signals by digital means, it is first necessary to convert them into
digital form, that is, to convert them to a sequence of numbers having finite precision. This
procedure is called analog‐to‐digital (A/D) conversion, and the corresponding devices are called
A/D converters (ADCs)

Conceptually, we view A/D conversion as a three step process. This process is illustrated in
figure 2.1

SAMPLING:
This is the conversion of a continuous time signal to a discrete time signal obtained by taking
“samples” of continuous time signal at discrete time instants. Thus, if xa(t) is the input to the
sampler, the output is xa(nT)≡x(n), where T is called the sampling interval.

QUANTIZATION:
This is the conversion of discrete time continuous valued signal into a discrete time discrete
valued (digital) signal. The value of each signal sample is represented by a value selected from a
finite set of possible values. The difference between the un-quantized sample x(n) and the
quantized output xq(n) is called the quantized error.

CODING:
In the coding process, each discrete value xq(n) is represented by a b‐bit binary sequence.

Figure 2.1: Basic parts of an analog‐to‐digital (A/D) converter.

There are many ways to sample an analog signal. We limit our discussion to periodic or uniform
sampling, which is the type of sampling used most often in practice. This is described by the
relation

( ) ( ) (2.1)
Where x(n) is the discrete time signal obtained by “taking samples” of the analog signal xa(t)
every T seconds. This procedure is illustrated in figure 2.2. The time interval T between
successive samples is called the sampling period or sample interval and its reciprocal 1/T=F s is
11
Digital Signal Processing Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

called the sampling rate (samples per second) or the sampling frequency (hertz).

Figure 2.2: Periodic sampling of an analog signal

Periodic sampling establishes a relationship between the time variables t and n of continuous time
and discrete time signals respectively. Indeed, these variables are linearly related through the
sampling period T or, equivalently, through the sampling rate Fs= 1/T, as

(2.2)

There exists a relationship between the variables F (or Ω) for analog signals and the frequency
variable ƒ (or ω) for discrete time signals. To establish this relationship, consider an analog
sinusoidal signal of the form
( ) ( ) (2.3)

Which, when sampled periodically at a rate Fs =1/T samples per second, yields

( ) ( ) ( ) . . // (2.4)

The frequency variables F and ƒ are linearly related as

(2.5)

Or, equivalently, as
(2.6)

The relation in (1) justifies the name relative or normalized frequency, which is sometimes used
to describe the frequency variable f. As (2.1) implies, we can use f to determine the frequency F
in hertz only if the sampling frequency Fs is known.
The range of frequency variable F or Ω for continuous time sinusoids is

(2.7)

(2.8)

However, the situation is different for discrete time sinusoids.

(2.9)

12
Digital Signal Processing Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

(2.10)

By substituting the given equations, we find that the frequency of the continuous time sinusoid
when sampled at a rate Fs=1/T must fall in the range:

(2.11)

Or, equivalently,

(2.12)

From these relations we observe that the fundamental difference between the continuous time
and discrete time signals is in their range of values of the frequency variables F and f, or Ω and
. Periodic sampling of a continuous time signal implies a mapping of the infinite frequency
range for the variable F (or Ω) into a finite frequency range for the variable f (or ). Since the
highest frequency in a discrete time signal is = π or f = 1/2, it follows that, with a sampling
rate Fs, the corresponding highest value of F and Ω are

(2.13)

(2.14)

EXERCISE:
Task # 1: Write a script to generate a continuous time sinusoid signal with amplitude=2 for
a time0 to 1 sec and taken the frequency as a user input by using input command.

Task # 2: Write a script to convert continuous time signal of task#1 to a discrete time signal
and take the sampling frequency as input which should be less than twice the maximum signal
frequency in Hertz.

Task # 3: Write a script to convert continuous time signal of task#1 to a discrete time signal
and take the sampling frequency as input which should be equal to twice the maximum signal
frequency in Hertz.

Task # 4: Write a script to convert continuous time signal of task#1 to a discrete time signal
and take the sampling frequency as input which should be greater than twice the maximum signal
frequency in Hertz.

Task # 5: Write a script using subplot command to generate task #1, task#2, task#3 and
task#4plots. Analyze the four plots, what happen by increasing the sampling frequency?

Task # 6: Consider the analog signal


( ) ( )
 Determine the minimum sampling rate required to avoid aliasing.
 Suppose that the signal is sampled at the rate Fs=200 Hz. What is the discrete time signal
obtained after sampling? Plot the discrete‐time signal.
 Suppose that the signal is sampled at the rate Fs=75 Hz. What is the discrete time signal
obtained after sampling? Plot the discrete‐time signal.

13
Digital Signal Processing Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

14
Digital Signal Processing Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 03
Examine effects of quantization on discrete time continuous signals

QUANTIZATION:
Digital signal is a sequence of numbers (samples) in which each number denotes a finite number
having finite precision.

The process of converting a discrete time continuous valued (DTCV) signal into a discrete time
discrete valued (DTDV) signal is known as Quantization. In this process each sample expresses
a value as finite (rather than infinite) number. The error introduced in representing the
continuous valued signal by a finite set of discrete value levels is called Quantization error or
Quantization noise.

We express the quantizer operation on the sampled signal x(n) as Q[x(n)] and the quantized
signal can be expressed as xq(n) which denotes the sequence of quantized samples at the
quantizer output. Hence
, ( )- (3.1)

The quantization error is a sequence eq(n) defined as the difference between the quantized value
and the actual sample value. Thus
( ) ( ) ( ) (3.2)
It is obvious that the signal cannot be processed by using calculator or digital computer since
only the first few samples can be stored and manipulated. For example, most calculators process
number with only eight significant digits.

We assume that we want to use only one significant digit. To eliminate the excess digit we either
simply discard them (truncation) or discard them by rounding the resulting number (rounding).
The resulting quantized signals xq(n) are shown by the numerical illustrations in the Table 3.1 as
below:

Table 3.1: Error Computation and Analysis

The values allowed in the digital signal are called the quantization levels whereas the
15
Digital Signal Processing Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

distance ∆ between two successive quantization levels is called quantization step size or
resolution. The rounding quantizer assigns each sample of x (n) to the nearest quantization
level. In contrast, a quantizer that performs truncation would have assigned each sample of
x(n) to the quantization level below it.
The quantization error eq (n) in rounding is limited to the range of -∆/2 to ∆/2, that is;
( ) (3.3)

The instantaneous quantization error cannot exceed half of the quantization step.
If xmin and xmax represent the minimum and maximum values of x (n) and L is the number of
quantization levels, then
(3.4)

The dynamic range of the signal is Xmax‐Xmin. In our example we have Xmax = 1, Xmin = 0, and
L = 11, which leads to ∆ = 0.1. Note that if the dynamic range is fixed, increasing the number of
quantization levels L results in a decrease of the quantization step size, thus the quantization error
decreases and the accuracy of the quantizer increases. In practice, we can reduce the quantization
error to an insignificant amount by choosing a sufficient number of quantization levels.

SQNR (SIGNAL TO QUANTIZATION RATIO)


The „quality‟ of the quantized signal is measured by the signal‐to‐quantization noise ratio
(SQNR) which is mathematically written as:
(3.5)
Where, Px and Pq are the average powers of the DTCV and quantized signals respectively, and
may be written as:
∑ | ( )| (3.6)

And,
∑ | ( ) ( )| (3.7)

EXERCISE:
Task # 1: Simulate a discrete time continuous valued (DTCV) sinusoid of 1/50
cycles/sample with length of the signal to be 500 & choose the no. of significant digits for round‐
off and apply to the signal generated above. Compute the error signals and SQNR.

Task # 2: For fo = 1/50 and N = 200, write a program to quantize the signal x (n), using

a) Truncation
b) Rounding to 64,128 and 256 levels. In each case plot the signals x (n), x q (n) and eq (n) and
also compute the corresponding SQNR

16
Digital Signal Processing Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

17
Digital Signal Processing Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

18
Digital Signal Processing Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 4
Examine Discrete Fourier Transform using butterfly method

DISCRETE FOURIER TRANSFORM:


The discrete Fourier transform (DFT) is one of the specific forms of Fourier analysis. It transforms
one function into another, which is called the frequency domain representation, or simply the DFT, of
the original function (which is often a function in the time domain). But the DFT requires an input
function that is discrete and whose non-zero values have a limited (finite) duration. Such inputs are
often created by sampling a continuous function, like a person's voice. And unlike the discrete-time
Fourier transform (DTFT), it only evaluates enough frequency components to reconstruct the finite
segment that was analyzed. Its inverse transform cannot reproduce the entire time domain, unless the
input happens to be periodic (forever). Therefore it is often said that the DFT is a transform for Fourier
analysis of finite-domain discrete-time functions. The sinusoidal basis functions of the decomposition
have the same properties.

Since the input function is a finite sequence of real or complex numbers, the DFT is ideal for
processing information stored in computers. In particular, the DFT is widely employed in signal
processing and related fields to analyze the frequencies contained in a sampled signal, to solve partial
differential equations, and to perform other operations such as convolutions. The DFT can be
computed efficiently in practice using a fast Fourier transform (FFT) algorithm.

In the context of fast Fourier transform algorithms, a butterfly is a portion of the computation that
combines the results of smaller discrete Fourier transforms (DFTs) into a larger DFT, or vice versa
(breaking a larger DFT up into sub transforms). The name "butterfly" comes from the shape of the
data-flow diagram in the radix-2 case, as described in the diagram. The same structure can also be
found in the Viterbi algorithm, used for finding the most likely sequence of hidden states.

Most commonly, the term "butterfly" appears in the context of the Cooley–Tukey FFT algorithm,
which recursively breaks down a DFT of composite size n = rm into r smaller transforms of
size m where r is the "radix" of the transform. These smaller DFTs are then combined via size-
r butterflies, which themselves are DFTs of size r (performed m times on corresponding outputs of the
sub-transforms) pre-multiplied by roots of unity (known as twiddle factors). (This is the "decimation
in time" case; one can also perform the steps in reverse, known as "decimation in frequency", where
the butterflies come first and are post-multiplied by twiddle factors)

Signal-flow graph connecting the inputs x (left) to the outputs y that depend on them (right) for a
19
Digital Signal Processing Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

"butterfly" step of a radix-2 Cooley–Tukey FFT. This diagram resembles a butterfly (as in the morpho
butterfly shown for comparison), hence the name, although in some countries it is also called the
hourglass diagram.

RADIX-2 BUTTERFLY DIAGRAM:


In the case of the radix-2 Cooley–Tukey algorithm, the butterfly is simply a DFT of size-2 that takes
two inputs (x0, x1) (corresponding outputs of the two sub-transforms) and gives two outputs (y0, y1)
by the formula (not including twiddle factors):

(4.1)

(4.2)

If one draws the data-flow diagram for this pair of operations, the (x0, x1) to (y0, y1) lines cross and
resemble the wings of a butterfly

More specifically, a radix-2 decimation-in-time FFT algorithm on n = 2 p inputs with respect to a


primitive n-th root of unity relies on O (n log n) butterflies of the form:

(4.3)

(4.4)
Where k is an integer depending on the part of the transform being computed. Whereas the
corresponding inverse transform can mathematically be performed by replacing ω with ω−1 (and
possibly multiplying by an overall scale factor, depending on the normalization convention), one may
also directly invert the butterflies:

( ) (4.5)

( ) (4.6)

Corresponding to a decimation-in-frequency FFT algorithm.

20
Digital Signal Processing Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Fig 4.1: A decimation-in-time radix-2 FFT breaks a length-N DFT into two length-N/2 DFTs followed
by a combining stage consisting of many butterfly operations.

EXERCISE:
Task # 1: Given a Sequence x(n), compute DFT of the sequence by DIT butterfly method on
Simulink.
a) X(n) = {4,-3,2,0,-1,-2,3,1}
b) X(n) = {1,1,1,1,1,1,1,1}
c) X(n) = {3,0,2,9}
d) X(n) = {9,12,6,2}

Task # 2: Prove above task on script file. Also perform these tasks via DIF method.

Task # 3: Given a sequence X[k] , Compute IDFT by using DIT butterfly method.

i) X[k] = {20 -4+6i -4 -4-6i}


ii) X[k] = {61 -2+5i -9 -2+5i}
iii) X[k] = {40 -6+i -10-2i 8-i -8+i -10+2i -6-i 60}

Task # 4: Prove above task on script File. Also perform these tasks via DIF method.

21
Digital Signal Processing Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

22
Digital Signal Processing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 5
Computation of Z – transform

FREQUENCY RESPONSE AND STABILITY CRITERIA OF Z –


TRANSFORM
There are numerous systems that are described by difference equations rather than differential
equations. In continuous systems, inputs and outputs are related by differential equations and
Laplace transform techniques are used to solve those differential equations. In sampled systems,
inputs and outputs are related by difference equations and Z-transform techniques are used to solve
those differential equations. Z-transform plays the role in sampled systems and represents systems
with transfer functions while Laplace transform plays the role in continuous systems and represent
systems with transfer functions.

Z- TRANSFORM:
Z-transform is discrete in nature or we can say that Z-transform operates in discrete time domain.
With the help of Z-transform we can check the stability of the systems such as filters, speech
processing systems, etc. The Z-transform, like many integral transforms, can be defined as either a
one-sided or two-sided transform. The bilateral or two-sided Z-transform of a discrete-time signal
x[n] is the function X(z) defined as

( ) * , -+ ∑ , - (5.1)

Where, n is an integer and z is, in general, a complex number

( ) (5.2)

Where, A is the magnitude of z, and φ is the complex argument (also referred to as angle or phase) in
radians. Alternatively, in cases where x[n] is defined only for n ≥ 0, the single-sided or unilateral Z-
transform is defined as

( ) * , -+ ∑ , - (5.3)

STABILITY CRITERIA FOR Z – TRANSFORM:


Once the poles and zeros have been found for a given Z-Transform, they can be plotted onto the Z-
Plane. The Z-plane is a complex plane with an imaginary and real axis referring to the complex-
valued variable z. The position on the complex plane is given by r℮^(jθ) and the angle from the
positive, real axis around the plane which is denoted by θ. When mapping poles and zeros onto the
plane, poles are denoted by an "x" and zeros by an "o".

Figure 5.1: Z-Plane


23
Digital Signal Processing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Where, r shows the factor of stability in Z transform as in this topic we are going to check the
relationship between Z transform and frequency response. If the poles lie inside the unit circle the
system is said to be stable, if the poles lies on the unit circle the system is said to be marginally stable,
and if the poles lies outside the unit circle the system will be unstable. The placement of poles and
zeros in the unit circle provides us the frequency response as well as the stability of the system.

ZPLANE: Z-plane zero-pole plot. ZPLANE (Z,P) plots the zeros Z and poles P (in column
vectors)with the unit circle for reference. Each zero is represented with an 'o' and each pole with an 'x'
on the plot. Multiple zeros and poles are indicated by the multiplicity number shown to the upper
right of the zero or pole.

Example: z = [1 2]; % coefficient of zeros


p = [1 0.9]; % coefficient of poles
zplane (z, p)

FUNCTIONS RELATED TO Z-TRANSFORM:


Following are the MATLAB commands which are related to the Z transform;

 freqz used for calculating / displaying frequency response


 impz used for calculating / displaying impulse response
 z place plots the zeros and poles with unit circle
 tf2zp finds zeros, poles and gain from H = B/A
 ZP2tf Transforms from zero, poles , gain back to t = B/A
 Residuez Finds residues, poles, direct terms of partial fraction
 Poly convert roots to polynomial
 Roots computes roots of a polynomial
 conv used for multiplying 2 polynomials A & B.

24
Digital Signal Processing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

EXERCISES:

Task # 1: Find out the zeros and poles of the following transfer functions by using „roots‟
command and also plot them by using „pzmap‟ command.

Task # 2: Use the „freqz‟ function to evaluate the frequency response of a Z–Transform
shown of task 1. Where -20 ≤ ω ≤ 20 is the frequency vector in radians/seconds. (Use “linespace”
function to generate a vector with 200 samples).
Hint: H = freqz (b, a, w)

Task # 3: For above task, also plot the magnitude response (in dB) and phase response (in
degree) by using the subplot command.

Task # 4: Write a MATLAB program to find poles and zeros of the system given by:
y(n) = x(n) + 2x(n-1) - 0.9y(n-1)

25
Digital Signal Processing Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

26
Digital Signal Processing Lab Session 06
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 6
Design and analyze digital FIR filter using MATLAB tools

ELECTRONIC FILTER:
Electronic filters are electronics circuits which perform signal processing functions, specifically to
remove unwanted frequency components from the signal and/or to enhance wanted ones. Electronic
filters can be:

 Passive or active
 Analog or digital
 High-pass, low-pass, band-pass, band-reject (notch), or all-pass
 Discrete time (sampled) or continuous time
 Linear or non-linear
 Infinite impulse response (IIR type) or finite impulse response (FIR type)

The most common types of electronic filters are linear filters, regardless of other aspects of their
design.

DIGITAL FILTERS
A digital filter is a system that performs mathematical operations on a sampled, discrete- time signal
to reduce or enhance certain aspects of that signal. This is in contrast to the other major type of
electronic filter, the analog filter, which is an electronic circuit operating on continuous-time analog
signals. An analog signal may be processed by a digital filter by first being digitized and represented
as a sequence of numbers, then manipulated mathematically, and then reconstructed as a new analog
signal. In an analog filter, the input is “directly” manipulated by the circuit.

In digital signal processing applications, it is often necessary to change the relative amplitudes of
frequency components or remove undesired frequencies of a signal. This process is called filtering.
Digital filters are used in a variety of applications. Digital filter design requires the use of both
frequency domain and time domain techniques. This is because filter design specifications are often
given in the frequency domain, but filters are usually implemented in the time domain with a
difference equation. Typically, frequency domain analysis is done using the Z-transform and the
Discrete Time Fourier Transform (DTFT).

In general, a linear and time invariant digital filter with input x(n) and output y(n) may be specified by
its difference equation.

( ) ∑ ( ) ∑ ( ) (6.1)

where bi and ak are coefficients which parameterize the filter. This filter is said to have N zeros and M
poles. Each new value of the output signal, y(n), is determined by the past values of the output and by
present and past values of the input. The impulse response, h(n), is the response of the filter to an input
of δ(n), and is therefore the solution to the recursive difference equation.

( ) ∑ ( ) ∑ ( ) (6.2)

27
Digital Signal Processing Lab Session 06
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

There are two general cases of digital filters: infinite impulse response (IIR) and finite impulse
response (FIR). The FIR case occurs when ak = 0, for all k. Such a filter is said to have no poles, only
zeros. In this case the above difference equation becomes:

( ) ∑ ( ) (6.3)

FIR DESIGN
There are numerous software packages available that will provide a necessary tools to design digital
filters, both FIR and IIR. In this lab, we will design our filter using the Filter Design and Analysis
Tool (fdatool) from MATLAB. The most straight forward way to start the tool is to type “fdatool” on
the command line in the main MATLAB window. This tool invoke MATLAB to generate the desired
filter coefficients according to our specifications. The GUI of this tool presaented in the figure below.
For more details, refer to Lab 7.

Figure 6.1: FDA Tool Graphical User Interface

28
Digital Signal Processing Lab Session 06
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

EXERCISE:

Task # 1: Design low pass filter with eleven filter length having cutoff frequency 0.25 KHz and
sampling frequency 8 KHz. Using rectangular, hamming and hanning window method.

Task # 2: Design high pass filter to meet the following specifications:


Cutoff frequency (fc) = 250Hz
Sampling frequency (fs) = 1KHz.
Filter length (N) = 8

Task # 3: Design a band pass filter for following specifications:


Upper cutoff frequency (fc1) = 100Hz
Lower cutoff frequency (fc2) = 200Hz
Sampling frequency (fs) = 1KHz.
Filter length (N) = 9

Task # 4: Obtain the coefficients of an FIR low pass filter to meet the following specifications
using
Linear phase method:
Stopband attenuation = 50dB
Passband ripple = 0.05dB
Sampling frequency = 8KHz
Passband frequency = 600Hz
Stopband frequency = 3400Hz

29
Digital Signal Processing Lab Session 06
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

30
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 7
Demonstrate DSP Design on FPGA using XILINX system generator
TOOLS:
 Matlab 2008b or newer version
 Xilinx ISE 12.1 or newer version
 Xilinx FPGA device

DESCRIPTION:
Xilinx offers a variety of high-quality state of the art products for DSP design. We will work with
field-programmable gate arrays (FPGAs). In order to do so, we need Simulink for development and
verification of the design and after functional verification by simulations, Xilinx System Generator
will translate our design into FPGAs. XSG will create the project files (HDL) that we can then
synthesize, simulate, implement and download to the FPGA with Xilinx ISE Project Navigator.

We will become familiar with the Xilinx tools using an example-based approach. For this purpose, we
will implement a digital filter using The Multiplier Accumulator (MAC) unit which is the basic
element to implement a Digital filter on a FPGA.

Use XSG under Simulink environment in Matlab to implement FIR Digital Filter.

 Type-I FIR Lowpass filter


 Filter of 6th order
 Use of multiple MACs to implement design.

STARTING SYSTEM GENERATOR


 To Start Xilinx System Generator, select Start Programs Development Xilinx ISE
Design Suite 12.4 or latest  System Generator  Xilinx System Generator.
 This will start MATLAB and Simulink simulation environment as shown in Figure 7.1.
 The Simulink library browser shows a list of all the different Toolboxes installed within
MATLAB. Xilinx System Generator components will appear under three categories:

1. Xilinx Blockset
2. Xilinx Reference Blockset
3. Xilinx XtremeDSP Kit

 The category Xilinx Blockset contains all the basic blocks used in various numbers of
applications and will be used in this lab.
 Create a new Simulink model by selecting File New  Model

31
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Figure 7.1: Simulink Model.

 In the library browser window, expand the Simulink Library, and click Sources
 Add the Sine Wave source on the worksheet: Scroll through the library to find the Sine Wave, left
click Sine Wave, and drag it onto the worksheet
 Add the Scope sink element and write it to the Sine Wave source on the worksheet: From
Simulink Simulink → Sinks, add the Scope block, and draw a wire from the Sine Wave to the
Scope block
 Assign a frequency of 2*pi*(1/150) to the Sine Wave element, show port data types, and change
simulation parameter‟s stop time to inf (infinity)
1. Double-click the Sine Wave block
The Block Parameters dialog box opens.
2. Change the frequency to 2*pi*(1/150) and click OK to close the dialog box
3. On the worksheet, go to Format → Port/Signal Displays and click Port Data Types.
The signal width is displayed on the wire as shown in the following picture
4. From your project sheet, pull down the Simulation menu and select Configuration
Parameters
5. From the Simulation Parameters dialog box, select Solver in the left hand window and
change the stop time to inf, and click OK.
This allows your simulation to run to infinity (until you manually stop the simulation).

 Parameterize the Scope block, and run the simulation


1. Double-click the Scope block
2. Click the Scope Parameters button
3. In the Scope Parameters box, set the time range to 500, and click OK
4. Run the simulation: From your Simulink project worksheet, click Start Simulation
button, or use Simulation → Start
5. On the Scope display, click Autoscale button so the output will fit into the Scope
6. View the Scope output

32
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

7. A smooth sine wave should fit into your space window. This is what you would
expect because you are running double-precision software simulation

Figure 7.2 Simulink Scope

THE XILINX BLOCK SET, GATEWAYS


Use the Xilinx Gateway In, Gateway Out, System Generator, and MUX blocks, as shown
below, which provide interface to Xilinx Blocksets in Simulink.

1. Using Simulation → Configuration Parameters dialog box, set the stop time to 500, and
click OK.
2. From the Xilinx Blockset (in the Simulink Library Browser), open Basic Elements and
drag the Gateway In block onto the design sheet. Droop it on the connection between the
Sine Wave and the output Scope. It will automatically insert itself.
3. Note: The Gateway In/Out blocks are required to convert double-precision floating point
numbers used by Simulink in a simulation to bit fix point numbers used by Xilinx blocks.
Thus, a conversion is required when communicating with Xilinx blocks and Simulink
blocks.
4. Double-click Gateway In to open the Block Parameters
5. Set the Number of bits to 8 and Binary Point to 2
6. Similarly, drag a Gateway Out block onto the sheet, and drop it between the Gateway In
block and the output Scope block
7. Add and connect a Simulink MUX between the Gateway Out and the Scope by using
Simulink → Signal Routing
8. Add an additional net between the Sine Wave and the MUX
9. Note: This will make the scope display both the double-precision sine wave and the user-
defined precision sine wave that has gone into and back out of the Xilinx gateways
10. Add a system generator token from the Xilinx Blockset → Basic Elements library to the
design
11. To view the number of signals going into the MUX, select Wide nonscalar lines, Signal
dimensions, and Port data types under the Format → Port/Signal Displays menu
33
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

12. Save above model with under File Save As with name sine_wave.

Figure 7.3: Port display settings


Note: Now look at your port types. Notice that the gateway in block has changed the signals
from double-precision to fixed-point types. Fixed-point looks like Fix_8_2 in this case.

Figure 7.4: View Signal on Simulink

ANALYZE PRECISION, QUANTIZATION AND SAMPLE RATE


Run the simulation with default settings and understand and understand the output. Change
the data type and simulate, and analyze the simulation output. Change the sampling period
from one to five and see effect on the quantization.

PREPARING SYSTEM GENERATOR FOR HARDWARE/SOFTWARE


CO-SIMULATION
In the previous section we verified the functionality of our simple DSP system using Simulink
simulation models. Usually several issues may arise when the model is transformed into
34
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

hardware. System Generator provides several methods to transform the models built using
Simulink into hardware. One of these methods is called Hardware/Software co-simulation.
Hardware/Software co-simulation enables building a hardware version of the model and using
the flexible simulation environment of Simulink. We can perform several tests to verify the
functionality of the system in hardware. HW/SW Co-simulation supports FPGAs from Xilinx
on boards that support JTAG or Ethernet connectivity. Several boards are predefined on
System Generator for co-simulation, rest can be defined by including required board files..
Follow following steps to setup chosen platform for HW/SW Co-Simulation.

 Double click on the System Generator block. A dialogue box will show up as shown in
Figure 5.5. This dialogue box allows you to select the type of the hardware generated
using system generator.
 In the compilation list select Hardware Co-Simulation Chosen FPGA  JTAG.
 Click Generate to build the hardware system. This step will generate a bitstream that will
later be used to configure the FPGA. ISE flow is used by System Generator to build this
bitstream. The progress of the process is displayed in the Compilation Status window

Figure 7.5: Compilation Status window


 When the compilation is complete, a new library is created including one block as shown
in Figure 7.6. The library name should be “sine_wave_hwcosim_lib" and the block name
should be “sine_wave_hwcosim" The block has one input and one output as required by
the DSP system. This block includes all the functionality required for the system to be
executed on the FPGA.
 Now we are ready to perform HW/SW Co-Simulation for our DSP system.
 Make a copy of the model generated “sine_wave_hwcosim" to the model sine_wave
replace all components as shown in figure 7.6.

35
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

 Double click on the “sine_wave_hwcosim"block. The block properties window will


appear as shown in Figure 7.6. Under the cable tab select Xillinx Platform USB. Click
OK.
 Now the design is ready for Co-Simulation. Click the Start Simulation button in the model
window toolbar to start the Co-Simulation. The System Generator will first download the
bitstream associated with the block “sine_wave_hwcosim”.
 When the download completes, System Generators reads the inputs from Simulink
simulation environment and send them to the design on the board using the JTAG
connection. System Generator then reads the output back from JTAG and sends it to
Simulink for displayed.
 After the simulation is completed the results should be displayed. We can verify the
results by comparing the simulation output to the expected output

Figure 7.6: JTAG cosimulation


IMPLEMENT A TYPE-I FIR FILTER
Implement a Type-I FIR Filter using Xilinx Blockset in Simulink. The design characteristics
are the following:

 Separate multiplier and accumulator per filter coefficient


 Low Pass Filter of order 6
 Coefficients generated using the FDA Xilinx Tool
 Sampling frequency of 1kHz
1. In the project sheet, select File → New → Model
2. A new Simulink project opens.
36
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

3. Add two Sine inputs to the worksheet.


4. Add the Sum block from the Simulink Math Operations Library and connect it to the

sine blocks.
Figure 7.7 FIR Filter model

5. Add the Xilinx Gateway in block.


6. Add the Delay block from the Basic Elements library of the Xilinx Blockset.
7. Add the Xilinx Constant Block from the Basic Elements Xilinx Blockset.
8. Add the Xilinx Multiplier Block form the Index Xilinx Blockset.
9. Repeat step 5, 6, 7.
10. Add the Xilinx Adder/Substractor from the Index Xilinx Blockset.
11. Repeat steps 5, 6, 7, 8 until the design looks like figure 7.7.
12. Add the Xilinx Gateway Out block
13. Add two Scope blocks and connect one to the sine inputs and the other to the output of
the Gateway out and the output of the Sum block.
14. To increase the number of inputs to the scope, double-click on it, on the menu click on
Parameters and change the number of axis.
15. Wire all the blocks and add the System Generator token from the Xilinx Basic
Elements Library as well as the FDA Tool from the Xilinx DSP Library.
16. The final diagram should look like Figure 7.7.

SIMULATE THE TYPE-I FIR FILTER USING SIMULINK


Configure the inputs and simulation parameters as specified below. Next, simulate the Filter
in Simulink and verify the design functionality.

 Two Sine inputs: low and high frequencies.


 16 bit input: signed data (2‟s complement) binary point 13, and sampling period of 0.001
seconds.
 Multiplier Block latency of 1 and Full precision.
 Lowpass Type-I FIR filter of order 6.
37
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

 Simulation parameters: Stop time 0.5 seconds.

1. Set the frequencies of the sine inputs. One to 5Hz and the other to 300 Hz
2. Configure the inputs by double-clicking the Gateway In blocks to open their
Parameters dialog box.
3. Set the Number of bits to 16 and the Binary Point to 14.
4. Set the Overflow to Saturate and Sample period to 0.001 seconds.
5. Design the 6th order low pass filter by double-clicking on the FDA Tool block
6. On Response Type choose Lowpass.
7. Set the Design Method to FIR and from the bottom down menu select Least-squares.
8. Set the Filter Order to 6.
9. On Frequency Specifications select Normalized for the units and set the wpass to 0.1
and the wstop to 0.25.

Figure 7.8: FDA tool


10. Click on the Design Filter button.
11. Click on the File menu → Export and the Export window appears. Choose Export to
Workspace and set the Variable Names to filter_coeff.
12. Click on Export botton.
13. On the Matlab workspace, double click the filter_coeff variable.
14. Click the View Menu → Numerical Array Format → long on Matlab.
15. Double click on the Xilinx Constant Block, set the Number of bits to 16, the Binary
Point to 14 and Signed (2‟s complement) type of data
38
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

16. On the same block, edit the Constant value to the values of the filter_coeff variable
accordingly to their position in the array.
17. Note: Do this for the seven coefficients. Do not change the order of the coefficients
since each one of them is associated to a specific delay value and keep in mind that
Matlab index start at 1 that corresponds to the first coefficient value which has no
delay.
18. Double click on the System Generator block and se the Simulink System Period to
1/1000.
19. Save the design on your work directory as Lowpass.mdl and run the simulation by
clicking on the Start Simulation button.
20. The graphs of the input and output should look like figure 7.9.
21. For Hardware/Software co-simulation follow the steps discussed in Preparing System
Generator for Hardware/Software Co-Simulation section.

Figure 7.9: Signal view

EXERCISE:
Task # 1: Implement the following Moving average filter on FPGA using XSG and
verify using hardware in a loop.
-1 -1 -1 a
In z z z
Gateway In a +b X >> 2 Out
Random b
Delay Delay1 Delay2 Gateway Out
Source
AddSub Shift

a a Out T ime
a +b a +b Scope
Gateway Out1
b b
Sy stem
Generator AddSub1 AddSub2

Gateway Out
Resource JT AG
Estimator Gateway In T ime
Co-sim
Gateway Out1 Scope1

Mov_avg_rand_noise
hwcosim

39
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

40
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 8
Demonstrate FIR filter using FIR compiler on XILINX FPGA

PROBLEM STATEMENT:
You are DSP Designer in a company. Your company is investigating using Digital Filters instead
of analog for its Security Tag detectors in an attempt to improve performance and reduce cost of
the overall system. This will enable the company to further penetrate the growing security
market space. The specification of the single channel, single rate filter is specified below:

• Sampling Frequency (Fs) = 1.5 MHz


• Fstop 1 = 270 KHz
• Fpass 1 = 300 KHz
• Fpass 2 = 450 Khz
• Fstop 2 = 480 KHz
• Attenuation on both sides of the passband = 54 dB
• Pass band ripple = 1
The company has chosen to go with FPGAs due to their flexibility and time to market and
performance advantages over DSP Processors. Your HDL design experience is limited and hence
XSG for DSP appears to be an excellent solution for implementing the filter in an FPGA.

Your manager has requested that you create a prototype of the filter to be implemented on their
target FPGA board that is almost complete. The prototype must be finished as quickly as
possible for the imminent Aggressive Security convention, which is the industry‟s largest
convention of the year, so it must not be missed.

Your manager has provided a starting model that includes input sources and output sink. Your
design must be simulated using a Random Source and the chirp from the DSP Blockset. To
analyze the output of the filter, input and output signals are displayed in a spectrum scope. A
spectrum scope is used to compare the frequency response of the fixed-point FIR filter, which
will be implemented in the FPGA.

Two different sources are used to simulate the filter:

• The chirp block, which sweeps between the specified frequencies of 0 to 750kHz
• The random source generator, which outputs a random signal of uniform distribution with a
range of 0 to 1. Uniform is a better choice to drive a fixed-point filter because it is bounded.

41
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

PROCEDURE

This lab comprises 3 primary steps:

• Generate coefficients for a FIR filter


• Model and simulate the FIR filter
• Finally, perform hardware-in-the-loop verification.

STEP 1: GENERATE COEFFICIENTS FOR THE FIR FILTER


Open a filter model from previous lab in Matlab. Add the FDA Tool block from the Xilinx
Blockset  DSP blockset to a design containing a DA FIR filter. Generate coefficients for the
FIR filter in the using the FDA Tool block for the following specifications.

• Fpass Sampling Frequency (Fs) = 1.5 MHz


• Fstop 1 = 270 kHz
• 1 = 300 kHz
• Fpass 2 = 450 kHz
• Fstop 2 = 480 kHz
• Attenuation on both sides of the passband = 54 dB
• Pass band ripple = 1

 Open the MATLAB command window by double-clicking on the MATLAB icon on your
desktop, or go to Start Menu  All Programs  MATLAB  R2010a or latest 
MATLAB R2010a or latest
 In Matlab, change directory to c:/xup/dsp_flow/labs/labnumber/
 Open the filter.mdl model from the MATLAB console window
 Add the FDATool block by from Xilinx Blockset  DSP to the design
 Enter the following filter parameters in the FDATool Design Filter window (Figure 14.1)

• Response Type: Bandpass


• Units: KHz
• Sampling Frequency (Fs) = 1.5 MHz
• Fstop 1 = 270 kHz Hint: Fpass 1 = 300 kHz
• Fpass 2 = 450 kHz
• Fstop 2 = 480 kHz
• Attenuation on both sides of the passband = 54 dB(Astop1 and Astop2 parameters)
• Pass band ripple = 1(Apass)

42
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Figure 8.1. Design a Filter in FDATool.

 Click the Design Filter button to determine the filter order. The spectrum window will be
updated and will look like as shown in Figure 14.2

Figure 8.2. Designed Filter’s Magnitude Response.

 Export the coefficients in the Workspace with Numerator variable name as Num (Figure 3)
using File  Export

Note: This will add Num variable in your MATLAB workspace. For a FIR filter, Num
represents coefficients that are used in the filter. This is also an optional step as the coefficients
are still available through the FDATool block

43
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Figure 8.3. Exporting Coefficients in the Workspace.

 Type Num in the MATLAB console window to see the list of coefficients
 Type max(Num) and min(Num) in the MATLAB console window to determine the
maximum coefficient value that adequately specifies the coefficient width and binary point

STEP 2: MODEL AND SIMULATE THE FIR FILTER


Add the FIR filter block from the Xilinx DSP library and associate the generated coefficients.
Simulate the design and verify functionality. Add the convert block on the output of the FIR
block to reduce the dynamic range. Simulate the design to verify functionality.

 Add the FIR (FIR Compiler 5.0) filter block from the Xilinx Blockset  DSP library to the
design and constant block from Xilinx Blockset  Basic Blocks
 Double-click the FIR block and enter the following parameters in the block parameter
window (Figure 14.4). Click OK.

Filter Specification
 Coefficients : xlfda_numerator(‟FDATool‟)
 Number of Coefficient Sets: 1
 Filter type: Single_rate
 Select format: Sample_Period
 Implementation
 Filter Architecture: Distributed Arithmetic

• Coefficient Structure: Inferred


• Coefficient Type: Signed

44
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

• Quantization: Quantize_only
• Coefficients Width: 12
• Coefficients Fractional Bits: 12

Figure 8.4. FIR Filter Block Parameters.

 Add and parameterize the constant block to Boolean and connect the blocks to have the
design resemble to Figure 14.5

Figure 8.5. FIR Filter Block Based Design Ready for Simulation.

 Double-click the Gateway In block and set the format to FIX_8_6 and sampling period to
1/1500000
 Select the Chirp Source and start the simulation
 Bring the scope to the front and verify that the signal coming out of the FIR filter has been
attenuated and they look like Figure 14.6 and Figure 14.7, below.

45
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Figure 8.6. Attenuation in Passband (Spectrum Scope).

Figure 8.7. Attenuation in Stopband (Spectrum Scope).

 Select the Random Source and run the simulation (Figure 8.8)

46
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Figure 8.8. Random Source (Spectrum Scope).

 Stop the simulation


 Add a Convert block (Xilinx Basic Elements) on the FIR output and configure it as FIX_8_6
with quantization as Truncate and Overflow as Wrap
Note: Your design should look like that shown in Figure 14.9.

Figure 8.9. Completed FIR Filter Design.

 Run the simulation using the Chirp signal and white noise inputs, noting the reduction in
dynamic range due to the reduced number of output bits. See Figure 8.10 and 8.11.

47
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Figure 8.10. Filter response due to chirp input.

Figure 8.11. Filter response due to white noise input.

48
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

STEP3: PERFORM HARDWARE-IN-THE-LOOP VERIFICATION


Using the System Generator token, generate the hardware and verify that the design works
through the hardware board. Simulate the design through Simulink.

 Save the model as bandpass_filter_hw.mdl


 Double-click the System Generator token and set the following parameters
In Compilation Window: Compilation: Hardware Co-Simulation  target FPGA  JTAG

o Synthesis Tool: XST


o Target Directory: c:/xup/dsp_flow/labs/labno/hwcosim (or ./hwcosim)
o Create Testbench: Unchecked
o Create Interface document: Unchecked In Clocking window
o Simulink system period: 1/1500000

 Leave rest of the settings to default and Click Apply


Note: Make sure the System Generator block‟s window shows chosen FPGA board as the
device.
 If the board is not existed, you have to install the plugin
 Click the Generate button
 A dialog box opens showing the compilation process progress as shown in Figure 14.12

Figure 8.12. Compilation Progressing in Command Window.

When the generation is successfully completed, a new Simulink library window will open up
and a compiled block with appropriate number of inputs and outputs will be displayed

Figure 8.13. Compiled Block Opened in a New Simulink Window.

49
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

 Copy the compiled block into the design and connect it as shown in Figure 14.14

Figure 14.14. Complete Design Ready for the Hardware in the Loop Simulation.
 Connect the hardware board and simulate the design through Simulink.
 Connect the power cable to the hardware board
 Connect the download cable between the board and PC
 Double-click on the hardware co-simulation block and select the Digilent USB JTAG Cable
from the cable tab, which is used for configuring the FPGA on the board
 Select random source and click the run button ( ) in the Simulink window to run the
simulation. The configuration bit file will be downloaded and a simulation will be run
 The simulation result in the output scope will display output of the Simulink simulator on the
top and the hardware output in the bottom plots (Figure 14.15)

50
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Figure 14.15. Simulation Result Showing Simulator’s Output on the Top and Hardware
Output at the Bottom.

 Click stop button and turn off the power


 Save the model

51
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

EXERCISE:
Task # 1: Based on the defined specifications, what is the minimum filter order?
Task # 2: Fill in following information related to the coefficients

a. Maximum value:
b. Minimum value:

Task # 3: Use the Resource Estimator block from XSG library to estimate the resources.

c. No. of Slices
d. No. of DSP48s
e. No. of registers
f. Min clock period

Task # 4: Generate Simulation Result Showing Simulator‟s Output on the Top and
Hardware Output at the Bottom. Paste the screen shot here.

52
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

53
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

54
Digital Signal Processing Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 09
Examine Aliasing Effect in Analog Signals

ALIASING EFFECT:
We only sample the signal at intervals. We don't know what happened between the samples. A crude
example is to consider a 'glitch' that happened to fall between adjacent samples. Since we don't measure
it, we have no way of knowing the glitch was there at all as shown in fig 9.1.

Figure 9.1: Basic view of sampling theorem

In a less obvious case, we might have signal components that are varying rapidly in between samples.
Again, we could not track these rapid inter‐sample variations. We must sample fast enough to see the
most rapid changes in the signal. Sometimes we may have some a priori knowledge of the signal, or be
able to make some assumptions about how the signal behaves in between samples. If we do not sample
fast enough, we cannot track completely the most rapid changes in the signal. Some higher frequencies
can be incorrectly interpreted as lower frequencies

Figure 9.2: Overlapping of High frequency signal into Low frequency signal (f s ≤ 2 fm)

55
Digital Signal Processing Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

In the fig 4.2:, the high frequency signal is sampled just under twice every cycle. The result is that each
sample is taken at a slightly later part of the cycle. If we draw a smooth connecting line between the
samples, the resulting curve looks like a lower frequency. This is called 'aliasing' because one frequency
looks like another.

Note that the problem of aliasing is that we cannot tell which frequency we have ‐ a high frequency looks
like a low one so we cannot tell the two apart. But sometimes we may have some a priori knowledge of
the signal, or be able to make some assumptions about how the signal behaves in between samples, that
will allow us to tell unambiguously what we have.

Nyquist showed that to distinguish unambiguously between the signal frequencies we must sample faster
than twice the frequency of the highest frequency component.

Figure 9.3: Reconstruction of signal with (fs = 2fm)

In the diagram, the high frequency signal is sampled twice every cycle. If we draw a smooth connecting
line between the samples, the resulting curve looks like the original signal. But if the samples happened to
fall at the zero crossings, we would see no signal at all ‐ this is why the sampling theorem demands we
sample faster than twice the highest signal frequency as it will avoids aliasing.

The highest signal frequency allowed for a given sample rate is called the Nyquist frequency. Actually,
Nyquist says that we have to sample faster than the signal bandwidth, not the highest frequency. But this
leads us into multirate signal processing which is a more advanced subject. Nyquist showed that to
distinguish unambiguously between all signal frequencies we must sample at least twice the frequency of
the highest frequency component.

56
Digital Signal Processing Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

EXERCISE:

Task # 1: Plot two CT signals of 10Hz and 110Hz for 0 < t < 0.2 sec. Sample at Fs = 100
Hz and plot them in discrete form.

Task # 2: For a CT signal: x(t) = sin (2πFot) whose sampled version will be:
x(n) = sin (2π t) where n is a set of integers and sampling interval Ts =1/Fs.

(i) Plot the signal x (n) for n = 0 to 99 for Fs = 5 kHz and Fo= 0.5, 2, 3 and 4.5 kHz. Explain
the similarities and differences among various plots.

(ii) Suppose that Fo = 2 kHz and Fs = 50 kHz.


a. Plot the signal x (n).
b. Plot the signal y (n) created by taking the even numbered samples of x(n).
c. Is this a sinusoidal signal? Why or why not? If so, what is the frequency?

57
Digital Signal Processing Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

58
Digital Signal Processing Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 10
Examine audio processing

AUDIO PROCESSING USING MATLAB:


To execute audio files using MATLAB commands and to observe a human generated audio signal on
time scope through Simulink. Audio signals, much like images, can undergo filtering. It is somewhat
easier to understand the impact of signal processing on audio, since audio needs not be translated from a
spatial to a frequency domain. To load a wave (PCM) audio file, MATLAB provides the function
wavread.

funky = wavread('funky.wav');
It's important to capture the sampling frequency at which the sound was recorded; otherwise the speed of
playback and result s of further processing is not guaranteed to be correct:

[funky, f] = wavread( 'funky.wav');

To play a wave file at sampling frequency f:


wavplay( funky, f);
To view the waveform, plot the wave. Since audio is represented with many thousand samples per
second, it may be required to plot small portions of the waveform at a time.

SPECTROGRAM
Two‐dimensional plots of audio waves can be used to easily identify magnitude; however, combined
frequency distributions and magnitudes are more easily viewed in a spectrogram:
spectrogram (funky, 512 , f);
where 512 is the number of samples that are used for the discrete Fourier Transform, and thus a grouping
factor of samples per column in the spectrogram image.

Figure 10.1: Spectrogram

59
Digital Signal Processing Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

INTRODUCTION TO SIMULINK
Simulink is a software package for modeling, simulating, and analyzing dynamical systems. It supports
linear and nonlinear systems, modeled in continuous time, sampled time, or a hybrid of the two. Systems
can also be multirate, i.e., have different parts that are sampled or updated at different rates.

For modeling, Simulink provides a graphical user interface (GUI) for building models as block diagrams,
using click-and-drag mouse operations. With this interface, you can draw the models just as you would
with pencil and paper (or as most textbooks depict them). Simulink includes a comprehensive block
library of sinks, sources, linear and nonlinear components, and connectors. To customize and create own
blocks S-Functions can be used, which is another skill.

MATLAB and Simulink are integrated; you can simulate, analyze, and revise your models in either
environment at any point.

GETTING STARTED WITH SIMULINK

OPENING SIMULINK LIBRARY BROWSER:


1. In the MATLAB command window write a command “Simulink” or click on Simulink icon
displayed at the toolbar. New Simulink window will be appeared click on library browser and
expand these libraries to access various Toolboxes, Blocksets and Simulink functions.

Fig. 10.2: Simulink Library Browse Fig. 10.3: Expended Libraries

60
Digital Signal Processing Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

2. Write “Simulink3” in Command Window to get Simulink Block Library. This is another way of
accessing Simulink Library. Double clicking each icon will open the corresponding library. Block
sets and Toolboxes can be opened in the same way.

Figure. 10.4: Simulink Block Library

Figure. 10.5: Simulink Library of Blocksets and Toolboxes

OPENING NEW SIMULINK MODEL:


Click to create a new model button on Simulink.

Fig. 10.6: Opening New model (.mdl file)

61
Digital Signal Processing Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

HUMAN GENERATED AUDIO SIGNAL USING SIMULINK


The blocks used to generate a human voice in Simulink are;

Unbuffer (DSP Block set):


Convert a frame to scalar samples output at a higher sample rate.

From Wave Device ( DSP Blockset):


It reads audio data samples from a standard Windows audio device in real time. Previously, only for
Win95/98/NT. Now MATLAB versions support up till Windows 7 (64 bit editions included)

To Wave file (DSP Blockset):


Writes audio data samples to a standard Windows PCM format ".WAV" audio file. Previously, only for
Win95/98/NT. Now MATLAB versions support up till Windows 7 (64 bit editions included).

TIME SCOPE (DSP BLOCKSET):

Provides real time monitoring of the output signal.

Figure 10.7: Simulink blockset for human generated audio signal

Figure 10.8: Time-scope view of human generated audio signal

62
Digital Signal Processing Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

EXERCISE:

Task # 1: Write a MATLAB script to accomplish the following tasks:


a. Record your utterance of "we" and play it backwards. Does it sound like "you"?
b. Record your utterance of "you" and play it backwards. Does it sound like "we"?
c. Record your utterance of "We are you" and play it backwards. What does it sound like?

Task # 2: Write a MATLAB script that can read the wav file "hello.wav" and display the following
information:
a. Number of sample points.
b. Sampling rate.
c. Bit resolution
d. Time duration of the recording (in terms of seconds)
Generate the output as following:
Information of Sound file "hello.wav"
Sample Points = 88200 samples
Sampling Rate = 44100 samples/sec
Bit Resolution = 16 bits/sample
Time Duration = 2 seconds

Task # 3: Write a MATLAB script to record your utterance of "today is my birthday". Try to
explain the playback effect you observe after you try the following operations on the
audio signals.
a. Multiply the audio signals by -1.
b. Reverse the audio signals in time axis.
c. Multiply the audio signals by 10.
d. Replace each sample by its square root.
e. Replace each sample by its square.

Task # 4: Write a MATLAB script to record your utterance with a sample rate of 32 KHz and 8-bit
resolution. Try to resample the audio signals at decreasing sample rates of 16 KHz, 8
KHz, 4 KHz, 2 KHz, 1 KHz, and so on. At which sample rate you start to have difficulty
in understanding the contents of the utterance?

Task # 5: Write a MATLAB script to resample the audio signals in "sunday.wav" such that new
waveform has a new sample rate of 11025. Plot these two waveforms and their absolute
difference by using subplot.

63
Digital Signal Processing Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

64
Digital Signal Processing Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 11
Explore time parameter and classify discrete time system

MANIPULATION OF THE TIME PARAMETER


In this Lab we will look at three signal operations affecting the time parameter of the signal; time shifting,
time scaling and time reversal. These operations are very common components to real-world systems and,
as such, should be understood thoroughly when learning about signals and systems.
Some common operations on signals affect the time parameter of the signal. One of these is time shifting
in which a quantity is added to the time parameter in order to advance or delay the signal. Another is the
time scaling in which the time parameter is multiplied by a quantity in order to dilate or compress the
signal in time. In the event that the quantity involved in the latter operation is negative, time reversal
occurs.

TIME SHIFTING:
Time shifting is, as the name suggests, the shifting of a signal in time. This is done by adding or
subtracting a quantity of the shift to the time variable in the function. Subtracting a fixed positive quantity
from the time variable will shift the signal to the right (delay) by the subtracted quantity, while adding a
fixed positive amount to the time variable will shift the signal to the left (advance) by the added quantity.
As shown in figure 11.1, f (t−T) moves f (t) to the right by T which is an example of delaying a signal.

Figure. 11.1: Time shifting of a signal

If a signal can be expressed in the form as shown below in equation 11.1, we say that x(t) is a time-shifted
version of s(t). An example of time shifting is also shown in figure 11.2 for graphical illustration.

Figure. 11.2: Time-shifting of a signal s(t)

Consider a simple function as shown in equations 11.1 below, when this function is shifted by t1=2
seconds it gives the equation 11.2 which is simply s(t) with its origin shifted to the right, or delayed, by 2
seconds.

s(t) = t 0≤t≤1 (11.1)


x (t) = s (t -2) = t - 2 0 ≤ t-2 ≤ 2
=t-2 2≤t≤3 (11.2)

65
Digital Signal Processing Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Similarly, shifting the function s(t) as shown in equation, by t1 = -1 seconds yields equation 3 which is
simply s (t) with its origin shifted to the left, or advance in time, by 1 second.

y (t) = s (t +1) = t + 1 0≤t+1≤1


=t+1 -1 ≤ t ≤ 0 (11.3)

A positive phase indicates a shift to the left whereas a negative phase indicates a shift to the right.

TIME SCALING:
Time scaling compresses or dilates a signal by multiplying the time variable by some quantity. If that
quantity is greater than one, the signal becomes narrower and the operation is called compression, while
if the quantity is less than one, the signal becomes wider and is called dilation.

Figure 11.3: Time scaling of a signal ‘f(t)’

TIME REVERSAL:
A natural question to consider when learning about time scaling is: What happens when the time variable
is multiplied by a negative number? The answer to this is time reversal. This operation is the reversal of
the time axis, or flipping the signal over the y-axis.

Figure 11.4: Reversal of the time axis

CLASSIFICATION OF DISCRETE TIME SYSTEMS

DISCRETE SYSTEMS & ITS PROPERTIES


A discrete-time system takes a sequence x(n) called excitation and transforms it into another sequence
y(n) (called response). A system which possesses both Linearity and Time invariance properties is known
as LTI system.

66
Digital Signal Processing Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

1- LINEARITY

The two conditions of linearity are additive rule and homogeneity rule shown in eq. 11.4 and eq. 11.5
respectively. These two criteria can be combined into one equation known as the ‘superposition
principle’ is shown in equation 9.6 and depicted in Figure 11.5.

y[n] = Sys { 1 [n] + 2 [n] } = Sys { 1 [n] } + Sys { 2 [n] } (11.4)

y[n] = Sys { α 1 [n] } = α Sys { 1 [n] } (11.5)

y[n] = Sys { α1 1 [n] + α2 2 [n] } = α1 Sys { 1 [n] } + α2 Sys { 2 [n] } (11.6)

Figure 11.5: Diagrammatic representation of Linearity property

2- TIME INVARIANCE

A system is called time invariant if its input-output characteristics do not change with time and a system
whose impulse response h(n) doesn‟t change with respect to time. The Condition for time invariance is
shown in eq 11.7. For the system to be considered time-invariant, the only effect of time-shifting the input
signal should be to cause an equal amount of time shift in the output signal shown in Figure 11.6.

Sys { 1 [n]} = y[n] implies that Sys 1 [n - k]= y[n - k] (11.7)

Figure 11.6: Diagrammatic representation of Time Invariance property

67
Digital Signal Processing Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

EXERCISES:

Task # 1: Write a script that delays the unit impulse by 5 samples.

Task # 2: Generate a script that uses user input to shift unit impulse right or left. Use MATLAB
input command to take the number of samples to shift the signal and use switch option or
If - else statement to decide whether to shift the signal to the right (delay) or to the left
(advance).

Task # 3: Repeat task # 2 with unit step response.

Task # 4: Create a function that flip the sequence first and then advance the sequence. The function
will receive two arguments as defined below, first is input signal which needs to be
flipped and then advances, and second is the number of samples by which the signal
should be advanced.
[x]= flipadv (u,s)

Task # 5: Generate a function that advances the sequence first and then flip the sequence. The
function will receive two arguments as defined below, first is input signal which needs to
be moved and then flipped, and second is the number of samples by which the signal
should be advanced.
[x]= advflip (u,s)

Task # 6: Create a Triangular wave with unit amplitude. Use subplot command to show the effect
of compression and dilation.

Task # 7: Generate a Square wave with amplitude from -5 to 5. Plot the signal which shows the
original signal along with its flipped signal.

Task # 8: Prove the Linearity property by using the following parameters


a) x1 = Unit Step (Step time = 1 & Final value = 1)
b) x2 = Unit Step (Step time = 5 & Final value = 3)
c) α1 = 1
d) α2 = 2
e) Sys(H) = x (n – 3)

Task # 9: Verify the Linearity property by using the following parameters


a) x1 = Unit Step (Step time = 1 & Final value = 1)
b) x2 = Unit Step (Step time = 5 & Final value = 3)
c) α1 = 7
d) α2 = 19
e) Sys(H) = 5 * X (n – 7)

Task # 10: Check whether the system and whose parameters are as follows, is Linear or not?
a) x1 = Unit Step (Step time = 1 & Final value = 1)
b) x2 = Unit Step (Step time = 5 & Final value = 3)
c) α1= 7
d) α2 = 19
e) Sys(H) = X2(n– 1)

68
Digital Signal Processing Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Task # 11: Check the property of Time Invariance on systems of task 1 to task 4. Also comment
whether the system is LTI or not?

Task # 12: By using hand calculations, prove that the results generated by SIMULINK are correct.
Check whether the systems of task 1 to task 4 are LTI or not?

Task # 13: Prove Linearity property by giving random signal and system as an input.

Task # 14: Design Time Invariance System by giving random signal and system.

69
Digital Signal Processing Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

70
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 12
Demonstrate TMS320C6713DSK processor and related software’s

REQUIREMENTS:
 PC with XP installation
 TMS320C6713DSK DSP starter kit
 MATLAB & Code Composer Studio (CCS)

DSP BOARD HIGHLIGHTS:


Texas Instruments TMS320C6713 DSP operates at 225 MHz, has following features:

 An AIC23 stereo codec


 8 MB of synchronous DRAM
 512 KB of non-volatile Flash memory
 4 user accessible LEDs and DIPs witches
 Configurable boot options
 Standard expansion connectors for daughter card
use
 JTAG emulation through on-board JTAG
emulator with USB host interface or external
emulator
 Single voltage power supply(+5V)

FUNCTIONAL OVERVIEW OF DSP BOARD:


 The DSP on the 6713 DSK interfaces to on-board peripherals through a 32-bit wide EMIF (External
Memory Interface).The SDRAM, Flash and CPLD are all connected to the bus.
 EMIF signals are also used for daughter cards. The DSP interfaces to analog audio signals through an
onboard AIC23 codec and four 3.5mm audio jacks (microphone input, line input, line output, and
headphone output). The codec can select the microphone or the line input as the active input. The
analog output is sent to both the line out and headphone out connectors. The line out has a fixed gain,
while the headphone out allows for an adjustable gain connectors.
 A device called a CPLD (Complex Programmable Logic Device) is used to implement logic that ties
the board components together.
 The DSK includes 4 LEDs and a 4 position DIP switch which allow for interactive feedback.
 Simulink communicates with Code Composer Studio through Real-Time Workshop. Code Composer
Studio communicates with the DSK through an embedded JTAG emulator with a USB host interface.
MATLAB communicates with CCS via Link for Code composer Studio. The DSK can also be used
with an external emulator through the external JTAG connector.

71
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

DSP BOARD COMPONENTS


DSP board components and their specifications are given in table below:

Components Details

TMS320C6416T DSP 1GHz MHz, fixed point, 1Mbyte internal RAM

CPLD Programmable "glue" logic

External SDRAM 16Mbytes, 64-bit interface

External Flash 512Kbytes, 8-bit interface


Stereo, 8KHz –96KHz sample rate, 16 to 32 bit samples, Mic, line-
AIC23 Codec
in, line-out and speaker jacks
4 User LEDs Writable through CPLD

4 User DIP Switches Readable through CPLD

8 Configuration Switches Selects power-on configuration and boot modes

Daughter card Expansion Interface Allows user to enhance functionality with add-on daughter cards

HPI Expansion Interface Allows high speed communication with another DSP
Provides high speed JTAG debug through widely accepted USB host
Embedded JTAG Emulator
interface
Table 12.1: 6416T DSK Specifications
CONFIGURATION SWITCHES
The 6416T DSK has 8 configuration switches that allow users to control the operational state of the DSP
when it is released from reset. The configuration switch block is labeled SW3 on the DSK board, next to
the reset switch. Configuration switch 1 controls the endianness of the DSP while switches 2 and 3
configure the boot mode that will be used when the DSP starts executing. Configuration switches 5-8
used to configure the EMIF and DSP frequencies.
The default configuration settings are to have all switches off. This configures the DSK to boot from the
on-board Flash in little endian mode.

Table 12.2: Configuration switch settings

72
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

The following table shows the switch position settings for desired CPU and EMIFA frequencies.

Table 12.3: CPU and EMIFA frequency configuration switch settings

AIC23 STEREO CODEC


The DSK uses a Texas Instruments AIC23 (part #TLV320AIC23) stereo codec for input and output of
audio signals. The codec samples analog signals on the microphone or line inputs and converts them into
digital data that can be processed by the DSP. When the DSP is finished with the data it uses the codec to
convert the samples back into analog signals on the line and headphone outputs so the user can hear the
output.
Four industry-standard 3.5mm stereo jack connectors are used in the audio interface:
 One jack is for connecting audio input from a microphone.
 One jack for connecting stereo audio line input.
 One jack for outputting stereo audio line output (un-amplified).
 One jack for connecting stereo audio output to a speaker (amplified).

USER LEDS
The four users controllable LEDs allow for user feedback and display of simple status information. They
are controlled by writing to the CPLD USER_REG register. They can also be set or cleared through the
LED Module of the Board Support Library.

73
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

STATUS INDICATORS
The status indicators monitor the following functions. The PWR LED is hardwired on the +5V supply and
will illuminate whenever the power is connected. The RESET LED illuminates when the RESET event
occurs. The USB_IN_USE LED is on when USB emulation is used and goes off when an external
emulator is applied. The USB BUSY LED indicates that a USB emulator transaction is in progress.

DIP SWITCHES
The four DIP switches allow simple feedback from the user. The DIP switches can be read through the
CPLD USER_REG register. They can also be read using the DIP Switch module of the Board Support
Library.

POWER SUPPLY
An included 5V external power supply is used to power the board. On-board voltage regulators provide
the 1.4V DSP core voltage, 3.3V digital and 3.3V analog voltages. A voltage supervisor monitors the
internally generated voltage, and will hold the board in reset until the supplies is within operating
specifications and the reset button is released. If desired, JP1, JP2 and JP4 can be used as power test
points for the core, I/O and system power supplies.

DSP BOARD FEATURES


The DSK supports a TMS320C6416T DSP which can operate at a clock frequency of up to 1 GHz. The
DSP core is designed for extremely high performance. Beyond the DSP core, the „6416 integrates a
number of on-chip resources that improve functionality and minimize hardware development complexity.
Features of the processor include:

EMIFA – EXTERNAL MEMORY INTERFACE A


A 64-bit bus on which external memories and other devices can be connected. It included features like
internal wait state generation and SDRAM control. The EMIF can interface to both synchronous and
asynchronous memories.

EMIFB – EXTERNAL MEMORY INTERFACE B


A 16-bit bus on which external memories and other devices can be connected. Similar to EMIFA but with
narrower bus width. Used for devices those are not as performance critical or do not require maximum
bandwidth.

MCBSPS – MULTICHANNEL BUFFERED SERIAL PORTS


Each McBSP can be used for high speed serial data transmission with external devices or reprogrammed
as general purpose I/Os. McBSP2 is used to transmit and receive audio data from the AIC23 stereo codec.
McBSP1 is used to control the codec through its serial control port. McBSP0 is always brought out to the
peripheral expansion connector. The MISC register in the CPLD is used to select whether McBSP1 and
McBSP2 are routed to the AIC23 or the expansion connectors.

74
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

1MBYTE INTERNAL MEMORY


High speed internal memory for maximum performance.

ON-CHIP PLL
Generate processor clock rate from slower external clock reference.

3 TIMERS
Generate periodic timer events as a function of the processor clock. Used by DSP/BIOS to create time
slices for multitasking.

EDMA CONTROLLER
Enhanced DMA controller allows high speed data transfers without intervention from the DSP.

ENDIANNESS
Endianness is a term that refers to the byte ordering of multi-byte data types. Specifically, a system is
called big endian if byte 0 contains the most significant byte of the data or little endian if byte 0 contains
the least significant byte. The 6416 supports both modes and the processor endianness can be controlled
at boot time through one of the configuration switches. The DSK default is little endian mode and all of
the DSK specific code examples are distributed in little endian format.

BASIC OPERATION OF THE BOARD:


 Connect the included power supply to the DSK.
 Connect the DSK to your PC with the USB cable.

INITIAL CONFIGURATION:
First perform the diagnostic test to check whether the board is properly connected & is not
defected (Caution: This test should not be performed frequent on kit, it may damage the kit)

Steps are as follows:


 Power up DSK and watch LEDs
 Power On Self Test (POST) program stored in
 FLASH memory automatically executes
 POST takes 10-15 seconds to complete
 All DSK subsystems are automatically tested
 During POST, a 1kHz sinusoid is output from the AIC23 codec for 1 second Listen with headphones
or watch on oscilloscope
 If POST is successful, all four LEDs blink 3 times and then remain on
 Install Code Composer Studio (CCS)

75
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

 Directions in “Quick Start Installation Guide”


 Diagnostic utility automatically installed

CODE COMPOSER STUDIO IDE:


 Connect power supply to DSK
 Wait for POST to complete
 Connect USB cable from PC to DSK
 If this is the first time connecting the DSK, you may be asked to install a driver. The driver is on
the Code Composer Studio CD and will automatically be found by Windows if the CD is in the drive.
 Launch Code Composer Studio C6713 DSK
 CCS will load and wait for your input

CONNECTING TO THE C6713 DSK:

76
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

OPENING AN EXISTING PROJECT


Project->Open

COMPILING/BUILDING A PROJECT
Project->Build (F7)

LOADING AND RUNNING A PROJECT ON THE C6713 DSK:


File-> Load Program (ctrl+L)

77
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Debug->Run (F5 or the Run button )

HALTING A RUNNING PROGRAM ON THE C6713 DSK:


Debug->Halt (shift+F5 or the Halt button). 

Exercise:
Task # 1: Write a brief report (2 to 3 pages) about your learning, observation and understanding of
this lab.

Task # 2: Blinks LED #0 at a rate of about 4 times per second using the LED module of the 6713
DSK Board Support Library. The example also reads the state of DIP switch #3 and lights LED #3 if the
switch is depressed or turns it off if the switch is not depressed.

78
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

79
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

80
Digital Signal Processing Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 13
Audio processing using DSK-6713 board

TOOLS:
 Code Composer Studio (latest verion)
 C-6713 DSK Board

DESCRIPTION:
This lab uses the AIC23 codec module of the 6713 DSK Board Support Library to generate a 1 KHz sine
wave on the audio outputs for 5 seconds. The sine wave data is pre-calculated in an array called sine
table. The codec operates at 48 KHz by default. Since the sine wave table has 48 entries per period, each
pass through the inner loop takes 1 millisecond. 5000 passes through the inner loop takes 5 seconds.

STEPS
1. Open the software install in your computer with icon on the desktop named 6713/6416 DSK CCS
(latest version).

2. Now select the 'Debug-->connect‟ option to built the project or either press 'Alt+C' (short key).

81
Digital Signal Processing Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

3. Now select the 'Project-->Open' from above to

4. A window will appear to open the project and Browse to your project destination and select
(tone.pjt) file. URL (C:\CCStudio\examples\dsk6713\bsl\tone.pjt)

82
Digital Signal Processing Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

5. After the selection of (tone.pjt) Project file, the project directories will appear in the left bar.

6. Now select the 'Project-->Built‟ option to built the project or either press 'F7' (short key).

7. After selecting the 'Built' option a window will appear in the bottom. The window will show the built
status and error if occurred during the built.

83
Digital Signal Processing Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

8. Now select 'project-->Compile File' option from the above toolbar or either press 'Ctrt + F7' (short
key) to compile the project.

9. The window will appear in the bottom which shows the compile status and error if occurred during
compilation.

10. Now select the 'File-->Load Program' option from the above toolbar or either press 'Ctrl + L'(short
key) to load the program.

84
Digital Signal Processing Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

11. A window will appear to select the (tone.out) file which is present in the 'Debug' folder of the
project location.

12. Now select the 'Debug-->Run' from the above toolbar or either press 'F5'(short key) to run the
program.
13. Finally the program will show the output on the DSP kit

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

85
Digital Signal Processing Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

EXERCISE:
Task # 1: Modify the C program by inserting this line of code to set the sampling rate to 8 kHz.
Build a new project and perform a real-time testing. After the program is running, compare the sound
effects for the sampling rates at 8 kHz and 48 kHz. What is the frequency of sine wave that you generated
with 8 kHz sampling rate? Why? Also, how many seconds the tone last? Why?

Task # 2: Now modify the previous program to generate 1 kHz sine wave on the audio outputs for
10 seconds.

86
Digital Signal Processing Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

87
Digital Signal Processing Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

88
Digital Signal Processing Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 14

Execute LED blinking program for DSK-6713 and 6416 board

The Board Support Library is divided into several modules, each of which has its own include file. The
file dsk6713.h must be included in every program that uses the BSL. This lab also includes
DSK6713_led.h and DSK6713_dip.h because it uses the LED and DIP modules. This lab blinks LED #0
at a rate of about 2.5 times per second using the LED module of the DSK6713 Board Support Library.
The example also reads the state of DIP switch #3 and lights LED #3 if the switch move up and down,
you will see LED #3 change with it. The purpose of this lab is to demonstrate basic BSL usage as well as
provide a project base for your own code.

STEPS:

1. Open the software install in your computer with icon on the desktop named 6713/6416 DSK
CCS(latest version).

89
Digital Signal Processing Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

2. Now select the 'Debug-->connect‟ option to build the project or either press 'Alt+C' (short key).

3. Now select the 'Project-->Open' from above toolbar.

90
Digital Signal Processing Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

4. A window will appear to open the project and Browse to your project destination and select (led.pjt)
file. URL (C:\CCStudio\examples\dsk6713\bsl\led\led.pjt)

5. After the selection of (led.pjt) Project file, the project directories will appear in the left bar.

6. Now select the 'Project-->Built' option to build the project or either press 'F7' (short key).

91
Digital Signal Processing Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

7. After selecting the 'Built' option a window will appear in the bottom. The window will shows the
built status and error if occurred during the built.

8. Now select 'project-->Compile File' option from the above toolbar or either press 'Ctrt + F7' (short
key) to compile the project.

9. The window will appear in the bottom which shows the compile status and error if occurred during
compilation.

92
Digital Signal Processing Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

10. Now select the 'File-->Load Program' option from the above toolbar or either press 'Ctrl + L'(short
key) to load the program.

11. A window will appear to select the (led.out) file which is present in the 'Debug' folder of the project
location.

93
Digital Signal Processing Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

12. Now select the 'Debug-->Run' from the above toolbar or either press 'F5'(short key) to run the
program.

13. Finally, the program will show the output on the DSP kit

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

94
Digital Signal Processing Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

EXERCISE:

Task # 1: Keeping in view the theory for sinusoidal wave generation, write a polling-based
program so that once dip switch #3 is pressed, LED #3 turns on and a 666.66 Hz
sinusoidal is generated for approximately 5 seconds. If it‟s again turned off, the sine wave
gets grounded (zero amplitude).

Task # 2: Connect MIC and Speakers to In and Out of DSP kit ports respectively. Now if you press
dip switch # 1, the MIC starts working and vice versa.

Task # 3: This lab blinks LED #2 at a rate of about 2.5 times per second using the LED module of
the DSK6713 Board Support Library. The example also reads the state of DIP switch #2
and lights LED #2 if the switch move up and down

95
Appendix
1. Basic functionalities of MATLAB

Defining a scalar:

x=1
Defining a column vector

v = [1;2;3]

Defining a row vector

w = [1 0 1]

Transpose a vector

W = w‟
Defining a range for a vector

X = 1:.5:5
Empty vector

Y=[]
Defining a matrix

M=[123;321]
Zero matrix

M = zeros(2,3) % 1st parameter is row, 2nd parameter is col.


ones matrix

m = ones(2,3)
The identity matrix

I = eye(3)
Define a random matrix or vector

R = rand(1,3)
Access a vector or matrix

R(3)
Access a row or column of matrix

I(2,:) %2nd row


Arithmetic operations

x=[ 1 2 3 4 5]

96
x= 2 * x
x= x / 2

y=[12345]
z=x+y
point by point mult/div use “.“

W = x.*y
Control Flow in MATLAB

To control the flow of commands, the makers of MATLAB supplied four devices a
programmer can use while writing his/her computer code
the for loops
• the while loops

• the if-else-end constructions

• the switch-case constructions

Syntax of the for loop is shown below

for k = array

commands

end

The commands between the for and end statements are executed for all %values stored in
the array.

Suppose that one-need values of the sine function at eleven evenly %spaced points n/10, for
n = 0, 1, …, 10. To generate the numbers in %question one can use the for loop
for n=0:10

x(n+1) = sin(pi*n/10);

end

x =

Columns 1 through 7

0 0.3090 0.5878 0.8090 0.9511 1.0000


0.9511
Columns 8 through 11
0.8090 0.5878 0.3090 0.0000
The for loops can be nested

H = zeros(5);

97
for k=1:5

for l=1:5

H(k,l) = 1/(k+l-1);

end

end

H=

1.0000 0.5000 0.3333 0.2500 0.2000


0.5000 0.3333 0.2500 0.2000 0.1667
0.3333 0.2500 0.2000 0.1667 0.1429
0.2500 0.2000 0.1667 0.1429 0.1250
0.2000 0.1667 0.1429 0.1250 0.1111
Syntax of the while loop is

while expression

statements
end

This loop is used when the programmer does not know the number of repetitions a priori.
Here is an almost trivial problem that requires a use of this loop. Suppose that the number is
divided by 2. The resulting quotient is divided by 2 again. This process is continued till the
current quotient is less than or equal to 0.01. What is the largest quotient that is greater than
0.01?

To answer this question we write a few lines of code

q = pi;

while q > 0.01

q = q/2;

end

q=

0.0061

Syntax of the simplest form of the construction under discussion is if


expression

98
commands

end

This construction is used if there is one alternative only. Two alternatives require the
construction

if expression

commands (evaluated if expression is true)

else

commands (evaluated if expression is false)

end

If there are several alternatives one should use the following construction

if expression1

commands (evaluated if expression 1 is true)

elseif expression 2

commands (evaluated if expression 2 is true)

elseif …

...

else

commands (executed if all previous expressions evaluate to false)

end

Syntax of the switch-case construction is

switch expression (scalar or string)


case value1 (executes if expression evaluates to value1)

commands

case value2 (executes if expression evaluates to value2)

commands
...

otherwise

99
statements

end

Switch compares the input expression to each case value. Once the %match is found it
executes the associated commands.

In the following example a random integer number x from the set {1, 2, … , 10} is generated.
If x = 1 or x = 2, then the message Probability = 20% is displayed to the screen. If x = 3 or 4
or 5, then the message Probability = 30 is displayed, otherwise the message Probability =
50% is generated. The script file fswitch utilizes a switch as a tool %for handling all cases
mentioned above

% Script file fswitch.

x = ceil(10*rand); % Generate a random integer in {1, 2, ... , 10} switch x

case {1,2}

disp('Probability = 20%');

case {3,4,5}

disp('Probability = 30%');

otherwise

disp('Probability = 50%');

end

Note: use of the curly braces after the word case. This creates the so called cell array
rather than the one-dimensional array, which %requires use of the square brackets.

6. Creating functions using m-files

Files that contain a computer code are called the m-files. There are two kinds of m-files: the
script files and the function files. Script files do not take the input arguments or return the
output arguments. The function files may take input arguments or return output arguments.
To make the m-file click on File next select New and click on M-File from the pull-down
menu. You will be presented with the MATLAB Editor/Debugger screen. Here you will
type your code, can make %changes, etc. Once you are done with
typing, click on File, in the MATLAB Editor/Debugger screen and select Save As… .
Chose a name for your file, e.g., firstgraph.m and click on Save. Make sure that your file is
saved in the directory that is in MATLAB's search path. If you %have at least two files with
duplicated names, then the one that occurs first in MATLAB's search path will be executed.
To open the m-file from within the Command Window type edit firstgraph %and then
press Enter or Return key.

100
Here is an example of a small script file

% Script file firstgraph.

x = -10*pi:pi/100:10*pi;

y = sin(x)./x;

plot(x,y)

grid

Enter this code in the MATLAB editor and save it as firstgraph.m. This function call be
called from command line as

firstgraph

Here is an example of a function file

function [b, j] = descsort(a)

% Function descsort sorts, in the descending order, a real array a.

% Second output parameter j holds a permutation used to obtain

% array b from the array a.

[b ,j] = sort(-a);

b = -b;

Enter this code in the MATLAB editor and save it as descsort.m . This function call be
called from command line as

X=1:10

descsort(X)

7. Graphs in MATLAB

save the script file and the run it

Script file graph1.

Graph of the rational function y = x/(1+x^2).

for n=1:2:5

n10 = 10*n;

101
x = linspace(-2,2,n10);

y = x./(1+x.^2);
plot(x,y,'r')

title(sprintf('Graph %g. Plot based upon n = %g points.' ...

,(n+1)/2, n10))

axis([-2,2,-.8,.8])

xlabel('x')

ylabel('y')

grid

pause(3)

end%Several graphs using subplot

graph1

Script file graph2.

Several plots of the rational function y = x/(1+x^2)

in the same window.

k = 0;

102
for n=1:3:10

n10 = 10*n;
x = linspace(-2,2,n10);

y = x./(1+x.^2);

k = k+1;

subplot(2,2,k)

plot(x,y,'r')

title(sprintf('Graph %g. Plot based upon n = %g points.' ...

, k, n10))

xlabel('x')

ylabel('y') axis([-2,2,-
.8,.8]) grid
pause(3);

end
graph2

Unit sample (impulse) sequence

>>n=-5:5; 0 n0
 [ n]  
>>x=[n==0]; 1 n0
>>stem (n,x)

103
Unit step sequence

>>n=-5:5; 0 n  0
u[n]  
>>x=[n>=0]; 1 n  0
>>stem (n,x)

Unit ramp sequence

>>n=-5:5;
>>x=n.*[n>=0];
>>stem(n,x)

Exponential sequences

>>n=-20:20;
>>x=(0.9.^n).*[n>=0]; x[n]  A n
>>stem(n,x)

Sinusoidal Sequences
>>n=-5:40; xn  coso n   
>>x=4*cos(0.1*pi*n+pi/3);
>>stem(n,x)

Illustration of the Sampling Process in the Time-Domain:


clf;
t = 0:0.005:1;
F =10;
Omega=2*pi*F; xa = cos(Omega*t);
subplot(2,1,1)
plot(t,xa);grid
xlabel('Time, msec');ylabel('Amp'); title('Conti-time signal x_a(t)');
axis([0 1 -1.2 1.2])
subplot(2,1,2);
Fs =20;
T = 1/Fs; n = 0:T:1;
w=2*pi*F;xs = cos(w*n);

k = 0:length(n)-1;
stem(k,xs);grid;
xlabel('Time index n');ylabel('Amp');title('Discrete-time signal x(n)');

104
axis([0 (length(n)-1) -1.2 1.2])
Change of Frequency of the signal and sampling frequency:

clf;
t = 0:0.005:1;
F =input('The frequency in Hz.=');
Omega=2*pi*F; xa = cos(Omega*t);
subplot(2,1,1)
plot(t,xa);grid
xlabel('Time, msec');ylabel('Amp'); title('Conti-time signal x_a(t)');
axis([0 1 -1.2 1.2])
subplot(2,1,2);
Fs =input('The Sampling frequency in Hz.=');
T = 1/Fs; n = 0:T:1;
w=2*pi*Fs;xs = cos(w*n);
k = 0:length(n)-1;
stem(k,xs);grid;
xlabel('Time index n');ylabel('Amp');title('Discrete-time signal x(n)');
axis([0 (length(n)-1) -1.2 1.2]);

Illustration of Aliasing Effect in Time-Domain:

clf;
t = 0:0.0005:1;f = 13;
xa = cos(2*pi*f*t);
subplot(2,1,1)
plot(t,xa);grid
xlabel('Time, msec');ylabel('Amplitude');
title('Continuous-time signal x_{a}(t)');
axis([0 1 -1.2 1.2])
subplot(2,1,2);
T = 0.1;f = 13;n = (0:T:1)';
xs = cos(2*pi*f*n);
t = linspace(-0.5,1.5,500)';
ya = sinc((1/T)*t(:,ones(size(n))-(1/T)*n(:,ones(size(t)))')*xs;
plot(n,xs,'o',t,ya);grid;

xlabel('Time, msec');ylabel('Amplitude');
title('Reconstructed continuous-time signal y_{a}(t)');

105
axis([0 1 -1.2 1.2]);

%Discrete Fourier Transform


k=0:3;
x=[1 1 2 2];
X=fft(x,4); % 4-point DFT of x:
subplot(211); stem(k,abs(X));
xlabel('k'); ylabel('Amplitude'); grid;
title(„DFT‟);
subplot(212); stem(k,angle(X));
xlabel('k'); ylabel('Phase'); grid;
amplitude obtained by dft
6
Amplitude

0
0 0.5 1 1.5 2 2.5 3
Time index n
phase obtained by dft
4

2
phase

-2

-4
0 0.5 1 1.5 2 2.5 3
Time index n

%Inverse-DFT
Y=[6.0000 , -1.0000 + 1.0000i , 0 , -1.0000 - 1.0000i];
y=ifft(Y,4);
n=0:3;
stem(n,y); grid
xlabel('Time index n'); title(„inverse DFT‟);

106
amplitude obtained by idft
2

1.8

1.6

1.4

1.2
Amplitude

0.8

0.6

0.4

0.2

0
0 0.5 1 1.5 2 2.5 3
Time index n

FIR Low pass filter design using the window method


B = FIR1(N,Wn) designs an N'th order lowpass FIR digital filter and returns the filter coefficients in
length N+1 vector B.
The cut-off frequency Wn must be between 0 < Wn < 1.0, with 1.0 corresponding to half the sample
rate.
By default FIR1 uses a Hamming window.

MATLAB CODE:
n=50; % Order 50
Wn=0.4; % Cut-off at normalized frequency 0.4 (digital frequency 0.4*pi)
b=fir1(n,Wn) % defaults to lowpass filter
[H,q]=freqz(b,1,512); % Note a=[1]
mag=abs(H); % Magnitude response
plot(q,mag,'.');
title(' fir1 filter, order=50, Wn=0.4*pi');
xlabel('Digital Frequency (rad/sample)');
ylabel(' Magnitude Response');

107
RUBRIC

Course Code: _______________ Week #: _______________ Lab #: _______________

Assigned task: __________________________________________________________________________________

______________________________________________________________________________________________

CRITERIA AND SCALES


Criterion 1: To what extent has the student organized the circuit components / hardware resources?
0 1-2 3-4
The circuit components / hardware The circuit components / hardware
The circuit components/ hardware
resources have been laid in a resources have been partially
resources have been well organized
haphazard manner organized
Criterion 2: Is the student at ease with handling of the equipment?
0 1-2 3-4
The student is not confident with the The student is confident to some The student is confident with the use
handling of equipment extent with the handling of equipment of equipment
Criterion 3: How well has the student interconnected the circuit components / hardware resources?
0 1-2 3-4
Student has no idea how to connect
Circuit components / hardware Circuit components / hardware
the circuit components / hardware
resources are not connected properly resources are properly connected
resources
Criterion 4: Has the student been able to achieve the desired outputs?
0 1-2 3-4
The task is incomplete, no outputs Task has partially been completed on Task has been completed on time,
have been achieved time, the outputs are erroneous desired outputs have been achieved
Criterion 5: How would you grade the interaction of the student with lab resources (lab personnel, participant students,
equipment)?
0 1-2 3-4
The student was aware of lab
The student took no notice of the lab The student effectively interacted
resources for a short period of time
resources with the lab resources
but was mostly unconcerned
Criterion 6: What is the student’s level of confidence with the Simulation Tool Interface, if used?
0 1-2 3-4 5
The student is familiar with The student is familiar with
The student is unfamiliar The student is proficient
the visible features of the the unexposed features of
with the tool with the tool
tool the tool

Total Marks: ________

Teacher’s Signature: _______________________________

108
RUBRIC

Course Code: _______________ Week #: _______________ Lab #: _______________

Assigned task: __________________________________________________________________________________

______________________________________________________________________________________________

CRITERIA AND SCALES


Criterion 1: To what extent has the student organized the circuit components / hardware resources?
0 1-2 3-4
The circuit components / hardware The circuit components / hardware
The circuit components/ hardware
resources have been laid in a resources have been partially
resources have been well organized
haphazard manner organized
Criterion 2: Is the student at ease with handling of the equipment?
0 1-2 3-4
The student is confident to some
The student is not confident with the The student is confident with the use
extent with the handling of
handling of equipment of equipment
equipment
Criterion 3: How well has the student interconnected the circuit components / hardware resources?
0 1-2 3-4
Student has no idea how to connect
Circuit components / hardware Circuit components / hardware
the circuit components / hardware
resources are not connected properly resources are properly connected
resources
Criterion 4: Has the student been able to achieve the desired outputs?
0 1-2 3-4
The task is incomplete, no outputs Task has partially been completed on Task has been completed on time,
have been achieved time, the outputs are erroneous desired outputs have been achieved
Criterion 5: How would you grade the interaction of the student with lab resources (lab personnel, participant students,
equipment)?
0 1-2 3-4
The student was aware of lab
The student took no notice of the lab The student effectively interacted
resources for a short period of time
resources with the lab resources
but was mostly unconcerned
Criterion 6: What is the student’s level of confidence with the Simulation Tool Interface, if used?
0 1-2 3-4 5
The student is familiar with The student is familiar with
The student is unfamiliar The student is proficient
the visible features of the the unexposed features of
with the tool with the tool
tool the tool

Total Marks: ________


Teacher’s Signature: _______________________________

109
RUBRIC

Course Code: _______________ Week #: _______________ Lab #: _______________

Assigned task: __________________________________________________________________________________

______________________________________________________________________________________________

CRITERIA AND SCALES


Criterion 1: To what extent has the student organized the circuit components / hardware resources?
0 1-2 3-4
The circuit components / hardware The circuit components / hardware
The circuit components/ hardware
resources have been laid in a resources have been partially
resources have been well organized
haphazard manner organized
Criterion 2: Is the student at ease with handling of the equipment?
0 1-2 3-4
The student is confident to some
The student is not confident with the The student is confident with the use
extent with the handling of
handling of equipment of equipment
equipment
Criterion 3: How well has the student interconnected the circuit components / hardware resources?
0 1-2 3-4
Student has no idea how to connect
Circuit components / hardware Circuit components / hardware
the circuit components / hardware
resources are not connected properly resources are properly connected
resources
Criterion 4: Has the student been able to achieve the desired outputs?
0 1-2 3-4
The task is incomplete, no outputs Task has partially been completed on Task has been completed on time,
have been achieved time, the outputs are erroneous desired outputs have been achieved
Criterion 5: How would you grade the interaction of the student with lab resources (lab personnel, participant students,
equipment)?
0 1-2 3-4
The student was aware of lab
The student took no notice of the lab The student effectively interacted
resources for a short period of time
resources with the lab resources
but was mostly unconcerned
Criterion 6: What is the student’s level of confidence with the Simulation Tool Interface, if used?
0 1-2 3-4 5
The student is familiar with The student is familiar with
The student is unfamiliar The student is proficient
the visible features of the the unexposed features of
with the tool with the tool
tool the tool

Total Marks: ________


Teacher’s Signature: _______________________________

110
RUBRIC

Course Code: _______________ Week #: _______________ Lab #: _______________

Assigned task: __________________________________________________________________________________

______________________________________________________________________________________________

CRITERIA AND SCALES


Criterion 1: To what extent has the student organized the circuit components / hardware resources?
0 1-2 3-4
The circuit components / hardware The circuit components / hardware
The circuit components/ hardware
resources have been laid in a resources have been partially
resources have been well organized
haphazard manner organized
Criterion 2: Is the student at ease with handling of the equipment?
0 1-2 3-4
The student is confident to some
The student is not confident with the The student is confident with the use
extent with the handling of
handling of equipment of equipment
equipment
Criterion 3: How well has the student interconnected the circuit components / hardware resources?
0 1-2 3-4
Student has no idea how to connect
Circuit components / hardware Circuit components / hardware
the circuit components / hardware
resources are not connected properly resources are properly connected
resources
Criterion 4: Has the student been able to achieve the desired outputs?
0 1-2 3-4
The task is incomplete, no outputs Task has partially been completed on Task has been completed on time,
have been achieved time, the outputs are erroneous desired outputs have been achieved
Criterion 5: How would you grade the interaction of the student with lab resources (lab personnel, participant students,
equipment)?
0 1-2 3-4
The student was aware of lab
The student took no notice of the lab The student effectively interacted
resources for a short period of time
resources with the lab resources
but was mostly unconcerned
Criterion 6: What is the student’s level of confidence with the Simulation Tool Interface, if used?
0 1-2 3-4 5
The student is familiar with The student is familiar with
The student is unfamiliar The student is proficient
the visible features of the the unexposed features of
with the tool with the tool
tool the tool

Total Marks: ________


Teacher’s Signature: _______________________________

111
RUBRIC

Course Code: _______________ Week #: _______________ Lab #: _______________

Assigned task: __________________________________________________________________________________

______________________________________________________________________________________________

CRITERIA AND SCALES


Criterion 1: To what extent has the student organized the circuit components / hardware resources?
0 1-2 3-4
The circuit components / hardware The circuit components / hardware
The circuit components/ hardware
resources have been laid in a resources have been partially
resources have been well organized
haphazard manner organized
Criterion 2: Is the student at ease with handling of the equipment?
0 1-2 3-4
The student is confident to some
The student is not confident with the The student is confident with the use
extent with the handling of
handling of equipment of equipment
equipment
Criterion 3: How well has the student interconnected the circuit components / hardware resources?
0 1-2 3-4
Student has no idea how to connect
Circuit components / hardware Circuit components / hardware
the circuit components / hardware
resources are not connected properly resources are properly connected
resources
Criterion 4: Has the student been able to achieve the desired outputs?
0 1-2 3-4
The task is incomplete, no outputs Task has partially been completed on Task has been completed on time,
have been achieved time, the outputs are erroneous desired outputs have been achieved
Criterion 5: How would you grade the interaction of the student with lab resources (lab personnel, participant students,
equipment)?
0 1-2 3-4
The student was aware of lab
The student took no notice of the lab The student effectively interacted
resources for a short period of time
resources with the lab resources
but was mostly unconcerned
Criterion 6: What is the student’s level of confidence with the Simulation Tool Interface, if used?
0 1-2 3-4 5
The student is familiar with The student is familiar with
The student is unfamiliar The student is proficient
the visible features of the the unexposed features of
with the tool with the tool
tool the tool

Total Marks: ________


Teacher’s Signature: _______________________________

112

You might also like