signal processing manual 2009
TRANSCRIPT
-
8/8/2019 Signal Processing Manual 2009
1/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 DepartmentSir Syed University of Engineering & Technology
University Road, Karachi 75300http://www.ssuet.edu.pk/
http://www.ssuet.edu.pk/http://www.ssuet.edu.pk/ -
8/8/2019 Signal Processing Manual 2009
2/59
SIR SYED University of Engineering & Technology, KarachiElectronic Engineering Department
EE 402 Signal Processing
Contents
Lab Laboratory Exercises Page
Simulation based Labs
1 MATLAB Fundamentals 12 Continuous-Time Signals 43 Discrete-Time Signals 74 Sampling of Analog Signals 105 Convolution and Correlation 146 Discrete Fourier Transform 177 Filters 198 Introduction to Simulink 23
Hardware based Labs9 Introduction to DSP Kit and related
Softwares26
10 Building an Audio Effect Processor 3411 i) LED Dancing Program
ii) Reading the Switch Value3839
12 i) Sound Playing Demoii) Digital Amplifier
4243
13 i) Echo Generation
ii) Reverb Generation
45
4714 i) Digital Sound Recorder
ii) PWM Generation4951
-
8/8/2019 Signal Processing Manual 2009
3/59
Signal Processing Lab 1
1 MATLAB fundamentals:
In this course we will use software MATLAB to implement and simulate digital signal processingalgorithms.The name MATLAB stands for MATrix LABoratory. Originally MATLAB was developed to dealwith 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 thenumber of column equals to 1; and it includes scalars when both the number of rows andcolumns equal 1. Furthermore, matrices can be either real-valued or complex valued, which is themost general case.There is a small tutorial in this exercise for newcomer to become familiar with the MATLABfundamentals. 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 helpon 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 advancesearch 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 seekingthrough 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 whichthe 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
-
8/8/2019 Signal Processing Manual 2009
4/59
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 notationfirst : last
For example, [ creates the vector]5:1 [ ]54321 . An spacing can be introduced between two elements of a vector by using the colon notation
first : spacing : last
For example, [ creates the vector]5:2:1 [ ]531 .
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.
[ ] [ ]69;4754;23 + - subtracts two vectors/matrices of identical size, or a vector/matrix
B2 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
BB 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
B/1 performs vector/matrix multiplication. The number of columns in the first vector/matrix must
equal to the number of rows in the second. Example:
1.5 and complex matrices:
general, any matrix within the MATLAB can be complex-valued. However, for efficient storage,
gned, by default, the value
BB
Real
In
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 knownto deal with complex-valued matrices:
The variables i and j are assi 1=i . This is used to define thecomplex values. For example,
10*5 j+
generates a complex-valued variable.
matrix can be extracted by using the function REAL and
o produce the complex conjugate of a matrix.
The real part of a complex-valuedimaginary part can be extracted by using the function IMAG. Both functions deliver the real-
valued matrices as outputs.
The function CONJ is used t
2
-
8/8/2019 Signal Processing Manual 2009
5/59
Signal Processing Lab 1
The special character generates the complex conjugate transpose of a matrix, the hermitianmatrix. 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 theyhave .m extension as the last part of their file name.
There are two types of M-types:
Script files
Function files1.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, togetherwith 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
( ) )10:1(*10,1 ionesa += 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 mst 1= .Task # 6: Use MATLAB help to get familiar with the syntax ofFOR, 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
-
8/8/2019 Signal Processing Manual 2009
6/59
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 of6.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 [ ].30.....2,1,0 The next command generates the sine wavevector with the same number of elements as . Note that the first index of is 1, not 0, with period ofy x y
2 and a total of 31 samples, consists of 4.75 cycles of the sine wave.y
The Plotcommand, along with grid, title,xlabel andylabel, 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
-
8/8/2019 Signal Processing Manual 2009
7/59
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 Plotcommand or by holding the first signal plot before plotting the second signal.Hold on
andHold offcommands is used to hold the plot. Different colors and different line types can be used to plotmultiple 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
-
8/8/2019 Signal Processing Manual 2009
8/59
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) ofPlotcommand by using MATLAB help.
Try to change the color and line type of the plot in the above examples.Task#2: Investigatesubplot command by using MATLAB help to understand the above example.
Task#3: Generate a decaying sinusoid with 1001 samples and spacing mst 1= . Plot the result withreference 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 functiony=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 functiony=rect(t) to plot the rectangular function, Uses the definition of rectangle
function in terms of unit step function.Task#7: Write a functiony=tri(t) to plot a triangular function, defined as 1-|t| for |t| 1 and zero otherwise.
6
-
8/8/2019 Signal Processing Manual 2009
9/59
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. Adiscrete-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 systemanalysis. Sinusoids can be defined in a manner analogous to their CT counterparts as
+=
N
nAng
2cos][
or ( )+= nAng cos][ or ( ) += fnAng 2cos][
where:
A =real constant
=real phase shift, rad
=Fundamental period, samples per cyclesN
and f and are related to through = =N N/1 f 2/ .There are some important differences between CT and DT sinusoids. The first is the fact that ifwe create a DT sinusoid by sampling a CT sinusoid, their period may not be the same and, infact, the DT sinusoid may not even be period periodic. Let a DT sinusoid
[ ] ( )+= KnAng 2cos
1.2. Discrete-Time Signal Representation:
The following methods are use to illustrate the discrete-time signals:
1.2.1. Sequence representation:
( ) KK ,1,3,3,1,2,1,3 =
nx
Where arrow ( ) represents the reference time 0=t
1.2.2. Functional representation:
( )
== =
=
=
=
33
1221
13
3,01
n
nn
n
n
nx
1.2.3. Tabular representation:
n 3210123
( )nx 1331213
1 7
-
8/8/2019 Signal Processing Manual 2009
10/59
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) ofPlotcommand by using MATLAB help.Try to change the color and line type of the plot in the above examples.
Task#2: Investigatesubplot command by using MATLAB help to understand the above example.
Task#3: Generate a decaying sinusoid with 1001 samples and spacing mst 1= . Plot the result withreference 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 functiony=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 functiony=rect(t) to plot the rectangular function, Uses the definition of rectangle
function in terms of unit step function.Task#7: Write a functiony=tri(t) to plot a triangular function, defined as 1-|t| for |t| 1 and zero otherwise.
2 8
-
8/8/2019 Signal Processing Manual 2009
11/59
Signal Processing Lab 3
3
9
-
8/8/2019 Signal Processing Manual 2009
12/59
Signal Processing Lab 4
4. Sampling of Analog Signals:
Most signals of practical interest, such as speech, biological signals, seismic signals, radarsignals, sonar signals, and various communications signals such as audio and video signals, areanalog. To process analog signals by digital means, it is first necessary to convert them intodigital 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 calledA/D converters (ADCs)
Conceptually, we view A/D conversion as a three step process. This process is illustrated infigure 4.1
1. SamplingThis 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. QuantizationThis 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 selectedfrom 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.
Sampler Quantizer
Coder
xq(x(n)
Digit
al
signal
Analo
g
signal
xa(t
Quantized
signal
Discrete
time signal
01010...
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 uniformsampling, which is the type of sampling used most often in practice. This is described by therelation
( )
-
8/8/2019 Signal Processing Manual 2009
13/59
Signal Processing Lab 4
Where x(n) is the discrete time signal obtained by taking samples of the analog signal ( )txa every T seconds. This procedure is illustrated in figure 4.2. The time interval T betweensuccessive samples is called the sampling period or sample interval and its reciprocal 1/T=Fs iscalled the sampling rate (samples per second) or the sampling frequency (hertz).
1 2 3 4 5 6 7 8 9
T 2T 5T9T t=nT
xa(t)x(n)= xa(nT)
xa(t)
n0
x(n)
Figure 4.2: Periodic sampling of an analog signal
Periodic sampling establishes a relationship between the time variables t and n of continuoustime and discrete time signals, respectively. Indeed, these variables are linearly related throughthe sampling period T or, equivalently, through the sampling rate Fs= 1/T, as
sF
nnTt ==
There exists a relationship between the variable F (or) for analog signals and the frequencyvariable (or) for discrete time signals. To establish this relationship, consider an analog
sinusoidal signal of the form
( ) )2cos( += FtAtx a Which, when sampled periodically at a rate =1/T samples per second, yieldssF
( ) )2cos()( += FnTAnxnTxa
)2
cos(
+=
sF
nFA
The frequency variables F and are linearly related as
sF
Ff = (4.1)
or, equivalently, as
T= (4.2)
11
-
8/8/2019 Signal Processing Manual 2009
14/59
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 . As (4.1) implies, we can use to determine the
frequency F in hertz only if the sampling frequency is known.
f f
sF
The range of the frequency variable F or for continuous time sinusoids are
-
8/8/2019 Signal Processing Manual 2009
15/59
Signal Processing Lab 4
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 maximumsignal 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 signalfrequency in Hertz.
Task#4: Write a script to convert continuous time signal of task#1 to a discrete time signal andtake the sampling frequency as input which should be greater than twice the maximumsignal frequency in Hertz.
Task#5: Write a script using subplot command to generate task #1, task#2, task#3 and task#4plots. Analyze the four plots, what happen by increasing the sampling frequency?
Task#6: Consider the analog signal
( ) )100cos(3 ttx a = (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 timesignal 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 signalobtained after sampling? Plot the discrete-time signal.
(iv) What is the frequency 0
-
8/8/2019 Signal Processing Manual 2009
16/59
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 Msamples and can be
designated as follows:
[xk]=[x0
[yk]=[y0
x1 x2LxM1]
y1 y3LyM1]
This notation implies that both sequences have the same length, which may not be the case and indeed israrely with FIR filtering, where the data sequence is usually much longer than the impulse response. Whenthe sequences are of different lengths, we use the convention of adding zeros to the right end of the shortersequence. For example, if an FIR filter with impulse response [hk] and length 4 were processing an inputsignal [xk]of lengthM= 9, we would have
[xk]=[x0
[yk]=[h0
x1 x2
h1 h2
x3 x4 x5 x6 x7
h3 0 0 0 0 0]
x8]
The convolution function of the two sequences [xk]and [yk]is obtained by
cxy (n)=conv{[xk], [yk]}
n
=xkynkk=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
cxy (n)=
xkynkk=
=xk h k
14
-
8/8/2019 Signal Processing Manual 2009
17/59
Signal Processing Lab 5
the generalized form of the convolution sum. In this equation is known as convolution star, signifies theoperation of convolution.
If the input consists of a continuous sequence of impulses then the above summation may be replaced by
integral.
cxy (t)=+
xytd=
This expression is known as convolution integral.
The Correlation function of the two sequences [xk]and [yk]is obtained by
rxy (n)=xcorr{[xk], [yk]}
n
=xnyn+kk=0
This function may be extended to waveforms of infinite duration by writing them as
rxy (n)=
xkyn+kk=
When [xk]and [yk]are different sequences, rxy (n)is the cross-correlation function. When [xk]and [yk]are same sequences, rxx (n)is the auto-correlation function.
15
-
8/8/2019 Signal Processing Manual 2009
18/59
Signal Processing Lab 5
Exercise:
Task#1: Two data sequences are given as follows:
1321
=kx
1121 =
ky
Compute by hand the convolution function ( )nCxy .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 func ion Ct xy(n) of the following sequences:
010020100 =
kx
00006.08.0100
=ky
Task#5: Compute by hand the complete autocorrelation function of
{ }00010211 =kx
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
-
8/8/2019 Signal Processing Manual 2009
19/59
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 alimited (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 Fourieranalysis 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 idealfor 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 sampledsignal, to solve partial differential equations, and to perform other operations such as
convolutions. The DFT can be computed efficiently in practice using a fast Fouriertransform (FFT) algorithm.
The sequence of N complex numbers x0, ..., xN1 is transformed into the sequence of Ncomplex numbers X0, ..., XN1 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 Xkfrom 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 isapplied 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 hasmore.
FFT(X,[],DIM) orFFT(X,N,DIM): applies the FFT operation across the dimension DIM.
17
-
8/8/2019 Signal Processing Manual 2009
20/59
Signal Processing Lab 6
Exercise:
1001
=n
x
Task#1: Data sequence is given as follows:
Compute by hand the DFT function .k
X
Task#2: Use FFTcommand 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.
Task#4:Plot an
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
-
8/8/2019 Signal Processing Manual 2009
21/59
Signal Processing Lab 7
Filters:
Electronic filters are electronic circuits which perform signal processing functions, specifically to removeunwanted 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, theanalog 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 areused 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 domainanalysis is done using the Z-transform and the Discrete Time Fourier Transform (DTFT).
In general, a linear and time invariant digital filter with inputx(n) and outputy(n)may be specified by itsdifference equation.
(1)=
=
=M
k
k
N
i
i knyainxbny1
1
0
)()()(
where biand ak are coefficients which parameterise the filter. This filter is said to haveNzeros andMpoles.
Each new value of the output signal,y(n) , is determined by past values of the output, and by present and pastvalues of the input. The impulse response, h(n) , is the response of the filter to an input of (n) , and istherefore the solution to the recursive difference equation.
(2)=
=
=
M
k
k
N
i
i knhainbnh1
1
0
)()()(
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 thiscase, the difference equation in (2) becomes
(3)
=
=1
0
)()(N
i
i inbnh
19
-
8/8/2019 Signal Processing Manual 2009
22/59
Signal Processing Lab 7
Since (3) is no longer recursive, the impulse response is finite with lengthN.In the case where ak 0 , the difference equation usually represents an IIR filter. In this case, (2) will usuallygenerate an impulse response which has nonzero values as n. However, later we will see that for certainvalues of ak0 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 differenceequations. The Z-transform of a discrete time signal,x(n), is given by
(4)n
n
znxzX
=
= )()(
The DTFT may be thought of a special case of the Z-transform, wherez is evaluated on the unit circle in the
complex plane.
(5)jw
n
ez
jw
enx
zXeX jw
=
=
=
=
)(
|)()(
From the definition of the Z-transform, a change of variable shows that a delay ofKsamples in the time
domain is equivalent to multiplication by Z-kin the Z-transform domain.
[ ]
)(
)(
)(
)()(
)(
zXz
zmxz
zmx
zknxknx
k
m
mk
km
m
n
nz
=
+
=
=
=
=
=
(6)
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:
(8)=
=
=M
k
k
k
N
i
i
i zYzazXzbzY1
1
0
)()()(
20
-
8/8/2019 Signal Processing Manual 2009
23/59
Signal Processing Lab 7
(9)
=
=
=+
1
01
)(]1)[(N
i
i
i
M
k
k
k zXzbzazY
=
=
+
==M
k
k
k
N
i
i
i
za
zb
zX
zYzH
1
1
0
1)(
)()( (10)
From this form, we see that any filter, which can be represented by a difference equation, has a rationaltransfer 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 evaluatingH(z) on the unit circle.
=
=
+
=M
k
jwk
k
N
i
jw
ijw
ea
eb
eH
1
1
0
1
)( (11)
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
any discrete time filter described by a difference equation. Note that the boxes containing the symbolz1
represent unit delays, while a parameter written next to a signal path represents multiplication by thatparameter.
Figure 1: Direct form implementation for a discrete time filter described by a general difference equation21
-
8/8/2019 Signal Processing Manual 2009
24/59
Signal Processing Lab 7
Exercise:
Task#1: Generate two sinusoid signals with frequency of 100 Hz and 400 Hz. Add these two signals. Designa 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. Takingsinusoid 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.
y(n) =x(n-1)+ay(n-1)
a=0.97
22
-
8/8/2019 Signal Processing Manual 2009
25/59
Signal Processing Lab 8
1. Introduction to SIMULINKSimulink is a software package for modeling, simulating, and analyzing dynamical systems. Itsupports linear and nonlinear systems, modeled in continuous time, sampled time, or a hybrid ofthe two. Systems can also be multirate, i.e., have different parts that are sampled or updated atdifferent rates.
For modeling, Simulink provides a graphical user interface (GUI) for building models as blockdiagrams, using click-and-drag mouse operations. With this interface, you can draw the modelsjust as you would with pencil and paper (or as most textbooks depict them). This is a far cry fromprevious simulation packages that require you to formulate differential equations and differenceequations 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 blocksS-Functionscan be used, which is another skill.
MATLAB and Simulink are integrated; you can simulate, analyze, and revise your models ineither 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 theSimulink Library Browser or just writeSimulink in Command window prompt.Expending these libraries can access variousToolboxes, Blocksets and Simulinkfunctions.
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 SimulinkLibrary. Double clicking each icon will open the corresponding library.
23
-
8/8/2019 Signal Processing Manual 2009
26/59
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
-
8/8/2019 Signal Processing Manual 2009
27/59
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
-
8/8/2019 Signal Processing Manual 2009
28/59
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 thanCCS.
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
-
8/8/2019 Signal Processing Manual 2009
29/59
Signal Processing Lab 9
Waveform Generator:Specifying Waveform Parameter Valuesa value for a
ctions:
Osc
e has rich triggering possibilities. Here we explain only the most
tures that might be necessary for accomplishing a particular task.
e
e
The
at allows you to get rid of random noise. The output
ainly caused
settings on a floppy disk. First, set up the oscilloscope's settings of your needs.
While working with the signal generator, you will often need to enter
parameter of the generated waveform. To do this, follow these instru
Turn the knob on the front panel of the signal generator until you reach thedesired 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.
illoscope:
Triggering
The oscilloscop
important fea
Setting up an external trigger. Press Edge in the trigger section of theoscilloscope's controls. Set triggering to external by pressing th
corresponding soft key Ext. Note, it is necessary to connect a BNC cable tothe 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.
Us ful Features
re are also a number of very useful features that might help you.
feature th Averaging: asignal of the codec of our DSP board is relatively noisy. This is mby 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 thecorresponding 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 scalingwhich tries to determine the parameters automatically. Press Auto Scale to
enable it.
Saving a screenshot: this feature allows you to save a screenshot of theoscilloscope's display to a floppy disk as an image file. So you can easilyinclude 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 theinternal floppy drive and press Quick Print.
Saving oscilloscope's settings: this is a very useful feature that allows you tostore 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
27
-
8/8/2019 Signal Processing Manual 2009
30/59
Signal Processing Lab 9
When ready, push Save/Recall >Save and then choose a slot by pressing theTo 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 actuallyrestore the saved settings.
ware
de Composer Studio:
1.1.2. Soft
Co Before starting Code Composer Studio (CCS), ensure that the DSP board ised with power and connected to the PC.
There should be an icon on the desktop. If necessary, start CCS from the Starts >Texas Instruments >Code Composer Studio 2
CS to load a DSP program
after build". Press OK.
ery instruction to
one of the eight functional units and you should ensure that all eight units are
n Linear Assembly and C/C++, the
0 bits
its
typical DSP Program for Real-Time Block Processing usedt
main.c does the whole initialization and remains in an endless loop. The blocks.h provides constants for the block processing environment iggered
by the DMA's hardware interrupt. It manages circular buffers the DMA
alls the
provid
menu: Start >Program
('C6000)>Code Composer Studio.
For more convenience, you should enable C
automatically into the DSP's memory after a successful compilation/linking.
In CCS, choose Option>Customize. Press the Program Load Options tab andput a check mark on Load program
TMSC6000 Optimizing C Compiler
There are three possibilities to program TI's C6000 DSPs: Assembly, LinearAssembly, and C/C++. In Assembly, you have to allocate ev
working concurrently permanently. Ioptimizer 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 4 oat 32 bits double 64 bits pointer 32 bStructure of a
in his Laboratory
function init()is called, where you can do additional initializations.
isr_tttt.c contains the Interrupt Service Routine (ISR) which is tr
uses to transfer data between the memory and the codec and it c
28
-
8/8/2019 Signal Processing Manual 2009
31/59
Signal Processing Lab 9
function processing() where the actual signal processing happens. The tttt
heapsize, ...)
lobal) objects (e.g. additional buffers or filter coefficients).
We or
rses/dsplab/.
In your home directory, you have to create the folder L:/DSP LAB/ where forhave to copy and unzip the required files. For
e source code files double-clicking opens the file in a text editor
window.
load it into the DSP's memory. It's also possible to do an
Incremental Build where only the modified files are compiled.
g loaded. It
might couse the DSP board or the the computer to halt.
For
suc
ope
does not run properly.
>Restart.
This problem happens very often, especially when it is the first program
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,
userfiles The init() and processing() functions are defined here and all thenecessary (g
algorithm modules functions and structures for filters, _t, ...Building a Program in CCS
will provide you with most of the source code. You can find *.zip files f
the different experiments on our webpage psc.inw.tugraz.at/cou
each laboratory exercise you
some of the experiments, you have to modify or add source code. Allnecessary source files of a DSP program will be bundeled to a so-calledPROJECT.
In the main menu, choose Project>Open and select the *.pjt fileappropriate for your exercise. In the Project view window you can see alist of th
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
To run a program, choose Debug>Run or press the F5 button. Rememberthat the program must be successfully compiled, linked, and loaded into
the DSP's memory. Do not run the DSP without a program bein
more convenience, we sometimes provide a WORKSPACE file. Using
h a file opens the specified projects and editor windows automatically. To
n such a *.wks file, click File>Workspace>Open .
Troubles with CCS>Known Bugs
CCS built and loaded the interrupt-based program successfully but itRestart the DSP program: Debug
after starting CCS.
29
-
8/8/2019 Signal Processing Manual 2009
32/59
Signal Processing Lab 9
Really nothing works any more.
problem happens when a big amount of data is
transmitted through the parallel connection (e.g. while debugging).
uLau
Tes on andinstallation. The following message is then displayed:
s that the first three switches, USER_SW1, USER_SW2, and,are all in the up (ON) position. Change the switches to (1 1 0 x)2
t two switches are up (press the third switch down). The fourthswitch is not used. Repeat the procedure to select GEL > Check DSK > Quick
UsiSimRea I C/C++ code
that can be compiled using CCS. The Embedded Target for TI C6000 DSP
programming interface) required by Real-Time
le.
isn
p
ith the C6711 DSK. These configuration setting are required andare similar for all the experiments. While this configuration generally has
red that these setting do exist. This is
Close (or kill) CCS, power-down and power-up the DSP board, and start
CCS again. This
Q ick Test of DSKnch CCS from the icon on the desktop. Press GEL >Check DSK > Quickt. The Quick Test can be used for confirmation of correct operati
Switches: 7Revision: 2
Target is OK
This assumeUSER_SW3
so that the firs
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 basedon 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 asinterrupts, LEDs, SDRAM, DMA, serial ports, and timers.
ng DSP Kit via Matlab:
ulink uses a block based approach to algorithm design and implementation.l-Time Workshop converts these Simulink models into ANS
provides the APIs (AdvancedWorkshop 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 executab
This code can then be downloaded on the target DSP from where it runs. Thapproach allows for rapid prototyping. Also, a model built once in Simulink ca
be made to run on various system as long as one has the appropriate Embedded
target toolbox.
Initial configuration (for all labs):This section describes how configure Simulink and Real-Time Worksho
for use w
to be done only once, it must be ensu
the first step in any experiment using Simulink.
Check if CCS is properly installed
30
-
8/8/2019 Signal Processing Manual 2009
33/59
Signal Processing Lab 9
To verify that CCS is properly installed on the system, enter ccsboardinfoat the Matlab command line. Matlab should return information similar to
ollowing listing:
--------- --- --------------------------- --------------0 C6711 DSK 0 CPU_1 TMS320C6x1x
ter c6000lib es:
C6000: DSP Core Support, C62x DSP Library, C64x DSP Library, C6416
Support, C6711 DSK Board Support, RTDX Instrumentation,
Configuration Parameters for C6000 Hardware1. Launch Matlab
nch Simulink
the f
Board Board Proc Processor Processor
Num Name Num Name Type--- ------------------
To ensure Embedded Target for TI C6000 DSP is installed, en
Matlab should display the C6000 block library containing the librari
DSK Board Support, C6701 EVM Board Support, C6711 DSK Board
TMDX326040 Daughtercard Support.
Figure 2: Software overview
2. At the Matlab command line, type simulink to lau
31
-
8/8/2019 Signal Processing Manual 2009
34/59
Signal Processing Lab 9
3. Create a new model in Simulink.
uration
Parametersime Workshop category.
e the Make command and Template makefile
7. Choose the Optimization category in the Select tree. For Simulation
8. Choose the TI C6000 target sel.... Set Code generation target type
9
10. In the Select tree, choose the Debug category. Select Verbose build
11. In the Select tree, choose the Solver category. Ensure that Solver is set
Building a Simple I/O system with the C6711 DSKTo build th
1. Perform the steps in section using DSP Kit via MATLAB.e Out, LineIn. The goal is to
e In jack and passesgnal through, unchanged, to the Headphone/Line out jack.
edded Target
4 to-Analog
Figure 3: Simple I/O
6. Double clicking a block displays the block parameters. Wh e parametersare userdefinable, others are not. The ADC source field ca t to either Mic
In or Line In. If the input one then the field should be set to
Mic In; otherwise, it should be set to Line In. In the ADC block, Stereo should
4. To open the Configuration Parameters, select Simulation!Config
5. In the Select tree, chose the Real-T
6. For Target Selection, choose the file ti c6000.tlc. Real-Time Workshopwill automatically chang
selections.
and Code generation, un-select Block reduction optimization andImplement logic signals....
to C6711DSK.. Choose the TI C6000 compiler. Set Symbolic debugging.
here.
to Fixed type / discrete.
e model for a Single Audio Effect, follow these steps:
2. The DSK has two input and output jacks: Lin
implement a system that accepts an audio signal via the Linthat si
3. Select the Simulink Library Browser window and select Emb
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.
. Place the ADC (Analog-to-Digital Converter) and DAC (Digital-
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
ADC DAC
C6711 DSK C671
ADC
1 DSK
DAC
ile somn bese
is from the microph
be unchecked and the output data type set to integer. NOTE: The sample rate
32
-
8/8/2019 Signal Processing Manual 2009
35/59
Signal Processing Lab 9
can also be set here. For most applications, this is either set to 8kHz (speechapplications) 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 tomemory needs and computational load).
. Double click the DAC block. Ensure that the Word Length field is thesame (16-bit) for both the ADC and DAC blocks.
. Save the model:
Select File > Save As > ...location
78
jack.ng the headphones to the Headphone jack.
1 eady to run. Verify that the DSK board
command on the Simulinkmodel toolbar (the icon with the 3 arrows) to begin compiling the model and
tran
uter,
12.
sembly code will be compiled and loaded
e CCS and return to the model in Simulink.
rite a brief report (2 to 3 pages) about your learning, observation and understanding of
is lab.
9. Ensure that the hardware is connected properly by:
(a) Connecting the microphone to the Mic In(b) Connecti
0. The model is now complete and r
is connected properly .Use the Incremental Build
sferring the code to the DSK.
11. If this is the first time the board has been used since turning on the compa DSK Startup window will open temporarily to configure the board.
The system will first compile code in Matlab, then Code Composer Studio
(CCS) will be opened, where as
onto the DSP. Once in CCS, a progress window will open as the code isloaded 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. Clos
Task:
W
th
33
-
8/8/2019 Signal Processing Manual 2009
36/59
Signal Processing Lab 10
1. Building an Audio Effect Processor:
1.1.Overview:In this laboratory exercise, students will create an audio effects processor usingTMS320C6711.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 definedas
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 TargetPreferences 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 explorethe effect of each on the output signal.
Figure 1:Real time single echo filter [1]
Z-40
C6711
DSK
Line In
C6711
DSK
34
-
8/8/2019 Signal Processing Manual 2009
37/59
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 theC6711 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 Supportlibrary 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
-
8/8/2019 Signal Processing Manual 2009
38/59
Signal Processing Lab 10
Figure 2: Real time reverberation filter [1]
Z-20
Reset
C6711 DSK
C6711 DSK
DACLine In
C6711 DSK
ADC
Audio Reverberation C6711 DSK Implementation
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 TargetPreferences 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
-
8/8/2019 Signal Processing Manual 2009
39/59
Signal Processing Lab 10
Reset
C6711 DSK
C6711 DSKLine In
C6711 DSK
ADC
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
-
8/8/2019 Signal Processing Manual 2009
40/59
Signal Processing Lab 11
1. The LED Dancing Program:
1.1. Program Led.c:
#include "stdio.h"
#define LED_OFF 0x07000000#define msec 500void 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 theDSK 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
-
8/8/2019 Signal Processing Manual 2009
41/59
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, Ihave 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) tocreate delay. The rest of the program is very simple to understand if you properly learnedthe 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.c8. Delay.c
9. Rts6701.lib
10. Led.c
All the files are provided by the Texas except ledcontrol.cand 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 tocontrol 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
-
8/8/2019 Signal Processing Manual 2009
42/59
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 bein 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 correctvalue. But do not get confused because I have also written a function shortsw_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 100On 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.c6. 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
-
8/8/2019 Signal Processing Manual 2009
43/59
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, thethird 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 processcontinues indefinitely.
2. Write a program such that when the user presses the switches the LEDs will be turnedon 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 OffOn Off On On Off On
On On Off On On Off
On On On On On On
41
-
8/8/2019 Signal Processing Manual 2009
44/59
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 givesan 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 digitalvalue 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
-
8/8/2019 Signal Processing Manual 2009
45/59
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 wellas 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 Adjustmentcreates a sub menu on the gel menu bar with the name Gain Adjustment but when it
will be loaded (from fileLoad 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
-
8/8/2019 Signal Processing Manual 2009
46/59
Signal Processing Lab 12
To run this program correctly you must include the following files:
1. C6xdsk.cmd
2. C6xdsk.h
3. C6xinterrupts.h4. 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 writtenby 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 theslider 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
-
8/8/2019 Signal Processing Manual 2009
47/59
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 theexpression given below:
Outputt = input + 0.1*amplitude*buffer[i];buffer[i] = input;
To explain these expression please analyze the following block diagram. Believe me, thisis the best way to understand. I have also visualized it with the help of the following
block diagram:
45
-
8/8/2019 Signal Processing Manual 2009
48/59
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.h4. C6xdskinit.h
5. C6xdskinit.c
6. Vectors_11.asm
7. Echo.c
8. Rts6701.lib
46
-
8/8/2019 Signal Processing Manual 2009
49/59
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 headwith 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
-
8/8/2019 Signal Processing Manual 2009
50/59
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 isonly 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
-
8/8/2019 Signal Processing Manual 2009
51/59
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 && ii)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
-
8/8/2019 Signal Processing Manual 2009
52/59
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 recordingwill 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 therecording 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 lastone, 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
-
8/8/2019 Signal Processing Manual 2009
53/59
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 arewritten 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
-
8/8/2019 Signal Processing Manual 2009
54/59
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"&_in);
amp_out=(short)((amp_in/3)*32767);
52
-
8/8/2019 Signal Processing Manual 2009
55/59
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
-
8/8/2019 Signal Processing Manual 2009
56/59
Signal Processing Lab 14
}}
2.2 How it works:
You are already familiar with the concept of PWM that how it is generated from 555timer IC and from microcontroller, the terms regarding to PWM that is On-Duty Cycleand 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 cycleby 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 transformingthe formula of On-duty cycle:
ton = (Duty Cycle/100)*Tton = (Duty Cycle/100)/F
But, we have already converted the percentage value in the decimal value so this isimplemented 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
-
8/8/2019 Signal Processing Manual 2009
57/59
Signal Processing Lab 14
As we know that the sampling time of the codec is fixed at 8KHz, so the followingexpression 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 andcount_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;
}
elsecount_on=count_on-temp2;
if(t2!=0)
{if(t2>=500)
count_off=count_off+1-temp3;
elsecount_off=count_off-temp3;
}
elsecount_off=count_off-temp3;
}
ton=0;
55
-
8/8/2019 Signal Processing Manual 2009
58/59
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 codecis 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 at32767 (and 32768). So, the following expression calculate the codes for the amplitude
you enter:
amp_out=(short)((amp_in/3)*32767);
56
-
8/8/2019 Signal Processing Manual 2009
59/59
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, theprocessor 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.