You are on page 1of 53

AIR UNIVERSITY

Department of Electrical Engineering

EE433 Digital Signal Processing


(Lab Manual)
Instructors:

Ms. Asma Asif


Mr. Waseem Khan

DIGITAL SIGNAL PROCESSING

Lab Manual

Name:

_____________________

Roll No:

_____________________

Class:

_______

Air University, Islamabad

__

Contents and Tentative Sequence of Labs

TITLE
Lab 1

Introduction to DSP kit TI C6713 using an existing project

Lab 2

Create, configure and build a new project in CCS and debugging using
Breakpoints and watch window : Dot product of two arrays

Lab 3

Discrete time signals: Time domain representation in Matlab


(generating and plotting sinusoidal, square and triangular waveforms)

Lab 4

Configuring McBSP and interfacing with the codec TLV320AIC23: Sine


Generation

Lab 5

Using a Timer on DSP

Lab 6

Profiling and LOG_printf

Lab 7

Discrete-Time Signals and Systems: Frequency Domain Analysis in Matlab

Lab 8

Codec Input/output and Graphing an Array

Lab 9

Input to DSK: sinusoidal waveform to the LINE IN connector on the DSK and
graph the input signal

Lab 10

Project Discussion / Lab Exam

Lab 11

Project Work

Lab 12

Final Viva / Presentations

GENERAL INSTRUCTIONS
1.
COURSE DESCRIPTION:
EE 433, digital signal processing is a seventh semester electrical engineering laboratory
course. It lays important theoretical foundations of electrical engineering and covers realtime signal processing techniques.
Tools: The first three labs are purely dedicated to an introduction to the basic tools. The
code composer studio is presented and a simple example is discussed. This experiment is
based on TI documentation [9] and does not involve Simulink. Basic hardware
components are explored, including the coder-decoder CODEC), which serves as the
analog-to-digital and digital-to-analog interface. To demonstrate the basic abilities of the
DSP board a sine wave generator is implemented.
About This Manual
This manual describes the board level operations of the TMS320C6713 DSP Starter Kit
(DSK) module. The DSK is based on the Texas Instruments TMS320C6713 Digital
Signal Processor. The TMS320C6713 DSK is a table top card to allow engineers and
software developers to evaluate certain characteristics of the TMS320C6713 DSP to
determine if the processor meets the designers application requirements. Evaluators can
develop software to execute onboard or expand the system in a variety of ways.
Prerequisite knowledge: Signals and Systems, Coding in Matlab, Programming in C
Reference Book
Digital Signal Processing and Application with the C6713 and C6416DSK by Rulph
Chassaing
Related Documents
Texas Instruments TMS320C67xx DSP CPU Reference Guide
Texas Instruments TMS320C67xx DSP Peripherals Reference Guide
2.
LAB NOTEBOOKS:
You are required to maintain a lab (engineering) notebook. In a lab notebook,
experimentation is recorded as it is done. (This means, don't take data on scrap paper and
recopy it into your lab notebook at home.) The lab notebook is discussed in detail in the
section on lab notebooks.
The lab instructor will collect and grade your lab notebook several times during the
semester. Lab work should be completed at the time of the experimentation; however,

most people will require some time outside the lab to complete the analysis and write up.
We feel that after a week or so, going back and trying to analyze and write up
experimentation is of little value and a waste of your time; therefore, all work must be
completed in your lab notebook within one week of the experimentation. After that, you
should be working on the next week's laboratory work and not going back. After one
week, your lab instructor may grade your experimentation in your lab notebook (missing
work counts as zero).
You are required to date and sign each entry in your lab notebook.
3.

PREPARATION AND PLANNING:

Some preparation is necessary before coming to lab. Before you start an experiment,
make sure you read and understand the lab. This should be done BEFORE coming to
l a b . Good experimentation requires adequate planning. You should have a good idea
what your objectives are, how you plan on accomplishing them, and what the results are
that you expect to get.
An experiment will usually run more smoothly if you have some idea what the outcome
of the experiment should be before hand. Errors in procedure can often be identified and
corrected if you can see that the result doesn't make sense.
4.
QUIZZES:
There will be quizzes in alternate lab sessions. The quizzes will normally be entrance
quizzes, that is, they will be conducted at the start of the lab. You should be well
prepared for the quiz and should make sure that you read and understand the theory
relative to the lab. In fact, the quizzes will test you on your theoretical proficiency as well
as practical knowledge delivered to you during the lab sessions. Quizzes may be
announced as well as unannounced.
5.
CHEATING AND PLAGIARISM:
Cheating and plagiarism are inconsistent with the professionalism required of an
engineer. We therefore take a strict action against this in the electrical engineering
laboratory courses. Both are grounds for an F in the course. Keep in mind that cheating
and letting one cheat are equal crimes and bear same consequences.

6.

DISTRIBUTION OF MARKS:

Marks will be distributed as follows:


Quizzes
3 marks
Lab P r a c t i c a l Exam
4 marks
Lab Notebook
3 marks
Project
5 marks
Final Viva
3 marks
Attendance
2 marks
(2 marks will be awarded for 90~100% attendance, 1 for 80~90% attendance and 0 for
below 80%)
Note: Missing work counts as zero.
7.
POLICY ON COMMON WORK:
It i s assumed that you will be working with your lab partner/s when performing any
experiment in the lab. Thus, the results and analyses may be common to some extent.
Indicate who your lab partner/s is/are on all common work. Turning in someone else's
work (that is, work not done by either you or you and your lab partner/s) for a grade is
ground for an F in the course. Moreover, analysis and discussion of the experiment
results should be your own. If you submit your partners comments/analysis with your
name, you and your partner both will be marked zero.
8. LAB NOTEBOOK
You are required to maintain a lab notebook in the electrical engineering laboratory
courses. Lab notebooks are customarily used in engineering as permanent records of
experiments done. Your lab notebook should be a permanent record of your
experimentation. You are required to make entries in it as you do the experimentation
and analyze the results.
Outer cover:
The outer cover should have course name, your name, roll number, discipline, class,
section and semester on it.
First page:
The first page should be used as an index or table of contents. List all experiments on it.
Recording each lab:
Each lab should contain the following parts: (The order may vary for different labs,
and some of the parts listed may not apply to all labs.)

1. Title: This should include the title of the lab and the lab n u m b e r .
2. Objectives: Briefly state the purpose of the experiment and the concepts to be
investigated.
3. Equipment list: List all critical equipment and instruments used. Equipment can be
listed either in an initial list or as used. You should have enough information to go
back and repeat the lab with the same equipment.
4. Block diagrams you have to draw block diagrams of all the experiments that you
will implement(This will almost always save you time in the end since without a good
design diagram to work from, you will make more mistakes, have more difficulty
taking data, and have more difficulty troubleshooting your circuits.)
5. Data: Data should be tabulated in vertical columns. Data tables should be labeled.
Listing the units at the top of a column i s usually preferred to repeating the same unit
with each data entry.
6. Calculations: Include sample calculations of each type. (Include enough to show
how the calculations were done; however, do not use your notebook as a worksheet.)
7. Graphs: Include curves of data, wave shape diagrams, etc. Each curve or diagram
should have a title. When plotting curves, the independent variable should be on
horizontal axis. Use scales that are easily interpolated and consistent with the
accuracy of the data. Draw the vertical and horizontal axis inside the border of the
graph paper, and label the variable and units on each axis. Draw small circles around
each data point, and draw the best smooth curve through the data.
8. Analysis and Conclusions: Discuss and evaluate the results. Don't just present the
results, but interpret what they mean. If you get an unexpected result, explain why it
is unexpected and what may be the cause of the error. Be clear and concise.
9. Procedural Explanations: As you do the experiment, include brief statements of
what you are doing. Another person should be able to follow what you did.

SUGGESTIONS:
1. The lab notebook should be independent of the lab manual or instructions. It should
make sense" without referencing back to the lab manual or instructions. Brief
procedural statements should be included as needed. Questions should be rewritten as
statements of fact.
2. Extra pages such as curves plotted on graph paper, computer printouts, etc. should
be attached in the lab notebooks (glue, staple, or tape). Do not attach lab
handouts.
3. Note any special problem encountered in performing the experiment in your lab
notebook (i.e., erratic readings, etc.).
4. Use a consistent pattern of headings and subheadings.
5. Record observations directly. Recopying from scrap paper should be avoided. It is
important in engineering to develop the ability to record neat and readable data
directly. Time spent recopying is usually time wasted.
6. Your lab notebook should have sufficient information and clarity to return to the lab
at a later date and repeat t experiment and for another person to understand what you
did and what your results and conclusions are.

DECLARATION
I declare that I have read and understood all the aforementioned instructions and that I
will abide by them during the whole semester.

Student Signature: ______________

----------------------LAB 1-----------------------

Introduction to DSP Kit C6713


Objective:
To get the students introduced with Digital Signal Processors and the DSP kit based
on TMS320C6713.
What is a DSP?
It is a processor specially designed for processing of digital signals. DSPs differ
from general purpose processors (such as 8086, P-III, P-IV, etc.) in architecture as well as
their applications. General purpose processors are utilized primarily for data
manipulation while DSPs for mathematical operations.
DSP Chip History:

First Commercial DSPs


 1982 NEC PD7720
 1982 TMS 32010

These chips initially cost around $600. Now cost less than $1

Texas Instruments (TI) DSP Family


 Low Cost, Fixed-Point, 16-Bit Word length Motor control, disk head positioning,
control
Fixed vs. Floating-Point DSPs:
DSPs are available both in fixed-point as well floating-point versions. The first ones
are optimized for operating integers while the later ones are designed to operate on
floating-point numbers.
Advantages of DSPs over Analog Circuits:

Can implement complex linear or nonlinear algorithms

Can modify easily by changing software

Reduced parts count makes fabrication easier.

High reliability

TMS320C6713 DSK Features:

A TMS320C6713 DSP operating at 225 MHz.

An AIC23 stereo codec with Line In, Line Out, MIC, and headphone stereo jacks

16 Mbytes of synchronous DRAM


512 Kbytes of non-volatile Flash memory (256 Kbytes usable in default
configuration)
4 user accessible LEDs and DIP switches
Software board configuration through registers implemented in CPLD
Configurable boot options
Expansion connectors for daughter cards

Board Layout:
The C6713 DSK is a 8.75 x 4.5 inch (210 x 115 mm.) multi-layer board which is
powered by an external +5 volt only power supply. Figure shows the layout of the
C6713 DSK.

First Lab Session:


In this lab you will learn to open build and run an existing project. You will also
complete a short assignment in this session. You should also browse through the

10

online manuals for the CPU, peripherals, and software development tools.
Remember that this class is not a race and you should work carefully and
understand exactly what you are doing at each step.
Getting started with the DSP kit:
You must have the followings to proceed with the lab exercises.
a.
Hardware:
1.
DSP kit based on TMS320C6713 DSP
2.
USB cable to connect PC and DSK
3.
Power adapter and power cable for DSK
4.
Oscilloscope
5.
Audio lead to connect DSK with oscilloscope / speaker

b. Software:
Code Composer Studio v3.1- This gives an integrated development environment used to
1.
create and edit source code
2.
compile programs
3.
load programs into DSP, run programs, single-step execution, break points, read
memory and registers, profile running programs, etc.
4. build libraries.
5.
debug a program in real-time

Startup your DSK


1. Connecting the DSK to Your PC:
1.1 Connect the supplied USB cable to your PC or laptop.
1.2 Connect the included 5V power adapter brick to your AC power source using
the AC power cord.
1.3 Apply power to the DSK by connecting the power brick to the 5V input on the
DSK.

11

1.4

When power is applied to the board, the Power On Self Test (POST) will run.
LEDs 0-3 will flash. When the POST is complete all LEDs blink on and off
then stay on. At this point your DSK is functional

2. Testing Your Connection:


If you want to test your DSK and USB connection you can launch the C6713 DSK
Diagnostic Utility from the icon on your desktop.

From the diagnostic utility, press the start button to run the diagnostics. In
approximately 30 seconds all the on-screen test indicators should turn green. During
POST, a 1 kHz sinusoid is output from the AIC23 codec for 1 second. You can
listen this tone on speaker or watch on oscilloscope using appropriate cable.
3. Starting Code Composer Studio:
Launch CCS from the icon on the desktop.

A USB enumeration process takes place. Then CCS will be opened and the LEDs
will turn off. Select Debug Connect menu item. This will establish a connection
between your PC and the DSP kit. The symbol at the left bottom of the window will
change from Not Connected to Connected.

Not Connected

Connected

4. Quick Test of DSK:


Select GEL Check DSK Quick Test from the menu. The quick test can be
used for confirmation of correct operation and installation. The following message
is then displayed:
Switches: 15
Board Revision: 2
CPLD Revision: 2

12

This assumes that the four dip switches (0, 1, 2, 3) are all in the up position. Change
the switches to (1110)2 so that the last three switches (1, 2, 3) are up and press the
first switch (0) down. Repeat the procedure to select GEL Check DSK
Quick Test and verify that the value of the switches is now 14 (with the display
Switches: 14). You can set the value of the four user switches from 0 to 15
5. Running an existing project in CCS:
5.1 Create a folder with your name in D:\ drive. This is your working folder for DSP
labs.
5.2 Browse to locate Start folder in C:\CCStudio_v3.1\MyProjects. Copy this folder
Start in your working folder.
5.3 Select Project Open menu item and browse to locate and open start.pjt. Double
clicking on Start.pjt(Debug) makes the components of the project visible.
5.4 Open the file main.c under Source subfolder.
5.5 At this stage the CCS screen will look similar to this.

5.6
5.7
5.8
5.9

Select Project Build menu item. This will build the project and create a hex file
start.out in the Debug folder. This file is the one that will be executed by the DSP.
Select Debug Connect from the menu.
Select File Load Program from the menu. This will open up a window to allow
you to select start.out and will copy the file into the memory of DSP.
When the .out file is loaded into DSP memory, the DSP is ready to execute the
program. Press button
program.

or select Debug Run from the menu to execute the

13

5.10 You will see a message Hello World in the Stdout (standard output) window.
5.11 If the processor is still running, halt it.
Use button
or select Debug Halt from the menu.
5.12 If
you
wish to re-run the program, select Debug Restart menu
item and run the program using Debug Run.
5.13 Select Debug Reset from the menu. This is the software reset of DSK. Now you
will not be able to run the program without loading it (step 8) again.

Warning: You are required to save all your work (projects,


files, data, etc.) in your working folder with
your group number (e.g. BETE-Gp3). Do check the
location where you are saving, before pressing
the button. Any work saved on Desktop or in C:\
drive will not be marked.

Assignment 1:
Modify the program to print a table of 17 like this. Use for loop.
17 x 1 = 17
17 x 2 = 34
..
17 x 10 = 170
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

14

----------------------LAB 2-----------------------

Create, Configure and Build a New


Project in CCS and Debugging Using
Breakpoints and Watch Window
Objective:
In this lab you will learn to create, configure and build a new project. You will also learn
to add breakpoints and watch variables.
1. Creating a new Project:
1.1 Open CCS and create new project (Project: New).
1.2 Select your working folder in the Location field.
1.3 Type Lab2 in Project Name field.
1.4 Select TMS320C67XX in Target field and click on Finish. This will create a
project dotp.pjt. Note that a folder dotp has also been created in your working
folder. All your project files will locate in this folder.
1.5 Now create a new source file (File New Source File). Add the following
code to this file. Save this file as dotp.c in dotp folder. The code can also be
found in the file dotp.txt in the instructors share folder.

15

int dotp(short *a, short *b, int ncount);


//function prototype
#include <stdio.h>
//for printf
#define count 4
//# of data in each array
short x[count] = {1,2,3,4};
//declaration of 1st array
short y[count] = {1,2,4,6}; //declaration of 2nd array
main()
{
int result = 0;
//result sum of products
result = dotp(x, y, count);
//call dotp function
printf("result = %d (decimal) \n", result); //print result
}
int dotp(short *a, short *b, int ncount)
{
int sum = 0;
int i;
for (i = 0; i < ncount; i++)
sum += a[i] * b[i];
return(sum);
}
1.6

//dot product function


//init sum variable

//sum of products
//return sum as result

Right click on dotp.pjt in project window and select Add Files to Project.
Browse in the opened window to select dotp.c.
1.7 In the same fashion add the following files to your project
C:\CCStudio_v3.1\Support\vectors.asm
[used to set up interrupt vectors]
C:\CCStudio_v3.1\Support\c6713dsk.cmd
[linker command file this or another cmd file is required]
C:\CCStudio_v3.1\C6000\cgtools\lib\rts6700.lib
[run-time support library functions - required]
1.8 At this stage the CCS project window should look similar
to this.
1.9 Now build the program and ignore the warnings if any.
1.10 Load the program and run.
1.11 You should get the following result in the output window.
result = 41 (decimal)
1.12 This is the result of dot product of two arrays as
implemented in the program.

16

2.

Breakpoints and watch window:


Breakpoints allow you to stop the DSP, executing a program, for a while and have a
look on values stored in DSP memory. It is a debug tool. Some more debug tools
will be introduced in the coming lab sessions.
2.1 Select Debug Restart menu item. This will
make the DSP restart the program placed in its
memory. Select Debug Go Main from the
menu. This will take the DSP to the start of main( )
function, as indicated by the yellow pointer.
2.2 Locate the line
sum += a[i] * b[i];
in the code and double-click on the left side of
this line. This will add a breakpoint on this line,
indicated by a red mark.
2.3 Now run the program. You will see the Double-click here
pointer has moved to the line where you have
put a breakpoint. Now DSP has executed the code upto this point.
2.4 Right click on the variable sum and select Add to Watch Window. A watch
window will be opened and the variable sum is added to it. For now the value
stored in this variable is zero.
2.5 Run the program again. Now sum is updated and you see the yellow pointer at the
same location. This is because you have placed the breakpoint in a loop and every
time when the loop is executed, it encounters the breakpoint and stops.
2.6 Now run the program few more times and see the variable updated, until the
program ends and it comes out of the code.
Note: You can also execute a single step from Debug menu. Step Into takes you
into any function called while Step Over executes the functions called in a single
step and jump to the next line in the same routine. If you have stepped into a
function, Step Out completes the execution of the function takes you out of it.

Assignment 2
In your working folder, create a new project A2.pjt and create a file A2.c and add
to the project. Write code to calculate moving average of a 20-element array taking
four elements at a time. The program will take elements 1,2,3,4 for the first time,
calculates their average and stores in another array. In consecutive iterations it will
take elements 2,3,4,5, then 3,4,5,6, and so on, each time calculating average of four
elements and saving in the array. When it is done, print the output array.

17

----------------------LAB 3-----------------------

Discrete Time Signals: Time Domain


Representation in Matlab
Objectives:
1.

2.
3.

To learn how to generate some basic discrete-time signals in MATLAB and


perform elementary operations on them, which are the main objectives of this first
exercise.
To learn the application of some basic MATLAB commands and how to apply them
in simple digital signal processing problems.
To learn how plot signals in time-domain with a variety of flavours.

MATLAB Commands Used


The MATLAB commands you will encounter in this exercise are as follows:
Operators and Special Characters
: .
%
+

Elementary Matrices and Matrix Manipulation


i
ones pi
rand
randn
Elementary Functions
cos
exp

imag

zeros

real

Data Analysis
Sum
Two-Dimensional Graphics
axis
grid
legend
stem
title
xlabel

plot
stairs
ylabel

General Purpose Graphics Functions


subplot
hold

18

Signal Processing Toolbox


sawtooth
square
sin
cos
For additional information on these commands, see the MATLAB Reference Guide
[Mat05] or type help command name in the Command window. To get a quick start
download

Introduction:
1.
Unit Impulse and Unit Step Sequences
The unit impulse sequence, often called the discrete-time impulse, denoted by [n],
is defined by
[n] = 1,
for n = 0,
0,
for n 0.
(1)
The unit step sequence, denoted by [n], is dened by
u[n] = 1,
0,

for n 0,
for n < 0

(2)

Examples:
A unit step sequence u[n] can be generated using the MATLAB command
u = [zeros(1,N) ones(1,M)];
(where M and N are integers)
(example: u = [zeros(1,4) ones(1,10)]; )
A unit impulse sequence ud[n] of length N and delayed by M samples, where M <
N, can be generated using the MATLAB command
ud = [zeros(1,N)
1
zeros(1,M)];
(where M and N are integers)
(example: ud = [zeros(1,5) 1
zeros(1,7)]; )
A delayed unit step sequence can be generated in a manner similar to that used in
the generation of a delayed unit sample sequence.
Program P1 _1 can be used to generate and plot a unit step sequence.
% Program P1_1
% Generation of a Unit Impulse Sequence
% Generate a vector from -10 to 20
n = -10:20;
% Generate the unit sample sequence
u = [zeros(1,10) 1 zeros(1,20)];
% Plot the unit sample sequence
stem(n,u);
xlabel(Time index n);ylabel(Amplitude);
title(Unit Sample Sequence);

19

axis([-10 20 0 1.2]);
Lab Exercise 1:
1.1 Run Program P1 _1 to generate the unit step sequence u[n] and display it.
1.2 What are the purposes of the commands axis, title, xlabel, and ylabel?
1.3 Modify Program P1_1 to generate a delayed unit sample sequence ud[n] with a
delay of 11 samples. Run the modified program and display the sequence
generated.
1.4 Modify Program P1_ 1 to generate a delayed unit step sequence sd[n] with an
advance of 7 samples. Run the modified program and display the sequence
generated
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

20

2.

Exponential Signals
The exponential sequence is given by
x[n] = An,
where A and are real or complex numbers. By expressing
= e+j,
and A = |A|ej,
we can rewrite Eq. (3) as
x[n] = |A|en+j(n+)= |A|en cos(n + ) + j|A|en sin(n + )
or x[n] = |A|en cos(2fn + ) + j|A|en sin(2fn + )
Here is frequency in radians/s while f is frequency in Hz.

(3)

(4)

Examples : Exponential Signals


Exponential sequence can be generated using the MATLAB operators .^ and exp( )
function.
Program P1_2 given below can be employed to generate a complex-valued
exponential sequence.
% Program P1_2
% Generation of a complex exponential sequence
c = -(1/12)+(pi/6)*i;
K = 2;
n = 0:40;
x = K*exp(c*n);
subplot(2,1,1);
stem(n,real(x));
xlabel(Time index n);ylabel(Amplitude);
title(Real part);
subplot(2,1,2);
stem(n,imag(x));
xlabel(Time index n);ylabel(Amplitude);
title(Imaginary part);
Program P1_ 3 given below can be employed to generate a real-valued exponential
sequence.
% Program P1_3
% Generation of a real exponential sequence
n = 0:35; a = 1.2; K = 0.2;
x = K*a.^n;
stem(n,x);
xlabel(Time index n);ylabel(Amplitude);

21

Lab Exercise 2
2.1 Run Program P1_2 and generate the complex-valued exponential sequence.
2.2 Which parameter controls the rate of growth or decay of this sequence? Which
parameter controls the amplitude of this sequence?
2.3 What will happen if the parameter c is changed to (1/12)+(pi/6)*i?
2.4 What are the purposes of the operators real and imag?
2.5 What is the purpose of the command subplot?
2.6 Run Program P1_3 and generate the real-valued exponential sequence.
2.7 Which parameter controls the rate of growth or decay of this sequence? Which
parameter controls the amplitude of this sequence?
2.8 What is the difference between the arithmetic operators ^ and .^ ?
2.9 What will happen if the parameter a is less than 1? Run Program P1 3 again
with the parameter a changed to 0.9 and the parameter K changed to 20
2.10 What is the length of this sequence and how can it be changed?
2.11 You can use the MATLAB command sum(s.*s) to compute the energy of a
real sequence s[n] stored as a vector s. Evaluate the energy of the real-valued
exponential sequences x[n] generated in Questions Q1.5 and Q1.10. Explain
in your own words how this command works on the input vector s.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

22

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

3.

Sinusoidal Signals
In continuous-time, a sinusoidal signal can be expressed as
x(t) = A cos(ot + )
(5)
Here A, o, and are real numbers and are called the amplitude , the angular
frequency , and the initial phase of the sinusoidal signal, respectively. fo= o/2 is
the frequency in Hz. When we sample the continuous-time signal to get discrete-

23

time signal, actually we replace t by nT , where T is the sampling period


(duration between two successive samples) and n is the sample number.
Then Eq. (5) becomes
x(nT) = A cos(onT + )
(6)

Example :
Sinusoidal sequences can be generated in MATLAB using the trigonometric
functions cos( ) and sin( ).
Program P1_ 4 is a simple example that generates a sinusoidal signal.
% Program P1_4
% Generation of a sinusoidal sequence
close all;
clear all;
n = 0:40;
f = 1;
phase = 0;
A = 1.5;
T=0.01
%sampling period is 0.01 second
arg = 2*pi*f*n*T - phase;
x = A*cos(arg);
stem(n,x);
% Plot the generated sequence
axis([0 40 -2 2]);
grid;
title(Sinusoidal Sequence);
xlabel(Sample index n);
ylabel(Amplitude);
figure;
%create new figure
stem(n*T,x);
grid;
title(Sinusoidal Sequence);
xlabel(Time);
ylabel(Amplitude);

Lab Exercise 3
1.17 Run Program P1_4 to generate the sinusoidal sequence and display it.
1.18 What is the frequency of this sequence and how can it be changed? Which
parameter controls the phase of this sequence? Which parameter controls the
amplitude of this sequence? What is the period of this sequence?

24

1.19
1.20
1.21
1.22

1.23
1.24

1.25

1.26

1.27

1.28

What is the length of this sequence and how can it be changed?


Compute the average power of the generated sinusoidal sequence.
What are the purposes of the axis and grid commands?
Modify Program P1_4 to generate a sinusoidal sequence of frequency 0.5 Hz
and display it. Compare this new sequence with the one generated in Question
Q1.17. Now, modify Program P1_4 to generate a sinusoidal sequence of
frequency 1.5 Hz and display it. Compare this new sequence with the one
generated in Question Q1.17. Comment on your results.
Rerun P1_4 with T = 0.005. What changes do you observe in the signal
displayed?
Modify the above program to generate a sinusoidal sequence of length 50,
frequency 0.8, amplitude 2.5, and phase shift 90 degrees and display it. What
is the period of this sequence?
Replace the stem command in Program P1_4 with the plot command and run
the program again. What is the difference between the new plot and the one
generated in Question Q1.17?
Replace the stem command in Program P1_4 with the stairs command and run
the program again. What is the difference between the new plot and those
generated in Questions Q1.17 and Q1.24?
How the sampling period and number of cycles displayed in a figure in
above exercises are related to each other? If we like to increase the number of
cycles displayed, how should we change the sampling period? What other
parameters can be changed to increase the number of cycles? Try increasing
them.
Like sinusoidal signals, you can also generate other periodic signals in
Matlab, such as square-wave using square( ) and sawtooth wave using
sawtooth( ) function. Get help on these functions from Matlab and generate
the two signals with sampling frequency 1000 Hz and signal frequency 100
Hz.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

25

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

26

----------------------LAB 4-----------------------

Configuring McBSP and Interfacing


with the Codec TLV320AIC23
Objective:
In this lab you will learn to configure McBSP (multi-channel buffered serial port) and
interface with the codec TLV320AIC23. You will also learn to graph a variable with
variety of parameters.
1. McBSP on C6713

Most of TI DSPs have built-in multi-channel buffered serial port (McBSP). It is


similar to a computer serial port, with some additional features.

In C6713, McBSP has two serial channels called McBSP0 and McBSP1.

On DSK6713, McBSP1 is connected to a codec (coder-decoder).

The codec has an Analog-to-Digital Coveter (ADC) and a Digital-to-Analog


Converter (DAC).

With this McBSP1 to codec connection, DSP can send/receive digital data to/from
codec.

In todays lab, we will use DAC portion of codec, therefore we will send digital
data to codec.
2. Codec TLV320AIC23

This is a 16-bit audio codec that converts an analog signal to digital data and vice
versa at sampling rates ranging from 8 kHz to 96 kHz.

When used as a DAC, it receives a 16-bit digital sample from DSP thru McBSP1
and generates equivalent analog value.

If the sampling rate is 8 kHz, it will receive 8000 digital samples per second and
generate their equivalent analog values. In this case any two consecutive samples
will be 125 us apart.

After every 125 us, it generates an interrupt for DSP. In response the DSP sends
next digital sample and so on.

27

3. Hardware Interrupts

An interrupt generated by a hardware module may be termed as hardware interrupt


(HWI).

In CCS, for each HWI, an interrupt service routine (ISR) is defined.

ISR is a function written in a source code file, which executes at the occurrence of
the corresponding HWI.
4. Interrupts in C6713

16 interrupt sources (timers, serial ports, )

12 interrupt events (INT4 to INT15) are available to user

INT0 to INT3 are reserved

Interrupt events must be mapped to interrupt sources

Interrupt vectors must be set up. An interrupt vector is a special pointer to the
start of the interrupt service routine (ISR). There are 12 interrupt vectors.

1
2
3

16

Timer0 interrupt
Timer1 interrupt
McbSP0 interrupt
.
.........
DMA interrupt

INT4
INT5
INT6
.
.....
Mapping INT15

Interrupt sources

Interrupt events
Codec-McBSP Interface and Interrupt

5. Generating Sine Wave with Codec

28

DMA ISR
Timer0 ISR
..
..
.........
McBSP0 ISR
ISRs

Digital value sent to codec must be 16-bit long.


The 16-bit word can take values -32768 to 32767.
Each value sent to codec converts into a voltage level in the range +Vmax and Vmax.
In this exercise we have used following 8 sample values to generate a sine wave.
0,
7070, 10000, 7070, 0, -7070, -10000, -7070, 0
These samples were calculated as sine values of 8 angle values on circle and
multiplied by 10000. These samples are 10000*sin(0), 10000*sin(45)
10000*sin(90), 10000*sin(135) and so on.
The 360 degrees of a circle is divided into 8 sections and we have got 8 digital
samples.

If you want to have 10 digital samples per cycle, you will have to divide the circle
into 10 sections.
These samples will be sin(0), sin(36), sin(72), sin(108), sin(144),.. multiplied by
a factor such as 10000.
The selection of number of samples per cycle depends on the sampling frequency
and signal frequency.

In this lab exercise, we have configured the codec for sampling frequency 8 kHz,
and we wanted to generate 1 kHz.
In other words we had 8000 samples per second and 1000 cycles per second.
Then it becomes very easy to find samples / cycles.

29

6. Lab Exercise:
6.1 Create a project sine1.pjt in your working folder. Create a new source file and
add the following code to the file. This code can also be found in the file
sine1.txt. Save this file as sine1.c and add to the project.

#include <std.h>
#include <dsk6713.h>
#include <DSK6713_AIC23.h>
Uint32 fs=DSK6713_AIC23_FREQ_8KHZ;
int loop = 0;
short sine_table[8]={0,7070,10000,7070,0,-7070,-10000,-7070};
values

//sine

int cntr = 0;
void c_int11(void)
{
short out_data = 0;
Uint32 in;
out_data = sine_table[loop];
if (++loop > 7) loop = 0;
output_sample(out_data);
return;
}
void main()
{
comm_intr();
while(1);
}

6.2
6.3

//ISR defined in .cdb

//if end of table reinit index


//real-time output

//init codec,DSK, MCBSP


//infinite loop
//end of main

Select File New DSP/BIOS configuration from the menu. This will open a
window. From this window select dsk6713.cdb and click OK.
Now you will see a Config Tool window with various system options, as shown
in the diagram.

30

6.4
6.5

6.6

6.7

6.8

Save the file as sine1.cdb.


Double-click on Scheduling. Double-click on HWI-Hardware Interrupt Routine
Service Manager. This will show you a list of interrupts ranging from
HWI_RESET to HWI_INT15. Right click on HWI_INT11 and select
Properties. This will open a window HWI_INT11 Properties.
Select MCSP_1_Transmit as interrupt source and type _c_int11 in the function
field. Note that you have defined a function c_int11( ) in your Lab3.c. Note that
you have set sampling frequency of 8 kHz for codec. Therefore the ISR will be
called 8000 times a second, during execution of program. The other options that
you have for sampling frequency are 16, 24, 32, 44, 48 and 96 kHz.
Now click on Dispatcher tab. Check Use Dispatcher. Now you have configured
interrupt 11 for McBSP1 transmit and an ISR for this interrupt has also been
declared. Click OK.
Save the file Lab3.cdb again and close. When a CDB file is saved, the Config
Tool creates a number of other files:

6.9

Now add this file to the project. When you add a CDB file to your project, CCS
automatically adds the .c, .cmd and assembly (.s62) files. To prevent confusion,
these files are added to the Generated Files folder. Remember that in previous
programs you had added a user-created .cmd file manually, that is done by the
software now.
6.10 Add the following files to the project.

31

C:\CCStudio_v3.1\C6000\dsk6713\lib\dsk6713bsl.lib
[Board Support library - required to use peripherals on-board]
C:\CCStudio_v3.1\Support\c6713dskinit.c
[Contains some useful functions for codec]
6.11 Right-click on sine1.pjt in project window and select Build Options. Click on
Compiler tab and click on Basic category. Select C671x in Target Version.
6.12 Now select Advanced category. In Memory Models select Far(-mem_model:data=far).
6.13 Then select Preprocessors category. In Pre-Define Symbol field, type
CHIP_6713. And in Include Search Path field, enter the complete path of the
file dsk6713.h. Click OK.

6.14 Build the project and load the .out file to the DSP. Run the program.
6.15 Connect the Line Out of DSP kit to the oscilloscope and see the waveform.
Measure the frequency and note down. You may also hear this as a tone on
speaker.

Assignment 3
1
In this lab, you generated 1 kHz sine wave. What factors decided the frequency of
the generated signal? Explain with calculations. What may be the simplest
modification in code required to generate a frequency of 2 kHz?
2
Create a project A3.pjt similar to Lab3 which should generate a sine wave with
frequency 8 kHz.

32

----------------------LAB 5-----------------------

Using a Timer on DSP


Objective
In this lab exercise you will learn to configure a timer and write ISR for interrupt
generated by timer.
1.

Create a project Timer1.pjt in your working folder in D: drive and add a new
timer1.c file having the following code. This code can be copied from the file
timer1.txt placed in instructors share folder.
#include <stdio.h>
#include <csl.h>
#include <csl_timer.h>
#include <csl_irq.h>
#define TIMER_CNT 20 /* Maximum count value */
static int cnt = 0;
void main()
{
/* Initialize the chip support library, must when using CSL */
CSL_init();
IRQ_map(IRQ_EVT_TINT1, 10); // Map T1 interrupt onto INT11
IRQ_globalEnable();
// Globally enable interrupts
IRQ_enable(IRQ_EVT_TINT1);
// Enable T1 interrupt
while(cnt <= TIMER_CNT);
}
/*------------------Timer 1 ISR ---------------------------Increments a count value every time when interrupt occurs and
exit the program when count reaches TIMER_CNT value -------*/
void HWI_T1(void) {
/* increments count value */
cnt++;
/* Exit from the program when certain count is reached */
if (cnt > TIMER_CNT)
{
printf("\nTEST PASSED\n");
exit(0);
}
printf("\n Count : %3d ",cnt);
return;
}

33

2.
3.

4.
5.
6.

Create a new CDB file and save as timer1.cdb.


In the left column of the Config Tool window, double-click on CSL-Chip Support
Library and double-click on TIMER-Timer Device. Right-click on TIMER
Configuration Manager and select Insert timerCfg. This will create timerCfg0
module.
Right-click on the newly-created timer configuration module and select Properties.
Under the General tab, type T1 in comment.
Click on Clock Control tab. In the Input Clock Source select (CPU clock)/4. In
the Clock/Pulse Mode select Clock mode.
Click on Counter Control tab. In the Timer Operation select Start with reset. In
the Period Value, type 0x10000. This value sets the number of clock cycles after
which an interrupt will be generated. This value can be converted to time using
following relation.
Interrupt

7.

8.

Period Value
period in seconds = 2
Clock Frequency

In our case Period Value is 10000 hex or 65536 decimal and clock frequency is
CPU clock/4 or 225/4 = 56.25 MHz. Hence an interrupt will be generated after
every 2.33 ms (2*65536 / 56.25 MHz = 2.33 ms). Click OK. It is a 32-bit timer and
at maximum you can set 4294967295 (4.29 x 109) as period value*.
Double-click on Timer Resource Manager. You will see three timers numbered
from 0 to 2. Timer2 is not available in C6713 while Timer0 is not available to user.
Right-click on Timer_Device1 and select Properties. Mark the two available
options. In Pre-Initialize with field select timerCfg0. This is the same timer
configuration module that you have created and setup in steps 3 ~ 6. Now timer 1
has been configured to interrupt CPU after every 1.165 ms.
Now configure INT 10 and associate it with Timer 1. When you have configured
INT 10, it should look like following. Dont forget to check Use Dispatcher.

* 232 -1 = 4294967295

34

9.
10.

11.
12.

Save this CDB file as timer1.cdb and close. Add this file to project.
Open Build Options dialog box and select Compiler tab. Under Basic category,
select C671x as Target Version. Under Preprocessor category type CHIP_6713
in Pre-Define Symbol field. Click OK.
Build, load and run the program.
This program will print count values from 1 to 20 and exit.

Assignment 4
Create a new project Timer_LED.pjt. In this project, use timer1 to generate
interrupt after every 2 seconds. At the occurrence of interrupt, toggle LED 0.
Consequently, LED 0 will flash with 2 seconds ON and 2 seconds OFF.
Hint: Use following functions to access LEDs.
DSK6713_LED_init( ) [For initialization, call once at the start of code]
DSK6713_LED_on(n)
DSK6713_LED_off(n)
DSK6713_LED_toggle(n)
where n = 0, 1, 2 ,3 indicating the LED to access.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

35

----------------------LAB 6-----------------------

Profiling and LOG_printf


Objective
In this exercise you will learn to profile a function and to use LOG_printf, a timeefficient version of the conventional printf function.
1.

Create a project MyPrint.pjt in your working folder in D: drive and add a new file
print.c having the following code. This code can be copied from the file print.txt
placed in instructors share folder.
#include <stdio.h>
void print_hello();
void main()
{
print_hello();
fflush(stdout);
return;
}
void print_hello()
{
printf("Hello World");
}

2.
3.

Create a new DSP/BIOS configuration file and save as print.cdb. Use the default
settings of .cdb file. Add this file to the project.
Build and load the project. Select Debug Go Main.

36

4.

5.

6.

7.

8.

9.

Select Profile Setup. This will open a profile setup window. In this window you
can select the general or specific items for which you want data collected. Click on
the button in this window. This will enable profiling for this project.
In the profiling setup window, click on Ranges tab. In the Range Type column,
double-click on Functions. Then double-click on Disabled. You will see here a list
of functions that are currently disabled for profiling. You are interested in profiling
the function print_hello( ). To enable this function for profiling, locate this function
in the list and right-click and select Enable/Disable Selected Item(s).
Now click Custom tab. In this tab you will select the data that you want to collect
for the selected function. In this exercise, we are interested in noting the number of
cycles taken by the selected the function to execute. Select Cycles from this list.
Now select Profile Viewer menu item. In the profile viewer window, you will
see the selected functions and the corresponding set of data selected in step 6, when
you run the program.
Run the program. You will see Hello World displayed in message window. When
it has displayed the message, halt the DSP if it is still running. Now you will see the
profile viewer window populated with some information for print_hello( ) function.
In the profile view window, you will see the information about the number of cycles
for print_hello( ) function in the following categories.
Cycles: Incl. Total
Cycles: Excl. Total
Exclusive (Excl.) shows the cycles for the specified function only.
Inclusive (Incl.) is the cycles required for the specified function plus all subfunctions.

37

10.

11.

12.

13.

For example:
Incl Total = Excl Total + printf (not shown)
2025
25
2000
In this exercise you have established to count the number of cycles required to
execute a function. In a similar fashion you can profile any function or even a range
of code in any of your project.
Close the project and reset the DSP using Debug Reset CPU menu item.

LOG_printf
Normally, for debugging purposes, we want to display information in CCS message
window. For this we use printf( ) function. But this function requires extensive
program, and data memory and the DSP has to format the string in this technique.
Therefore this function takes too many cycles to perform. This is wastage of DSP
cycles. Here we will introduce another technique used for printing messages,
similar to printf( ). This technique leaves the formatting job for CCS. LOG_printf( )
function gives raw information to CCS which is then formatted by CCS itself and
displayed. In the subsequent steps you will learn how to use LOG_printf( ).
Create a new project print_LOG.pjt and add a new file print_LOG.c to the project.
Add the following code to this file.
#include <stdio.h>
#include <log.h>
#include "print_LOGcfg.h"
void print_hello();
void main()
{
print_hello();
}
void print_hello()
{
LOG_printf(&trace,"Hello World");
}

14.

15.

Now create a new DSP/BIOS configuration file and save as print_LOG.cdb. In this
CDB file, double-click on Instrumentation. Within this category, right-click on
LOG-Event Log Manager and select Insert LOG. This will create a new log event
named LOG0. Rename LOG0 as trace. Save the CDB file and close.
Build and load program. Select Debug Go Main from the menu.

38

16.

17.
18.

19.

Now select DSP/BIOS Message Log from the menu. This will open a message
window with Log Name trace. In this window you will see the message displayed
by LOG_printf( ) function, when you will run the program.
Before running the program, setup the profiler as you did in steps 4~7.
Run the program. You will see Hello World displayed in the new message
window and the profiler will display the cycles information about the print_hello( )
function.
Note this information. You must have observed that LOG_printf( ) is less time
consuming as compared to printf( ). And you know, for DSP code, time is a
precious commodity.

39

----------------------LAB 7-----------------------

Discrete-Time Signals and Systems:


Frequency Domain Analysis in Matlab
Objective:
This lab exercise will familiarize the students with the frequency domain concepts and
the effect of filtering as observed in time-domain as well as frequency domain.

1.

2.

Signals and Matlab


To generate a signal in Matlab you must specify
o
Sampling frequency (Fs) or time period (Ts)
o
Duration of this signal (T)
Then you can define a vector representing time
o
t = 0:Ts:T
Now you must specify the type of signal to be generated.
If it is a periodic one, it may be cos, sin, square, etc. In all cases you must know the
frequency (f) of the signal you like to generate.
o
cos (2 * pi * f * t)
o
sin (2 * pi * f * t)
o
square (2 * pi * f * t)
Frequency Domain analysis
In time domain, we plot the signal versus time. This shows, at what time, what was
the amplitude of the signal.
In frequency domain, we plot the amplitude and/or phase of a signal versus
frequency. This shows what was the amplitude or phase of a certain frequency
present in the signal.
Its a tool used for analysis. It gives a clear picture of frequency contents present in
the signal and the frequency band occupied by the signal.
Frequency band is the range of frequencies occupied or utilized by a signal. The
width of this band is called bandwidth.
This tool is generally used by designers, regulatory authorities, certification bodies,
etc.

40

As far as this course is concerned, we are studying frequency domain to observe


filtering effect.

3.

Matlab and frequency domain analysis


Fourier transform is the tool used to transform a signal from time-domain to
frequency- domain.
In Matlab, we use fft( ) for this transformation.
Fourier transform of a real signal is always complex.
In this course, we will be interested in the amplitude of Fourier transform, for which
we use abs( ).
To go back to time-domain ifft( ) is used.

Note: fft = Fast Fourier transform


ifft = Inverse Fast Fourier transform
4.

Filtering
In signal processing, filtering is the process of selecting some frequencies and
suppressing others.
It is similar to a window through which you can see a selected portion of an object.
A signal when filtered may loss some of its frequency contents.

Few Common Type of filters

41

5.

6.

Impulse Response and Frequency Response


The characteristic of filters when represented in frequency domain is called
frequency response.
When represented in time domain, it is called impulse response.
Filtering and convolution
Usually we perform filtering operation in time domain, while in frequency domain
we analyze the frequency contents of signals as well as behaviour of the filter.
To perform filtering operation on a signal in time domain, we convolve the impulse
response with the signal.
If an original signal is represented as x[n] and impulse response is h[n], the filtered
signal will be determined using the relation

y[n] = x[n] * h[n] =

x[n k ]h[k ]
k =

To make simple you may consider convolution as dot product of two arrays. We
will discuss this aspect of convolution in detail in a coming lab.

Instructions: For each exercise create new m-file. All m-files should reside in your
working folder\MatlabLab2\...
7.

Matlab Exercises
7.1 Taking FFT of sinusoidal signals
Exercise-1

Generate a sine wave of frequency 100 Hz, with sampling frequency 1 kHz for a
time span of 5 seconds.

Define a vector freq in this way
freq = 0:Fs-1

where Fs is the sampling frequency in Hz.

Take FFT of this signal in the following way.
freq_domain = fft (time_domain_signal,Fs)

The function fft( ) gives you complex numbers. You may find amplitude or phase
from this sequence of complex numbers. To find out amplitude use abs( ) function
and plot it on y-axis versus freq on x-axis.

In the figure you will get a peak at freq = 100. This conveys information to you that
signal fed to fft( ) function contains 100 Hz frequency.

This figure gives you another peak at 900 Hz. What does it mean?
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

42

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Exercise-2
Generate a signal containing frequencies 70 Hz, 200 Hz and 300 Hz and take
fft( ) of the signal and plot its amplitude.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

7.2

FFT of non-sinusoid signals

Exercise-3
Generate a square wave with frequency 100 Hz and sampling frequency 1000Hz for

a time span of 10 seconds. Use square( ) function.

Take FFT of this signal and plot its amplitude. Discuss the figure generated. What
information do you get from it?
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

43

7.3 Filtering
Exercise-4
Generate a square wave with parameters same as in Exercise-5.


Design a FIR filter with and cut-off frequency 200 Hz, using fir1( ) function.
fir1(N, w)
where N is the filter order and w is the normalized cut-off frequency. It is
defined as w = 2fc / Fs, where fc is cut-off frequency in Hz.

Use conv( ) function to convolve the signal with the filter.

Plot the output of the filter both in time-domain and frequency domain.

How the filtering process has modified the signal? Discuss.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

44

----------------------LAB 8-----------------------

Codec Input/output and Graphing an


Array
Objective
In this lab you will implement a modified version of Lab 3 in which you generated a sine
wave. You will also learn to take digitized samples of analog input to codec. Further you
will learn to graph a variable array in CCS.
1.

Create a new project sine2.pjt and create new source file sine2.c and add the
following code to this file. This code can be found in the file sine2.txt. This is the
same program as sine1 except the sine table is defined as float. The float values,
before sending to codec, are converted to short to make it compatible with the
codec.
#include <dsk6713.h>
#include <DSK6713_AIC23.h>
Uint32 fs=DSK6713_AIC23_FREQ_8KHZ;
float sine_table[8]={0,0.707,1,0.707,0,-0.707,-1,-0.707}; //sine values
int loop = 0;
void c_int11(void)
//ISR defined in .cdb
{
short out_data;
out_data = (short)(sine_table[loop]*32767);
if (++loop > 7) loop = 0;
//if @end of table reinit index
output_sample(out_data);
//real-time output
return;
}
void main()
{
comm_intr();
while(1);
}

//init codec, DSK, McBSP


//infinite loop
//end of main

45

2.
3.
4.

Add all necessary files to the project, configure the build options as required, build,
load and run the program.
You will observe a sine wave again with the same frequency of 1 kHz, but with
minor difference.
Create a new project sine_in.pjt and create new source file sine_in.c and add the
following code to this file. This code can be found in the file sine_in.txt.

#include <dsk6713.h>
#include <DSK6713_AIC23.h>
Uint32 fs=DSK6713_AIC23_FREQ_8KHZ;
short signal_in[1000];
int cntr = 0;
void c_int11(void)
{
short sample_rcvd;
Uint32 in;
in = input_sample();
sample_rcvd = (short)in;
signal_in[cntr] = sample_rcvd;
if (++cntr>999)
cntr = 0;
output_sample(sample_rcvd);
return;
}
void main()
{
comm_intr();
while(1);
}

5.
6.

7.
8.
9.

//ISR defined in .cdb

//real-time output

//init codec,DSK, MCBSP


//infinite loop
/end of main

Add necessary files and configure build options as required. Build the program and
load into DSP. From Debug menu select Go Main.
Now power up the function generator and set the function generator for 200 Hz sine
wave with 1Vpp and zero offset. To verify these parameters, see the output on
oscilloscope.
Now connect the output of function generator to the Line In of the kit.
Run the program.
Place a breakpoint on the line
cntr = 0;
46

10.
11.

12.

13.
14.
15.

16.
17.
18.

As soon as you place the breakpoint, the processor stops running and you will see a
pointer at this line.
Now you can see the samples of the signal input to DSP that you have received and
saved in signal_in[ ] array. Right-click in the main window and select Insert
Graph. This will open Graph Property Dialog Box.
In this dialog box, in the Start Address field, type signal_in. Similarly modify
other fields as follows, and click OK.
Acuisition Buffer Size : 1000
Display Data Size : 1000
DSP Data Type : 16-bit signed integer
You will now see a graph on which x-axis shows the sample-index and y-axis
represents sampled values. This graph must be smooth sine wave.
Determine the number of samples taken to complete a cycle. With this number can
you measure the frequency of this wave? [Hint: You know the sampling frequency].
Right-click on graph and select Properties. The same dialog box will be opened.
Now select FFT Magnitude in Display Type and type 8000 in Sampling Rate.
Type 100,000 in Maximum Y-value field. Click OK
Now you will see the same signal in frequency domain. If the peak of this graph is
not visible try a bigger value in Maximum Y-value.
X-axis of this graph represents the frequency while y-axis represents magnitude.
Which frequency does the peak correspond to?

Assignment 5
Did you find any difference between the observations made in Lab3 and Lab4a?
1.
Explain and justify if any.
2.
In the following line of code in Lab4a.c
out_data = (short)(sine_table[loop]*32767);
Replace the multiplying factor 32767 with a suitable one such that the output
observed at oscilloscope is 1 Vpp. Selection of the factor should be based on
calculations.
3.
In Lab4a, divide out_data by 2 before sending to codec, build and run the program.
Do you observe anything different?
4.
In Lab4a, multiply out_data by 2 before sending to codec, build and run the
program. Explain and justify your observation.
In Lab4b, what is the maximum signal frequency that you can capture? Try
5.
increasing signal frequency. What do you observe? Justify your observation.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------47

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

48

----------------------LAB 9-----------------------

Implementation of Filters
on DSK6713
Objective
In this exercise, you will learn how to implement a simple filter in CCS.
Digital signal processing allows the inexpensive construction of a wide variety of filters.
The signal is sampled and an analog to digital converter turns the signal into a stream of
numbers. A computer program running on a CPU or a specialized DSP (or less often
running on a hardware implementation of the algorithm) calculates an output number
stream. This output can be converted to a signal by passing it through a digital to analog
converter. There are problems with noise introduced by the conversions, but these can be
controlled and limited for many useful filters. Due to the sampling involved, the input
signal must be of limited frequency content or aliasing will occur.

The following diagram shows the basic setup of such a system.

Note that in a digital filter, the signal is represented by a sequence of numbers, rather than
a voltage or current.

49

Advantages of digital filters


The following list gives some of the main advantages of digital over analog filters.
1.

2.
3.

4.

5.

A digital filter is programmable, i.e. its operation is determined by a program stored


in the processor's memory. This means the digital filter can easily be changed
without affecting the circuitry (hardware). An analog filter can only be changed by
redesigning the filter circuit.
Digital filters are easily designed, tested and implemented on a general-purpose
computer or workstation.
The characteristics of analog filter circuits (particularly those containing active
components) are subject to drift and are dependent on temperature. Digital filters do
not suffer from these problems, and so are extremely stable with respect both to
time and temperature.
Unlike their analog counterparts, digital filters can handle low frequency signals
accurately. As the speed of DSP technology continues to increase, digital filters are
being applied to high frequency signals in the RF (radio frequency) domain, which
in the past was the exclusive preserve of analog technology.
Digital filters are much more versatile in their ability to process signals in a variety
of ways; this includes the ability of some types of digital filter to adapt to changes
in the characteristics of the signal.

Fast DSP processors can handle complex combinations of filters in parallel or cascade
(series), making the hardware requirements relatively simple and compact in comparison
with the equivalent analog circuitry.

50

Lab Exercise
1.

Create a project avg_flt.pjt and add following code to the new source file avg_flt.c
Add other necessary files and set build options as required.
#include <dsk6713.h>
#include <DSK6713_AIC23.h>
Uint32 fs=DSK6713_AIC23_FREQ_8KHZ;
int cntr = 0;
short buf[4] = {0,0,0,0};
int sum=0;
void c_int11(void)
//ISR defined in .cdb
{
short out_data = 0;
Uint32 in;
int i;
in = input_sample();
for (i=0;i<3;i++)
buf[i] = buf[i+1];
buf[3] = (short)in;
sum = 0;
for (i=0;i<4;i++)
sum = sum + buf[i];
sum = sum/4;
out_data = (short)sum;
output_sample(out_data);
return;
}
void main()
{
comm_intr();
while(1);
}

2.

3.
4.

//init codec,DSK, MCBSP


//infinite loop
//end of main

In this code we have implemented a moving average filter with 4 taps. Using a
signal generator, feed a sinusoidal signal with 1 Vpp into Line In of DSP kit and
connect Line Out to oscilloscope.
Build and run the program.
Sweep the input frequency from 0 to 2 kHz. What did you observe at the output?

51

Assignment 6
1.
How will you explain your observation in step 4? You may get help with Matlab to
justify your answer.
2.
Write a program lowpass.pjt to implement a 16-order low-pass FIR filter with cutoff frequency at 5 kHz. Generate filter coefficients using fir1 command in Matlab.
Set sampling frequency 48 kHz in this program. Sweep input frequency from 0 to
15 kHz, keeping input signal amplitude 1 Vpp. Describe and justify the output
observed.
What will happen if you change sampling frequency to 96 kHz in the project
3.
lowpass.pjt, keeping other parameters unchanged? Have you observed any
difference in the behaviour of the filtering process? If yes, why?
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

52

You might also like