DSP Lab Manual 2023
DSP Lab Manual 2023
DSP Lab Manual 2023
DEPARTMENT OF
ELECTRONICS & COMMUNICATION ENGINNEERING
1
List of Experiments:
5 Analysis in Z- domain 39
2
Instructions to the Students:
1. All the students are required to come prepared for the experiments to be done
in the lab.
2. Students should try to analyze and understand the solved problems and then
try to solve the unsolved problems of the experiment in the lab.
4. Students have to get their results verified and observation copies checked by
the instructor before leaving the lab.
5. Maintain a separate folder in the computer you use, where you save all the
programs you do in the lab.
Evaluation plan
3
Experiment No. 1: Introduction to MATLAB and CCS
4
Command window consists of prompt for entering the command for the execution of the
particular function. Suppose we want to create a variable with a vector we can enter the
following at the command prompt and press ENTER key.
>> a = [1 2 3 4 5]
a=
1 2 3 4 5
This will create a vector with variable name ‘a’. If the command which is entered at prompt is
terminated by the semicolon, then the values corresponding to the variable is not shown in
the command window when you press the ENTER key. Similarly, the command, which does the
particular function, can be entered at the prompt, which is shown as follows.
a=
1 1
1 1
The above shown command will create a matrix of size 2x2 with all ones. There are many
commands like this are available in the MATLAB, which are given in various tool boxes. In this
lab students will get acquainted with the usage of these commands using some examples. The
function rand will generate uniformly distributed random elements and randn will generate
normally distributed random elements.
R = randn(4,4)
R=
The data set can be saved in a file such with an extension of .mat, .dat and .txt using save
command and same can be retrieved using load function. The load function reads binary files
containing matrices generated by earlier MATLAB sessions, or reads text files containing
numeric data. The text file should be organized as a rectangular table of numbers, separated
by blanks, with one row per line, and an equal number of elements in each row. For example,
outside of MATLAB, create a text file containing these four lines:
5
4.0 15.0 14.0 1.0
Save the file as myfile.dat in the current directory. The statement load myfile.dat reads the file
and creates a variable, containing the example matrix.
M-Files
You can create your own matrices using M-files, which are text files containing MATLAB code.
Use the MATLAB Editor to create a file containing the same statements you would type at the
MATLAB command line. Save the file under a name that ends in .m.
Let us learn this by writing a simple program for generating a sine wave and plotting it using
plot command. In File menu select the New option in and then select M-file.
Matlab editor window will open. Then enter the following program.
6
Figure 1. 1 Matlab editor window with a program
Save the program from save menu with any meaningful file name. Strictly don’t use file
name, which is already a MATLAB command. This will overwrite the existing command file
which is a built in function. The program can be executed by selecting the Run option from
the Debug menu. The output is plotted in separate window which is shown in figure 1.3
Always use commands such as clc, close all and clear all, before starting any program in the
MATLAB editor.
Help for the MATLAB commands are available from the help menu or by typing help followed
by the command name in the command window.
Activity Questions
Students must complete the execution of activity questions in the lab and write down the
programs or answers in the observation book.
7
1. Study the following command function through the help menu and check it in the
command window with suitable illustrations:
i) fliplr vii) plot xiii) disp xix) angle
ii) zeros viii) title xiv) eye xx) abs
iii) linspace ix) subplot xv) num2str xxi) log
iv) sin x) who xvi) floor xxii) double
v) cos xi) whos xvii) sqrt xxiii) save
vi) figure xii) input xviii) exp xxiv) load
2. Assume array c is defined as shown, and determine the contents of the following sub-
arrays.
1.1 −3.2 3.4 0.6
𝑐 = [0.6 1.2 −0.6 3.1]
1.3 0.6 5.5 0.0
i) c(2,3) iv) c(1:2,2:end) vii) c(1:2,2:4)
ii) c(2,:) v) c(6) viii) c([1 3],2)
iii) c(:,end) vi) c(4:end) ix) c([2 2],[3 3])
3. Assume a, b, c and d are defined as follows
1 0 −1 2 3
𝑎= [ ],𝑏 = [ ],𝑐 = [ ],𝑑 = 5
2 1 0 1 2
What is the result of the following expressions?
i) a+b
ii) a+c
iii) a+d
iv) a .* b
v) a * b
8
Introduction to CCS: 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++, Code Composer lets you edit, build, debug, profile
and manage project from a single unified environment. Other unique features include
graphical signal analysis, injection/extraction of data signals via I/O, multi-processor
debugging, automated testing and customization via a C-interpretive scripting
language and much more.
1. IDE
2. Debug IDE
3. Advanced watch windows
4. Integrated editor
5. File I/O, Probe points, and graphical algorithm scope probes.
6. Advanced graphical signal analysis
7. Interactive profiling
8. Automated testing and customization via scripting
9. Visual project management system
10. Compile in the background while editing and debugging
11. Multi-processor debugging
12. Help on the target DSP
1. Launch CCS: Launch the CCS v6 icon from the Desktop or go to All Programs -> Texas
2. Choose the location for the workspace, where your project will be saved.
→Specify the name of the project in the space provided e g., Project Name: test
9
Note: For newly arrived kits use “connection”: Texas Instruments XDS100V3 USB
Debug pro
Press “verify” button to check the proper connection of the kit with the system.
6. Click Finish
10
8. BUILD
Build the program to check your code.
Go to
Project → Build project.
9. DEBUG
After successful Build, connect the kit with the system using the JTAG
emulator and power the kit.
Click the Debug as shown in the below figure.
10. RUN
Wait until the program loaded to the hardware automatically.
Now you can run the code, by selecting Run-> Resume.
11
Once you run the program the output will be printed in the Console Window.
Once you run the program, 128 no’s of sine samples has been printed in the Console
Window.
12
Set the Graph Properties as shown in the Picture
Start Address: m
Click: Ok
Graph will be plotted as shown below:
13
GENERAL PROCEDURE FOR WORKING WITH THE REAL TIME
PROJECTS USING C6748LCDK:
Repeat the steps 1 to 6 of previous method and Create the source file (C-code) and
save it.
1. Now add the following library files and supporting files of codec to your project. To
add files, go to Project-> Add files.
2. Right click on the project name and choose “Show Build Settings..”
➔ Build-> C6000 Compiler-> Include Options -> Click “Add” as shown in the figure.
14
According to your requirement you can use the following connections:
OR
15
Experiment No. 2: Analysis of signals in time domain
Objective:
To study signals in time-domain and understand the concepts of generation
of signals and sampling,
The signals we use in the real world (such as voice signal) are "analog"
signals. To process these signals in computing devices, we need to convert
them in to "digital" form. While an analog signal is continuous in both time
and amplitude, a digital signal is discrete in both time and amplitude. To
convert a signal from continuous time to discrete time, sampling is used. The
value of the signal is taken at certain intervals in time to get discrete samples
of the signal.
16
Example-1: Generate and plot the following signals
a) Unit-step function
b) Delayed step function with a delay of n0 = 5.
c) Step function with amplitude m= 5
d) Rectangular window of length 5;
e) Ramp signal
Solution:
17
Output:
0.5 0.5
0 0
0 5 10 15 0 5 10 15
x[n]
0.5
0 0
0 5 10 15 0 5 10 15
n ----->
18
Ramp Function
20
Amplitude
10
0
0 5 10 15
n ----- >
clc;
clea
r
all;
clos
e
all;
Fs = 1000; % sampling frequency
f = 200; % signal frequency
T = 0:1/Fs:(1/f); % generation of the time sequence at sampling
% frequency fs for 1 period duration.
x = 5*sin(2*pi*f*t); %sine wave of freq. Of f hz and
amplitude 5; sampled at fs
subplot(3,1,1); stem(t,x);
title('Sine wave sampled at 1000 Hz 1 period duration'); ylabel('Amplitude')
Fs1 =10000; % Different sampling
frequency f = 200;
t = 0:1/Fs1:(1/f);
x=
5*sin(2*pi*f*t);
subplot(3,1,2);stem
(t,x);
title('Sine wave sampled at 10000 Hz for 1 period
duration '); ylabel('Amplitude')
19
Output:
Sine wave sampled at 1000 Hz 1 period duration
5
Amplitude
0
-5
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
-3
x 10
Sine wave sampled at 10000 Hz for 1 period duration
5
Amplitude
-5
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
-3
x 10
Sine wave sampled at 10000 Hz for 2 cycle duration
5
Amplitude
-5
0 0.001 0.002 0.003 0.004 0.005 0.006 0.007 0.008 0.009 0.01
n ---- >
#include<stdio.h>
int res[32];
main()
{ int j ,k=0,l,m,n;
for(j=0;j<4;j++)
{ m =0 ;
n= 3;
for(l=0;l<8;l++)
{
if(l<5)
{ res[k]=m++;
printf("%d\n",res [k]);
k++;
}
else
{ res[k]=n--;
printf("%d\n",res[k]);
k++;
}
}//for l
}//for j
k++;
}
20
Figure 2.3 Results of example 3
#include "L138_LCDK_aic3106_init.h"
#include "math.h"
#define SAMPLING_FREQ 48000
#define PI 3.14159265358979
float frequency = 1000.0;
float amplitude = 20000.0;
float theta_increment;
float theta = 0.0;
interrupt void interrupt4(void) // interrupt service routine
{
theta_increment = 2*PI*frequency/SAMPLING_FREQ;
theta += theta_increment;
if (theta > 2*PI) theta -= 2*PI;
output_left_sample((int16_t)(amplitude*sin(theta)));
return;
}
int main(void)
{
L138_initialise_intr(FS_48000_HZ,ADC_GAIN_0DB,DAC_ATTEN_0DB,LCDK_LINE_INPUT
);
while(1);
}
21
Experiment No. 3: Time domain analysis of systems.
Objective:
To study systems in time-domain and understand the concepts of
convolution, correlation and impulse response.
Solution:
clc;
close all;
clear all;
x = [3,11,7,0,-1,4,2]; % Given sequence x[n]
nx = -3:3;
ny = nx + 2; % Shifted x[n] ; delay of 2
units
y1 = x;
w = randn(1, length(y1)); % Random sequence
22
generation
y = y1 + w;
nyb = ny(1)+nx(1); % Starting point
nye = ny(length(y1))+nx(length(x)); % Ending point
ny = nyb:nye;
xcr = xcorr(x,y); % cross-correlation
plot(ny,xcr);
title('Cross-correlation example');
xlabel('Time, n');
Output:
Cross-correlation example
200
180
160
140
120
100
80
60
40
20
0
-4 -2 0 2 4 6 8
Time, n
Note: The signal x and its delayed signal y have maximum correlation at time
n = 2. Hence, the correlation plot shows a maximum peak at n = 2. Such
signal processing is used in Radar applications.
23
Solution:
clc;
close all;
clear all;
N = 20;
b = [5 0 0];
a = [1 -0.6 -0.16];
f = [1, zeros(1,N-1)]; % generation of unit impulse δ[n]
h = filter(b, a, f); % input to the system is δ[n]; output is impulse
response h[n]
n = 0: 1: N-1;
stem(n, h);
title('Unit Impulse Response, h[n]'), xlabel('n'), ylabel('Amplitude');
Output:
4.5
3.5
3
Amplitude
2.5
1.5
0.5
0
0 2 4 6 8 10 12 14 16 18 20
n
24
Exercise:
1. Find the system output y[n]; 0 n 10 of an LTI system with impulse
response
h[n] = (0.5)𝑛{𝑢[𝑛] – 𝑢[𝑛 – 10]) when the inputs are
a) 𝑥[𝑛] = (0.8)𝑛(𝑢[𝑛]– 𝑢[𝑛 − 5])
b) x[n] = δ[n] + 3δ[n – 1] + 4δ[n – 3]
𝜋𝑛
c) 𝑥 [𝑛] = sin ( 25 )(𝑢[𝑛] − 𝑢 [𝑛 − 100]))
25
3. Write a MATLAB program to generate a pure sine wave of frequency
80Hz and add additive white Gaussian noise with SNR of 10dB. (Use the
function awgn.) Find and plot the autocorrelation of the resulting
sequence.
26
for(i=m;i<n;i++)
x[i]=0;
m=n;
}
y[0]=0;
a[0]=h[0];
for(j=1;j<n;j++) /*folding h(n) to h(-n)*/
a[j]=h[n-j];
/*Circular convolution*/
for(i=0;i<n;i++)
y[0]+=x[i]*a[i];
for(k=1;k<n;k++)
{
y[k]=0;
/*circular shift*/
for(j=1;j<n;j++)
x2[j]=a[j-1];
x2[0]=a[n-1];
for(i=0;i<n;i++)
{
a[i]=x2[i];
y[k]+=x[i]*x2[i];
}
}
/*displaying the result*/
printf(" the circular convolution is\n");
for(i=0;i<n;i++)
printf("%d \t",y[i]);
27
Experiment 2: To perform linear convolution.
#include<stdio.h>
#define LENGHT1 6 /*Lenght of i/p samples sequence*/
#define LENGHT2 4 /*Lenght of impulse response Co-efficients */
int x[2*LENGHT1-1]={1,2,3,4,5,6,0,0,0,0,0}; /*Input Signal Samples*/
int h[2*LENGHT1-1]={1,2,3,4,0,0,0,0,0,0,0}; /*Impulse Response Coefficients*/
int y[LENGHT1+LENGHT2-1];
main()
{
int i=0,j;
for(i=0;i<(LENGHT1+LENGHT2-1);i++)
{
y[i]=0;
for(j=0;j<=i;j++)
y[i]+=x[j]*h[i-j];
}
for(i=0;i<(LENGHT1+LENGHT2-1);i++)
printf("%d\n",y[i]);
}
#include<stdio.h>
#include<math.h>
#define PI 3.14
#define PTS 512
void main()
{
int i,j;
for (i = 0 ; i < PTS ; i++)
28
{
x[i] = sin(2 * PI * 100 * i / 8000.0);
y[i]=0.0;
}
#include<stdio.h>
#include<math.h>
#define PI 3.14
#define PTS 512
void main()
29
{
int i,j;
for (i = 0 ; i < PTS ; i++)
{
x[i] = sin(2*PI*i*20/128.0);
y[i]=0.0;
n[i]=x[i] + rand() * 10 ;
}
void main()
{
int i,j;
for (i = 0 ; i < PTS ; i++)
{
x[i] = sin(2 * PI * 100 * i / 8000.0);
y[i]=0.0;
}
Objectives:
To study the frequency-domain representation of signals and systems.
31
Solution:
clc;
clear all;
close all;
w = [0:1:500]*pi/500; % defining 501 values of radian frequency ω
in the range 0 to π
x = exp(j*w)./(exp(j*w)-0.5);
subplot(121)
plot(w, abs(x)), title('Magnitude response'), xlabel('w'), ylabel('Amplitude');
subplot(122), plot(w,angle(x));
title('Phase Response'), xlabel('w(radians)'), ylabel('Angle');
Output:
32
Example-2: Verify the symmetry property of DTFT for the impulse
response given below:
ℎ[𝑛] = 𝑎𝑛𝑢[𝑛], |𝑎| < 1
Solution:
clc;
clear all;
close all;
b = [1 0 0];
a = [1 -0.5 0]; % assuming a = 0.5
N = 512;
[h w] = freqz(b,a,N,'whole');
w = w-pi;
subplot(121), plot(w,abs(h));
title('Magnitude Response'), xlabel('w(radians)'), ylabel('Amplitude');
subplot(122), plot(w,angle(h));
title('Phase Response'), xlabel('w(radians)'), ylabel('Angle');
Output:
33
Figure 4.2 Results of example-2
Discrete Fourier Transform
35
Output:
-1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Time in sec
Magnitude
Response
500
Amplitude
0
0 50 100 150 200 250 300 350 400 450 500
Phase Response
Angle in Degrees
200
-200
0 50 100 150 200 250 300 350 400 450 500
Frequency in Hz
36
sumim=0;
for(n=0;n<N;n++)
{
sumre=sumre+x[n]* cos(2*pi*k*n/N);
sumim=sumim-x[n]* sin(2*pi*k*n/N);
}
out_real[k]=sumre;
out_imag[k]=sumim;
printf("X([%d])=\t%f\t+\t%fi\n",k,out_real[k],out_imag[k]);
}
}
Output:
37
Exercise:
3.Find and plot the frequency response of a causal 3-point moving averager.
Generate first 100 samples of 0.9n u[𝑛] and corrupt it using a random signal.
Pass the corrupted signal through the moving point averager and plot the
output.
4.Find the DFT of multitone sine wave with 30Hz, 80Hz, 120Hz frequency
components and plot the magnitude vs. frequency in Hz.
38
Experiment No. 5: Analysis in Z-domain
Objective:
Introduction:
39
Solution:
clc;
clear all;
close all;
n = 0:100;
u = [n>=0];
x = 3*cos(n*pi/3).*u; % input signal
y = filter(b, a, x); % o/p signal
figure;
subplot(211), plot(n,x);
subplot(212), plot(n,y);
Output:
r = -0.55556 1.5556
p = 0.9 0.9
k=0
41
Figure 4.1 Pole zero plot
Magnitude Response
150
100
Amplitude
50
0
0 0.5 1 1.5 2 2.5 3 3.5
Frequency in radians
Phase Response
0
Phase in radians
-1
-2
-3
0 0.5 1 1.5 2 2.5 3 3.5
Frequency in radians
4
Amplitude
0
0 5 10 15 20 25 30
Sample Number
-2
-4
0 10 20 30 40 50 60 70 80 90 100
15
10
-5
0 10 20 30 40 50 60 70 80 90 100
1
Y + (z) = [ X + (z) + x(−1) + z −1 X + (z) + x(−2) + z −1 x(−1) + z −2 X + (z)]
3
+ 0.95[ y(−1) + z −1Y + (z)] − 0.9025[ y(−2) + z −1 y(−1) + z −2Y + (z)
1 1 −1 1 −2
+ z z
Y (z) = 3 3 3
+
X + (z) + 1.4742+ 2.1383z −1
1− 0.5z −1
Step3: Compute X +(z) =
1− z −1 + z −2
+
and simplifying, we will obtain Y (z) as a rational function.
Step4:
0.0584+ j3.9468 0.0584- j3.9468 0.8453+ j2.0311 0.8453- j2.0311
Y+ (z) = − j
+ j
+ j
+ − j
44
Step5: By applying the inverse z- transform
− jn jn
y(n) = (0.0584 + j3.9486)e 3
+ (0.0584 − j3.9486)e 3
+
jn − jn
(0.8453+ j2.031)(0.9 5) e n 3
+ (0.8453. j2.031)(0.95) e n 3
MATLAB solution:
clc;
clear all;
close all;
a = [1 -0.95 0.9025]; % Denominator coefficient as in step 2
b = [1 1 1]/3; % Numerator coefficient as in step 2
y = [-2 -3]; % Initial conditions array
x = [1 1]; % Initial conditions array
xic = filtic(b,a,y,x); % converts past input x and output y into
initial %conditions which is required for the
computation of %Y(z). Refer Step 2
ax = [1 -1 1]; bx = [1 -0.5]; % X(z) transform coeffs
ay = conv(a, ax) % Gives denominator polynomial coefficients
of Y(z)
by = conv(b, bx) + conv(xic,ax)% Gives numerator polynomial
coefficients of Y(z)
[R, p, C] = residuez(by, ay);
disp('Residues '), disp( R), disp('Ploes '), disp( p), disp('Direct Term
'), disp(C);
Output:
45
The Y+(z) in the partial fraction form has residues, pole values as shown
below.
Residues
0.0584 - 3.9468i
0.0584 + 3.9468i
0.8453 + 2.0311i
0.8453 - 2.0311i
Ploes
0.5000 + 0.8660i
0.5000 - 0.8660i
0.4750 + 0.8227i
0.4750 - 0.8227i
jn − jn
(0.8453+ j2.031)(0.9 5)n e 3
+ (0.8453. j2.031)(0.95)n e 3
,
46
n ≥ 0.
Exercise:
1. An anti-causal LTI system is described by the system function
(z 2 −1)
H (z) = . Determine the following analytically and using
(z − 3)2
MATLAB
a) impulse response
b) difference equation representation
c) pole-zero plot
d) output y[n] if the input is x(n) = 3sin( n) u(n)
3
47
Experiment No. 6: IIR Filter Design – 1
Theory: Digital IIR filters are mainly designed from analog filters (classical
techniques). The widely used IIR filters are Butterworth, Chebyshev l (Type
I and II), and Elliptic.
Butterworth filters:
Here N is the order of the filter and Ωc = 3dB cut-off frequency (rad/sec).
In the above figure, Rp and Rs represent the pass band and stop band
attenuations, respectively, and Ω𝑝 and Ω𝑠 are the corresponding edge
frequencies in rad/sec.
48
Chebyshev: A Chebyshev filter with ripples in pass-band is categorized as
type-1, whereas, the one with ripples in the stop-band comes under type-2.
The figures shown below are examples of type-I filters.
49
Elliptic: They have ripples in both pass band and stop-band.
Implementation in MATLAB:
Solution:
b= 0.0979
a= 1.0000 2.033 2.0671 1.2988 0.5044 0.0979
51
Example-2: Design an analog Butterworth low-pass filter, given the
following specifications and also plot the frequency response.
Rp = 1dB, Rs = 40dB, fp = 100Hz and fs = 500Hz
Solution:
clc;
clear all;
close all;
rp = 1; %Pass-band attenuation
rs = 40; %Stop-band attenuation
wp = 2*pi*100; %Frequency should be in rad/sec
ws = 2*pi*500;
[N, wc] = buttord(wp,ws,rp,rs,'s'); %Getting the order N and the
3dB cut-off freq
[b, a] = butter(N,wc,'s'); %Getting the numerator &
denominator polynomial coeffs
[H, W] = freqs(b,a); %Complex freq.response of analog
filter
plot(W/(2*pi),20*log10(abs(H))), grid on;
title('Frequency Response');
xlabel(' Frequency in Hz '),ylabel(' Magnitude in dB ');
disp(' the order and cut off frequency in Hz are '),disp( N),disp(
wc/(2*pi));
52
Solution:
Order: 4
Cut-off frequency(Hz): 158.119
Frequency Response
0
-10
-20
-30
Magnitude in dB
-40
-50
-60
-70
-80
-90
0 200 400 600 800 1000 1200 1400 1600
Frequency in Hz
53
Exercise
1. Given the following filter specifications: Passband edge: 200Hz;
Rp= 1dB; Stopband edge: 700Hz; Rs= 50 dB.
a. Design an analog lowpass Butterworth filter
b. Design an analog lowpass Chebyshev Type 1 filter
c. Design an analog lowpass Chebyshev Type 2 filter
d. Design an analog lowpass Elliptic filter
Plot the frequency response for each case and compare them.
Note: Refer “butter” function to design high pass and other filters.
54
Experiment No. 7: IIR Filter Design – 2
Note: The functions buttord and butter can also be used to design a digital
filter directly. For example, the following function returns the order N and
the cutoff frequency of digital filter with specifications, wp, ws, rp, rs.
55
functions can be used to design Chebyshev lowpass (Type 1 and 2), and Elliptic
digital IIR filters respectively.
Solution:
% Analog design
T = 1; % assumed
wa_p = wp/T;
wa_s = ws/T;
56
Figure 7.1 Frequency response
Example-2: Simulate a signal with 50Hz and 200 Hz frequency. Filter the
signal through a 3rd order digital Butterworth LPF with 3-dB cutoff frequency
100 Hz. Plot the spectrum of the input and the filtered signal.
Solution:
57
k=W*Fs/(2*pi); % defining frequency vector for
plotting
plot(k,20*log10(abs(H))), grid on;
title('Frequency Response');
xlabel(' Frequency in Hz '),ylabel(' Magnitude in dB ');
% Filter testing
yb = filter(b,a,x) ;
% Getting spectrum and plot
N = 512;
w = [0:N/2 - 1]* (Fs/N) ; %defining frequency vector for
plotting
X = fft(x,N);
Yb = fft(yb,N);
figure(2);
subplot(211), plot(w,abs(X(1:N/2)));
title('Spect rum of input signal ' ) ;
subplot(212), plot(w,abs(Yb(1:N/2)));
title('Spectrum of filtered signal ' ) ;
58
Figure 7.3 Input and output for example-2
Exercise:
1. Transform
𝑠+1
𝐻𝑎(𝑠) =
𝑠2 + 5𝑠 + 6
59
into a digital filter H(z) using the impulse invariance technique in which T = 0.1s.
First find the solution analytically and then verify your result with the help of a
MATLAB program. Also plot the magnitude responses of the analog and the
resulting digital filter and comment on the result.
Note: Refer MATLAB functions to design high pass and other filters.
60
Generating IIR coefficient Using MATLAB for CCS project:
1. Start MATLAB
61
7. Export SOS and Gain
62
8. Come back to Matlab Command prompt select New Script type the Script for IIR filter (Given
below) save it in same workspace with L138_iirsos_coeffs.m, run the script to check error
% L138_IIRSOS_COEFFS.M
% MATLAB function to write SOS IIR filter coefficients
% assumes that coefficients have been exported from
% filterDesigner as two matrices
% first matrix has format
% [ b10 b11 b12 a10 a11 a12
% b20 b21 b22 a20 a21 a22
% ...
% ]
% where bij is the bj coefficient in the ith stage
% second matrix contains gains for each stage
%
function L138_iirsos_coeffs(coeff,gain)
%
num_sections=length(gain)-1;
fname = input('enter filename for coefficients ','s');
fid = fopen(fname,'wt');
fprintf(fid,'// %s\n',fname);
fprintf(fid,'// this file was generated using');
fprintf(fid,'\n// function L138_iirsos_coeffs.m\n',fname);
fprintf(fid,'\n#define NUM_SECTIONS %d\n',num_sections);
% first write the numerator coefficients b
% i is used to count through sections
fprintf(fid,'\nfloat b[NUM_SECTIONS][3] = { \n');
for i=1:num_sections
if i==num_sections
fprintf(fid,'{%2.8E, %2.8E, %2.8E} };\n',...
coeff(i,1)*gain(i),coeff(i,2)*gain(i),coeff(i,3)*gain(i));
else
fprintf(fid,'{%2.8E, %2.8E, %2.8E},\n',...
coeff(i,1)*gain(i),coeff(i,2)*gain(i),coeff(i,3)*gain(i));
end
end
% then write the denominator coefficients a
% i is used to count through sections
fprintf(fid,'\nfloat a[NUM_SECTIONS][3] = { \n');
for i=1:num_sections
if i==num_sections
fprintf(fid,'{%2.8E, %2.8E, %2.8E} };\n',...
63
coeff(i,4),coeff(i,5),coeff(i,6));
else
fprintf(fid,'{%2.8E, %2.8E, %2.8E},\n',...
coeff(i,4),coeff(i,5),coeff(i,6));
end
end
fclose(fid);
// main.c
//
// IIR filter implemented using second order sections
// floating point coefficients read from file
//
#include "L138_LCDK_aic3106_init.h"
#define NUM_SECTIONS 2
float b[NUM_SECTIONS][3] = {
{3.70298373E-03, 7.40596747E-03, 3.70298373E-03},
{2.36088362E-02, 2.36088362E-02, 0.00000000E+00} };
float a[NUM_SECTIONS][3] = {
{1.00000000E+00, -1.93814524E+00, 9.52957174E-01},
{1.00000000E+00, -9.52782328E-01, 0.00000000E+00} }; //Chebyshev 1 LPF Fc = 1KHz
Fs=48000KHz */
// Coefficients copied from
“elliptic.cof”
input = (float)input_left_sample();
64
for (section=0 ; section< NUM_SECTIONS ; section++)
{
yn = b[section][0]*input + w[section][0];
w[section][0] = b[section][1]*input + w[section][1] - a[section][1]*yn;
w[section][1] = b[section][2]*input - a[section][2]*yn;
input = yn; // output of current section will be input to next */
return;
}
int main(void)
{
L138_initialise_intr(FS_48000_HZ,ADC_GAIN_0DB,DAC_ATTEN_0DB,LCDK_LINE_INPUT);
while(1);
} // end of main()
11. Follow the instruction in Expt. No. 1 for real time implementation.
65
Experiment No. 8: FIR Filter Design
For an Nth order filter, there are N+1 coefficients or filter length is N+1.
Important design methods are window based design and frequency sampling design.
Window based Design: The commonly used windows are hamming window and
Kaiser Window.
2𝜋𝑛
0.54 − 0.46 cos(𝑁−1 ) ,0≤𝑛≤𝑁−1
Hamming window, [𝑛] = {
0, 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒
The normalized transition width is δw, (transition width divided by sampling frequency
or (ws-wp) divided by 2π) and filter length 𝑁 are related by δw=3.3/ 𝑁, and the designed
filter will have a stop band attenuation of 53 dB.
2𝑛 2
𝐼0[𝛽√1−(1− 𝑁−1
) ]
Kaiser window, [𝑛] =
𝐼0(𝛽)
Where I0[.] is modified zero order Bessel function and β is a parameter that depends on
N.
𝑠 𝐴 −7.95
The filter length M is given by 𝑀 = [14.36𝛿 𝑤
]+1
0.1102(𝐴𝑠 − 8.7), 𝐴𝑠 ≥ 50
where 𝛽 = {
0.5842(𝐴𝑠 − 21)0.4 + 0.07886(𝐴𝑠 − 21), 21 < 𝐴𝑠 < 50
66
The other windows are rectangular, hanning, Bartlett, Blackman and raised cosine.
𝛼 { 2(𝑁−𝑘)
} , 𝑘 = 𝑁−1 + 1, … , 𝑁 + 1
𝑁 2
𝑁−1
where, 𝛼 = , and if N is even, lower integer of 𝑁−1 is taken for k.
2 2
67
Note: The length M can be estimated as follows
For LPF/HPF:
For BPF:
Example-1: Design, using window based approach, a low-pass digital FIR filter whose
desired specifications are: wp = 0.2π rad, ws = 0.3π rad, Rp = 0.2dB, As = 50dB.
a) Hamming window
Solution:
clc, clear all, close all;
wp = 0.2*pi;
ws = 0.3*pi;
N = ceil(6.6*pi/(ws-wp)); % estimates order of the filter
b = fir1(N, 0.2);
[H,W] = freqz(b,1,512);
68
plot(W/pi,20*log10(abs(H))), grid on, title('FIR filter using Hamming window');
xlabel('Normalized Frequency'), ylabel('Gain in dB');
-20
-40
Gain in dB
-60
-80
-100
-120
-140
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency
Example-2: Design the filter specified in problem no.1 using frequency sampling
design technique assuming linear phase.
Solution:
69
k1 = 0: floor((M-1)/2);
k2 = floor((M-1)/2)+1:M-1;
angH = [-alpha*(2*pi)*k1/M, alpha*(2*pi)*(M-k2)/M];
H = Hrs.*exp(j*angH);
h = real(ifft(H,M));
[H,W]=freqz([h],1,1024);
plot(W/pi,20*log10(abs(H))), zoom on, grid on;
title('FIR LPF using frequency sampling design');
xlabel('Normalized Frequency'), ylabel('Gain in dB');
% Note that stop band attenuation is not very good, is about 15dB only
Solution:
-10
-20
Gain in dB
-30
-40
-50
-60
-70
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency
Exercise:
1. Design, using Kaiser window based approach, a low-pass digital FIR filter whose
desired specifications are: wp = 0.2π rad, ws = 0.3π rad, Rp = 0.2dB, As = 50dB.
2. Design and plot the frequency response of a linear phase band-pass filter whose
70
specifications are as follows: Lower pass band edge = 400Hz, upper pass-band
edge = 500Hz, lower stop- band edge = 300Hz and upper stop-band edge = 600Hz,
Rp = 0.5dB and As = 40dB. The sampling frequency is 2 kHz.
a. using hamming window
b. using Kaiser window
3. Design the same filter in sample problem 2 with M = 25 and compare them.
4. The attenuation in stop band was observed to be not adequate in the above
problem. To improve, a few non-zero points are considered in the transition
band. These values are normally estimated by optimization techniques. In the
above problem, use Hrs(k) = [ 1, 1, 1, 0.5, 0.1 , zeros(1,11), 0.1,0.5,1,1]
Compare the results and find out whether there is any improvement. If there is,
then at what cost?
5. Design the filter specified in problem 2 using frequency sampling designing
technique.
6. Certain signal has 10Hz, 30Hz and 50Hz components. Simulate this signal.
Design suitable FIR filter using the following methods to select only 30Hz
component. Filter the signal using the filters, and plot the spectrum of the input
and the filtered signal. Hence compare the performance of the filters.
a) Window method
b) Frequency sampling designing
71
MATLAB program for obtaining the FIR coefficients:
// L138_fir_intr.c
#include "L138_LCDK_aic3106_init.h"
#define N 19
float h[N] = {0.00665241844915033, 0.00944800191495295,
0.0172251675376609, 0.0295945800356777, 0.0453802313441362,
0.0627672476626719, 0.0795656961393253,
0.0935476786398745, 0.102800730412649, 0.106036495727802,
72
0.102800730412649,
0.0935476786398745, 0.0795656961393253,
0.0627672476626719, 0.0453802313441362, 0.0295945800356777,
0.0172251675376609,
0.00944800191495295, 0.00665241844915033};
float x[N]; // filter delay line
interrupt void interrupt4(void)
{
short i;
float yn = 0.0;
x[0] = (float)(input_left_sample()); // input from ADC
for (i=0 ; i<N ; i++) // compute filter output
yn += h[i]*x[i];
for (i=(N-1) ; i>0 ; i--) // shift delay line
x[i] = x[i-1];
output_left_sample((uint16_t)(yn)); // output to DAC
return;
}
int main(void)
{
L138_initialise_intr(FS_48000_HZ,ADC_GAIN_0DB,DAC_ATTEN_0DB,LCDK_LINE_I
NPUT);
while(1);
}
Note: Follow the instructions given in Expt. No. 1 for real time implementation.
73
Experiment No. 9
Image Processing Applications
Objective:
1. To study the processing of digital images using MATLAB.
2. To study the processing of digital images using CCS simulation.
MATLAB Programs:
1. For any image file available on your disk, perform the following tasks:
(a) Read and display the image.
(b) Get the negative of the image.
(c) Rotate and display the image.
Solution:
clc;
close all;
clear all;
% a)
a = imread('image.bmp','bmp');
subplot(221),imshow(a), title('a) Image');
% b)
b = double(a);
b = 256-b;
b =uint8(b);
subplot(222), imshow(b), title('b) Negative of the image');
% c)
c = a';
subplot(223), imshow(c), title('c) Image rotated anti-clockwise');
2. Write a MATLAB program to compress an image using 2D-DCT and then try
reconstructing the image by using only 50% of the DCT coefficients.
Solution:
clc;
close all;
clear all;
a = imread('image.bmp','bmp');
subplot(221), imshow(a);
title('Given image');
a1 = dct2(a);
a2 = log(abs(a1));
a3 = mat2gray(a2);
subplot(222),imshow(a3);
title('DCT of the image');
a4 = triu(a1);% Taking only upper triangle of the DCT matrix
a5 = idct2(a4);
a6 = mat2gray(abs(a5));
subplot(223), imshow(a6);
title('Reconstructed image after compression');
74
Exercise Programs:
1 2 3 0 1
𝐴 = [0 8 6] and 𝐵 = [1 0]
5 3 1 3 5
5. Compute the DFT of an image and plot the response with centered low frequencies.
(Use fft2 and fftshift functions.)
6. Write a MATLAB program to detect the sharp edges in an image in the horizontal
direction.
7. Write a MATLAB program to add ‘salt and pepper’ type of noise to an image, and
then filter it. Show all the three images on the same plot.
8. Write a program to read an image and highlight only specified region. (Use iroipoly
function.)
9. Re-size an image to twice its size. Add salt and pepper noise with a density of 0.25.
Filter the noisy image with median filtering using window sizes 3x3, 5x5 and 7x7.
More than one repetition may be done. Display and compare the resulting images.
Which one is most suitable for further processing? (Use imresize, imnoise and
medflt2functions.)
10. Compute the Fourier Transform of an image .Rotate the original image by 45 degrees
and compute the FT of the rotated image. Move the origin to the center of the FT.
Display the logarithm of magnitude of the FT before and after rotation. What happens
to the FT after rotation? (Use fft2, imrotate, fftshift, abs, log and imagesc functions.)
CCS Program:
PREREQUISITES:
1. CCSv5/6 should be installed
2. C64XPLUS-IMGLIB should be installed from http://www.ti.com/tool/sprc264.
1. Create a project:
Goto File ->new->CCS project and enter the details as below.In “Advanced Settings” choose the
Linker command file: as “linker_dsp.cmd” (Browse from ‘IMGLibcall_with logo\src’ folder given at
the time of installation)
75
2. Adding the files:
➢ Right click on project name-> Add files..-> Add ‘IMAGEMAIN.c’ and
‘STARCOMLOGO.c’ from ‘src’ folder.
➢ Add all the files from ‘src\lib files’.
➢ Add ‘wolf.c’ from ‘bitmaps’ folder.
76
Plot for output image:
(d) (e)
Figure 1: (a) Input image (b) Sharpened image (c) Smoothened image (d) Threshold image
(e) Filtered image
77
Expt. No. 10: Audio and Communication applications
Please go through experiment-1 for instructions on how to run a real-time experiment in
LCDKC6748 kit. All the following are real-time experiments.
// L138_echo_intr.c
#include "L138_LCDK_aic3106_init.h"
int16_t input,output,delayed;
int16_t buffer[BUF_SIZE];
int i = 0;
input = input_left_sample();
delayed = buffer[i];
i = (i+1)%BUF_SIZE;
output_left_sample(output);
return;
int main(void)
int i;
buffer[i] = 0;
L138_initialise_intr(FS_48000_HZ,ADC_GAIN_0DB,DAC_ATTEN_0DB,LCDK_MIC_INPUT);
78
while(1);
2. Creating DELAY
This program takes the Mic input and plays it after a delay. Output is observed using loud
speaker connected to LINE_OUT.
// L138_delay_intr.c
//
#include "L138_LCDK_aic3106_init.h"
#define BUF_SIZE 24000
uint16_t input,output,delayed;
uint16_t buffer[BUF_SIZE];
int i = 0;
int main(void)
{
int i;
3. AUDIO PLAYBACK
In this experiment, an audio input is given to the kit using LINE_IN port (you may use an
auxiliary cable to connect a mobile phone and play an audio file). Same audio will be played
in the loud speaker connected to LINE_OUT.
#include "L138_LCDK_aic3106_init.h"
interrupt void interrupt4(void) // interrupt service routine
{
uint32_t sample;
79
sample = input_sample(); // read L + R samples from ADC
output_sample(sample); // write L + R samples to DAC
return;
}
int main(void)
{
L138_initialise_intr(FS_48000_HZ,ADC_GAIN_0DB,DAC_ATTEN_0DB,LCDK_LIN
E_INPUT)
;
while(1);
}
Low frequency components of an audio sample are called bass (played using speakers called
woofers), and high frequency components are called treble (played using tweeters).
In this experiment, we will design a low-pass filter (to get bass components) and a high-pass
filter (to get treble) components of the audio file.
80
a) Response type – Low pass
b) Design method – FIR (select Window method)
c) Specify order: 10
d) Window: Hamming
e) Units – Hz
f) Sampling frequency: (Fs) – 48000
g) Cutoff frequency (Fc): 3000
// L138_fir_intr.c
#include "L138_LCDK_aic3106_init.h"
//(Change N according to the number of coefficients)
#define N 11
81
L138_initialise_intr(FS_8000_HZ,ADC_GAIN_0DB,DAC_ATTEN_0DB,LCD
K_LINE_INPUT);
while(1);
}
5. Perform FSK based digital modulation and observe the waveform using CC studio
#include<stdio.h>
#include<math.h>
#define TIME 336 //length of FSK signal
#define PI 3.14
float fh[TIME],fl[TIME],FSK[TIME];
int input_string[8],scale_data[TIME];
void main()
{
int i,j,k,l;
printf("\nEnter your digital data string in the form of 1 & 0s\n");
for(i=0;i<8;i++) //data in binary format
scanf("%d",&input_string[i]);
k=0;
for(k=0;k<TIME;k++)
{
for(j=0;j<8;j++)
{
for(i=0;i<21;i++)
{
scale_data[k]=input_string[j]; // Scaling input data
k++;
}
}
}
for(i=0;i<TIME;i++)
{
fh[i]=sin(2*PI*2000*i/10000);//high frequency
fl[i]=sin(2*PI*1000*i/10000);//low frequency
}
//assigning high frequency to bit 1
k=0;
for(l=0;k<TIME;l++)
{
for(i=0;i<8;i++)
{
if(input_string[i]==1)
{
for(j=0;j<21;j++)
{
FSK[k]=fh[j];
k++;
82
}
}
else
//assigning low frequency to bit 0
{
if(input_string[i]==0)
{
for(j=0;j<21;j++)
{
FSK[k]=fl[j];
k++;
}}}}}}
After executing the code in the console window, we need to enter the input sequence
Fill the details as shown and click OK. You will see two address blocks.
83
and
Repeat the same experiment for different values of input combinations and record the FSK
output waveform.
84
Reference
1. Sanjit K. Mitra ,“Digital Signal Processing Laboratory Using
Matlab”, Mcgraw-Hill College, 2005.
2. D.G. Manolakis and Vinay K. Ingle, “Applied Digital Signal
Processing”, Cambridge University Press, 2012.
3. MATLAB help
4. CCStudio manual
85