You are on page 1of 116

ELECTRONICS COMMUNICATION ENGG RGIT

Rajiv Gandhi Institute of Technology


Cholanagar, Hebbal, R.T.Nagar (po) Bangalore-32

V SEMESTER B.E

DSP LAB - 06ECL57

ACADEMIC YEAR 2010 – 2011

ELECTRONICS & COMMUNICATION ENGINEERING

LABORATORY MANUAL

NAM E OF THE STUDENT :

UNIVERSITY SEAT NO. :

SEMESTER :

BATCH :

DSP LAB (06ECL57) V SEMESTER


DSP MAT LAB MANUAL 2010-2011

INTRODUCTION TO MAT LAB

MATLAB stands for matrix laboratory. It is a technical computing environment


for high performance numeric computation and visualization.

Matlab integrated numeric analysis, matrix computation, signal processing and


graphics in an easy to use environment.

There are several toolboxes available from mat lab. These tool boxes are
collections of functions written for special application such as symbolic computation,
image processing, statistics, and control system design.

In Matrix laboratory there exist 3 major windows which is termed as basic


windows as listed below
1. Command window.
2. Graphics or figure window.
3. Editor window.

COMMAND WINDOW
This is the main window .it is characterized by the Matlab command prompt’>>’.
when you launch an application program, MATLAB puts you in this window, all
commands including those for running user written programs are typed in this window at
the MATLAB prompt.

GRAPHICS or FIGURE WINDOW


The output of all the graphics commands typed in the command window is
flushed to the graphics or figure window. The user can create as many as many figure
windows, as the system memory will allow.

Dept of E&C, RGIT, Bangalore 2


DSP MAT LAB MANUAL 2010-2011

EDITOR WINDOW
This is where you write, edit, create, and save your own programs in files called
‘m-files’. MATLAB provides its own built in editor.

MATLAB FILE TYPES


Mat lab has three types of files for storing.
1. M-files
2. MAT –files
3. MEX-files.

M-files
They are standard ASCII text files with an .m extension to the file name. They are
two types of m-files namely script file function file.

MAT-files
These are binary data files, with a .m extension to the file name. MAT files are
created by MATLAB when you save the data with the save command. The data is written
in a special format that only MATLAB can read.

MEX-files
These are MATLAB callable FORTRAN and C programs with an . mex
extension to the file name.

Dept of E&C, RGIT, Bangalore 3


DSP MAT LAB MANUAL 2010-2011

BUILT IN FUNCTIONS

Dept of E&C, RGIT, Bangalore 4


DSP MAT LAB MANUAL 2010-2011

1. VERIFICATION OF SAMPLING THEOREM

Procedure: -

1. Select a frequency of ‘f’ Hz


2. To generate a sine wave of F Hz, define a closely spaced time vector(to represent
analog signal, at least 1000 samples pr cycle)t=0:1/1000:1;
3. Generate the sinusoid, and plot the signal x_analog=sin(2*pi*F*t)
4. Select a sampling frequency Fs=10Fsamples/sec,generate a suitable time scale for
this sampling signal n=0:1/Fs:1;%vector to define the sampling instants
5. Sample the analog signal at the instants specified by ’n ’
x_discreate =sin (2*pi*F*n) plot this using separate subplot and stem
6. Modify the vector n used for discrete simulation ,with more time points in-
between and get the new interpolated vector ni;
7. Generate the interpolated sinusoid ’xni’ for the interpolated vector ‘ni’. This is an
approximation for analog reconstruction.
8. Compare the analog signal with the reconstructed signal. Repeat the experiments
for different values of analog sinusoid frequency and verify the reconstructed
signal with the analog signal

MATLAB program to illustrate sampling theorem


% First File to be named 'sample_t.m'
close all;

f1 = input ('The Frequency of the first sine wave in Hz: ');

f2 = input ('The Frequency of the second sine wave in Hz: ');

Fs = 2*max(f1,f2);

w2 = max(f1,f2)/(4*max(f1,f2));

N = 2;

t = 0:0.01:N*2*pi;

x = 2*sin(f1*t)+2*sin(f2*t);

x = x/6;

Dept of E&C, RGIT, Bangalore 5


DSP MAT LAB MANUAL 2010-2011

% Plot Original Signal

figure;

subplot(2,1,1)

plot(t,x);

title('Original Signal');

xlabel('Time -->');

ylabel('Amplitude');

% Create Low Pass Filter

h = fir1(10,w2);

resp = figure;

% Magnitude and Phase Response of Filter

freqz(h);

title('Magnitude and Phase Plot of Low Pass Filter');

samp_s(f1,f2,Fs,h,N,'Sampled at Nyquist Rate','Reconstructed from


Nyquist signals');

samp_s(f1,f2,Fs/4,h,N,'UnderSampled Samples','Reconstructed from


Undersampled samples');

samp_s(f1,f2,Fs*4,h,N,'OverSampled Samples','Reconstructed from


Oversampled samples');

% Second File to be named “samp_s.m”


function [xn,y]=samp_s(f1,f2,Fs,h,N,Title_signal,Title_Reconstruct)

figure;

%% Plot Sampled Signal Sampled at Nyquist Rate.

Ts = 0:1/Fs:N*2*pi;

subplot(2,1,1);

xn = sin(f1*Ts)+sin(f2*Ts);

Dept of E&C, RGIT, Bangalore 6


DSP MAT LAB MANUAL 2010-2011

xn = xn/3;

stem(xn);

xl='Samples -->';

yl='Amplitude-->';

title(Title_signal);

xlabel(xl);

ylabel(yl);

%% Reconstruct the signal by passing Sampled signal through a low pass

% filter

y = conv(xn,h);

subplot(2,1,2);

% Plot Reconstructed Signal

plot(y);

title(Title_Reconstruct);

xlabel(xl);

ylabel(yl);

RESULT: - VERIFICATION OF SAMPLING THEOREM


The Frequency of the first sine wave in Hz: 10 Amplitude of first sine wave: 1
The Frequency of the second sine wave in Hz: 20 Amplitude of first sine wave: 1
The sampling frequency in Hz = 100 Phase shift for first wave:0

Dept of E&C, RGIT, Bangalore 7


DSP MAT LAB MANUAL 2010-2011

The number periods for display = 5

2. IMPULSE AND STEP RESPONSE OF THE GIVEN SYSTEM

Procedure:-

Dept of E&C, RGIT, Bangalore 8


DSP MAT LAB MANUAL 2010-2011

1. Rewrite the difference equation so that y[n] and its delayed samples are on the
LHS
2. Create a matrix a for the coefficients of y[n] and its delayed versions
3. Create a matrix b for the coefficients of x[n] and its delayed versions
4. Generate impulse excitation signal delta [n]
5. Find the response h[n] of the filter defined by a & b coefficients , so the input
impulse excitation , using filter command
6. Display the impulse response h[n].

MATLAB CODE
clear
close all
clc
% SOLVE THE GIVEN DIFFERENCE EQUATION Y(N) - y(N-1) + 0.9Y(N-2) = X(N)
% FIND THE TRANSFER FUNCTION OF THE GIVEN DIFFERENCE EQUATION
H(Z) = Y(Z)/X(Z)
% NUMERATOR POLYNOMIAL IS 'A' AND DENOMINATOR POLYNOMIAL IS
'B'
% FOR THE ABOVE EXAMPLE B = [1] AND A = [ 1 -1 0.9 ]
b = [1];
a = [1 -1 0.9];
% H(N) IS REQUIRED FOR N = -20,-19,...,100
% SO GENERATE IMPULSE SEQUENCE OF THE ABOVE LENGTH
% N - TIME INDEX
n = [-20:100];
% X IS THE IMPULSE SEQUENCE
x = [(n == 0)];
% FIND THE OUTPUT OF THE SYSTEM FOR THE IMPULSE SEQUENCE WHICH
IS THE
% IMPULSE RESPONSE
h = impz(b,a);

Dept of E&C, RGIT, Bangalore 9


DSP MAT LAB MANUAL 2010-2011

h = filter(b,a,x);
% PLOT THE INPUT AND THE OUTPUT
figure(1);
subplot(2,1,1);
stem(n,x);
xlabel('Time index n');
ylabel('Amplitude');
title('Impulse Sequence');
grid on;

subplot(2,1,2);
stem(n,h);
%stem(h);
xlabel('Time Index n');
Ylabel('Amplitude');
title('Impulse Response');
grid on;

% GENERATE THE STEP SEQUENCE


% N - TIME INDEX
% X IS THE STEP RESPONSE
x = [(n >= 0)];
% FIND THE OUTPUT OF THE SYSTEM FOR THE STEP SEQUENCE
s = filter(b,a,x);
% PLOT THE INPUT AND THE OUTPUT
figure(2);
subplot(2,1,1);
stem(n,x);
xlabel('Time Index');
ylabel('Amplitude');
title('Step Sequence');

Dept of E&C, RGIT, Bangalore 10


DSP MAT LAB MANUAL 2010-2011

grid on;

subplot(2,1,2);
stem(n,s);
xlabel('Time index n');
ylabel('Amplitude');
title('Step Response');
grid on;

RESULT:-IMPULSE AND STEP RESPONSE OF THE GIVEN SYSTEM

Dept of E&C, RGIT, Bangalore 11


DSP MAT LAB MANUAL 2010-2011

3. LINEAR CONVOLUTION OF TWO SEQUENCES

Dept of E&C, RGIT, Bangalore 12


DSP MAT LAB MANUAL 2010-2011

Procedure:-
1. Read the input sequence, x[n] and plot
2. Read the impulse response of the system, h[n] and plot
3. Convolve the two results and plot them
Description:-
Linear Convolution involves the following operations.
1. Folding
2. Multiplication
3. Addition
4. Shifting

These operations can be represented by a Mathematical Expression as follows:

y[n] = ∑ x[k]h[n-k]

x[ ]= Input signal Samples


h[ ]= Impulse response co-efficient.
y[ ]= Convolution output.
n = No. of Input samples
h = No. of Impulse response co-efficient.

Eg: x[n] = {1, 2, 3, 4}


h[k] = {1, 2, 3, 4}

Where: n=4, k=4. : Values of n & k should be a multiple of 4.


If n & k are not multiples of 4, pad with zero’s to make
multiples of 4
r= n+k-1 : Size of output sequence.
= 4+4-1
= 7.
r= 0 1 2 3 4 5 6

Dept of E&C, RGIT, Bangalore 13


DSP MAT LAB MANUAL 2010-2011

n= 0 x[0]h[0] x[0]h[1] x[0]h[2] x[0]h[3]


1 x[1]h[0] x[1]h[1] x[1]h[2] x[1]h[3]
2 x[2]h[0] x[2]h[1] x[2]h[2] x[2]h[3]
3 x[3]h[0] x[3]h[1] x[3]h[2] x[3]h[3]

Output: y[r] = { 1, 4, 10, 20, 25, 24, 16}.

NOTE: At the end of input sequences pad ‘n’ and ‘k’ no. of zero’s

%Another Program:
clc;
close all;
x=input('Enter the input sequence x[n]: ');
h=input('Enter the system function h[m]: ');
n=length(x);
m=length(h);
l=n+m-1;
y=zeros(1,l);
x=[x,zeros(1,l-n)];
h=[h,zeros(1,l-m)];

for i=1:l,
for j=1:i,
y(i)=y(i)+x(j)*h(i-j+1);
end
end
disp(y)

RESULT: - LINEAR CONVOLUTION OF TWO FINITE LENGTH


SEQUENCE IN TIME DOMAIN

Dept of E&C, RGIT, Bangalore 14


DSP MAT LAB MANUAL 2010-2011

Dept of E&C, RGIT, Bangalore 15


DSP MAT LAB MANUAL 2010-2011

4. CIRCULAR CONVOLUTION OF TWO SEQUENCES.


Procedure:-
1. Enter the sequence x[n]
2. Enter the sequence y[n]
3. Find the lengths of x[n] and y[n],ie;Nx and Ny respectively
4. Check Nx=Ny:proceed if equal
5. Initialize a loop variable number of output points
6. For each out sample , access the samples of y[n] in the cyclic order
7. Find the sum of products of x[n] and cyclically folded and shifted y[n]

Description:-
Steps for Cyclic Convolution
Steps for cyclic convolution are the same as the usual convolution, except all index
calculations are done "mod N" = "on the wheel"
Steps for Cyclic Convolution

Step1: “Plot f[m] and h[−m]

Subfigure 1.1 Subfigure 1.2

Step 2: "Spin" h[−m] n times Anti Clock Wise (counter-clockwise) to get h[n-m]
(i.e. Simply rotate the sequence, h[n], clockwise by n steps)

Dept of E&C, RGIT, Bangalore 16


DSP MAT LAB MANUAL 2010-2011

Figure 2: Step 2

Step 3: Point wise multiply the f[m] wheel and the h[n−m] wheel. Sum=y[n]

Step 4: Repeat for all 0≤n≤N−1

Example 1: Convolve (n = 4)

Subfigure 3.1 Subfigure 3.2


Figure 3: Two discrete-time signals to be convolved.

• h[−m] =

Figure 4
Multiply f[m] and sum to yield: y[0] =3

• h[1−m]

Dept of E&C, RGIT, Bangalore 17


DSP MAT LAB MANUAL 2010-2011

Figure 5
Multiply f[m] and sum to yield: y[1] =5

• h[2−m]

Figure 6
Multiply f[m] and sum to yield: y[2] =3

• h[3−m]

Figure 7
Multiply f[m] and sum to yield: y[3] =1

Dept of E&C, RGIT, Bangalore 18


DSP MAT LAB MANUAL 2010-2011

MATLAB CODE
x=input('Enter the input sequence x[n]: ');
h=input('Enter the system function h[m]: ');
n=length(x);
m=length(h);
l=max(n,m);
y=zeros(1,l);
x=[x,zeros(1,l-n)];
h=[h,zeros(1,l-m)];
for i= 1:l,
j=i;
for k=1:l,
if(j<1)
j=l;
else j=j;
end
y(i)=y(i)+x(k)*h(j);
j=j-1;
end
end

display(x);
display(h);
display(y);

RESULT:-CIRCULAR CONVOLUTION OF TWO FINITE LENGTH


SEQUENCES IN TIME DOMAIN

Dept of E&C, RGIT, Bangalore 19


DSP MAT LAB MANUAL 2010-2011

Dept of E&C, RGIT, Bangalore 20


DSP MAT LAB MANUAL 2010-2011

5. AUTOCORRELATION
Procedure:-
1. Read the input sequence
2. Autocorrelate the signal using xcorr(x,x)
3. Display the Autocorrelation result in suitable axis
4. verify the correlation property:Rxx(0)=energy(x)
5. verify the property :Rxx is a even function
MATLABCODE
clear
clc
close all

% READ THE INPUT SIGNAL


x = input ('Enter the sequence');
%Define the axis
n = 0:1:length(x)-1;
% PLOT THE SIGNAL
subplot(2,1,1);
stem(n,x);
xlabel('n--->');
ylabel('x--->');
title('sequence x');
grid on;

% AUTOCORRELATE THE SIGNAL


Rxx = xcorr(x,x)
% AXIS FOR THE AUTOCORRELATION RESULT
nRxx = -length(x)+1:length(x)-1
% Display the result
subplot(2,1,2);
stem(nRxx,Rxx);

Dept of E&C, RGIT, Bangalore 21


DSP MAT LAB MANUAL 2010-2011

xlabel('nRxx--->');
ylabel('autocorrelation of x--->');
title('Autocorrelated sequence of x');
grid on;

%% VERIFICATION OF THE AUTOCORRELATION PROPERTIES


% PROPERTY-1: RXX(0) GIVES THE ENERGY OF THE SIGNAL
% Energy OF THE SIGNAL = SUM(SQUARES OF X)
energy = sum(x.^2);
% GET THE INDEX OF THE CENTER VALUE
center_index = ceil(length(Rxx)/2)
% ACCESS CENTER VALUE RXX(0)
Rxx_0 = Rxx(center_index)
% CHECK IF THE RXX(0) = ENERGY
if Rxx_0 == energy

disp('Rxx(0) gives energy -- propert-1 is proved');


else
disp('Rxx(0) gives energy -- propert-1 is not proved');
end

% PROPERTY-2: RXX IS EVEN


Rxx_Right = Rxx(center_index:1:length(Rxx));
Rxx_Left = Rxx(center_index:-1:1);
if Rxx_Right == Rxx_Left
disp('Rxx is even');
else
disp('Rxx is not even');
end

Dept of E&C, RGIT, Bangalore 22


DSP MAT LAB MANUAL 2010-2011

RESULT:- AUTOCORRELATION

Dept of E&C, RGIT, Bangalore 23


DSP MAT LAB MANUAL 2010-2011

6. CROSSCORRELATION
Procedure:-
1. Read the input sequence
2. Cross correlate the signal
3. Display the cross correlate result in suitable axis
4. Verify the correlation property:Rxx(0)=energy(x)
5. Verify the property :Rxx is a even function

MATLABCODE
clear
clc
close all

% READ THE INPUT SEUENCES


x = [2 -1 3 7 1 2 -3]
y = [1 -1 2 -2 4 1 -2 5]
%DEFINE THE AXIS
n1 = -4:1:2;
n2 = -4:1:3;
% PLOT THE SIGNAL
subplot(3,1,1);
stem(n1,x);
title('sequence-x');
grid on;
subplot(3,1,2);
stem(n2,y);
title('sequence-y');
grid on;

% CROSSCORRELATE THE SEQUENCES


r = conv(x, fliplr(y))

Dept of E&C, RGIT, Bangalore 24


DSP MAT LAB MANUAL 2010-2011

nr = -7:1:6;
subplot(3,1,3);
stem(nr,r);
title('Crosscorrelation sequence');
grid on;

RESULT:-
CROSSCORRELATION OF TWO SEQUENCES

Dept of E&C, RGIT, Bangalore 25


DSP MAT LAB MANUAL 2010-2011

7 (a). SOLUTION OF DIFFERENCE EQUATIONS


Procedure:-
1. Rewrite the given difference equation to have only the output terms on the RHS
and input terms to be on RHS
2. Create a Matrix of Y coefficients, A
3. Create a Matrix of X coefficients, B
4. Find The Impulse response of the system using IMPZ(B,A)
5. Plot the figure

MATLABCODE
clear
close all
clc

% THE INPUT SEQUENCE IS X(N) = U(N) - U(N-10)


% THE DIFFERENCE EQUATION IS Y(N) - 0.9Y(N-1) = X(N)
% FIND THE IMPULSE RESPONSE H(N) AND THE OUTPUT Y(N)
% FIND THE TRANSFER FUNCTION OF THE GIVEN DIFFERENCE EQUATION
H(Z) = Y(Z)/X(Z)
% NUMERATOR POLYNOMIAL IS 'A' AND DENOMINATOR POLYNOMIAL IS
'B'
% FOR THE ABOVE EXAMPLE B = [1] AND A=[1 -0.9]

b = [1];
a = [1 -0.9];
%a = [1,-5/6,1/6];

% FIND THE IMPULSE RESPONSE H(N)


% GENERATE IMPULSE SEQUENCE
% N -TIME INDEX

Dept of E&C, RGIT, Bangalore 26


DSP MAT LAB MANUAL 2010-2011

n = [-5:50];

% X IS THE IMPULSE SEQUENCE

x = [(n == 0)];

% FIND THE OUTPUT OF THE SYSTEM FOR THE IMPULSE SEQUENCE


% WHICH IS THE IMPULSE RESPONSE

h = filter(b,a,x);

% PLOT THE INPUT AND THE OUTPUT

figure(1)
subplot(2,1,1);
stem(n,x);
xlabel('n --> ');
ylabel('x --> ');
title('Impulse Sequence');
grid on;

subplot(2,1,2);
stem(n,h);
xlabel('n --> ');
ylabel('h --> ');
title('Impulse Response');
grid on;

% GENERATE THE INPUT SEQUENCE X(N)


x1 = [( n >= 0)];

Dept of E&C, RGIT, Bangalore 27


DSP MAT LAB MANUAL 2010-2011

x2 = (-1) * [( n - 10 ) >= 0];


x = x1 + x2;
%x = 2.^n

% FIND THE OUTPUT OF THE SYSTEM FOR THE INPUT SEQUENCE X(N)

y = filter(b,a,x);

% PLOT THE INPUT AND THE OUTPUT

figure(2)
subplot(2,2,1);
stem(n,x1);
xlabel('n --> ');
ylabel('x --> ');
title('Input squence x1(n)');
grid on;

subplot(2,2,2);
stem(n,x2);
xlabel('n --> ');
ylabel('x --> ');
title('Input squence x2(n)');
grid on;

subplot(2,2,3);
stem(n,x);
xlabel('n --> ');
ylabel('x --> ');
title('Input squence x(n)');
grid on;

Dept of E&C, RGIT, Bangalore 28


DSP MAT LAB MANUAL 2010-2011

subplot(2,2,4);
stem(n,y);
xlabel('n --> ');
ylabel('y --> ');
title('Output squence y(n)');
grid on;

RESULT:- DIFF EQN WITHOUT INITIAL COND

Dept of E&C, RGIT, Bangalore 29


DSP MAT LAB MANUAL 2010-2011

Dept of E&C, RGIT, Bangalore 30


DSP MAT LAB MANUAL 2010-2011

7(b). SOLUTION OF DIFFERENCE EQUATIONS GIVEN


WITH THE INITIAL CONDITIONS

clear
close all
clc
% SOLVE THE GIVEN DIFFERENCE EQUATION Y(N) - 1.5Y(N-1) + 0.5Y(N-2) =
X(N), N >= 0
% X(N) = (1/4)^n * U(N) SUBJECT TO Y(-1) = 4 AND Y(-2) = 10
% CALCULATE AND PLOT THE OUTPUT OF THE SYSTEM
% FIND THE TRANSFER FUNCTION OF THE GIVEN DIFFERENCE EQUATION
H(Z) = Y(Z)/X(Z)
% NUMERATOR POLYNOMIAL IS b AND DENOMINATOR POLYNOMIAL IS a
% FOR THE ABOVE EXAMPLE b = [1] AND a = [1 -1.5 0.5]

b = [1];
a = [1 -1.5 0.5];
% FIND THE INITIAL CONDITIONS FOR THE INPUT X SUCH THAT THE GIVEN
INITIAL CONDITIONS
% FOR Y ARE OBTAINED
yic = [4 10];
xic = filtic(b,a,yic);
xic
% GENERATE THE DISCRETE TIME INDEX
n = [0:7];
% GENERATE THE GIVEN INPUT X
x = (1/4).^n;
% FIND THE OUTPUT OF THE SYSTEM FOR THE INPUT SEQUENCE X
y = filter(b,a,x,xic);

Dept of E&C, RGIT, Bangalore 31


DSP MAT LAB MANUAL 2010-2011

% PLOT THE INPUT AND THE OUTPUT

figure(1)
subplot(2,1,1);
stem(n,x);
grid on;
xlabel('n --> ');
ylabel('x --> ');
title ('Input Sequence');
subplot(2,1,2);
stem(n,y);
xlabel('n --> ');
ylabel('y --> ');
title ('Output Sequence');
grid on;
RESULT:- DIFF EQN WITH INITIAL COND

Dept of E&C, RGIT, Bangalore 32


DSP MAT LAB MANUAL 2010-2011

8. COMPUTATION OF N-POINT DFT


Procedure:-
1) Enter the number of points, N
2) Enter the input sequence elements, x[n]
3) Create a vector for the sample index, ’n’
4) Initialize loop variable, ‘k’ for the DFT samples X(k)
5) Calculate the twiddle factor for each ‘k’
6) Multiply x[n] and the twiddle factors , elements-by-element
7) Sum all the products, assign to X(k)
8) Plot the magnitude and phase spectrum
9) Verify the results with built in function

clear
clc
close all
in =input('Enter a Sequence: ');
%% Description
N=length(in);
y=zeros(1,N);
%wn=exp(-(2*pi*i)/N);
for k=1:N,
for j=1:N,
y(k)=y(k)+in(j)*exp(-(2*pi*1i)*(j-1)*(k-1)/N);
end
end
out=y;
Mag_y=abs(y);
Phase_y=angle(y);
figure;
subplot(3,1,1)

Dept of E&C, RGIT, Bangalore 33


DSP MAT LAB MANUAL 2010-2011

stem(in);
subplot(3,1,2)
stem(Mag_y);
subplot(3,1,3)
stem(Phase_y);

%% To find IDFT
Y=zeros(1,N);
for k=1:N,
for j=1:N,
Y(k)=Y(k)+y(j)*exp((2*pi*1i)*(j-1)*(k-1)/N);
end
end
Y=Y/N;

RESULT:-

COMPUTATION OF DFT

Dept of E&C, RGIT, Bangalore 34


DSP MAT LAB MANUAL 2010-2011

9. LINEAR CONVOLUTION OF TWO FINITE LENGTH


SEQUENCESUSING DFT AND IDFT
Procedure:-
1) Find the length of the first sequence x[n]=x_length

Dept of E&C, RGIT, Bangalore 35


DSP MAT LAB MANUAL 2010-2011

2) Find the length of the first sequence h[n]=h_length


3) Estimate the number of samples in the result of linear convolution of x[n]
&h[n]=Y_length
4) If X_length <Y_length , pad enough number of zeros to x[n], so that the number
of samples in the modified x[n]=Y_length
5) If h_length <Y_length ,pad enough number of zeros to h[n], so that the number of
samples in the modified h[n]=Y_length
6) Take DFT for modified x[n]=x(k)
7) Take DFT for modified h[n]=H(k)
8) Compute Y(K)=X(K)*H(K)
9) Compute Y(n)=IDFT(Y(k))
10) Verify if Y[n]=conv(x,h)

clear
clc
close all
% FIRST SEQUENCE X1
x1 = [1 2 7 -2 3 -1 5];
nx1 = 0:length(x1)-1;
n1 = length(x1);
subplot(3,1,1);
stem(nx1,x1);
xlabel('n-->');
ylabel('x1-->');
title('First Sequence');
grid on;
% SECOND SEQUENCE X2
x2 = [1 3 5 -3 1];
nx2 = 0:length(x2)-1;
n2 = length(x2);

Dept of E&C, RGIT, Bangalore 36


DSP MAT LAB MANUAL 2010-2011

subplot(3,1,2);
stem(nx2,x2);
xlabel('n-->');
ylabel('x2-->');
title('Second Sequence');
grid on;

N = n1+n2-1;
% IF N > length(x1) or length(x2) ZERO PAD
newx1 = [x1,zeros(1,N-n1)];
newx2 = [x2,zeros(1,N-n2)];

% TAKE DFT OF FIRST SEQUENCE


x1dft = fft(newx1);
% TAKE DFT OF SECOND SEQUENCE
x2dft = fft(newx2);

% MULTIPLY THE TWO DFTS


ydft = x1dft .* x2dft

% TAKE IDFT OF THE PRODUCT OF TWO DFTS


disp('Response obtained by DFTs')
y = ifft(ydft)
n = 0:length(y)-1;
subplot(3,1,3);
stem(n,y);
xlabel('n-->');
ylabel('x2-->');
title('Linearly convoluted Sequence');
grid on;

Dept of E&C, RGIT, Bangalore 37


DSP MAT LAB MANUAL 2010-2011

% VERIFICATION WITH DIRECT CONVOLUTION


disp('Response obtained by DFTs')
Ydirect = conv(x1,x2)

RESULT:- LINEAR CONVOLUTION USING DFT AND IDFT

10. CIRCULAR CONVOLUTION OF TWO FINITE LENGTHS


Procedure:-
1) Find the length of the first sequence x[n]=x_length
2) Find the length of the first sequence h[n]=h_length

Dept of E&C, RGIT, Bangalore 38


DSP MAT LAB MANUAL 2010-2011

3) Estimate the number of samples in the result of linear convolution of x[n]


&h[n]=Y_length
4) If X_length <Y_length , pad enough number of zeros to x[n], so that the number
of samples in the modified x[n]=Y_length
5) If h_length <Y_length ,pad enough number of zeros to h[n], so that the number of
samples in the modified h[n]=Y_length
6) Take DFT for modified x[n]=x(k)
7) Take DFT for modified h[n]=H(k)
8) Compute Y(K)=X(K)*H(K)
9) Compute Y(n)=IDFT(Y(k))
10) Verify if Y[n]=conv(x,h)

MATLAB CODE

clear
clc
close all
% FIRST SEQUENCE X1
x1 = [1 0.5 1 0.5 1 0.5 1 0.5];
nx1 = 0:length(x1)-1;
n1 = length(x1);
subplot(3,1,1);
stem(nx1,x1);
xlabel('n-->');
ylabel('x1-->');
title('First Sequence');
grid on;

% SECOND SEQUENCE X2
x2 = [0 1 2 3];
nx2 = 0:length(x2)-1;

Dept of E&C, RGIT, Bangalore 39


DSP MAT LAB MANUAL 2010-2011

n2 = length(x2);
subplot(3,1,2);
stem(nx2,x2);
xlabel('n-->');
ylabel('x2-->');
title('Second Sequence');
grid on;

N = n1+n2-1;
% IF N > length(x1) or length(x2) ZERO PAD
newx1 = [x1,zeros(1,N-n1)];
newx2 = [x2,zeros(1,N-n2)];

% TAKE DFT OF FIRST SEQUENCE


x1dft = fft(newx1);
% TAKE DFT OF SECOND SEQUENCE
x2dft = fft(newx2);
% MULTIPLY THE TWO DFTS
ydft = x1dft .* x2dft

% TAKE IDFT OF THE PRODUCT OF TWO DFTS


disp('Response obtained by DFTs')
y = ifft(ydft)
n = 0:length(y)-1;
subplot(3,1,3);
stem(n,y);
xlabel('n-->');
ylabel('x2-->');
title('Linearly convoluted Sequence');
grid on;

Dept of E&C, RGIT, Bangalore 40


DSP MAT LAB MANUAL 2010-2011

% % VERIFICATION WITH DIRECT CONVOLUTION


disp('Response obtained by DFTs')
Ydirect = conv(x1,x2)

RESULT:-
CIRCULAR CONVOLUTION USING DFT AND IDFT

y(n)=
14.0000 - 0.0000i
16.0000 + 0.0000i
14.0000 - 0.0000i
16.0000 - 0.0000i

11. FIR FILTER DESIGN


Procedure:-
1) Get the sampling frequency
2) Get the pass band frequency

Dept of E&C, RGIT, Bangalore 41


DSP MAT LAB MANUAL 2010-2011

3) Get the stop band frequency or transition width


4) Get the pass band ripple and stop band attenuation
5) Select the window suitable for the stop band attenuation
6) Calculate the order ,N, based on the Transition width
7) Find the N window coefficients
8) Find truncated impulse response of h[n]
9) Verify the frequency response of h[n]

MALABCODE
clear

clc

close all

% ENTER THE SAMPLING FREQUENCY

Fs = input('Enter Sampling Frequency: '); %8000;

%NORMALIZED FREQUENCY = Fs/2

Fn = Fs/2;

% ENTER THE PASSBAND FREQUENCY

fp = input('Enter Pass Band Frequency: ');

Dept of E&C, RGIT, Bangalore 42


DSP MAT LAB MANUAL 2010-2011

% ENTER THE transition width

tw = input('Specify Transition Width: ');%500;

%NORMALIZE THE transition width TO NYQUIST FREQUENCY

twn = tw/Fn;

% ENTER THE STOPBAND ATTENUATION

As = input('Enter Stop Band Attenuation: ');

if As <= 21

N = ceil(2/twn);

wn = boxcar(N);

disp('Using Rectangular window')

elseif As > 21

Dept of E&C, RGIT, Bangalore 43


DSP MAT LAB MANUAL 2010-2011

N = ceil(6/twn);

wn = blackman(N);

disp('Using Blackman window')

end

% CALCULATE NORMALIZED CUT-OFF FREQUENCY

fc = (fp+tw)/Fn;

%WINDOWED RESPONSE COEFFICIENTS

hn= fir1(N-1,fc,wn);

% PLOT THE BLACKMAN WINDOW RESPONSE

wvtool(wn);

disp('Order of the Filter is'),N

Dept of E&C, RGIT, Bangalore 44


DSP MAT LAB MANUAL 2010-2011

% PLOT THE WINDOWED RESPONSE COEFFICIENTS

figure;

subplot(2,1,1);

plot(0:N-1,hn);

title('FIR filter coefficients h(n)')

% CALCULATE THE FREQUENCY RESPONSE AND PLOT IN A NEW FIGURE

[H,f] = freqz(hn,1,512,Fs);

mag = 20*log10(abs(H));

subplot(2,1,2);

plot(f,mag);

xlabel('frequency(Hz)-->');

ylabel('magnitude(dB)-->');

title('SMagnitude response');

Dept of E&C, RGIT, Bangalore 45


DSP MAT LAB MANUAL 2010-2011

grid on;

RESULT:- FIR FILTER DESIGN

Dept of E&C, RGIT, Bangalore 46


DSP MAT LAB MANUAL 2010-2011

12. IIR FILTER DESIGN


Procedure:-
1) Get the pass band and stop band edge frequencies
2) Get the pass band and stop band ripples
3) Get the sampling frequency
4) Get the order of the filter
5) Find the filter coefficients
6) Plot the magnitude response
MATLABCODE
clear
clc

close all

Dept of E&C, RGIT, Bangalore 47


DSP MAT LAB MANUAL 2010-2011

% ENTER THE SAMPLING FREQUENCY

Fs = input('ENTER THE SAMPLING FREQUENCY: ');

% ENTER THE PASSBAND FREQUENCY in hz

wp = input('ENTER THE PASSBAND FREQUENCY in hz: ');

% ENTER THE STOPBAND FREQUENCY in hz

ws = input('ENTER THE STOPBAND FREQUENCY in hz: ');

% ENTER THE PASSBAND RIPPLE & STOPBAND ATTENUATION

Rp = input('ENTER THE PASSBAND RIPPLE: ');

Rs = input('ENTER THE STOPBAND ATTENUATION: ');

%NORMALIZED SAMPLING FREQUENCY = Fs/2

Fn = Fs/2;

% DESIGN THE ANALOG BUTTERWORTH FILTER ORDER AND CUT-OFF


FREQUENCY

[N,wc] = buttord(wp/Fn, ws/Fn, Rp, Rs);

% Design the digital filter coeffecients

[b,a] = butter(N,wc);

Dept of E&C, RGIT, Bangalore 48


DSP MAT LAB MANUAL 2010-2011

% Display the frequency response of the digital filter coeffecients

[H,f] = freqz(b,a,512,8000);

subplot(2,1,1);

plot(f,20*log10(abs(H)))

xlabel('frequency(Hz)-->');

ylabel('magnitude(dB)-->');

title('Magnitude response');

grid on;

subplot(2,1,2);

plot(f,angle(H))

xlabel('frequency(Hz)-->');

ylabel('Angles(rad)--->');

title('Phase Response');

RESULT: - IIR FILTER DESIGN

Dept of E&C, RGIT, Bangalore 49


DSP MAT LAB MANUAL 2010-2011

Dept of E&C, RGIT, Bangalore 50


DSP MAT LAB MANUAL 2010-2011

PART – B
CODE COMPOSER STUDIO
(C/C++ Programming)

Dept of E&C, RGIT, Bangalore 51


DSP MAT LAB MANUAL 2010-2011

TMS320C6713 DSK BOARD FEATURES

Package Contents

The C6713™ DSK builds on TI's industry-leading line of low cost, easy-to-use
DSP Starter Kit (DSK) development boards. The high-performance board features the
TMS320C6713 floating-point DSP. Capable of performing 1350 million floating-point
operations per second (MFLOPS), the C6713 DSP makes the C6713 DSK the most
powerful DSK development board.

The DSK is USB port interfaced platform that allows to efficiently develop and
test applications for the C6713. The DSK consists of a C6713-based printed circuit board
that will serve as a hardware reference design for TI’s customers’ products. With
extensive host PC and target DSP software support, including bundled TI tools, the DSK
provides ease-of-use and capabilities that are attractive to DSP engineers.

Dept of E&C, RGIT, Bangalore 52


DSP MAT LAB MANUAL 2010-2011

The following checklist details items that are shipped with the C6713 DSK.

 TMS320C6713 DSK TMS320C6713 DSK development board

 Other hardware External 5VDC power supply

IEEE 1284 compliant male-to-female cable

 CD-ROM Code Composer Studio DSK tools

 Technical reference manual

The C6713 DSK has a TMS320C6713 DSP onboard that allows full-speed verification of
code with Code Composer Studio. The C6713 DSK provides:

 A USB Interface
 SDRAM and Flash ROM
 An analog interface circuit for Data conversion (AIC)
 An I/O port
 Embedded JTAG emulation support

Connectors on the C6713 DSK provide DSP external memory interface (EMIF) and
peripheral signals that enable its functionality to be expanded with custom or third party
daughter boards.
The DSK provides a C6713 hardware reference design that can assist you in the
development of your own C6713-based products. In addition to providing a reference for
interfacing the DSP to various types of memories and peripherals, the design also
addresses power, clock, JTAG, and parallel peripheral interfaces.The C6713 DSK

Dept of E&C, RGIT, Bangalore 53


DSP MAT LAB MANUAL 2010-2011

includes a stereo codec. This analog interface circuit (AIC) has the following
characteristics:

High-Performance Stereo Codec


• 90-dB SNR Multibit Sigma-Delta ADC (A-weighted at 48 kHz)
• 100-dB SNR Multibit Sigma-Delta DAC (A-weighted at 48 kHz)
• 1.42 V – 3.6 V Core Digital Supply: Compatible With TI C54x DSP Core
Voltages
• 2.7 V – 3.6 V Buffer and Analog Supply: Compatible Both TI C54x DSP
Buffer Voltages
• 8-kHz – 96-kHz Sampling-Frequency Support

Software Control Via TI McBSP-Compatible Multiprotocol Serial Port


• I 2 C-Compatible and SPI-Compatible Serial-Port Protocols
• Glueless Interface to TI McBSPs

Audio-Data Input/Output Via TI McBSP-Compatible Programmable Audio Interface


• I 2 S-Compatible Interface Requiring Only One McBSP for both ADC and
DAC
• Standard I 2 S, MSB, or LSB Justified-Data Transfers
• 16/20/24/32-Bit Word Lengths

The TMS320C6713™ DSP compose the floating-point DSP generation in the


TMS320C6000™ DSP platform. The C6713 device is based on the high-performance,
advanced very-long-instruction-word (VLIW) architecture developed by Texas
Instruments (TI), making this DSP an excellent choice for multichannel and
multifunction applications.
The 6713 DSK is a low-cost standalone development platform that enables
customers to evaluate and develop applications for the TI C67XX DSP family. The DSK
also serves as a hardware reference design for the TMS320C6713 DSP. Schematics,

Dept of E&C, RGIT, Bangalore 54


DSP MAT LAB MANUAL 2010-2011

logic equations and application notes are available to ease hardware development and
reduce time to market.

Operating at 225 MHz, the C6713 delivers up to 1350 million floating-point


operations per second (MFLOPS), 1800 million instructions per second (MIPS), and with
dual fixed-/floating-point multipliers up to 450 million multiply-accumulate operations
per second (MMACS).The DSK uses the 32-bit EMIF for the SDRAM (CE0) and
daughter card expansion interface (CE2 and CE3). The Flash is attached to CE1 of the
EMIF in 8-bit mode.

An on-board AIC23 codec allows the DSP to transmit and receive analog signals.
McBSP0 is used for the codec control interface and McBSP1 is used for data. Analog
audio I/O is done through four 3.5mm audio jacks that correspond to microphone input,
line input, line output and headphone output. The codec can select the microphone or the
line input as the active input. The analog output is driven to both the line out (fixed gain)
and headphone (adjustable gain) connectors. McBSP1 can be re-routed to the expansion
connectors in software.

A programmable logic device called a CPLD is used to implement glue logic


that ties the board components together. The CPLD has a register based user interface
that lets the user configure the board by reading and writing to the CPLD registers. The
registers reside at the midpoint of CE1.

The DSK includes 4 LEDs and 4 DIP switches as a simple way to provide the
user with interactive feedback. Both are accessed by reading and writing to the CPLD
registers. An included 5V external power supply is used to power the board. On-board
voltage regulators provide the 1.26V DSP core voltage, 3.3V digital and 3.3V analog
voltages.
A voltage supervisor monitors the internally generated voltage, and will hold the
boards in reset until the supplies are within operating specifications and the reset button is

Dept of E&C, RGIT, Bangalore 55


DSP MAT LAB MANUAL 2010-2011

released. If desired, JP1 and JP2 can be used as power test points for the core and I/O
power supplies.

Code Composer communicates with the DSK through an embedded JTAG


emulator with a USB host interface. The DSK can also be used with an external emulator
through the external JTAG connector.

TMS320C6713 DSP Features

 Highest-Performance Floating-Point Digital Signal Processor (DSP):


 Eight 32-Bit Instructions/Cycle
 32/64-Bit Data Word
 300-, 225-, 200-MHz (GDP), and 225-, 200-, 167-MHz (PYP) Clock Rates
 3.3-, 4.4-, 5-, 6-Instruction Cycle Times
 2400/1800, 1800/1350, 1600/1200, and 1336/1000 MIPS /MFLOPS
 Rich Peripheral Set, Optimized for Audio
 Highly Optimized C/C++ Compiler
 Extended Temperature Devices Available
 Advanced Very Long Instruction Word (VLIW) TMS320C67x™ DSP Core
 Eight Independent Functional Units:
 Two ALUs (Fixed-Point)
 Four ALUs (Floating- and Fixed-Point)
 Two Multipliers (Floating- and Fixed-Point)
 Load-Store Architecture With 32 32-Bit General-Purpose Registers
 Instruction Packing Reduces Code Size
 All Instructions Conditional
 Instruction Set Features
 Native Instructions for IEEE 754
 Single- and Double-Precision

Dept of E&C, RGIT, Bangalore 56


DSP MAT LAB MANUAL 2010-2011

 Byte-Addressable (8-, 16-, 32-Bit Data)


 8-Bit Overflow Protection
 Saturation; Bit-Field Extract, Set, Clear; Bit-Counting; Normalization
 L1/L2 Memory Architecture
 4K-Byte L1P Program Cache (Direct-Mapped)
 4K-Byte L1D Data Cache (2-Way)
 256K-Byte L2 Memory Total: 64K-Byte L2 Unified Cache/Mapped RAM, and
192K-Byte Additional L2 Mapped RAM
 Device Configuration
 Boot Mode: HPI, 8-, 16-, 32-Bit ROM Boot
 Endianness: Little Endian/Big Endian
 32-Bit External Memory Interface (EMIF)
 Glueless Interface to SRAM, EPROM, Flash, SBSRAM, and SDRAM
 512M-Byte Total Addressable External Memory Space
 Enhanced Direct-Memory-Access (EDMA) Controller (16 Independent Channels)
 16-Bit Host-Port Interface (HPI)
 Two Multichannel Buffered Serial Ports (McBSPs)
 Two Independent Clock Zones Each (1 TX and 1 RX)

Eight Serial Data Pins Per Port: Individually Assignable to any of the Clock Zones

 Each Clock Zone Includes:


 Programmable Clock Generator
 Programmable Frame Sync Generator
 TDM Streams From 2-32 Time Slots
 Support for Slot Bits Size8, 12, 16, 20, 24, 28, 32:
 Data Formatter for Bit Manipulation
 Wide Variety of I2S and Similar Bit Stream Formats
 Integrated Digital Audio Interface Transmitter (DIT) Supports:
 S/PDIF, IEC60958-1, AES-3, CP-430 Formats

Dept of E&C, RGIT, Bangalore 57


DSP MAT LAB MANUAL 2010-2011

 Up to 16 transmit pins
 Enhanced Channel Status/User Data
 Extensive Error Checking and Recovery
 Two Inter-Integrated Circuit Bus (I2C Bus™) Multi-Master and Slave Interfaces
 Two 32-Bit General-Purpose Timers
 Dedicated GPIO Module With 16 pins (External Interrupt Capable)
 Flexible Phase-Locked-Loop (PLL) Based Clock Generator Module

 IEEE-1149.1 (JTAG ) Boundary-Scan-Compatible


 Package Options:
 208-Pin Power PAD™ Plastic (Low-Profile) Quad Flat pack (PYP)
 272-BGA Packages (GDP and ZDP)
 0.13-µm/6-Level Copper Metal Process
 CMOS Technology
 3.3-V I/Os, 1.2-V Internal (GDP & PYP)
 3.3-V I/Os, 1.4-V Internal (GDP)(300 MHz only)

TMS320C6713 DSK Overview Block Diagram

Dept of E&C, RGIT, Bangalore 58


DSP MAT LAB MANUAL 2010-2011

Dept of E&C, RGIT, Bangalore 59


DSP MAT LAB MANUAL 2010-2011

INTRODUCTION TO CODE COMPOSER STUDIO

Code Composer is the DSP industry's first fully integrated development


environment (IDE) with DSP-specific functionality. With a familiar environment liked
MS-based C++TM, Code Composer lets you edit, build, debug, profile and manage
projects from a single unified environment. Other unique features include graphical
signal analysis, injection/extraction of data signals via file I/O, multi-processor
debugging, automated testing and customization via a C-interpretive scripting language
and much more.

CODE COMPOSER FEATURES INCLUDE:

• IDE
• Debug IDE
• Advanced watch windows
• Integrated editor
• File I/O, Probe Points, and graphical algorithm scope probes
• Advanced graphical signal analysis
• Interactive profiling
• Automated testing and customization via scripting
• Visual project management system
• Compile in the background while editing and debugging
• Multi-processor debugging
• Help on the target DSP

Note:-
Launch the DSK help file by opening the following file using Windows Explorer.

C:\CCStudio_v3.1\docs\hlp\c6713dsk.hlp

Dept of E&C, RGIT, Bangalore 60


DSP MAT LAB MANUAL 2010-2011

Documents for Reference:


spru509  Code Composer Studio getting started guide.
spru189  TMS320C6000 CPU & Instruction set guide
spru190  TMS320C6000 Peripherals guide
slws106d Codec(TLV320AIC23) Data Manual.
spru402  Programmer’s Reference Guide.
sprs186j  TMS320C6713 DSP

Soft Copy of datasheets are available at : C:\CCStudio_v3.1\docs\pdf.

Starting Code Composer


To start Code Composer Studio, double click the 6713 DSK CCStudio_v3.1 icon on your
desktop.

Start Code Composer Studio (ignore this if CCS is already running) by double-clicking
on the C6713 DSK icon on your desktop.

Use the Debug  Connect menu option to open a debug connection to the DSK
board

Dept of E&C, RGIT, Bangalore 61


DSP MAT LAB MANUAL 2010-2011

1. LINEAR CONVOLUTION

Description:-
Linear Convolution Involves the following operations.
6. Folding
7. Multiplication
8. Addition
9. Shifting

These operations can be represented by a Mathematical Expression as follows:

x[ ]= Input signal Samples


h[ ]= Impulse response co-efficient.
y[ ]= Convolution output.
n = No. of Input samples
h = No. of Impulse response co-efficient.

Algorithm to implement ‘C’ or Assembly program for Convolution:

Eg: x[n] = {1, 2, 3, 4}


h[k] = {1, 2, 3, 4}

Where: n=4, k=4. ;Values of n & k should be a multiple of 4.


If n & k are not multiples of 4, pad with zero’s to make
multiples of 4
r= n+k-1 ; Size of output sequence.
= 4+4-1

Dept of E&C, RGIT, Bangalore 62


DSP MAT LAB MANUAL 2010-2011

= 7.

r= 0 1 2 3 4 5 6
n= 0 x[0]h[0] x[0]h[1] x[0]h[2] x[0]h[3]
1 x[1]h[0] x[1]h[1] x[1]h[2] x[1]h[3]
2 x[2]h[0] x[2]h[1] x[2]h[2] x[2]h[3]
3 x[3]h[0] x[3]h[1] x[3]h[2] x[3]h[3]

Output: y[r] = { 1, 4, 10, 20, 25, 24, 16}.

NOTE: At the end of input sequences pad ‘n’ and ‘k’ no. of zero’s

Dept of E&C, RGIT, Bangalore 63


DSP MAT LAB MANUAL 2010-2011

C PROGRAM TO IMPLEMENT LINEAR CONVOLUTION

conv.cpp:
/* prg to implement linear convolution */
#include<cstdio>
using namespace std;

int *x,*h,*y;

int main()
{
int n,m,i,j,k;
printf("Enter Sequence Lengths n and m (space seperated) : ");
scanf("%d %d",&n,&m);
int l=m+n-1;
y=new int[l];
x=new int[l];
h=new int[l];

printf("Enter sequence x[n](space seperated): ");

for(i=0;i<l;i++)
{
if(i<n)
scanf("%d",&x[i]);
else x[i]=0;
}

printf("Enter sequence h[m](space seperated): ");


for(i=0;i<l;i++)
{
if(i<m)
scanf("%d",&h[i]);
else h[i]=0;
}

for(i=0;i<l;i++)
for(y[i]=0,j=0;j<=i;j++)
y[i] += x[j]*h[i-j];

for(i=0;i<l;i++)
printf("%d ",y[i]);
putchar('\n');

Dept of E&C, RGIT, Bangalore 64


DSP MAT LAB MANUAL 2010-2011

PROCEDURE:

 Open Code Composer Studio, make sure the DSP kit is turned on.

 Use the Debug  Connect menu option to open a debug connection to the DSK
board
 Start a new project using ‘Project-new ‘ pull down menu, save it in a
separate directory(C:\CCStudio_v3.1\myprojects) with name lconv.pjt.
 Add the source files conv.c

 to the project using ‘Project add files to project’ pull down menu.
 Add the linker command file hello.cmd .
(Path: C:\CCStudio_v3.1\tutorial\dsk6713\hello1\hello.cmd)
 Add the run time support library file rts6700.lib
(Path: C:\CCStudio_v3.1\c6000\cgtools\lib\rts6700.lib)
 Compile the program using the ‘Project-compile’ pull down menu or by
clicking the shortcut icon on the left side of program window.
 Build the program using the ‘Project-Build’ pull down menu or by
clicking the shortcut icon on the left side of program window.
 Load the program(lconv.out) in program memory of DSP chip using the
‘File-load program’ pull down menu.

 To View output graphically

Select view  graph  time and frequency.

Dept of E&C, RGIT, Bangalore 65


DSP MAT LAB MANUAL 2010-2011

Configure the graphical window as shown below

Dept of E&C, RGIT, Bangalore 66


DSP MAT LAB MANUAL 2010-2011

2. CIRCULAR CONVOLUTION
Description:-

Steps for cyclic convolution are the same as the usual convolution, except all index
calculations are done "mod N" = "on the wheel"

CPP PROGRAM TO IMPLEMENT CIRCULAR CONVOLUTION


#INCLUDE<CSTDIO>
using namespace std;
int *x,*h,*y;
int main()
{
int n,m,i,j,k;
printf("Enter n and m (space seperated) : ");
scanf("%d %d",&n,&m);
int l=m>=n?m:n;
y=new int[l];
x=new int[l];
h=new int[l];
printf("Enter a sequence(space seperated) of Length n : ");
for(i=0;i<l;i++)
{
if(i<n)
scanf("%d",&x[i]);
else x[i]=0;
}
printf("Enter a sequence(space seperated) of Length m : ");
for(i=0;i<l;i++)
{
if(i<m)
scanf("%d",&h[i]);
else h[i]=0;
}

Dept of E&C, RGIT, Bangalore 67


DSP MAT LAB MANUAL 2010-2011

//Computation of Circular Convolution


for(i=0;i<l;i++)
{
y[i]=0;
j=i;
for(k=0;k<l;k++)
{
j= j<0?l-1:j;
y[i]+=x[k]*h[j--];
}
}

//Print output
for(i=0;i<l;i++)
printf("%d ",y[i]);
putchar('\n');
}

IN PUT:
Eg: x[4]={1, 2, 3,4}
h[4]={1, 2, 3,4}
OUT PUT y[4]={26, 28, 26,20}

PROCEDURE:

 Open Code Composer Studio; make sure the DSP kit is turned on.
 Start a new project using ‘Project-new ‘ pull down menu, save it in a
separate directory(C:\CCStudio_v3.1\myprojects) with name cir conv.pjt.
 Add the source files Circular Convolution
 to the project using ‘Projectadd files to project’ pull down menu.
 Add the linker command file hello.cmd.
(Path: C:\CCStudio_v3.1\tutorial\dsk6713\hello1\hello.cmd)
 Add the run time support library file rts6700.lib
(Path: C:\CCStudio_v3.1\c6000\cgtools\lib\rts6700.lib)
 Compile the program using the ‘Project-compile’ pull down menu or by

Dept of E&C, RGIT, Bangalore 68


DSP MAT LAB MANUAL 2010-2011

clicking the shortcut icon on the left side of program window.


 Build the program using the ‘Project-Build’ pull down menu or by
clicking the shortcut icon on the left side of program window.
 Load the program(lconv.out) in program memory of DSP chip using the
‘File-load program’ pull down menu.

Dept of E&C, RGIT, Bangalore 69


DSP MAT LAB MANUAL 2010-2011

3. COMPUTATION OF N POINT DFT OF A GIVEN


SEQUENCE
Introduction:

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

CPP Program for DFT Computation

#include<cstdio>

#include<cmath>

using namespace std;

double* real;

double* imag;

double *x;

#define PI 3.14159265

Dept of E&C, RGIT, Bangalore 70


DSP MAT LAB MANUAL 2010-2011

int main(void)

int l,i=0;

printf("Enter the length of sequence: ");

scanf("%d",&l);

real=new double[l];

imag=new double[l];

x=new double[l];

printf("Enter the input sequence(space seperated): ");

while(i<l)

scanf("%le",&x[i++]);

for (i=0;i<l;i++)

real[i]=imag[i]=0;

putchar('\n');

//Compute DFT values

for(int k=0;k<l;k++)

for (int j=0;j<l;j++)

Dept of E&C, RGIT, Bangalore 71


DSP MAT LAB MANUAL 2010-2011

real[k]+= double(x[j])*cos(2*PI*k*j/l);

imag[k]-= double(x[j])*sin(2*PI*k*j/l);

//Print answer

for (i=0;i<l;i++)

printf("Real X[%d]= %f \tImaginary X[%d]= %f\n",i,real[i],i,imag[i]);

return 0;

PROCEDURE:

 Open Code Composer Studio, make sure the DSP kit is turned on.
 Use the Debug  Connect menu option to open a debug connection to the DSK
board
 Start a new project using ‘Project-new ‘ pull down menu, save it in a
separate directory(C:\CCStudio_v3.1\myprojects) with name dft.pjt.
 Add the source files dft.c
 to the project using ‘Projectadd files to project’ pull down menu.
 Add the linker command file hello.cmd .
(Path: C:\CCStudio_v3.1\tutorial\dsk6713\hello1\hello.cmd)
 Add the run time support library file rts6700.lib

Dept of E&C, RGIT, Bangalore 72


DSP MAT LAB MANUAL 2010-2011

(Path: C:\CCStudio_v3.1\c6000\cgtools\lib\rts6700.lib)
 Compile the program using the ‘Project-compile’ pull down menu or by
clicking the shortcut icon on the left side of program window.
 Build the program using the ‘Project-Build’ pull down menu or by
clicking the shortcut icon on the left side of program window.
 Load the program(dft.out) in program memory of DSP chip using the
‘File-load program’ pull down menu.

Dept of E&C, RGIT, Bangalore 73


DSP MAT LAB MANUAL 2010-2011

REAL TIME EXPERIMENTS

Procedure for Real time Programs :

1. Connect a Signal Generator/audio input to the LINE IN Socket or connect a


microphone to the MIC IN Socket.

Note:- To use microphone input change the analog audio path control register
value (Register no. 4) in Codec Configuration settings of the Source file
(Codec.c) from 0x0011 to 0x0015.

2. Connect CRO/Desktop Speakers to the Socket Provided for LINE OUT or connect a
headphone to the Headphone out Socket.

Dept of E&C, RGIT, Bangalore 74


DSP MAT LAB MANUAL 2010-2011

3. Now Switch on the DSK and Bring Up Code Composer Studio on the PC.

4. Use the Debug  Connect menu option to open a debug connection to the DSK
board

5. Create a new project with name codec.pjt.

6. Open the File Menu  new  DSP/BIOS Configuration select


“dsk6713.cdb” and save it as “xyz.cdb”

7. Add “xyz.cdb” to the current project.


Project Add files to project xyz.cdb

Dept of E&C, RGIT, Bangalore 75


DSP MAT LAB MANUAL 2010-2011

8. Automatically three files are added in the Generated file folder in project pane
xyzcfg.cmd Command and linking file
xyzcfg.s62  optimized assembly code for configuration
xyzcfg_c.c  Chip support initialization

9. Open the File Menu  new  Source file


10. Type the code in editor window. Save the file in project folder. (Eg: Codec.c).

Important note: Save your source code with preferred language extension. For
ASM codes save the file as code(.asm) For C and C++ codes code (*.c,*.cpp)
respectively.

11. Add the saved “Codec.c” file to the current project which has the main function and
calls all the other necessary routines.
Project  Add files to Project  Codec.c

12. Add the library file “dsk6713bsl.lib” to the current project


Path  “C:\CCStudio_v3.1\C6000\dsk6713\lib\dsk6713bsl.lib”
Files of type  Object and library files (*.o*, *.l*)

13. Copy header files “dsk6713.h” and “dsk6713_aic23.h” from and paste it in current
project folder.
C:\CCStudio_v3.1\C6000\dsk6713\include.

14. Add the header file generated within xyzcfg_c.c to codec.c

Note:- Double click on xyzcfg_c.c. Copy the first line header (eg.#include
“xyzcfg.h”) and paste that in source file (eg.codec.c).

Dept of E&C, RGIT, Bangalore 76


DSP MAT LAB MANUAL 2010-2011

15. Compile the program using the ‘Project-compile’ pull down menu or by
Clicking the shortcut icon on the left side of program window.

16. Build the program using the ‘Project-Build’ pull down menu or by clicking the
shortcut icon on the left side of program window.

17. Load the program (Codec. Out) in program memory of DSP chip using the
‘File-load program’ pull down menu.

18. Debug Run

19. You can notice the input signal of 500 Hz. appearing on the CRO verifying the codec
configuration.
20. You can also pass an audio input and hear the output signal through the speakers.
21. You can also vary the sampling frequency using the DSK6713_AIC23_setFreq
Function in the “codec.c” file and repeat the above steps.

5.0 Conclusion:
The codec TLV320AIC23 successfully configured using the board support library
and verified.

Dept of E&C, RGIT, Bangalore 77


DSP MAT LAB MANUAL 2010-2011

4. FINITE IMPULSE RESPONSE FILTER (FIR)

DESIGNING A FIR FILTER:


Following are the steps to design linear phase FIR filters Using Windowing Method.

I. Clearly specify the filter specifications.


Eg: Order = 30;
Sampling Rate = 8000 samples/sec
Cut off Freq. = 400 Hz.

II. Compute the cut-off frequency Wc


Eg: Wc = 2*pie* fc / Fs
= 2*pie* 400/8000
= 0.1*pie

III. Compute the desired Impulse Response h d (n) using particular Window
Eg: b_rect1=fir1 (order, Wc , 'high',boxcar(31));

IV. Convolve input sequence with truncated Impulse Response x (n)*h (n)

USING MATLAB TO DETERMINE FILTER COEFFICIENTS:


Using FIR1 Function on Matlab

B = FIR1(N,Wn) designs an N'th order lowpass FIR digital filter

and returns the filter coefficients in length N+1 vector B.

The cut-off frequency Wn must be between 0 < Wn < 1.0, with 1.0

corresponding to half the sample rate. The filter B is real and

has linear phase, i.e., even symmetric coefficients obeying B(k) =

B(N+2-k), k = 1,2,...,N+1.

Dept of E&C, RGIT, Bangalore 78


DSP MAT LAB MANUAL 2010-2011

If Wn is a two-element vector, Wn = [W1 W2], FIR1 returns an

order N bandpass filter with passband W1 < W < W2.

B = FIR1(N,Wn,'high') designs a highpass filter.

B = FIR1(N,Wn,'stop') is a bandstop filter if Wn = [W1 W2].

If Wn is a multi-element vector,

Wn = [W1 W2 W3 W4 W5 ... WN],

FIR1 returns an order N multiband filter with bands

0 < W < W1, W1 < W < W2, ..., WN < W < 1.

B = FIR1(N,Wn,'DC-1') makes the first band a passband.

B = FIR1(N,Wn,'DC-0') makes the first band a stopband.

For filters with a passband near Fs/2, e.g., highpass and bandstop filters, N must be
even.

By default FIR1 uses a Hamming window. Other available windows, including


Boxcar, Hanning, Bartlett, Blackman, Kaiser and Chebwin can be specified with an
optional trailing argument. For example,

B = FIR1(N,Wn,kaiser(N+1,4)) uses a Kaiser window with beta=4.

B = FIR1(N,Wn,'high',chebwin(N+1,R)) uses a Chebyshev window.

By default, the filter is scaled so the center of the first pass band has magnitude exactly
one after windowing. Use a trailing 'noscale' argument to prevent this scaling,

e.g. B = FIR1(N,Wn,'noscale'),

B = FIR1(N,Wn,'high','noscale'), B = FIR1(N,Wn,wind,'noscale').

Dept of E&C, RGIT, Bangalore 79


DSP MAT LAB MANUAL 2010-2011

5. Mat Lab Program to Generate

‘FIR Filter-Low Pass’ Coefficients Using FIR1

% FIR Low pass filters using rectangular, triangular and kaiser windows

% sampling rate – 8000

order = 50;

cf=[500/4000,1000/4000,1500/4000]; cf--> contains set of cut-off frequencies[Wc ]

% cutoff frequency – 500

b_rect1=fir1(order,cf(1),boxcar(51)); %Rectangular

b_tri1=fir1(order,cf(1),bartlett(51)); %Triangular

b_kai1=fir1(order,cf(1),kaiser(51,8)); %Kaisar [Where 8-->Beta Co-efficient]

% cutoff frequency - 1000

b_rect2=fir1(order,cf(2),boxcar(51));

b_tri2=fir1(order,cf(2),bartlett(51));

b_kai2=fir1(order,cf(2),kaiser(51,8));

% cutoff frequency - 1500

b_rect3=fir1(order,cf(3),boxcar(51));

b_tri3=fir1(order,cf(3),bartlett(51));

b_kai3=fir1(order,cf(3),kaiser(51,8));

Dept of E&C, RGIT, Bangalore 80


DSP MAT LAB MANUAL 2010-2011

fid=fopen('FIR_lowpass_rectangular.txt','wt');

fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -400Hz');

fprintf(fid,'\nfloat b_rect1[31]={');

fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect1);

fseek(fid,-1,0);

fprintf(fid,'};');

fprintf(fid,'\n\n\n\n');

fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -800Hz');

fprintf(fid,'\nfloat b_rect2[31]={');

fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect2);

fseek(fid,-1,0);

fprintf(fid,'};');

fprintf(fid,'\n\n\n\n');

fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -1200Hz');

fprintf(fid,'\nfloat b_rect3[31]={');

fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect3);

fseek(fid,-1,0);

fprintf(fid,'};');

fclose(fid);

winopen('FIR_highpass_rectangular.txt');

Dept of E&C, RGIT, Bangalore 81


DSP MAT LAB MANUAL 2010-2011

T.1 : Mat lab generated Coefficients for FIR Low Pass Kaiser filter:

Cutoff -500Hz
float b_kai1[51]={-0,0,0.0001,0.0002,0.0005,0.0008,0.0012,0.0013,0.001,-0,-0.0018,-
0.0045,
-0.0076,-0.0106,-0.0125,-0.0121,-
0.0082,0,0.0129,0.0302,0.0506,0.0723,0.0929,0.1099,0.1211,0.125,0.1211,0.1099,0.0929,
0.0723,0.0506,0.0302,0.0129,0,-0.0082,-0.0121,-0.0125,-0.0106,-0.0076,-0.0045,-
0.0018,-0,0.001,0.0013,0.0012,0.0008,0.0005,0.0002,0.0001,0,-0};

Cutoff -1000Hz
IMPLEMENTATION OF AN FIR FILTER :
float b_kai2[51]={- 0,-0,-0.0001,-0.0003,-0.0004,0,0.0009,0.0019,0.0018,-0,-0.0034,-
0.0064,-0.0059,0,0.0096,0.0171,0.0152,-0,-0.0238,-0.0426,-
0.0387,0,0.0711,0.1554,0.2237,0.25,0.2237,0.1554,0.0711,0,-0.0387,-0.0426,-0.0238,-
ALGORITHM TO IMPLEMENT :
0,0.0152,0.0171,0.0096,0,-0.0059,-0.0064,-0.0034,-0,0.0018,0.0019,0.0009,0,-0.0004,-
0.0003,-0.0001,-0,0};

We need -1500Hz
Cutoff to realize an advance FIR filter by implementing its difference equation as per
float
the b_kai3[51]={ A
specifications. 0,0.0001,0.0002,0.0001,-0.0003,-0.0008,-
direct form I implementation approach is taken. (The filter
0.001,0,0.002,0.0035,0.0024,-0.0022,-0.0078,-0.0092,-0.0023,0.011,0.0214,0.0173,-
coefficients are taken as ai as generated by the Matlab program.)
0.0059,-0.0369,-0.0514,-0.0247,0.0503,0.153,0.2424,0.2778,0.2424,0.153,0.0503,-
0.0247,-0.0514,-0.0369,-0.0059,0.0173,0.0214,0.011,-0.0023,-0.0092,-0.0078,-
0.0022,0.0024,0.0035,0.002,0,-0.001,-0.0008,-0.0003,0.0001,0.0002,0.0001,0};

Dept of E&C, RGIT, Bangalore 82


DSP MAT LAB MANUAL 2010-2011

T.2 :Matlab generated Coefficients for FIR Low Pass Rectangular filter

Cutoff -500Hz
float b_rect1[51]={-0.0046,0,0.005,0.0097,0.0133,0.0151,0.0147,0.0118,0.0068,-0,-
0.0077,-0.0152,-0.0214,-0.0251,-0.0253,-0.0213,-
0.0128,0,0.0165,0.0355,0.0557,0.0754,0.0929,0.1066,0.1154,0.1184,0.1154,0.1066,0.092
9,0.0754,0.0557,0.0355,0.0165,0,-0.0128,-0.0213,-0.0253,-0.0251,-0.0214,-0.0152,-
0.0077,-0,0.0068,0.0118,0.0147,0.0151,0.0133,0.0097,0.005,0,-0.0046};

Cutoff -1000Hz
float b_rect2[51]={-0.0091,-0,-0.0099,-0.0147,-0.0109,0,0.012,0.0179,0.0134,-0,-0.0152,-
0.0231,-0.0176,0,0.0207,0.0323,0.0254,-0,-0.0326,-0.0538,-
0.0456,0,0.0761,0.1614,0.2282,0.2535,0.2282,0.1614,0.0761,0,-0.0456,-0.0538,-0.0326,-
0,0.0254,0.0323,0.0207,0,-0.0176,-0.0231,-0.0152,-0,0.0134,0.0179,0.012,0,-0.0109,-
0.0147,-0.0099,-0,0.0091};

Cutoff -1500Hz
float b_rect2[51]={- 0.0021,0.0112,0.0126,0.0048,-0.0074,-0.0152,-
0.0125,0,0.0139,0.019,0.0103,-0.0076,-0.0224,-0.0223,-0.0049,0.0199,0.0344,0.0249,-
0.0077,-0.0447,-0.0582,-0.0265,0.0516,0.1524,0.237,0.27,0.237,0.1524,0.0516,-0.0265,-
0.0582,-0.0447,-0.0077,0.0249,0.0344,0.0199,-0.0049,-0.0223,-0.0224,-
0.0076,0.0103,0.019,0.0139,0,-0.0125,-0.0152,-0.0074,0.0048,0.0126,0.0112,0.0021};

Dept of E&C, RGIT, Bangalore 83


DSP MAT LAB MANUAL 2010-2011

T.3: Mat lab generated Coefficients for FIR Low Pass Triangular filter
Cutoff -500Hz
float b_tri1[51]={ [0,0,0.0005,0.0013,0.0024,0.0034,0.004,0.0037,0.0024,-0,-0.0035,-0.0075,-
0.0116,-0.0147,-0.016,-0.0144,-
0.0092,0,0.0134,0.0304,0.0502,0.0713,0.092,0.1105,0.1248,0.1334,0.1248,0.1105,0.092,0.0713
,0.0502,0.0304,0.0134,0,-0.0092,-0.0144,-0.016,-0.0147,-0.0116,-0.0075,-0.0035,-
0,0.0024,0.0037,0.004,0.0034,0.0024,0.0013,0.0005,0,0;]};

Cutoff -1000Hz
float b_tri2[51]={ 0,-0,-0.0008,-0.0018,-0.0018,0,0.0029,0.0051,0.0044,-0,-0.0062,-0.0103,-
0.0086,0,0.0118,0.0197,0.0165,-0,-0.0239,-0.0416,-
0.0372,0,0.0682,0.1512,0.2232,0.2582,0.2232,0.1512,0.0682,0,-0.0372,-0.0416,-0.0239,-
0,0.0165,0.0197,0.0118,0,-0.0086,-0.0103,-0.0062,-0,0.0044,0.0051,0.0029,0,-0.0018,-0.0018,-
0.0008,-0,0};

Cutoff -1500Hz
float b_tri3[51]={ 0,0.0005,0.0011,0.0006,-0.0012,-0.0032,-0.0032,0,0.0047,0.0073,0.0044,-
0.0035,-0.0114,-0.0123,-0.0029,0.0126,0.0233,0.0179,-0.0058,-0.0359,-0.0492,-
0.0235,0.048,0.1483,0.2407,0.2857,0.2407,0.1483,0.048,-0.0235,-0.0492,-0.0359,-
0.0058,0.0179,0.0233,0.0126,-0.0029,-0.0123,-0.0114,-0.0035,0.0044,0.0073,0.0047,0,-
0.0032,-0.0032,-0.0012,0.0006,0.0011,0.0005,0};

Dept of E&C, RGIT, Bangalore 84


DSP MAT LAB MANUAL 2010-2011

FLOWCHART FOR FIR:

START

Initialize the DSP Board.

Take a new input in ‘data’


from the analog in of codec in
‘data’

Initialize Counter = 0
Initialize Output = 0 , i =
0

Output += coeff[N-
i]*val[i]
Shift the input value by
one

NO
Is the loop
Cnt =
order

Poll the ready


bit, when
asserted A
proceed.

Dept of E&C, RGIT, Bangalore 85


DSP MAT LAB MANUAL 2010-2011

Output += coeff[0]*data
Put the ‘data’ in ‘val’
array.

Write the value ‘Output’


to Analog output of the
codec

Dept of E&C, RGIT, Bangalore 86


DSP MAT LAB MANUAL 2010-2011

C PROGRAM TO IMPLEMENT FIR FILTER:

fir.c

#include "xyzcfg.h"

#include "dsk6713.h"
#include "dsk6713_aic23.h"

float filter_Coeff[] ={0.000000,-0.001591,-0.002423,0.000000,0.005728,


0.011139,0.010502,-0.000000,-0.018003,-0.033416,-0.031505,0.000000,
0.063010,0.144802,0.220534,0.262448,0.220534,0.144802,0.063010,0.000000,
-0.031505,-0.033416,-0.018003,-0.000000,0.010502,0.011139,0.005728,
0.000000,-0.002423,-0.001591,0.000000 };

static short in_buffer[100];

DSK6713_AIC23_Config config = {\
0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Leftline input channel volume */\
0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume*/\
0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */\
0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */\
0x0011, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */\
0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */\
0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */\
0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */\
0x0081, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */\
0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \
};
/*

Dept of E&C, RGIT, Bangalore 87


DSP MAT LAB MANUAL 2010-2011

* main() - Main code routine, initializes BSL and generates tone


*/

void main()
{
DSK6713_AIC23_CodecHandle hCodec;

Uint32 l_input, r_input,l_output, r_output;

/* Initialize the board support library, must be called first */


DSK6713_init();

/* Start the codec */


hCodec = DSK6713_AIC23_openCodec(0, &config);

DSK6713_AIC23_setFreq(hCodec, 1);

while(1)
{ /* Read a sample to the left channel */
while (!DSK6713_AIC23_read(hCodec, &l_input));

/* Read a sample to the right channel */


while (!DSK6713_AIC23_read(hCodec, &r_input));

l_output=(Int16)FIR_FILTER(&filter_Coeff ,l_input);
r_output=l_output;

/* Send a sample to the left channel */


while (!DSK6713_AIC23_write(hCodec, l_output));

/* Send a sample to the right channel */

Dept of E&C, RGIT, Bangalore 88


DSP MAT LAB MANUAL 2010-2011

while (!DSK6713_AIC23_write(hCodec, r_output));


}
/* Close the codec */
DSK6713_AIC23_closeCodec(hCodec);
}
signed int FIR_FILTER(float * h, signed int x)
{
int i=0;
signed long output=0;
in_buffer[0] = x; /* new input at buffer[0] */
for(i=51;i>0;i--)
in_buffer[i] = in_buffer[i-1]; /* shuffle the buffer */
for(i=0;i<51;i++)
output = output + h[i] * in_buffer[i];
return(output);

HOW TO PROCEED:

1. Connect a Signal Generator/audio input to the LINE IN Socket or connect a


microphone to the MIC IN Socket.

Note:- To use microphone input change the analog audio path control register
value (Register no. 4) in Codec Configuration settings of the Source file (Fir.c)
from 0x0011 to 0x0015.

Dept of E&C, RGIT, Bangalore 89


DSP MAT LAB MANUAL 2010-2011

2. Connect CRO/Desktop Speakers to the Socket Provided for LINE OUT or


connect a headphone to the Headphone out Socket.

3. Now Switch on the DSK and Bring Up Code Composer Studio on the PC.

4. Use the Debug  Connect menu option to open a debug connection to the DSK
board
5. Create a new project with name Fir.pjt.

6. Open the File Menu  new  DSP/BIOS Configuration select


“dsk6713.cdb” and save it as “xyz.cdb”

Dept of E&C, RGIT, Bangalore 90


DSP MAT LAB MANUAL 2010-2011

7. Add “xyz.cdb” to the current project.


Project Add files to project xyz.cdb

8. Automatically three files are added in the Generated file folder in project pane
xyzcfg.cmd Command and linking file
xyzcfg.s62  optimized assembly code for configuration
xyzcfg_c.c  Chip support initialization

9. Open the File Menu  new  Source file


10. Type the code in editor window. Save the file in project folder. (Eg: Codec.c).

Important note: Save your source code with preferred language extension. For
ASM codes save the file as code(.asm) For C and C++ codes code (*.c,*.cpp)
respectively.

Dept of E&C, RGIT, Bangalore 91


DSP MAT LAB MANUAL 2010-2011

11. Add the saved “Fir.c” file to the current project which has the main function and
calls all the other necessary routines.
Project  Add files to Project  Codec.c

12. Add the library file “dsk6713bsl.lib” to the current project

Path  “C:\CCStudio_v3.1\C6000\dsk6713\lib\dsk6713bsl.lib”

13. Copy header files “dsk6713.h” and “dsk6713_aic23.h” from and paste it in
current project folder.
C:\CCStudio_v3.1\C6000\dsk6713\include.

14. Add the header file generated within xyzcfg_c.c to Fir.c

Note:- Double click on xyzcfg_c.c Copy the first line header (eg.xyzcfg.h) and paste
that in source file (eg.Fir.c).

15. Compile the program using the ‘Project-compile’ pull down menu or by
Clicking the shortcut icon on the left side of program window.

16. Build the program using the ‘Project-Build’ pull down menu or by clicking the
shortcut icon on the left side of program window.

17. Load the program (Codec.out) in program memory of DSP chip using the
‘File-load program’ pull down menu.

18. Debug Run

Dept of E&C, RGIT, Bangalore 92


DSP MAT LAB MANUAL 2010-2011

MATLAB GENERATED FREQUENCY RESPONSE

High Pass FIR filter(Fc= 800Hz).

Low Pass FIR filter (Fc=1000Hz)

Dept of E&C, RGIT, Bangalore 93


DSP MAT LAB MANUAL 2010-2011

Audio Application

Dept of E&C, RGIT, Bangalore 94


DSP MAT LAB MANUAL 2010-2011

Spectrogram with RTDX using MATLAB

This version of project makes use of RTDX with MATLAB for transferring data from the
DSK to the PC host. This section introduces configuration file(.CDB) file and RTDX
with MATLAB.

This project uses source program spectrogram_rtdx_mtl.c that runs on the DSK which
computes 256 point FFT and enables an RTDX output channel to write/send the resulting
FFT data to the PC running MATLAB for finding the spectrogram. A total of N/2 (128
points )are sent. The (.CDB) configuration file is used to set interrupt INT11. From this
configuration file select Input/Output  RTDX. Right click on properties and change the
RTDX buffer size to 8200. Within CCS, select tools  RTDX  Configure to set the
host buffer size to 2048(from 1024).

An input signal is read in blocks of 256 samples. Each block of data is then multiplied
with a hamming window of length 256 points. The FFT of the windowed data is
calculated and squared. Half of the resulting FFT of each block of 256 points is then
transferred to the PC running MATLAB to find the specrtrogram.

Dept of E&C, RGIT, Bangalore 95


DSP MAT LAB MANUAL 2010-2011

Spectrogram_rtdx_mtl.c Time-Frequency analysis of signals Using RTDX-MATLAB

#include "dsk6713_aic23.h" //codec-DSK support


file
Uint32 fs=DSK6713_AIC23_FREQ_8KHZ; //set sampling rate
#include <rtdx.h>
//RTDX support file
#include <math.h>
#include "hamming.cof" //Hamming window
coefficients
#define PTS 256 //# of points
for FFT
#define PI 3.14159265358979
typedef struct {float real,imag;} COMPLEX;
void FFT(COMPLEX *Y, int n); //FFT prototype
float iobuffer[PTS],iobuffer1[PTS],a[PTS]; //input
and output buffer
float x1[PTS]; //intermediate buffer
short i; //general
purpose index variable
int j, k,l, curr_block = 0; //index variables
short buffercount = 0; //number of new samples in iobuffer
short flag = 0; //set to 1 by ISR when iobuffer full
COMPLEX w[PTS]; //twiddle constants stored in
w
COMPLEX samples[PTS]; //primary working buffer
RTDX_CreateOutputChannel(ochan); //create output
channel C6x->PC

main()

Dept of E&C, RGIT, Bangalore 96


DSP MAT LAB MANUAL 2010-2011

{
for (i = 0 ; i<PTS ; i++) //set up twiddle constants in w
{
w[i].real = cos(2*PI*i/512.0); //Re component of twiddle constants
w[i].imag =-sin(2*PI*i/512.0); //Im component of twiddle constants
}
comm_intr(); //init DSK, codec, McBSP

while(!RTDX_isOutputEnabled(&ochan)) //wait for PC to enable RTDX


puts("\n\n Waiting . . . "); //while waiting
for(l=0;l<256;l++)
a[l]=cos(2*3.14*1500*l/8000);
for(k=0;k<5000;k++)
//infinite loop
{
while (flag == 0) ; //wait until iobuffer is full
flag = 0; //reset flag
for (i = 0 ; i < PTS ; i++) //swap buffers
{ iobuffer1[i]=iobuffer[i]+a[i];
samples[i].real=h[i]*iobuffer1[i]; //multiply by Hamming window coeffs
iobuffer1[i] = x1[i]; //process frame to iobuffer
}
for (i = 0 ; i < PTS ; i++)
samples[i].imag = 0.0; //imag components = 0
FFT(samples,PTS); //call C-coded FFT function
for (i = 0 ; i < PTS ; i++) //compute square of FFT magnitude
{
x1[i] = (samples[i].real*samples[i].real
+ samples[i].imag*samples[i].imag)/16; //FFT data scaling
}
RTDX_write(&ochan, x1, sizeof(x1)/2); //send 128 samples to PC

Dept of E&C, RGIT, Bangalore 97


DSP MAT LAB MANUAL 2010-2011

} //end of infinite loop}


//end of main

interrupt void c_int11() //ISR


{
output_sample((short)(iobuffer[buffercount])); //out from iobuffer
iobuffer[buffercount++]=(short)(input_sample()); //input to iobuffer
if (buffercount >= PTS) //if
iobuffer full
{
buffercount = 0;
//reinit buffercount
flag = 1;
//reset flag
}
}

FFT.c C callable FFT function in C

#define PTS 256 //# of points for FFT


typedef struct {float real,imag;} COMPLEX;
extern COMPLEX w[PTS]; //twiddle constants stored in w

void FFT(COMPLEX *Y, int N) //input sample array, # of points


{
COMPLEX temp1,temp2; //temporary storage variables
int i,j,k; //loop counter variables
int upper_leg, lower_leg; //index of upper/lower butterfly leg
int leg_diff; //difference between upper/lower leg
int num_stages = 0; //number of FFT stages (iterations)
int index, step; //index/step through twiddle constant

Dept of E&C, RGIT, Bangalore 98


DSP MAT LAB MANUAL 2010-2011

i = 1; //log(base2) of N points= # of stages


do
{
num_stages +=1;
i = i*2;
}while (i!=N);
leg_diff = N/2; //difference between upper&lower legs
step = 512/N; //step between values in twiddle.h
for (i = 0;i < num_stages; i++) //for N-point FFT
{
index = 0;
for (j = 0; j < leg_diff; j++)
{
for (upper_leg = j; upper_leg < N; upper_leg += (2*leg_diff))
{
lower_leg = upper_leg+leg_diff;
temp1.real = (Y[upper_leg]).real + (Y[lower_leg]).real;
temp1.imag = (Y[upper_leg]).imag + (Y[lower_leg]).imag;
temp2.real = (Y[upper_leg]).real - (Y[lower_leg]).real;
temp2.imag = (Y[upper_leg]).imag - (Y[lower_leg]).imag;
(Y[lower_leg]).real = temp2.real*(w[index]).real
-temp2.imag*(w[index]).imag;
(Y[lower_leg]).imag = temp2.real*(w[index]).imag
+temp2.imag*(w[index]).real;
(Y[upper_leg]).real = temp1.real;
(Y[upper_leg]).imag = temp1.imag;
}
index += step;
}
leg_diff = leg_diff/2;
step *= 2;

Dept of E&C, RGIT, Bangalore 99


DSP MAT LAB MANUAL 2010-2011

}
j = 0;
for (i = 1; i < (N-1); i++) //bit reversal for resequencing data
{
k = N/2;
while (k <= j)
{
j = j - k;
k = k/2;
}
j = j + k;
if (i<j)
{
temp1.real = (Y[j]).real;
temp1.imag = (Y[j]).imag;
(Y[j]).real = (Y[i]).real;
(Y[j]).imag = (Y[i]).imag;
(Y[i]).real = temp1.real;
(Y[i]).imag = temp1.imag;
}
}
return;
}

Dept of E&C, RGIT, Bangalore 100


DSP MAT LAB MANUAL 2010-2011

Spectrogram_RTDX.m For spectrogram plot using RTDX with MATLAB

clc;
ccsboardinfo %board info
cc=ccsdsp('boardnum',0); %set up CCS object
reset(cc); %reset board
visible(cc,1); %for CCS window
enable(cc.rtdx); %enable RTDX
if ~isenabled(cc.rtdx);
error('RTDX is not enabled')
end
cc.rtdx.set('timeout',50); %set 50sec timeout for RTDX
open(cc,'spectrogram1.pjt'); %open CCS project
load(cc,'./debug/spectrogram1.out'); %load executable file
run(cc); %run program
configure(cc.rtdx,2048,1); %configure one RTDX channel
open(cc.rtdx,'ochan','r'); %open output channel
pause(3) %wait for RTDX channel to open
enable(cc.rtdx,'ochan'); %enable channel from DSK
isenabled(cc.rtdx,'ochan');
M = 256; %window size
N = round(M/2);
B = 128; %No. of blocks (128)
fs = 8000; %sampling rate
t=(1:B)*(M/fs); %spectrogram axes generation
f=((0:(M-1)/2)/(M-1))*fs;
set(gcf,'DoubleBuffer','on');
y = ones(N,B);
column = 1;
set(gca,'NextPlot','add');
axes_handle = get(gcf,'CurrentAxes');

Dept of E&C, RGIT, Bangalore 101


DSP MAT LAB MANUAL 2010-2011

set(get(axes_handle,'XLabel'),'String','Time (s)');
set(get(axes_handle,'YLabel'),'String','Frequency (Hz)');
set(get(axes_handle,'Title'),'String','\fontname{times}\bf Real-Time Spectrogram');
set(gca,'XLim', [0 4.096]);
set(gca,'YLim', [0 4000]);
set(gca,'XLimMode','manual');
set(gca,'YLimMode','manual');
for i = 1:32768
w=readmsg(cc.rtdx,'ochan','single'); %read FFT data from DSK
w=double(w(1:N));
y(:, column) = w';
imagesc(t,f,dB(y)); %plot spectrogram
column = mod(column, B) + 1;
end
halt(cc); %halt processor
close(cc.rtdx,'ochan'); %close channel
clear cc %clear object

NOTE: For this example works with CCS 2.2 and Matlab 6.5.

Procedure:

22. Create a new project with name spectrogram.pjt.


23. Open “spectrogram.cdb” from given CD and save it in your new
project folder.
24. Copy the following files from the CD to your new project folder
1) c6713dskinit . c
2) FFT.c
3) spectrogram_rtdx_mtl.c
4) c6713dskinit . h
5) hamming.cof

Dept of E&C, RGIT, Bangalore 102


DSP MAT LAB MANUAL 2010-2011

6) spectrogram_RTDX.m

25. Add “spectrogram.cdb”, “c6713dskinit.c” and “spectrogram_rtdx_mtl.c”


to the current project.

26. Add the library file “dsk6713bsl.lib” to the current project


Path  “C:\CCStudio\C6000\dsk6713\lib\dsk6713bsl.lib”

5. Set the following compiler options.


Select Project  Build options.
Select the following for compiler option with Basic ( for category):
(1) c671x{mv6710} (for target version)
(2) Full symbolic debug (for Generate Debug info)
(3) Speed most critical(for Opt Speed vs. Size)
(4) None (for Opt Level and Program Level Opt)

Select The Preprocessor Category and Type for Define Symbols{d}:


CHIP_6713, and from Feedback category, select for Interlisting:
OPT / C and ASM{-s}

6 Build project.
7. Close CCS

8. Open MATLAB 6.5 and Run spectrogram_RTDX.m . within MATLAB ,CCS


will
enable RTDX and will load and run the COFF(.out) executable file. Then
MATLAB will plot the spectrogram of an input signal .

Dept of E&C, RGIT, Bangalore 103


DSP MAT LAB MANUAL 2010-2011

Noise removal using Adaptive Filters

Dept of E&C, RGIT, Bangalore 104


DSP MAT LAB MANUAL 2010-2011

Dept of E&C, RGIT, Bangalore 105


DSP MAT LAB MANUAL 2010-2011

Dept of E&C, RGIT, Bangalore 106


DSP MAT LAB MANUAL 2010-2011

Dept of E&C, RGIT, Bangalore 107


DSP MAT LAB MANUAL 2010-2011

C PROGRAM TO IMPLEMENT NOISE CANCELLATION :

#include "xyzcfg.h"

#include "dsk6713.h"
#include "dsk6713_aic23.h"
#define beta 1E-12 //rate of convergence
#define N 30
short int adaptive_filter(short int ,short int );
float delay[N];
float w[N];

//union{unsigned int uint; short channel[2];} AIC23_data;

DSK6713_AIC23_Config config = {\
0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Left line input channel volume */ \
0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume */\
0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */ \
0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */ \
0x0011, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */ \
0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */ \
0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */ \
0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */ \
0x0081, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */ \
0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \
};

/*

Dept of E&C, RGIT, Bangalore 108


DSP MAT LAB MANUAL 2010-2011

* main() - Main code routine, initializes BSL and generates tone


*/
void main()
{
DSK6713_AIC23_CodecHandle hCodec;

int l_input, r_input;


int l_output, r_output, T;

/* Initialize the board support library, must be called first */


DSK6713_init();

/* Start the codec */


hCodec = DSK6713_AIC23_openCodec(0, &config);

DSK6713_AIC23_setFreq(hCodec, 1);

for (T = 0; T < 30; T++)


{
w[T] = 0; //init buffer for weights
delay[T] = 0; //init buffer for delay samples
}

while(1)
{

/* Read a sample to the left channel */


while (!DSK6713_AIC23_read(hCodec,&l_input));

/* Read a sample to the right channel */


while (!DSK6713_AIC23_read(hCodec, &r_input));

Dept of E&C, RGIT, Bangalore 109


DSP MAT LAB MANUAL 2010-2011

l_output=(short int)adaptive_filter(l_input,r_input);
r_output=l_output;

/* Send a sample to the left channel */


while (!DSK6713_AIC23_write(hCodec, l_output));

/* Send a sample to the right channel */


while (!DSK6713_AIC23_write(hCodec, r_output));
}

/* Close the codec */


DSK6713_AIC23_closeCodec(hCodec);
}
short int adaptive_filter(short l_input1,short r_input1) //ISR
{
short i,output,T;
float yn=0, E=0, dplusn=0, desired=0, noise=0;

desired = l_input1;
noise = r_input1;
dplusn = desired + noise; //desired+noise
delay[0] = noise; //noise as input to adapt FIR

for (i = 0; i < N; i++) //to calculate out of adapt FIR


yn += (w[i] * delay[i]); //output of adaptive filter
E = (desired + noise) - yn; //"error" signal=(d+n)-yn
for (i = N-1; i >= 0; i--) //to update weights and delays
{
w[i] = w[i] + beta*E*delay[i]; //update weights
delay[i] = delay[i-1]; //update delay samples

Dept of E&C, RGIT, Bangalore 110


DSP MAT LAB MANUAL 2010-2011

}
output=((short)E); //error signal as overall output

//output=((short)dplusn);//output (desired+noise)
//overall output result
return(output);
}

PROCEDURE :

 Switch on the DSP board.


 Open the Code Composer Studio.
 Create a new project
Project  New (File Name. pjt , Eg: noisecancellation.pjt)
 Initialize on board codec.
Note: “Kindly refer the Topic Configuration of 6713 Codec using BSL”
 Add the above ‘C’ source file to the current project (remove codec.c source file
from the project if you have already added).
 Desired Signal  400 Hz
Noise  3.0 KHz
Input a desired sinusoidal signal into the Left channel and Noise signal of 3KHz
into the Right channel
 Build the project.
 Load the generated object file(*.out) on to Target board.
 Run the program.
 Observe the waveform that appears on the CRO screen. Verify that the 3 KHz
noise signal is being cancelled gradually.

Dept of E&C, RGIT, Bangalore 111


DSP MAT LAB MANUAL 2010-2011

7. IMPULSE RESPONSE
‘CPP’ Program to Implement Impulse response:

PROGRAM TO CALCULATE IMPULSE RESPONSE OF A SYSTEM

Output of a system is generally given by : y[n] = Sum(i=0->N-1)


(b[i]*x[n-i]) - Sum(j=1->M-1)(a[j]*y[n-j]) ____________(1);

The program implements the above Equation.


The resulting Transfer function from the above equation in terms of Z
Transform is given as:

Y(z)/X(z) = Numerator(z)/Denominator(z)

Numerator(z) = b0.z^0 + b1.z^(-1) + b2.z^(-2) + ...


Denominator(z) = a0.z^0 + a1.z^(-1) + a2. z^(-2) + ...
First asks for order of the coefficients of 'b' i.e., The magnitude of the
maximum power of the numerator of the transfer function.
Then input the coefficients of b: b0 b1 b2 ...

Then asks for the Order of the coefficients of 'a' i.e., The magnitude of
the maximum power of the denominator of the transfer function.
Then input the coefficients of a: a0 a1 a2 ...

Then Enter the length 'L' of the output sequence desired.

The Progam then prints 'L' values of h[n] (from n=0->L-1) Impulse
response for the given equation for an Impulse Input.

x[n]=1 ; for n==0;


x[n]=0 ; for n!=0;

Dept of E&C, RGIT, Bangalore 112


DSP MAT LAB MANUAL 2010-2011

Sample Output:

Enter order of 'b': 0


Enter Coefficeients of 'b': 1
Enter order of 'a': 1
Enter Coefficeients of 'a': 1 -0.5
Enter Number of Output Samples? 5
h[0] = 1.000000e+00
h[1] = 5.000000e-01
h[2] = 2.500000e-01
h[3] = 1.250000e-01
h[4] = 6.250000e-02

The above output is generated for an input of: y[n] - 0.5*y[n-1] = x[n]
which has a Transfer Function of :

Y(z)/X(z) = 1/( 1 - 0.5z^(-1))

#include <cstdio>

using namespace std;

double *y,*b,*a;

int main(void)

int N,M,L,i,j;

printf("Enter order of 'b': ");

scanf("%d",&N);

Dept of E&C, RGIT, Bangalore 113


DSP MAT LAB MANUAL 2010-2011

b= new double[++N];

printf("Enter Coefficeients of 'b': ");

for(i=0;i<N;i++)

scanf("%le",&b[i]);

printf("Enter order of 'a': ");

scanf("%d",&M);

a=new double[++M];

printf("Enter Coefficeients of 'a': ");

for(i=0;i<M;i++)

scanf("%le",&a[i]);

printf("Enter Number of Output Samples? ");

scanf("%d",&L);

y=new double[L];

for(int n=0;n<L;n++)

y[n]=0;

for(j=1;j<M;j++)

if((n-j)>=0)

y[n] -=a[j]*y[n-j];

Dept of E&C, RGIT, Bangalore 114


DSP MAT LAB MANUAL 2010-2011

for(i=0;i<N;i++)

if(!(n-i))

y[n]+=b[i];

printf("\t h[%d] = %le \n",n,y[n]);

return 0;

PROCEDURE:

 Open Code Composer Studio, make sure the DSP kit is turned on.
 Use the Debug  Connect menu option to open a debug connection to the DSK
board
 Start a new project using ‘Project-new ‘ pull down menu, save it in a
separate directory(C:\CCStudio_v3.1\myprojects) with name
Impulse_response.pjt.
 Add the source files impulse_res.c
 to the project using ‘Projectadd files to project’ pull down menu.
 Add the linker command file hello.cmd .
(Path: C:\CCStudio_v3.1\tutorial\dsk6713\hello1\hello.cmd)
 Add the run time support library file rts6700.lib
(Path: C:\CCStudio_v3.1\c6000\cgtools\lib\rts6700.lib)
 Compile the program using the ‘Project-compile’ pull down menu or by
clicking the shortcut icon on the left side of program window.

Dept of E&C, RGIT, Bangalore 115


DSP MAT LAB MANUAL 2010-2011

 Build the program using the ‘Project-Build’ pull down menu or by


clicking the shortcut icon on the left side of program window.
 Load the program(Impulse_response.out) in program memory of DSP chip using
the
‘File-load program’ pull down menu.
 Execute the program. Debugrun

Result: The result is displayed on the Debug window.

Dept of E&C, RGIT, Bangalore 116

You might also like