DSP Practical Workbook PDF
DSP Practical Workbook PDF
CS-419
Digital Signal Processing
Name : _____________________________
Year : _____________________________
Batch : _____________________________
Roll No : _____________________________
Department: _______________________________
Prepared by:
Revised in:
October 2019
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:
“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.
5 Computation of z – transform 23
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.
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.
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.
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.
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:
+ 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
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.
3
Digital Signal Processing Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
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
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
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.
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
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?
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
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.
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).
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)
(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)
(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?
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:
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.
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
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.
(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
(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)
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.
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
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)
( ) (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)
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.
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.
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 # 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.
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
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).
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
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.
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
35
Digital Signal Processing Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
sine blocks.
Figure 7.7 FIR Filter model
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.
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.
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:
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.
• 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
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)
42
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
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
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
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
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
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
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
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
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
48
Digital Signal Processing Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
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
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.
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.
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.
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.
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
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:
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.
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.
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.
61
Digital Signal Processing Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
62
Digital Signal Processing Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXERCISE:
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
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.
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.
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.
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.
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.
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.
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.
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.
67
Digital Signal Processing Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXERCISES:
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 # 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 # 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)
71
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Components Details
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.
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.
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.
74
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
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.
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)
75
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
76
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
COMPILING/BUILDING A PROJECT
Project->Build (F7)
77
Digital Signal Processing Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
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
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
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).
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]
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 = 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
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
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
H = zeros(5);
97
for k=1:5
for l=1:5
H(k,l) = 1/(k+l-1);
end
end
H=
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?
q = pi;
q = q/2;
end
q=
0.0061
98
commands
end
This construction is used if there is one alternative only. Two alternatives require the
construction
if expression
else
end
If there are several alternatives one should use the following construction
if expression1
elseif expression 2
elseif …
...
else
end
commands
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
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.
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
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
[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
for n=1:2:5
n10 = 10*n;
101
x = linspace(-2,2,n10);
y = x./(1+x.^2);
plot(x,y,'r')
,(n+1)/2, n10))
axis([-2,2,-.8,.8])
xlabel('x')
ylabel('y')
grid
pause(3)
graph1
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')
, k, n10))
xlabel('x')
ylabel('y') axis([-2,2,-
.8,.8]) grid
pause(3);
end
graph2
>>n=-5:5; 0 n0
[ n]
>>x=[n==0]; 1 n0
>>stem (n,x)
103
Unit step sequence
>>n=-5:5; 0 n 0
u[n]
>>x=[n>=0]; 1 n 0
>>stem (n,x)
>>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; xn coso n
>>x=4*cos(0.1*pi*n+pi/3);
>>stem(n,x)
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]);
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]);
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
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
______________________________________________________________________________________________
108
RUBRIC
______________________________________________________________________________________________
109
RUBRIC
______________________________________________________________________________________________
110
RUBRIC
______________________________________________________________________________________________
111
RUBRIC
______________________________________________________________________________________________
112