You are on page 1of 59

Electronic Laboratory Manual

EE-402 Signal Processing


Seventh Semester

Electronic Engineering Department

By
Irfan Ahmed Usmani (Assistant Professor)
Fawad Shaukat (Assistant Professor)
M. Fahad Wallam (Student, 2006 Batch)

Electronic Engineering Department


Sir Syed University of Engineering & Technology
University Road, Karachi 75300
http://www.ssuet.edu.pk/
SIR SYED University of Engineering & Technology, Karachi
Electronic Engineering Department

EE 402 Signal Processing

Contents

Lab Laboratory Exercises Page

Simulation based Labs


1 MATLAB Fundamentals 1
2 Continuous-Time Signals 4
3 Discrete-Time Signals 7
4 Sampling of Analog Signals 10
5 Convolution and Correlation 14
6 Discrete Fourier Transform 17
7 Filters 19
8 Introduction to Simulink 23

Hardware based Labs


9 Introduction to DSP Kit and related 26
Softwares
10 Building an Audio Effect Processor 34
11 i) LED Dancing Program 38
ii) Reading the Switch Value 39
12 i) Sound Playing Demo 42
ii) Digital Amplifier 43
13 i) Echo Generation 45
ii) Reverb Generation 47
14 i) Digital Sound Recorder 49
ii) PWM Generation 51
Signal Processing Lab 1

1 MATLAB fundamentals:

In this course we will use software MATLAB to implement and simulate digital signal processing
algorithms.
The name MATLAB stands for MATrix LABoratory. Originally MATLAB was developed to deal
with only one single but universal data type: the matrix.
A matrix is defined by [1]
• Its associated name
• The number of rows
• The number of column
• 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.
There is a small tutorial in this exercise for newcomer to become familiar with the MATLAB
fundamentals. It is recommended to try out introduced methods while solving the described tasks.

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

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

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

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

1
Signal Processing Lab 1

1.2.3 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 1 2 3 4 5 . ]
• 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 . ]
1.3 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.

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

2
Signal Processing Lab 1

• 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'
1.6 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
1.6.1 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.
1.6.2 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.

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


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

Exercise 1:
Task # 1: Try all help methods to get help of any function.
Task # 2: (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 # 3: Investigate the difference between multiplication ∗ and element-wise multiplication ⋅ ∗ of
vectors/matrices.
Task # 4: Generate a complex-valued matrix
a = ones(1,10) + i * (1 : 10)
and calculate the absolute square of all elements of all elements of this matrix.
Task # 5: Implement a function
[x]=sinewave(t)
which produces a sine wave of 1001 samples with spacing of ∆t = 1ms .
Task # 6: Use MATLAB help to get familiar with the syntax of FOR, WHILE and IF-ELSE statement.
Task # 7: Use FOR loop to generate a single vector y, which is a digitized unit sine wave with ten samples
per cycles, with 100 elements.

3
Signal Processing Lab 2

1 Continuous Time Signals:


1.1 Generation and Plotting of Continuous Time Signals:
A principle advantage of MATLAB in signal Processing is the simplicity with which signals of all types
can be generated and plotted. MATLAB supports a large variety of functions to visualize numerical data,
both as 2D and 3D graphs. The following basic features are often needed in our context of signal
processing:

• The function PLOT is the basic method for plotting 2D graphs.


• A single figure window can be split into several graphs with the SUBPLOT command.

Some examples will serve here to show how simple commands can readily be used to produce useful
signals and plots.

1.1.1. Sine Wave Generation:


The following commands will generate and plot 31 samples of a unit sine wave with a period of
6.28 samples.

» x=0:1.0:30;
» y=sin(2*pi*x/(2*pi));
» plot(y); grid on; title('Sine wave with period = 2pi');
» xlabel('Sample number'); ylabel('Amplitude')

[ ]
The first command establishes the vector x = 0,1,2.....30 . The next command generates the sine wave
vector y with the same number of elements as x . Note that the first index of y is 1, not 0, with period of
2π and a total of 31 samples, y consists of 4.75 cycles of the sine wave.
The Plot command, along with grid, title, xlabel and ylabel, causes the plot shown in the above figure.

With simple commands like these, one can usually create process and plot signals rapidly and efficiently.
Here are few more examples to generate and plot different signals.

1.1.2. Cosine wave:

» x=0:1.0:30;
» y=cos(2*pi*x/(2*pi));
» plot(y); grid on; title('cosine wave with period = 2pi');
» xlabel('Sample number'); ylabel('Amplitude')

4
Signal Processing Lab 2

1.2. Simultaneous Plot:

MATLAB provides facility to plot more than one signal on the same axis. One can plot multiple signals by
using a single Plot command or by holding the first signal plot before plotting the second signal. Hold on
and Hold off commands is used to hold the plot. Different colors and different line types can be used to plot
multiple signals on the same axis.

>> x=0:0.1:20;
>> y=sin(x);
>> z=cos(x);
>> plot(x,y,x,z)

Following sequence of commands also generate the same plot. This method holds first signal before
plotting the second signal.

>> plot(x,y)
>> hold on
>> plot(x,z,'g')
>> hold off

1.3. Sub plotting:


A single figure window can be split into several graphs with the SUBPLOT command. Here is an
example to get an idea about sub plotting.

>> t=linspace(0,20,300); %generates 300 equally spaced points between 0 and 20

>> x=sin(t);
>> y=cos(t);
>> z=tan(t);

5
Signal Processing Lab 2

>> subplot(2,2,1);
>> plot(t,x)
>> title('sine wave')
>> xlabel('time')
>> ylabel('Amplitude')

>> subplot(2,2,2);
>> plot(t,y)
>> title('cosine wave')
>> xlabel('time')
>> ylabel('Amplitude')

>> subplot(2,2,3);
>> plot(t,z)
>> title('tan wave')
>> xlabel('time')
>> ylabel('Amplitude')

Exercise 1:
Task#1: Investigate all the arguments (line type and line color) of Plot command by using MATLAB help.
Try to change the color and line type of the plot in the above examples.
Task#2: Investigate subplot command by using MATLAB help to understand the above example.
Task#3: Generate a decaying sinusoid with 1001 samples and spacing ∆t = 1ms . Plot the result with
reference to tome. Try to change the color and line type of the plot. Switch on the grid. Use xlabel,
ylabel and title commands to name the X-axis, Y-axis and the plot.
Task#4: Make a function to solve task#3 and call it from the workspace to get the plot.
Task#5: Write a function y=u(t) to plot the unit step function, defined as zero for input argument value less
than zero and one for input argument values greater than and equal to zero.
Task#6: Write a function y=rect(t) to plot the rectangular function, Uses the definition of rectangle
function in terms of unit step function.
Task#7: Write a function y=tri(t) to plot a triangular function, defined as 1-|t| for |t| ≤1 and zero otherwise.

6
Signal Processing Lab 3

1 Discrete-Time (DT) Signals:


A discrete-time signal x(n) is a function of an independent variable ‘n’, which is an integer. A
discrete-time signal is not defined at instants between two successive samples.

1.1. Discrete-Time Signal Functions:


Sinusoids are as important in DT signal and systems analysis as in CT signal and system
analysis. Sinusoids can be defined in a manner analogous to their CT counterparts as

⎛ 2πn ⎞
g[n] = A cos⎜ +θ ⎟
⎝ N ⎠
or g[n] = A cos(Ωn + θ )
or g[n] = A cos(2πfn + θ )
where:
A =real constant
θ =real phase shift, rad
N =Fundamental period, samples per cycles
and f and Ω are related to N through 1 / N = f = Ω / 2π .
There are some important differences between CT and DT sinusoids. The first is the fact that if
we create a DT sinusoid by sampling a CT sinusoid, their period may not be the same and, in
fact, the DT sinusoid may not even be period periodic. Let a DT sinusoid

g[n] = Acos(2πKn+)

1.2. Discrete-Time Signal Representation:


The following methods are use to illustrate the discrete-time signals:

1.2.1. Sequence representation:

{
x(n ) = K 3, − 1, 2, 1, − 3, 3, 1, K

}
Where arrow ( ↑ ) represents the reference time t=0
1.2.2. Functional representation:

⎧1 n = 0,3
⎪ −3 n =1


x(n ) = ⎨− 1 n = −2
⎪2 n = −1
⎪3 n = −3


1.2.3. Tabular representation:

n − 3 − 2 −1 0 1 2 3
x(n ) 3 −1 2 1 − 3 3 1
1 7
Signal Processing Lab 3

1.2.4. Simultaneous Plot:

1.3. Sub plotting:

Exercise 1:
Task#1: Investigate all the arguments (line type and line color) of Plot command by using MATLAB help.
Try to change the color and line type of the plot in the above examples.
Task#2: Investigate subplot command by using MATLAB help to understand the above example.
Task#3: Generate a decaying sinusoid with 1001 samples and spacing ∆t = 1ms . Plot the result with
reference to tome. Try to change the color and line type of the plot. Switch on the grid. Use xlabel,
ylabel and title commands to name the X-axis, Y-axis and the plot.
Task#4: Make a function to solve task#3 and call it from the workspace to get the plot.
Task#5: Write a function y=u(t) to plot the unit step function, defined as zero for input argument value less
than zero and one for input argument values greater than and equal to zero.
Task#6: Write a function y=rect(t) to plot the rectangular function, Uses the definition of rectangle
function in terms of unit step function.
Task#7: Write a function y=tri(t) to plot a triangular function, defined as 1-|t| for |t| ≤1 and zero otherwise.

2 8
Signal Processing Lab 3

3 9
Signal Processing Lab 4

4. Sampling of Analog Signals:


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 4.1

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.

2. 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 unquantized sample x(n) and
the quantized output xq(n) is called the quantized error.

3. Coding
In the coding process, each discrete value xq(n) is represented by a b-bit binary sequence.

xa(t x(n) xq( 01010...


Sampler n)
) Quantizer Coder

Analo Discrete Quantiz Digit


g time signal ed al
signal signal signal

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

x ( n ) = x a (n ), −∞ < n < ∞

10
Signal Processing Lab 4

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 4.2. The time interval T between
successive samples is called the sampling period or sample interval and its reciprocal 1/T=Fs is
called the sampling rate (samples per second) or the sampling frequency (hertz).

xa(t)
xa(t)
x(n) x(n)= xa(nT)

0 123456789 n
t
T 2T …5T……9T… t=nT

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

n
t = nT =
Fs
There exists a relationship between the variable 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

x a (t ) = A cos( 2 π Ft + θ )
Which, when sampled periodically at a rate Fs =1/T samples per second, yields

x a (nT ) ≡ x ( n ) = A cos( 2πFnT + θ )


2π nF
= A cos( +θ )
Fs

The frequency variables F and ƒ are linearly related as

F
f = (4.1)
Fs

or, equivalently, as

ω = ΩT (4.2)

11
Signal Processing Lab 4

The relation in (4.1) justifies the name relative or normalized frequency, which is sometimes used
to describe the frequency variable f . As (4.1) implies, we can use f to determine the
frequency F in hertz only if the sampling frequency Fs is known.

The range of the frequency variable F or Ω for continuous time sinusoids are

−∞ < F < ∞
−∞ < Ω < ∞ (4.3)

However, the situation is different for discrete time sinusoids.


−1 1
< f <
2 2
−π < ω < π (4.4)

By substituting from (4.1) and (4.2) into (4.4), we find that the frequency of the continuous time
sinusoid when sampled at a rate Fs=1/T must fall in the range

1 F F 1
− =− s ≤F ≤ s = (4.5)
2T 2 2 2T
Or, equivalently,
π π
− = −πFs ≤ Ω ≤ πFs = (4.6)
T T

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 values of F and Ω are

Fs 1
Fmax = =
2 2T
π
Ω max = πFs =
T

12
Signal Processing Lab 4

Exercise:

Task#1: Write a script to generate a continuous time sinusoid signal with amplitude=2 for a time
0 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#4
plots. Analyze the four plots, what happen by increasing the sampling frequency?
Task#6: Consider the analog signal
x a (t ) = 3 cos( 100 π t )
(i) Determine the minimum sampling rate required to avoid aliasing.
(ii) 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.
(iii) 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.
(iv) What is the frequency 0<F<Fs/2 of a sinusoid that yields samples identical to those
obtained in part (iii)? Give your observation regarding Aliasing effect.

13
Signal Processing Lab 5

5. Convolution and Correlation:


5.1 Introduction:
Convolution and Correlation are closely related operations that are basic to many areas of digital signal
processing.

Convolution can be described as the integral of the product of two data sequences, with one of the sequences
reversed and shifted relative to the other.

Correlation function of the two sequences is the same as the convolution without the reversal of one of the
sequences. It may therefore be described as the integral of the product of two sequences with one shifted
relative the other. The correlation function is used as a measure of how well two sequences are correlated, or
agree with one another, or are like one another.

5.2 Mathematical Form:


We assume that the two time series to be either convolved or correlated each have M samples and can be
designated as follows:

[xk ] = [x0 x1 x 2 L x M −1 ]

[y k ] = [y0 y1 y 3 L y M −1 ]

This notation implies that both sequences have the same length, which may not be the case and indeed is
rarely with FIR filtering, where the data sequence is usually much longer than the impulse response. When
the sequences are of different lengths, we use the convention of adding zeros to the right end of the shorter
]
sequence. For example, if an FIR filter with impulse response [hk and length 4 were processing an input
[ ]
signal x k of length M = 9, we would have

[xk ] = [x0 x1 x2 x3 x4 x5 x6 x7 x8 ]

[y k ] = [h0 h1 h2 h3 0 0 0 0 0]

[ ]
The convolution function of the two sequences x k and y k is obtained by[ ]
c xy (n ) = conv {[x k ], [ y k ]}
n
= ∑ x k y n −k
k =0

The function is referred to as the convolution sum of the inputs by the impulse response function and the
output is said to be given by the convolution of the input by the impulse response of the system.
This function may be extended to waveforms of infinite duration by writing them as


c xy (n ) = ∑x k y n −k
k =−∞

= xk ∗ hk

14
Signal Processing Lab 5

the generalized form of the convolution sum. In this equation ∗ is known as convolution star, signifies the
operation of convolution.

If the input consists of a continuous sequence of impulses then the above summation may be replaced by
integral.

+∞
c xy (t ) = ∫x τ y t −τ dτ
τ =−∞

This expression is known as convolution integral.

[ ] [ ]
The Correlation function of the two sequences x k and y k is obtained by

rxy (n ) = xcorr {[x k ], [ y k ]}


n
= ∑ xn y n+k
k =0

This function may be extended to waveforms of infinite duration by writing them as


rxy (n ) = ∑x k yn+k
k =−∞

• When [xk ] and [y k ] are different sequences, rxy (n ) is the cross-correlation function.
• When [xk ] and [y k ] are same sequences, rxx (n ) is the auto-correlation function.

15
Signal Processing Lab 5

Exercise:

{ }
Task#1: Two data sequences are given as follows:
xk = 1 2 3 1
= {1 − 1}

yk 2 1

Compute by hand the convolution function C xy (n ) .


Task#2: Use conv command to compute the convolution function for the given data sequence in Task#1.

Task#3: In MATLAB, conv command (function) neither provides nor accepts any timing information if the
sequences have arbitrary support. To solve this inconvenience, write a function
[y, ny] = conv_m(x, nx, h, nh)
a simple extension of MATLAB function conv, which performs the convolution of the given
sequences with their timing information.

Task#3: Repeat Task#2 using conv_m function.

Task#4: Compute the convolution function Cxy(n) of the following sequences:


{
xk = 0 0 1 0 2 0 0 − 1 0

}
yk = {0 0 1 0.8 0.6 0 0 0 0 }

Task#5: Compute by hand the complete autocorrelation function of


xk = {1 − 1 2 0 − 1 0 0 0}

Task#6: Use xcorr command to compute the autocorrelation function of the sequence given in Task#5.

Task#7: Calculate the energy of the given sequence in Task#5. Compare the result with its autocorrelation
function at n=0.

Task#8: Compute the cross correlation function rxy(n) of the given sequences in Task 4, for n = 0 through 4.

16
Signal Processing Lab 6

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

The sequence of N complex numbers x0, ..., xN−1 is transformed into the sequence of N
complex numbers X0, ..., XN−1 by the DFT according to the formula:

where is a primitive N'th root of unity.


The transform is sometimes denoted by the symbol , as in or or .

2. Inverse Discrete Fourier Transform:


The inverse discrete Fourier transform (IDFT) is given by

A simple description of these equations is that the complex numbers Xk represent the
amplitude and phase of the different sinusoidal components of the input "signal" Xn. The
DFT computes the Xk from the Xn, while the IDFT shows how to compute the Xn as a sum
of sinusoidal components with frequency k / N cycles per sample.

In Matlab DFT can be find by using following commands:


FFT(X): is the discrete Fourier transform (DFT) of vector X. For matrices, the FFT operation is
applied to each column. For N-D arrays, the FFT operation operates on the first non-
singleton dimension.
FFT(X,N): is the N-point FFT, padded with zeros if X has less than N points and truncated if it has
more.
FFT(X,[],DIM) or FFT(X,N,DIM): applies the FFT operation across the dimension DIM.

17
Signal Processing Lab 6

Exercise:

{ }
Task#1: Data sequence is given as follows:
xn = 1 0 0 1

Compute by hand the DFT function X k .


Task#2: Use FFT command to compute the DFT function for the given data sequence in Task#1.

Task#3: Plot the magnitude and phase graphs of DFT function of Task#2 in separate window.

n
Task#4: Plot a sequence. Where a=0.8 and define at n=0 to 35. Find its DFT, plot its magnitude and phase
graphs also.
Task#5: Taking the IDFT of the results of task #2 and verify that it gives you the same sequence as mention in
task#1.

Task#6: Design a DFT algorithm on C-language. The DFT is defined by the formula

18
Signal Processing Lab 7

Filters:

Electronic filters are electronic 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 (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
signal 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.

N −1 M
y(n) = ∑bi x(n − i) −∑ak y(n − k) (1)
i=0 k =1

where bi and ak are coefficients which parameterise 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 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.

N −1 M
h(n) = ∑biδ (n − i) −∑ak h(n − k) (2)
i=0 k =1

There are two general classes 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 difference equation in (2) becomes
N −1
h(n) = ∑biδ (n − i) (3)
i=0

19
Signal Processing Lab 7

Since (3) is no longer recursive, the impulse response is finite with length N.
In the case where ak ≠ 0 , the difference equation usually represents an IIR filter. In this case, (2) will usually
generate an impulse response which has nonzero values as n → ∞. However, later we will see that for certain
values of ak ≠0 and bi , it is possible to generate an FIR filter response.

The Z-transform is the major tool used for analysing the frequency response of filters and their difference
equations. The Z-transform of a discrete time signal, x(n), is given by


X ( z) = ∑ x ( n)
n = −∞
z −n (4)

The DTFT may be thought of a special case of the Z-transform, where z is evaluated on the unit circle in the
complex plane.

X (e jw ) = X ( z) | z=e jw

= ∑ x(n)
n=−∞
e jw (5)

From the definition of the Z-transform, a change of variable shows that a delay of K samples in the time
domain is equivalent to multiplication by Z-k in the Z-transform domain.

[z] ∞
x(n − k ) ⇔ ∑ x(n − k ) z −n
n=−∞

= ∑ x(m) z
m=−∞
−( m+k )

∑ x(m) z−m
(6)
−k
= z
m=−∞

= z −k X ( z)

We may use this fact to rewrite the equation (1) in the Z-transform domain, by taking Z-transforms of both
sides of the equation:

N −1 M
Y (z) = ∑bi z −i X (z) −∑ak z −k Y (z) (8)
i=0 k =1

20
Signal Processing Lab 7

M N −1
Y (z)[1+ ∑ak z −k ] = ∑bi z −i X (z) (9)
k =1 i =0

N −1

Y (z) ∑b i z −i
H (z) = = i=0
(10)
X (z) M
1 + ∑ ak z −k

k =1

From this form, we see that any filter, which can be represented by a difference equation, has a rational
transfer function (i.e. a transfer function which is a ratio of polynomials). From this result, we may compute
the frequency response of the filter by evaluating H(z) on the unit circle.

N −1

∑b i e − jw
H ( e jw ) = i=0
M (11)
1 + ∑ ak e − jwk

k =1

There are many different methods for implementing a general recursive difference equation. Depending on the
application, some methods may be more robust to quantisation error, require fewer multiplies or adds, or
require less memory. Fig. 1 shows a system diagram known as the direct form implementation; it works for
−1
any discrete time filter described by a difference equation. Note that the boxes containing the symbol z
represent unit delays, while a parameter written next to a signal path represents multiplication by that
parameter.

Figure 1: Direct form implementation for a discrete time filter described by a general difference equation

21
Signal Processing Lab 7

Exercise:

Task#1: Generate two sinusoid signals with frequency of 100 Hz and 400 Hz. Add these two signals. Design
a filter to extract 100 Hz signal.

Task#2: Taking the signals of Task#1, design a filter to extract 400Hz signal.

Task#3: Generate the code for the given FIR filter, having the coefficient b0=1, b1= -1 and b2=1. Taking
sinusoid as x(n) having 80 samples, frequency =1/8 and phase= pi/6.

y(n) = b0x(n) +b1x(n-1)+b2x(n-2)


Task#4 Generate the code for the FIR filter in Task#3, having the coefficient b0=1, b1= -1 and b2=2. Taking
impulse signal as x(n) having 16 samples.
Task#5: Generate the code for the given IIR filter, having the coefficient b0=0, b1= 1 and a0=1, a1=0.97.
Taking impulse signal as x(n) having 80 samples.

a=0.97

y(n) = x(n-1)+ ay(n-1)

22
Signal Processing Lab 8

1. 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). This is a far cry from
previous simulation packages that require you to formulate differential equations and difference
equations in a language or program. 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.

1.1. Getting Started with Simulink


1.1.1. Opening Simulink Library Browser:

1. In the Matlab command window click on the


Simulink Library Browser or just write
“Simulink” in Command window prompt.
Expending these libraries can access various
Toolboxes, Blocksets and Simulink
functions.

Fig. 1: Simulink Library Browser Fig. 2: Expended Libraries

2. Write “Simulink3” in CW to get Simulink Block Library. This is another way of access Simulink
Library. Double clicking each icon will open the corresponding library.

23
Signal Processing Lab 8

Blocksets and Toolboxes can be opened in the same way.

Fig. 3: Simulink Block Library

Fig. 4: Simulink Library of Blocksets and Toolboxes

1.1.2. Opening new Simulink model:

Click to create new model button on SLB.

Fig. 5: Opening New model


(.mdl file)

24
Signal Processing Lab 8

Exercise:
Task#1:
(a): Using Simulink, plot a sine wave between t=0s and t=10s.
(b): Using Simulink, plot a sine wave between t=0s and t=100s and also plot its Spectral
Density by setting Max step size to 0.02.

Task#2: Using Simulink, plot a Unit step Signal between t=0s and t=10s.

Task#3: Implement figure 6 in Simulink to understand the concept of synthesizing square wave.

Task#4: Implement the following continuous-time system with a Simulink model:


y(t) = 0.2x(t) +0.8 x(t -2) -0.4x(t -5)
Simulate the system between t=0s and t=10s with the following inputs:
a) x(t) = u(t) (Unit step)
b) x(t) = 2.5 sin(2*pi*f*t)

Task#5: Make a Simulink Model to record and write wave file from a wave device for the
duration of 10 sec at 8khz sampling rate and it also show its time plot.

25
Signal Processing Lab 9

1. Introduction to DSP Kit & related softwares:

1.1. Overview:
The purpose of this lab is to familiarize you with DSP Kit TMS320C6711, Simulink,
Real Time Workshop, Link for CCS and how they interact with Code Composer Studio
(CCS). This lab involves building relatively simple systems using Simulink rather than
CCS.

1.1.1. Hardware:

¾ DSP Board: Texas Instruments TMS320C6711 (DSP Starter Kit) DSK

• DSP: Fixed-point and floating-point arithmetic, eight functional units (two


multipliers and six ALUs), 150 MHz clock (up to 900 MFLOPS), 32 general-
purpose registers of 32-bit word length, 64K (+2x4K) bytes internal memory,
DMA controller (16 channels),external memory interface (32-bit address
space), multichannel serial port, host port interface.

• External Memory: 16M bytes SDRAM at 100 MHz and 128K bytes flash-
programmable ROM.

Figure 1: Hardware overview [2]

26
Signal Processing Lab 9

¾ Waveform Generator: Specifying Waveform Parameter Values

While working with the signal generator, you will often need to enter a value for a
parameter of the generated waveform. To do this, follow these instructions:

• Turn the knob on the front panel of the signal generator until you reach the
desired value. You can also specify which digit to modify by pressing the > or
< button. The flashing digit indicates the one that is incremented /
decremented if you turn the knob.

¾ Oscilloscope:

Triggering
The oscilloscope has rich triggering possibilities. Here we explain only the most
important features that might be necessary for accomplishing a particular task.

• Setting up an external trigger. Press Edge in the trigger section of the


oscilloscope's controls. Set triggering to external by pressing the
corresponding soft key Ext. Note, it is necessary to connect a BNC cable to
the Ext. Trigg. input on the scope's rear panel. We suggest to use external
triggering whenever it is possible.
• Setting up triggering to a corresponding input channel. Press Edge in the
trigger section and choose either channel 1 or channel 2 by pressing the
corresponding soft key.
Useful Features
There are also a number of very useful features that might help you.
• Averaging: a feature that allows you to get rid of random noise. The output
signal of the codec of our DSP board is relatively noisy. This is mainly caused
by higher frequency noise and cable connection imperfections.
To enable averaging, push Acquire in the Waveform section of the
oscilloscope's front panel. On the display, choose Averaging by pressing the
corresponding soft key. Turn the knob to set up an appropriate number of
triggering events to be averaged (usually 4 or 8 will already give a sufficient
noise removal).
• Auto scale: to quickly set up your oscilloscope, you can use auto scaling
which tries to determine the parameters automatically. Press Auto Scale to
enable it.
• Saving a screenshot: this feature allows you to save a screenshot of the
oscilloscope's display to a floppy disk as an image file. So you can easily
include it in your report. To enable this feature, you first have to set some
parameters: press Utility > Print Config. Set Print to=”Disk" and
Format=”TIF". Now, to save the display to a floppy disk, just insert one in the
internal floppy drive and press Quick Print.
• Saving oscilloscope's settings: this is a very useful feature that allows you to
store all current scope's settings in one of the three internal slots. You can
restore them whenever you need. You also have the possibility to save the
settings on a floppy disk. First, set up the oscilloscope's settings of your needs.

27
Signal Processing Lab 9

When ready, push Save/Recall >Save and then choose a slot by pressing the
To soft key or press New File to store onto a floppy disk. Push Press to Save
to actually save the settings. To restore saved settings, press Save/Recall
!Recall , choose source by pressing From, and push Press to Recall to actually
restore the saved settings.

1.1.2. Software

¾ Code Composer Studio:


• Before starting Code Composer Studio (CCS), ensure that the DSP board is
provided with power and connected to the PC.
• There should be an icon on the desktop. If necessary, start CCS from the Start
menu: Start >Programs >Texas Instruments >Code Composer Studio 2
('C6000)>Code Composer Studio.
• For more convenience, you should enable CCS to load a DSP program
automatically into the DSP's memory after a successful compilation/linking.
In CCS, choose Option>Customize. Press the Program Load Options tab and
put a check mark on “Load program after build". Press OK.

9 TMSC6000 Optimizing C Compiler


There are three possibilities to program TI's C6000 DSPs: Assembly, Linear
Assembly, and C/C++. In Assembly, you have to allocate every instruction to
one of the eight functional units and you should ensure that all eight units are
working concurrently permanently. In Linear Assembly and C/C++, the
optimizer takes this part. In this laboratory, we mostly use C/C++ and
sometimes hand-optimized assembly routines. C/C++ Data Types and Word
Lengths:
• char 8 bits
• short 16 bits
• int 32 bits
• long 40 bits
• oat 32 bits
• double 64 bits
• pointer 32 bits

9 Structure of a typical DSP Program for Real-Time Block Processing used


in this Laboratory

• main.c does the whole initialization and remains in an endless loop. The
function init()is called, where you can do additional initializations.

• blocks.h provides constants for the block processing environment

• isr_tttt.c contains the Interrupt Service Routine (ISR) which is triggered


by the DMA's hardware interrupt. It manages circular buffers the DMA
uses to transfer data between the memory and the codec and it calls the

28
Signal Processing Lab 9

function processing() where the actual signal processing happens. The tttt
is a substitution for the type of the actual working buffer (e.g. float or
short cmplx).
• vectors.asm is the interrupt vector table. There must be an entry for the
ISR above.
• lnk.cmd contains a memory map and arguments for the linker command
(e.g. libraries, heapsize, ...)
• userfiles The init() and processing() functions are defined here and all the
necessary (global) objects (e.g. additional buffers or filter coefficients).
• algorithm modules functions and structures for filters, _t, ...

9 Building a Program in CCS


We will provide you with most of the source code. You can find *.zip files for
the different experiments on our webpage psc.inw.tugraz.at/courses/dsplab/.
In your home directory, you have to create the folder L:/DSP LAB/ where for
each laboratory exercise you have to copy and unzip the required files. For
some of the experiments, you have to modify or add source code. All
necessary source files of a DSP program will be bundeled to a so-called
PROJECT.

• In the main menu, choose Project>Open and select the *.pjt file
appropriate for your exercise. In the Project view window you can see a
list of the source code files double-clicking opens the file in a text editor
window.

• To build a project, choose Project>Rebuild All from the main menu. This
will (re)compile all the files of the project, link them to the resulting *.out
file, and load it into the DSP's memory. It's also possible to do an
Incremental Build where only the modified files are compiled.

• To run a program, choose Debug>Run or press the F5 button. Remember


that the program must be successfully compiled, linked, and loaded into
the DSP's memory. Do not run the DSP without a program being loaded. It
might couse the DSP board or the the computer to halt.

For more convenience, we sometimes provide a WORKSPACE file. Using


such a file opens the specified projects and editor windows automatically. To
open such a *.wks file, click File>Workspace>Open .

9 Troubles with CCS>Known Bugs

• CCS built and loaded the interrupt-based program successfully but it


does not run properly.
Restart the DSP program: Debug>Restart.
This problem happens very often, especially when it is the first program
after starting CCS.

29
Signal Processing Lab 9

• Really nothing works any more.


Close (or kill) CCS, power-down and power-up the DSP board, and start
CCS again. This problem happens when a big amount of data is
transmitted through the parallel connection (e.g. while debugging).

9 Quick Test of DSK


Launch CCS from the icon on the desktop. Press GEL >Check DSK > Quick
Test. The Quick Test can be used for confirmation of correct operation and
installation. The following message is then displayed:

Switches: 7
Revision: 2
Target is OK

This assumes that the first three switches, USER_SW1, USER_SW2, and
USER_SW3,are all in the up (ON) position. Change the switches to (1 1 0 x)2
so that the first two switches are up (press the third switch down). The fourth
switch is not used. Repeat the procedure to select GEL > Check DSK > Quick
Test and verify that the value of the switches is now 3 (with the display
“Switches: 3”).You can set the value of the first three user switches from 0 to
7.Within your program you can then direct the execution of your code based
on these eight values. Note that the Quick Test cycles the LEDs three times.
A confidence test program example is included with the DSK to test and
verify proper operation of the major components of the DSK, such as
interrupts, LEDs, SDRAM, DMA, serial ports, and timers.

¾ Using DSP Kit via Matlab:


Simulink uses a block based approach to algorithm design and implementation.
Real-Time Workshop converts these Simulink models into ANSI C/C++ code
that can be compiled using CCS. The Embedded Target for TI C6000 DSP
provides the APIs (Advanced programming interface) required by Real-Time
Workshop to generate code specifically for the C6000 platform. Link for CCS is
used to invoke the code building process from within CCS to build an executable.
This code can then be downloaded on the target DSP from where it runs. This
approach allows for rapid prototyping. Also, a model built once in Simulink can
be made to run on various system as long as one has the appropriate Embedded
target toolbox.

9 Initial configuration (for all labs):


This section describes how configure Simulink and Real-Time Workshop
for use with the C6711 DSK. These configuration setting are required and
are similar for all the experiments. While this configuration generally has
to be done only once, it must be ensured that these setting do exist. This is
the first step in any experiment using Simulink.

9 Check if CCS is properly installed

30
Signal Processing Lab 9

To verify that CCS is properly installed on the system, enter ccsboardinfo


at the Matlab command line. Matlab should return information similar to
the following listing:

Board Board Proc Processor Processor


Num Name Num Name Type
--- --------------------------- --- --------------------------- --------------
0 C6711 DSK 0 CPU_1 TMS320C6x1x

• To ensure Embedded Target for TI C6000 DSP is installed, enter c6000lib

• Matlab should display the C6000 block library containing the libraries:
C6000: DSP Core Support, C62x DSP Library, C64x DSP Library, C6416
DSK Board Support, C6701 EVM Board Support, C6711 DSK Board
Support, C6711 DSK Board Support, RTDX Instrumentation,
TMDX326040 Daughtercard Support.

Figure 2: Software overview

9 Configuration Parameters for C6000 Hardware

1. Launch Matlab

2. At the Matlab command line, type simulink to launch Simulink

31
Signal Processing Lab 9

3. Create a new model in Simulink.

4. To open the Configuration Parameters, select Simulation!Configuration


Parameters
5. In the Select tree, chose the Real-Time Workshop category.

6. For Target Selection, choose the file ti c6000.tlc. Real-Time Workshop


will automatically change the Make command and Template makefile
selections.
7. Choose the Optimization category in the Select tree. For Simulation
and Code generation, un-select Block reduction optimization and
Implement logic signals....
8. Choose the TI C6000 target sel.... Set Code generation target type
to C6711DSK.
9. Choose the TI C6000 compiler. Set Symbolic debugging.
10. In the Select tree, choose the Debug category. Select Verbose build
here.
11. In the Select tree, choose the Solver category. Ensure that Solver is set
to Fixed type / discrete.

¾ Building a Simple I/O system with the C6711 DSK


To build the model for a Single Audio Effect, follow these steps:

1. Perform the steps in section ‘using DSP Kit via MATLAB’.


2. The DSK has two input and output jacks: Line Out, LineIn. The goal is to
implement a system that accepts an audio signal via the Line In jack and passes
that signal through, unchanged, to the Headphone/Line out jack.
3. Select the Simulink Library Browser window and select Embedded Target
for TI C6000. Within this group, select the C6711 DSK Board Support library.
There will be five (5) blocks displayed: ADC, DAC, LED, Reset, and Switch.
4. Place the ADC (Analog-to-Digital Converter) and DAC (Digital-to-Analog
Converter) blocks on your model by clicking and dragging.
5. Once they are on your model, connect the two, as shown in figure 3.

Line In
C6711 DSK C6711 DSK
ADC DAC

ADC DAC
Figure 3: Simple I/O

6. Double clicking a block displays the block parameters. While some parameters
are userdefinable, others are not. The ADC source field can beset to either Mic
In or Line In. If the input is from the microphone then the field should be set to
Mic In; otherwise, it should be set to Line In. In the ADC block, Stereo should
be unchecked and the output data type set to integer. NOTE: The sample rate

32
Signal Processing Lab 9

can also be set here. For most applications, this is either set to 8kHz (speech
applications) or 44.1kHz (music applications). The Samples per Frame
parameter tells the system how many samples to process at one time. The
greater the samples per frame, the longer it takes to process the signal (due to
memory needs and computational load).
7. Double click the DAC block. Ensure that the Word Length field is the
same (16-bit) for both the ADC and DAC blocks.
8. Save the model:
Select File > Save As > ...location
9. Ensure that the hardware is connected properly by:
(a) Connecting the microphone to the Mic In jack.
(b) Connecting the headphones to the Headphone jack.
10. The model is now complete and ready to run. Verify that the DSK board
is connected properly .Use the Incremental Build command on the Simulink
model toolbar (the icon with the 3 arrows) to begin compiling the model and
transferring the code to the DSK.
11. If this is the first time the board has been used since turning on the computer,
a DSK Startup window will open temporarily to configure the board.
12. The system will first compile code in Matlab, then Code Composer Studio
(CCS) will be opened, where assembly code will be compiled and loaded
onto the DSP. Once in CCS, a progress window will open as the code is
loaded onto the board.
13. The program, once loaded will begin to run. Test the model by speaking
into the microphone and listening to your speech through the headphones.
After verifying that the code works, stop the program by using the Halt
command in CCS. Close CCS and return to the model in Simulink.

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

33
Signal Processing Lab 10

1. Building an Audio Effect Processor:

1.1. Overview:
In this laboratory exercise, students will create an audio effects processor using
TMS320C6711.The effects that have to be implemented are echo, reverberation and
flange.

1.1.1. Designing a single echo effect in real time


In the previous lab, a basic I/O system for audio was built, compiled and run. This section
investigates data manipulation and representation on the DSK by designing a single echo
filter.

In this section, an echo filter is designed. An echo is a delayed, attenuated version of the
original signal. The difference equation describing a system with a single echo is defined
as

y[n] = x[n] + ax[n − D]

where a is the gain and D is the delay. Figure 1 shows the Simulink block diagram that
implements this filter.

1. Build and run the model in figure 1(using the Incremental Build button on the
model toolbar).
2. Add the C6711DSK target preferences block from the TI C6000 Target
Preferences block library. This block is not connected to any other block in the
model.
3. Test the model using the microphone (Mic In) and a pair of headphones
(Headphone).
4. Change the delay and gain by double clicking on the desired block and explore
the effect of each on the output signal.

Line In
C6711 Z-40 C6711
DSK DSK

Figure 1: Real time single echo filter [1]

34
Signal Processing Lab 10

1.1.2. Real time audio reverberation model


In this section a model that simulates audio reverberation is created and built.
Reverberation is the result of an infinite number of echoes added together, and can be
represented mathematically as

y[n] = x[n]+ax[n−D]−bx[n−D]

Where a and b are the gains and D is the delay.

For this experiment, a microphone is connected to the Mic In connector on the C6711
DSK and speakers (and an oscilloscope) connected to the Line Out connector on the
C6711 DSK. To test the model, speak into the microphone and listen to the output from
the speakers.

1. Open Simulink.
2. Create a new model by selecting File > New > Model from the Simulink
menu bar.
3. Use Simulink blocks to create the model shown in figure 2.
4. The Integer Delay block is in Discrete library of the Simulink blockset. The
Gain block is in the Commonly Used library of the simulink blockset. The Line
In and Line Out block for the C6711 DSK are in the C6711 Board Support
library of the Embedded Target for TIC6000 blockset.
5. From the TI C6000 Target Preferences block library, add the C6711DSK target
preferences block. This block is not connected to any other block in the model.
6. Click the C6711 DSK ADC block to select it. Select Block Parameters from the
Simulink Edit menu. Set the following parameters for the block:
• Select the +20 dB mic gain boost check box
• For Output data type, select Double from the list
• Set Scaling to Normalize
• Set Source gain to 0.0
• Enter 64 for Samples per frame
7. For ADC source, select Mic In.
8. Click OK to close the Block Parameters: ADC dialog.
9. Now set the options for the C6711 DSK DAC block.
• Set Scaling to Normalize
• For DAC attenuation, enter 0.0
• Set Overflow mode to Saturate.
10. Click OK to close the dialog.
11. Open the Configuration Parameters dialog, select Solver on the Select tree,
and set the appropriate options on the Solver pane for your model and for the
target.
• Under Solver options, select the fixed-step and discrete settings from the lists.
• Set the Fixed step size to auto and select Single Tasking for the Tasking mode.
12. Build and run the model (using the Incremental Build button on the model
toolbar).
13. Speak into the microphone connected to the board. The model should generate
a reverberation effect out of the speakers, delaying and echoing the words you
speak into the mic.

35
Signal Processing Lab 10

Audio Reverberation C6711 DSK Implementation

C6711 DSK
Line In DAC
C6711 DSK Z-20
ADC
Reset
C6711 DSK

Figure 2: Real time reverberation filter [1]

1.1.3. Real time audio flange model


A flange effect is a (time domain) audio effect, which is achieved by combining to
identical signal with each other, with one signal delayed by a gradually changing amount.
The difference equation for the flange effect is given by

y[n] = x[n] + ax[n − d(n)]

where the time varying delay is given by

d(n) = D + D2 (1 −sin( 2_fdnfs))

where D is a fixed delay, fd is the flanging frequency, and fs is the sampling rate. Figure 3
shows the Simulink block diagram that implements this system.

1. Build and run the model in figure 3 (using the Incremental Build button on the
model toolbar).
2. Add the C6711DSK target preferences block from the TI C6000 Target
Preferences block library. This block is not connected to any other block in the
model.
3. Test the system using recorded music or speech played through the Line In
connector of the DSK and a pair of headphones connected to the Headphone
connector.

36
Signal Processing Lab 10

Line In
C6711 DSK C6711 DSK
ADC DAC

Reset
C6711 DSK

Figure 3: Real time flange filter

Task:

Write a brief report (2 to 3 pages) about your learning, observations and understandings
of this lab.

37
Signal Processing Lab 11

1. The LED Dancing Program:

1.1. Program “Led.c”:

#include "stdio.h"
#define LED_OFF 0x07000000
#define msec 500
void main(void)
{
int LED[]={0x06000000,0x05000000,0x03000000};
short i=0,toggle=0;
comm_poll();
printf("The LED Dancing Program; Made By: M. Fahad Wallam");
led_control(LED_OFF);
while(1)
{
led_control(LED[i]);
delay_msec(msec);
if(i=2)
toggle=1;
else
toggle=0;
if(toggle=0)
i++;
else
i--;
}
}

1.2. How it works:

This is a simple LED-dancing program that demonstrate you how to control LEDs on the
DSK board. For controlling the LEDs the DSP processor must be in the 32-bit mode. You
also need to know the address of the IO port and the data bits to which the LEDs are
connected. But you do not have to worry

about all of it because I have written a function ‘void led_control(value)’ where ‘value’ is
the appropriate code for turning on/off the required LED. Below is the code for the
LEDs:

Codes Purpose
0x07000000 To turn off all 3 LEDs
0x06000000 To turn on the first LED
0x05000000 To turn on the second LED
0x03000000 To turn on the third LED

38
Signal Processing Lab 11

Remember: The LEDs are connected in the common anode configuration.

Like wise, I have also written the function ‘void delay(ms)’, where ‘ms’ is the argument
that represents time in milliseconds, to make your life easier. In the above program, I
have used the 500-millisecond time delay so that the turning on or off of an LED is
properly visible. Actually, the delay function uses the internal 32-bit timer (Timer 0) to
create delay. The rest of the program is very simple to understand if you properly learned
the C-programming language course in the second semester. To run this program
correctly you must include the following files:

1. C6xdsk.cmd
2. C6xdsk.h
3. C6xinterrupts.h
4. C6xdskinit.h
5. C6xdskinit.c
6. Vectors.asm (Note: you do not have to include Vectors_11.asm)
7. Ledcontrol.c
8. Delay.c
9. Rts6701.lib
10. Led.c

All the files are provided by the Texas except ‘ledcontrol.c’and ‘delay.c’ which is written
by myself. The description of all the files is given in the first chapter of the book
previously mentioned except ‘ledcontrol.c’ and ‘delay.c’. The ‘ledcontrol.c’ is used to
control the LEDs and the ‘delay.c’ is used to produce time delay.

2. Reading the Switch Value:

2.1. Program “Switch.c”:

#include "stdio.h"

void main(void)
{
unsigned short sw,temp=37;
comm_poll();
pritnf("The User Switches Reading Program; Made By: M. Fahad Wallam");
while(1)
{
sw=sw_read();
if(sw!=temp)
{
temp=sw;
printf("\nThe User Switch Value is %d",sw);
}
}
}

39
Signal Processing Lab 11

2.2. How it works:

It is also a very simple program that demonstrates how to read switch value from the
switches on the DSK board. For reading the Switches, again the DSP processor must be
in the 32-bit mode. You also need to know the address of the IO port and the data bits to
which the switches are attached. You also have to shift the bits in order to get correct
value. But do not get confused because I have also written a function ‘short
sw_read(void)’ that reads the switch value from the user switches and return it as a short
type. Below is the table for the switch values:

SW3 SW2 SW1 Value


Off Off Off 000
Off Off On 001
Off On Off 010
Off On On 011
On Off Off 100
On Off On 101
On On Off 110
On On On 111

To run this program correctly you must include the following files:

1. C6xdsk.cmd
2. C6xdsk.h
3. C6xinterrupts.h
4. C6xdskinit.h
5. C6xdskinit.c
6. Vectors.asm (Note: you do not have to include Vectors_11.asm)
7. Switch_read.c
8. Rts6701.lib
9. Switch.c

All the files are provided by the Texas except ‘switch_read.c’ and ‘switch.c’ that is
written by myself.

40
Signal Processing Lab 11

Tasks:

1. Write a program such that the first LED blinks three times, then second LED blinks
two times and then the third blinks only for one time. Reverse the order that is, the
third LED blinks for three times, then the second one blinks two times and the first
LED blinks one time. After that all three LED blinks three times. The process
continues indefinitely.

2. Write a program such that when the user presses the switches the LEDs will be turned
on according to the following table:

SW3 SW2 SW1 LED3 LED2 LED1


Off Off Off Off Off Off
Off Off On Off Off On
Off On Off Off On Off
Off On On Off On On
On Off Off On Off Off
On Off On On Off On
On On Off On On Off
On On On On On On

41
Signal Processing Lab 12

1. Sound Playing Demo:

1.1. Program “Sound.c”:

#include "stdio.h"

interrupt void c_int11()


{
output_sample(input_sample());
}

void main(void)
{
comm_intr();
printf("The Live Sound Playing Program; Made By: M. Fahad Wallam");
while(1)
{
}
}

1.2. How it works:

It is a very simple program. It gives the output same as the input. This program uses the
onboard TLC320AD535 (AD535) codec. It supports the sampling rates up to 16KHz but,
however, it is fixed at 8KHz on the board. It is interfaced with the serial port of the
processor. This program is an interrupt-based program. Every 125usec (1/8KHz) it gives
an interrupt. Upon receiving an interrupt, the processor jumps to the interrupt vector table
from where it gets the address of that interrupt and jumps to that address that is, here, it
jumps to c_int11() function. Now, here, the function ‘input_sample()’ reads the digital
value from the ADC and the function ‘output_sample()’ write the digital value (which is
read by the ‘input_sample()’ function) to the DAC.

To run this program correctly you must include the following files:

1. C6xdsk.cmd
2. C6xdsk.h
3. C6xinterrupts.h
4. C6xdskinit.h
5. C6xdskinit.c
6. Vectors_11.asm
7. Sound.c
8. Rts6701.lib

All the files are provided by the Texas except ‘sound.c’ that is written by myself.
You see how much it is simple!!!

42
Signal Processing Lab 12

2. Digital Amplifier:

2.1. Program “Digi_amp.c”:

#include "stdio.h"
short unsigned gain;
short output;

interrupt void c_int11()


{
output=gain*input_sample();
output_sample(output);
}

void main(void)
{
comm_intr();
printf("The Digital Amplifier; Made By: M. Fahad Wallam");
while(1)
{
}
}

2.2 Program “gain.gel”:

menuitem "Gain Adjustment"


slider Gain(0,40,1,1,gain_factor)
{
gain=gain_factor;
}

2.3. How it works:

It is also a very simple experiment just to show you how a gel (general extension
language) is used to make a slider bar. GEL (General Extension Language) is an
interpretive language that allows you to write functions to configure the CCS IDE as well
as access the target processor or simulator. It allows you to automate tasks similar to
macros, however, its C-like syntax

allows it to be much more powerful!!! GEL supports basic C constructs such as while
loops and if structures. In the “gain.gel” program, the “menuitem “Gain Adjustment””
creates a sub menu on the “gel” menu bar with the name “Gain Adjustment” but when it
will be loaded (from fileÆLoad Gel). Also, “slider Gain(1,40,1,1,gain_factor)” creates an
item “Gain” with in the “Gain Adjustment” sub menu. Parameters required by the slider
(from left to right) are: slider minimum value, slider maximum value, the change value
caused by an up or down click (or arrow keys) respectively and finally, the parameter to
which the slider value is assigned to.

43
Signal Processing Lab 12

To run this program correctly you must include the following files:

1. C6xdsk.cmd
2. C6xdsk.h
3. C6xinterrupts.h
4. C6xdskinit.h
5. C6xdskinit.c
6. Vectors_11.asm
7. Digi_amp.c
8. Rts6701.lib
9. gain.gel

All the files are provided by the Texas except ‘Digi_amp.c’ and ‘gain.gel’ that is written
by myself.

Task:
Write a program such that when the value on the slider bar is 1, 1Khz sine wave will be
produced, when the value on the slider bar is 2, 2Khz sine wave will be produced, when
the value on the slider bar is 3, 3Khz sine wave will be produced, when the value on the
slider bar is 4, 4Khz sine wave will be produced, when the value on the slider bar is 0, no
output will be produced. For the generation of sine wave program see the example 1.1 in
the book previous mentioned.

44
Signal Processing Lab 13

1. Echo Generation

1.1. Program “Echo.c”:

#include "stdio.h"
#define bufferlength 3000
#define amplitude 5;
short input;
int output;
int buffer[bufferlength];
short i = 0;

interrupt void c_int11()


{
input = input_sample();
output=input + 0.1*amplitude*buffer[i];
buffer[i] = input;
output_sample(output);
i++;
if (i >= bufferlength)
i = 0;
}

void main(void)
{
comm_intr();
printf("The Echo Generation; Copied from the book written by Rulph Chassing");
while(1)
{
}
}

1.2. How it works:

This experiment demonstrate you the power of DSP. The basic purpose of this program is
to introduce the sound processing techniques. The soul of the whole program is in the
expression given below:

Outputt = input + 0.1*amplitude*buffer[i];


buffer[i] = input;

To explain these expression please analyze the following block diagram. Believe me, this
is the best way to understand. I have also visualized it with the help of the following
block diagram:

45
Signal Processing Lab 13

The above figure is the block diagram of the Echo. In the above program, the delay factor
is calculated as:

Delay = 3000x125usec
Delay = 375 msec

Here, 125usec is the sampling time of the ADC and 3000 is the “bufferlength” of the
array, which is used as a delay-multiplying factor. You can see the effect by changing the
value of the “bufferlength” which is 3000 in above program. You can also change the
value of the “amplitude” which is 5 in the program.

To run this program correctly you must include the following files:

1. C6xdsk.cmd
2. C6xdsk.h
3. C6xinterrupts.h
4. C6xdskinit.h
5. C6xdskinit.c
6. Vectors_11.asm
7. Echo.c
8. Rts6701.lib

46
Signal Processing Lab 13

2. Reverb Generation:

2.1. Program “Reverbation.c”:

#include "stdio.h"
#define bufferlength 3000
#define amplitude 8;
short input;
int output;
int buffer[bufferlength];
short i = 0;
float old;

interrupt void c_int11()


{
input = input_sample();
old=(float)buffer[i]*0.1*amplitude;
output=(int)input+(int)old;
buffer[i]=output;
output_sample(output);
i++;
if (i >= bufferlength)
i = 0;
}

void main(void)
{
comm_intr();
printf("The Reverb Generation; Made By: M. Fahad Wallam");
while(1)
{
}
}

2.2 How it works:

Reverberation is the result of the many reflections of a sound that occur in a room. This is
also a very simple program. If you have understood the last program, it is not difficult for
you to understand this program; otherwise, you will find yourself to thrash your head
with this program. Well, lets try to understand this program. Same as in the previous
program, the spirit of the whole program is in the expressions given below:

old=(float)buffer[i]*0.1*amplitude;
output=(int)input+(int)old;
buffer[i]=output;

To explain these expressions please try to analyze the following block diagram again.

47
Signal Processing Lab 13

You have clearly noticed that the difference between the echo and reverberation is that
there is a positive feed back with the delay element in the reverberation while there is
only the delay element in the echo. The same analyzes is true for the case of
reverberation as that in the echo but remember the positive feed back path. Calculation of
delay element is also same as that in the case of echo.

To run this program correctly you must include the following files:

1. C6xdsk.cmd
2. C6xdsk.h
3. C6xinterrupts.h
4. C6xdskinit.h
5. C6xdskinit.c
6. Vectors_11.asm
7. Reverberation.c
8. Rts6701.lib

All the files are provided by the Texas except ‘Reverberation.c’ that is written by myself.

Task:

Write a program to produce the flange and chorus effect.

48
Signal Processing Lab 14

1. Digital Sound Recorder:

1.1. Program “digi_rec.c”:

#include "stdio.h"
#define N 8000*8;
unsigned short sw,i,j;
far short buffer[N];

interrupt void c_int11()


{
if(sw==0)
output_sample(input_sample());
else if(sw==1 && i<N)
{
buffer[i]=input_sample();
i++;
}
else if(sw==2 && j<=i)
{
output_sample(buffer[j]);
j++;
}
else if(sw==3 && j>0)
{
output_sample(buffer[j-1];
j--;
}
if(sw==2 && j>i)
j=0;
if(sw==3 && j==0)
j=i+1;
}

void main(void)
{
short temp=37;
comm_intr();
printf("The Digital Recorder; Made By: M. Fahad Wallam");
while(1)
{
sw=sw_read();
if(sw!=temp)
{
temp=sw;
if(sw==0)
printf("\nLive Play");
else if(sw==1)

49
Signal Processing Lab 14

{
i=0;
printf("\nRecording");
}
else if(sw==2)
{
j=0;
printf("\nRecorded Sound Playing in the Forward direction");
}
else if(sw==3)
{
printf("\nRecorded Sound Playing in the Reverse direction");
j=i+1;
}
else
printf("\nInvalid switch!!!");
}
}
}

1.2 How it works:

This is another very simple program. In this program, an array of size 8000x8 (equals to
16000) is declared which is used to store the samples of sound from ADC. The recording
will be of 8 seconds long. As the sampling time of ADC is 8 KHz, this means that there
are 8000 samples in a second and I declare the size of an array is 8000x8=16000, so the
recording time is 8 seconds. There are four options:

1) Just straight play (live play) that is no recording.


2) Recording the sound.
3) Play the recorded sound same as it was recoded.
4) Play the recorded sound in the reverse direction.

The working of the first option is very simple and explained in the experiment 3(a). The
second one has just described in the above paragraphs. The third one is the same as the
first one except that the samples stored in the array are now sent to the DAC. In the last
one, the samples are sent from the end of the array instead of from the start of the array.
Surprised to look its simplicity!!! Yes, this is your simple digital sound recorder.

To run this program correctly you must include the following files:

1. C6xdsk.cmd
2. C6xdsk.h
3. C6xinterrupts.h
4. C6xdskinit.h
5. C6xdskinit.c
6. Vectors_11.asm
7. Digi_rec.c

50
Signal Processing Lab 14

8. Rts6701.lib
9. Switch_read.c

All the files are provided by the Texas except ‘Digi_rec.c’ and ‘Switch_read.c’ that are
written by myself.

TASK [Optional]:

Write a program to modify this recorder as much as you can that is include the effects
like distortion, 3D effects, etc.

2. PWM (Pulse Width Modulation) Generation:

2.1. Program “PWM.c”:

51
Signal Processing Lab 14

#include "stdio.h"
unsigned short amp_out,ton,toff;
float amp_in,count_on,count_off;

interrupt void c_int11()


{
if(ton==0 && toff==0)
{
ton=(short)count_on;
toff=(short)count_off;
}
else
{
if(ton>0)
{
output_sample(amp_out);
led_control(0x0x00000000);
ton--;
}
else if(toff>0)
{
output_sample(0);
led_control(0x0x07000000);
toff--;
}
}
}

void main(void)
{
unsigned short temp1=37,sw,t1,t2,freq;
float temp2,temp3,dc,f1,f2;
comm_intr();
printf("The Variable PWM with Variable Amplitude generation Program; Made By: M.
Fahad Wallam");
while(1)
{
sw=sw_read();
if(sw!=temp1)
{
printf("\nEnter the Frequency (1 to 4000Hz): ");
scanf("%d",&freq);
printf("\nEnter the On Duty Cycle(%): ");
scanf("%f",&dc);
printf("\nEnter the Amplitude (0 to 3V): ");
scanf("%f"&amp_in);
amp_out=(short)((amp_in/3)*32767);

52
Signal Processing Lab 14

temp1=sw;
dc=(dc/100);
f1=(dc/freq);
f2=((1-dc)/freq);
count_on=8000/f1;
count_off=8000/f2;
temp2=count_on;
temp3=count_off;
while(temp2>=1)
temp2=temp2-1;
while(temp3>=1)
temp3=temp3-1;
t1=temp2*1000;
t2=temp3*1000;

if(t1=t2 && t1!=0)


{
count_on=count_on+1-temp2;
count_off=count_on-temp3;
}
else
{
if(t1!=0)
{
if(t1>=500)
count_on=count_on+1-temp2;
else
count_on=count_on-temp2;
}
else
count_on=count_on-temp2;
if(t2!=0)
{
if(t2>=500)
count_off=count_off+1-temp3;
else
count_off=count_off-temp3;
}
else
count_off=count_off-temp3;
}
ton=0;
toff=0;
}

53
Signal Processing Lab 14

}
}

2.2 How it works:

You are already familiar with the concept of PWM that how it is generated from 555
timer IC and from microcontroller, the terms regarding to PWM that is On-Duty Cycle
and Off-Duty Cycle, etc. Lets try to explore this program. First of all we investigate how
variable PWM will be produced and then try to understand the variable amplitude
methodology. The formula for On-Duty Cycle is:

Duty Cycle% = [ton/(ton+toff)]x100


Duty Cycle% = (ton/T)x100

Where, ‘T’ is the total time period. So,

T=1/F

Where, ‘F’ is the frequency of the PWM.


Now, we are interested to find the ton and toff. But, first we have to divide the duty cycle
by 100 because the user enters the value of duty cycle in percentage form. So, the
following expression performs this job for us:

dc=(dc/100);

Now, the next step is to find the value of ton, which can be found by simply transforming
the formula of On-duty cycle:

ton = (Duty Cycle/100)*T


ton = (Duty Cycle/100)/F

But, we have already converted the percentage value in the decimal value so this is
implemented by the following expression:

f1=(dc/freq);

f1 is used in place of ton. Similarly, the toff can be found by the following expression:

f2=((1-dc)/freq);

f2 is used in place of toff. Now, we have to find the some integer value for the ton and
toff so that the processor can be able to know how long the signal must be in the on state
and how long it must be in the off state depending upon the frequency and the duty cycle.

54
Signal Processing Lab 14

As we know that the sampling time of the codec is fixed at 8KHz, so the following
expression fulfils our requirements:

count_on=8000/f1;
count_off=8000/f2;

There is a problem with the above expressions that the value of the count_on and
count_off may have the decimal part. So, the following expressions are the solution of
this problem that is it discard the decimal part and approximate the their values:

temp2=count_on;
temp3=count_off;
while(temp2>=1)
temp2=temp2-1;
while(temp3>=1)
temp3=temp3-1;
t1=temp2*1000;
t2=temp3*1000;
if(t1=t2 && t1!=0)
{
count_on=count_on+1-temp2;
count_off=count_on-temp3;
}
else
{
if(t1!=0)
{
if(t1>=500)
count_on=count_on+1-temp2;

else
count_on=count_on-temp2;
}
else
count_on=count_on-temp2;
if(t2!=0)
{
if(t2>=500)
count_off=count_off+1-temp3;
else
count_off=count_off-temp3;
}
else
count_off=count_off-temp3;
}
ton=0;

55
Signal Processing Lab 14

toff=0;
}
}

The following expressions check the values of count_on and count_off and make the
decision about the duration of the output in the high position (1) and the low position (0):
if(ton==0 && toff==0)
{
ton=(short)count_on;
toff=(short)count_off;
}
else
{
if(ton>0)
{
output_sample(amp_out);
led_control(0x0x00000000);
ton--;
}

else if(toff>0)
{
output_sample(0);
led_control(0x0x07000000);
toff--;
}
}

Now we investigate the working of variable amplitude. You are all familiar that the codec
is of 16 bits. So,
216 = 65536

You also know that the codec supports the positive as well as negative amplitude value.
So,
65536/2=32768

So, from 0 to 32767 is for positive values and the remaining (i.e.; from 32768 to 65535)
is for negative values. You also know that the maximum amplitude that can be inputted
and outputted by the codec is 3V (and –3V). At these values the codec is saturated at
32767 (and 32768). So, the following expression calculate the codes for the amplitude
you enter:

amp_out=(short)((amp_in/3)*32767);

56
Signal Processing Lab 14

Note: The 0V is represented by 0 and 3V is represented by 32767. Also, the –1V is


represented by 65535 and –3V is represented by 32768.

One last thing to remember is that whenever you turn on or off any of the switch, the
processor will ask you to enter the duty cycle, amplitude, and frequency for the PWM.

To run this program correctly you must include the following files:

1. C6xdsk.cmd
2. C6xdsk.h
3. C6xinterrupts.h
4. C6xdskinit.h
5. C6xdskinit.c
6. Vectors_11.asm
7. PWM.c
8. Rts6701.lib
9. Switch_read.c

All the files are provided by the Texas except ‘PWM.c’ and ‘Switch_read.c’ that are
written by myself.

57

You might also like