Você está na página 1de 122

COLLEGE OF ENGINEERING

THIRUVANANTHAPURAM

DIGITAL SIGNAL PROCESSING


LABORATORY RECORD
YEAR 2014

GEORGE SEBASTIAN
Uni.Reg.no. 12400026

COLLEGE OF ENGINEERING
THIRUVANANTHAPURAM

Date:

DIGITAL SIGNAL PROCESSING


LABORATORY RECORD
YEAR 2014

Uni.Reg.No

12400026

Name

GEORGE SEBASTIAN

Roll no

27

Class EC

Batch S5

from Page No

to Page No 120

Certified Bonafide Record of work done


by

Thiruvananthapuram

Date

Faculty-in-charge

Date:

CONTENTS
1. Mathematical Operations on signal

1.1 Time Shifting Operation


1.2 Time Scaling Operation
1.3 Amplitude Scaling
1.4 Addition
1.5 Multiplication
1.6 Convolution with built in function
1.7 Convolution without built-in function
2. Random Sequence Generation

5
8
11
14
18
21
24
29

3.

4.

5.

2.1 Uniform distribution


2.2 Gaussian distribution
2.3 Rayleigh distribution

29
30

Convolution

34

3.1 Linear Convolution

35

3.2 Circular Convolution

37

3.3 Linear Convolution via circular convolution

39

Modulation

42

4.1 Amplitude Modulation

42

4.2 Frequency Modulation

44

4.3 Pulse Width Modulation

45

Discrete Fourier Transform

48

5.1 Finding N point DFT and IDFT

48

5.2 Magnitude and Phase plots

50

5.3 Spectral Analysis of signals

53

6. Convolution using DFT

60

6.1 Circular convolution using DFT

60

6.2 Linear convolution using DFT

62

Date:
7. Convolution using Overlap-save method

64

8. Convolution using Overlap-add method

68

9.

IIR filters

72

9.1 Butterworth low pass filter

72

9.2 Butterworth high pass filter

74

9.3 Butterworth band pass filter

76

9.4 Butterworth band stop filter

77

9.5Chebyshev I low pass filter

80

9.6 Chebyshev I high pass filter

82

9.7 Chebyshev I band pass filter

83

9.8 Chebyshev I band stop filter

85

10. FIR filter design

87

10.1 Filter using hamming window

89

10.2 Filter using hanning window

90

10.3 filter using frequency sampling method

91

11. Sampling rate conversion by rational factor

94

12. Optimal Equiripple Design technique for FIR filters

97

12.1 FIR low pass filter


13. Introduction to DSP development system

103

14. Programs using Code Composer Studio

115

14.1 Sine wave generation

115

14.2 FIR filtering

117

14.3 IIR filtering

119

Date:

EXPERIMENT NO:1
MATHEMATICAL OPERATIONS ON SIGNALS
AIM:
To perform the basic mathematical operations on discrete and continuous signals
(a) time shifting
(b) time scaling
(c) amplitude scaling
(d) addition
(e) multiplication
(f) convolution (with and without using built-in function)

THEORY:
The basic mathematical operations that can be performed on signals are time shifting,
time scaling, amplitude scaling, addition, multiplication and convolution.
Time shifting: Let x(t) denote a continuous-time signal. Then the signal y(t) obtained by
shifting the independent variable, time t, by a factor a is defined by
y(t) = x(t-a)
In discrete-time case, y[n] = x[n-k]
Time scaling: Let x(t) denote a continuous-time signal. Then the signal y(t) obtained by
scaling the independent variable, time t, by a factor a is defined by
y(t) = x(at)
In discrete-time case, y[n] = x[kn]
Amplitude scaling: Let x(t) denote a continuous-time signal. Then the signal y(t) resulting
from amplitude scaling applied to x(t) is defined by
y(t) = cx(t), where c is the scaling factor.
In a similar manner, for discrete-time signals, y[n] = cx[n]
Addition: The signal y(t) obtained by the addition of x1(t) and x2(t) is defined by
y(t) = x1(t) + x2(t)
4

Date:
For discrete-time signals, y[n] = x1[n] + x2[n]
Multiplication: The signal y(t) resulting from the multiplication of x1(t) and x2(t) is defined
by
y(t) = x1(t) x2(t)
For discrete-time signals, y[n] = x1[n] x2[n]

Convolution: Let x(t) be the input signal and h(t) be the impulse response. Then the output
signal y(t) is obtained by the convolution of x(t) and h(t).That is
y(t) =x(t) * h(t)
In discrete-time case, y[n] = x[n] * h[n].

The conv function is approximating the convolution integral by a summation. The data in
the 2 arrays x(t) and h(t) are samples of the continuous time signals with samples separated
by dt seconds. When the conv function is used with arrays x(t) and h(t) , the result is an array
of 2n-1 elements with data spacing of dt seconds. The first n elements correspond to the
correct output values over the same time interval for which the input signal and impulse
response have stored values. The remaining n-1 elements are computed based on the
assumption that both x(t) and h(t) are equal to 0 for all other time other than what was
represented by the arrays x(t) and h(t).

MATLAB Code:
PROGRAM 1.1
%TIME SHIFTING OPERATION
% Discrete Sequence-Time Shifting
clc
close all
clear all
x=input('Enter the input sequence x[n]
l=input('Enter the starting index
a=input('Enter the shift value x[n-a]
n=length(x);
t=l:1:(n+l-1);
subplot(2,1,1)
stem(t,x)
xlabel('Time index')
5

');
');
');

Date:
ylabel('Amplitude')
title('Input Signal x[n]')
axis([-10 10 -5 5])
t=a+l:1:(n+a+l-1);
subplot(2,1,2)
stem(t,x)
xlabel('Time index')
ylabel('Amplitude')
title('Time Shifted Signal x[n-a]')
axis([-10 10 -5 5])
gtext('George Sebastian 12400026')
% Continous Sequence-Time Shifting
clc
close all
clear all
A=input('Enter the max amplitude
');
f=input('Enter the frequency
');
a=input('Enter the time shift value x[t-a]
t=-3:0.001:3;
x=A*sin(2*pi*f*t);
subplot(2,1,1)
plot(t,x)
axis([-5 5 -5 5])
xlabel('Time index')
ylabel('Amplitude')
title('Input Signal x(t)')
t=-3+a:0.001:3+a;
y=A*sin(2*pi*f*(t));
subplot(2,1,2)
plot(t,y)
axis([-5 5 -5 5])
xlabel('Time index')
ylabel('Amplitude')
title('Time Shifted Signal x[t-a]')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Discrete samples:
Enter the input sequence x[n]
Enter the starting index
Enter the shift value x[n-a]

[1 2 3 1]
-3
2

');

Date:

Figure 1.1: Time shifting operation-discrete

Continuous Functions:
Enter the max amplitude
4
Enter the frequency
3
Enter the time shift value x[t-a]

Date:

Figure 1.1: Time shifting operation-continuous

PROGRAM 1.2:

%TIME SCALING OPERATION


%Discrete sequence
clc
close all
clear all
x=input('Enter the input sequence x[n]
l=input('Enter the starting index
a=input('Enter the scale value x[an]
n=length(x);
t=l:1:(n+l-1);
subplot(2,1,1)
stem(t,x)
m=1
s=(l/a):1:((n+l-1)/a)
axis([-5 5 -5 5])
8

');
');
');

Date:
xlabel('Time index')
ylabel('Amplitude')
title('Input Signal x[n]')
for k=(l/a):1:((n+l-1)/a)
y(m)=x((m*a)-(a-1))
m=m+1;
end
subplot(2,1,2)
stem(s,y)
axis([-5 5 -5 5])
xlabel('Time index')
ylabel('Amplitude')
title('Time Scaled Signal x[an]')
gtext('George Sebastian 12400026')

%Continuous signal
clc
close all
clear all
A=input('Enter the max amplitude
');
f=input('Enter the frequency
');
a=input('Enter the time scale value x(at)
t=-3:0.001:3;
x=A*sin(2*pi*f*t);
subplot(2,1,1)
plot(t,x)
axis([-5 5 -5 5])
xlabel('Time index')
ylabel('Amplitude')
title('Input Signal x(t)')
y=A*sin(2*pi*f*a*(t));
subplot(2,1,2)
plot(t,y)
axis([-5 5 -5 5])
xlabel('Time index')
ylabel('Amplitude')
title('Time Scaled Signal x(at)')
gtext('George Sebastian 12400026')

');

Date:

SAMPLE OUTPUT
DISCRETE SEQUENCE
Enter the input sequence x[n]
[1 2 3 4 3 2 1 0 1]
Enter the starting index
-3
Enter the scale value x[an]
3

Figure 1.2: Time scaling operation-discrete

CONTINUOUS SIGNAL
Enter the max amplitude
5
Enter the frequency
1
Enter the time scale value x(at)

10

Date:

Figure 1.2: Time scaling operation-continuous

PROGRAM 1.3:
%AMPLITUDE SCALING OPERATION
%Discrete sequence
clc
close all
clear all
x=input('Enter the input sequence x[n]
');
l=input('Enter the starting index
');
a=input('Enter the amplitude scale value ax[n]
n=length(x);
t=l:1:(n+l-1);
subplot(2,1,1)
stem(t,x)
axis([-5 5 -5 5])
xlabel('Time index')
ylabel('Amplitude')
title('Input Signal x[n]')
t=l:1:(n+l-1);
y=a.*x;
subplot(2,1,2)
11

');

Date:
stem(t,y)
axis([-5 5 -5 5])
xlabel('Time index')
ylabel('Amplitude')
title('Amplitude Scaled Signal ax[n]')
gtext('George Sebastian 12400026)
% Continous Sequence-Amplitude Scaling
clc
close all
clear all
A=input('Enter the max amplitude
');
f=input('Enter the frequency
');
a=input('Enter the amplitude scale ax[t]
t=-3:0.001:3;
x=A*sin(2*pi*f*t);
subplot(2,1,1)
plot(t,x)
axis([-5 5 -5 5])
xlabel('Time index')
ylabel('Amplitude')
title('Input Signal x(t)')
t=-3:0.001:3;
y=a*A*sin(2*pi*f*(t));
subplot(2,1,2)
plot(t,y)
axis([-5 5 -5 5])
xlabel('Time index')
ylabel('Amplitude')
title('Amplitude Scaled Signal x[t-a]')
gtext('George Sebastian 12400026')

');

SAMPLE OUTPUT

DISCRETE SEQUENCE
Enter the input sequence x[n]
[1 2 3 4 3 2 1]
Enter the starting index
-2
Enter the amplitude scale value ax[n]
0.5

12

Date:

Figure 1.3: Amplitude scaling operation-discrete

CONTINUOUS SIGNAL
Enter the max amplitude
2
Enter the frequency
2
Enter the amplitude scale ax[t]

13

1.5

Date:

Figure 1.3: Amplitude scaling operation-continuous

PROGRAM 1.4:
%ADDITION OF SIGNALS
%Discrete Signal Addition
clc
clear all
close all
x=input('Enter the first signal x[n]
');
lx=input('Enter its starting index
');
y=input('Enter the second signal y[n]
');
ly=input('Enter its starting index
');
mx=length(x);
my=length(y);
tx=lx:lx+mx-1;
subplot(3,1,1)
stem(tx,x)
title('First signal x[n]')
xlabel('Time index')
ylabel('Amplitude')
axis([-5 5 -5 5])
ty=ly:ly+my-1;
subplot(3,1,2)
14

Date:
stem(ty,y)
title('Second signal x[n]')
xlabel('Time index')
ylabel('Amplitude')
axis([-5 5 -7 7])
p=abs(lx-ly);
if(lx>ly)
t1=ly;
x=[zeros(1,p) x];
else
t1=lx;
y=[zeros(1,p) y];
end
mx1=length(x);
my1=length(y);
q=abs(mx1-my1);
if(mx1>my1)
y=[y zeros(1,q)];
else
x=[x zeros(1,q)];
end
z=x+y;
t2=length(z);
tz=t1:t1+t2-1;
subplot(3,1,3)
stem(tz,z)
title('Sum signal z[n]=x[n]+y[n]')
xlabel('Time index')
ylabel('Amplitude')
axis([-5 5 -7 7])
gtext('George Sebastian 12400026')

%Continous signal addition


clc
clear all
close all
t=-1:0.01:1;
A1=input('Enter the amplitude
x(t)
');
f1=input('Enter the frequency
x(t)
');
x=A1*sin(2*pi*f1*t);
A2=input('Enter the amplitude
y(t)
');
f2=input('Enter the frequency
y(t)
');
y=A2*sin(2*pi*f2*t);
subplot(3,1,1)

of the first sinusoidal wave


of the first sinusoidal wave
of the second sinusoidal wave
of the second sinusoidal wave

15

Date:
plot(t,x)
title('First signal x(t) ')
xlabel('Time index')
ylabel('Amplitude')
subplot(3,1,2)
plot(t,y)
title('Second signal y(t) ')
xlabel('Time index')
ylabel('Amplitude')
axis([-2 2 -5 5])
z=x+y;
subplot(3,1,3)
plot(t,z)
title('Sum signal z(t)=x(t)+y(t)')
xlabel('Time index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT

DISCRETE SEQUENCE
Enter
Enter
Enter
Enter

the
its
the
its

first signal x[n]


[1 2 3 4 3 2 0]
starting index
-3
second signal y[n]
[1 0 1 0 2 0]
starting index
-2

16

Date:

Figure 1.4: Addition of signals-discrete

CONTINUOUS SIGNAL

Enter
Enter
Enter
Enter

the
the
the
the

amplitude
frequency
amplitude
frequency

of
of
of
of

the
the
the
the

first sinusoidal wave x(t)


first sinusoidal wave x(t)
second sinusoidal wave y(t)
second sinusoidal wave y(t)

17

2
2
2
1

Date:

Figure 1.4: Addition of signals-continuous

PROGRAM 1.5:
% MULTIPLICATION OF SIGNALS
%Discrete Signal Multiplication
clc
clear all
close all
x=input('Enter the first signal x[n]
');
lx=input('Enter its starting index
');
y=input('Enter the second signal y[n]
');
ly=input('Enter its starting index
');
mx=length(x);
my=length(y);
tx=lx:lx+mx-1;
subplot(3,1,1)
stem(tx,x)
title('First signal x[n]')
xlabel('Time index')
ylabel('Amplitude')
axis([-5 5 -10 10])
ty=ly:ly+my-1;
subplot(3,1,2)
18

Date:
stem(ty,y)
title('Second signal x[n]')
xlabel('Time index')
ylabel('Amplitude')
p=abs(lx-ly);
if(lx>ly)
t1=ly;
x=[zeros(1,p) x];
else
t1=lx;
y=[zeros(1,p) y];
end
mx1=length(x);
my1=length(y);
q=abs(mx1-my1);
if(mx1>my1)
y=[y zeros(1,q)];
else
x=[x zeros(1,q)];
end
z=x.*y;
t2=length(z);
tz=t1:t1+t2-1;
subplot(3,1,3)
stem(tz,z)
title('Product signal z[n]=x[n].*y[n]')
xlabel('Time index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')
%Continous signal multiplication
clc
clear all
close all
t=-1:0.01:1;
A1=input('Enter the amplitude of
x(t)
');
f1=input('Enter the frequency of
x(t)
');
x=A1*sin(2*pi*f1*t);
A2=input('Enter the amplitude of
');
f2=input('Enter the frequency of
');
d=input('Enter the duty cycle of
');
y=A2*square(2*pi*f2*t,d*100);
subplot(3,1,1)
19

the first sinusoidal wave


the first sinusoidal wave
the second square wave y(t)
the

second square wave y(t)

the second square wave y(t)

Date:
plot(t,x)
title('First signal x(t) ')
xlabel('Time index')
ylabel('Amplitude')
subplot(3,1,2)
plot(t,y)
title('Second signal y(t) ')
xlabel('Time index')
ylabel('Amplitude')
z=x.*y;
subplot(3,1,3)
plot(t,z)
title('Product signal z(t)=x(t).*y(t)')
xlabel('Time index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
DISCRETE SEQUENCE
Enter
Enter
Enter
Enter

the
its
the
its

first signal x[n]


[4 2 3 0 5 2 6]
starting index
-1
second signal y[n]
[4 5 3 5 1 3 ]
starting index
-4

Figure 1.5: Multiplication of signals-discrete


20

Date:

CONTINUOUS SIGNAL
Enter
Enter
Enter
Enter
Enter

the
the
the
the
the

amplitude of the first sinusoidal wave x(t)


4
frequency of the first sinusoidal wave x(t)
2
amplitude of the second square wave y(t)
2
frequency of the second square wave y(t)
2
duty cycle of the second square wave y(t)
0.5

Figure 1.5: Multiplication of signals-continuous

PROGRAM 1.6.1:
%Discrete Signal Convolution using built in function
clc
clear all
close all
x=input('Enter the input sequence x[n]
');
lx=input('Enter its starting index
');
h=input('Enter the impulse response h[n]
');
lh=input('Enter its starting index
');
mx=length(x);
t=lx:lx+mx-1;
subplot(3,1,1)
stem(t,x)
21

Date:
title('Input sequence x[n]')
xlabel('Time index')
ylabel('Amplitude')
mh=length(h);
t=lh:lh+mh-1;
subplot(3,1,2)
stem(t,h)
title('Impulse Response h[n]')
xlabel('Time index')
ylabel('Amplitude')
z=conv(x,h);
m=length(z);
t=lx+lh:lx+lh+m-1;
subplot(3,1,3)
stem(t,z)
title('Convoluted sequence z[n]=x[n]*h[n]')
xlabel('Time index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')
%Continuous signal
clc;
clear;
tx=-1:0.001:1;
x=2*rectpuls(tx,2);
subplot(311);
plot(tx,x,'k-','LineWidth',1.5);
title('First signal x(t)');
xlabel('Time index');
ylabel('Amplitude');
axis([-4 4 -5 5]);
ty=-2:0.001:2;
y=2*sawtooth(2*pi*0.25*ty+pi);
subplot(312);
plot(ty,y,'k-','LineWidth',1.5);
title('Second signal y(t)');
xlabel('Time index');
ylabel('Amplitude');
axis([-4 4 -5 5]);
t=-3:0.001:3;
z=0.001*conv(x,y);
subplot(313);
plot(t,z,'r-','LineWidth',1.5);
title('Linear convolution output y(t)=x(t)*h(t)');
xlabel('Time index');
ylabel('Amplitude');
axis([-4 4 -5 5]);
gtext('George Sebastian 12400026')

22

Date:

SAMPLE OUTPUT

DISCRETE SEQUENCE
Enter
Enter
Enter
Enter

the
its
the
its

input sequence x[n]


[1 2 3 4 1 0 1]
starting index
-2
impulse response h[n]
[1 1 1]
starting index
-2

Figure 1.6.1: Convolution of signals using built-in functions-discrete

23

Date:
CONTINUOUS SIGNAL

Figure 1.6.2: Convolution of signals using built-in functions continuous

PROGRAM 1.6.2:
%Discrete Signal Convolution without using built in function
clc
clear all
close all
x=input('Enter the input sequence x[n]
');
lx=input('Enter its starting index
');
h=input('Enter the impulse response h[n]
');
lh=input('Enter its starting index
');
mx=length(x);
t=lx:lx+mx-1;
subplot(3,1,1)
stem(t,x)
title('Input sequence x[n]')
xlabel('Time index')
ylabel('Amplitude')
axis([-5 5 -5 5])
mh=length(h);
t=lh:lh+mh-1;
subplot(3,1,2)
24

Date:
stem(t,h)
title('Impulse Response h[n]')
xlabel('Time index')
ylabel('Amplitude')
X=[x zeros(1,mh)];
H=[h zeros(1,mx)];
for i=1:mx+mh-1
y(i)=0;
for j=1:mx
for k=1:mh
if(j+k)==(i+1)
y(i)=y(i)+X(j).*H(k);
end
end
end
end
m=length(y);
t=lx+lh:lx+lh+m-1;
subplot(3,1,3)
stem(t,y)
title('Convoluted Response y[n]=x[n]*h[n]')
xlabel('Time index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')
%Continuous Convolution Without using built in function
clc
clear all
close all
l=input('Enter the width of the triangular pulse
');
A=input('Enter the amplitude of the triangular pulse
');
h=input('Enter the impulse response h(t)
');
lh=input('Enter its starting index
');
mh=length(h);
t=lh:lh+mh-1;
tx=-2:0.01:2;
x=A*tripuls(tx,l);
subplot(3,1,1)
plot(tx,x)
title('Input signal x(t)')
xlabel('Time index')
ylabel('Amplitude')
subplot(3,1,2)
stem(t,h)
title('Impulse Response h(t)')
xlabel('Time index')
ylabel('Amplitude')
X=[x zeros(1,mh)];
H=[h zeros(1,l)];
25

Date:
for i=1:l+mh
y(i)=0;
for j=1:l
for k=1:mh
if(j+k)==(i+1)
y(i)=y(i)+X(j).*H(k);
end
end
end
end
t=(-l/2)+lh:(l/2)+lh+mh-1;
subplot(3,1,3)
plot(t,y)
title('Convoluted signal y(t)=x(t)*h(t)')
xlabel('Time index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT

DISCRETE SEQUENCE
Enter the input sequence x[n] [1 2 3 4 0 2 1]
Enter its starting index -3
Enter the impulse response h[n] [1 1 1]
Enter its starting index -2

26

Date:

Convolution of signals without using built-in functions-discrete

CONTINUOUS SIGNAL

Enter
Enter
Enter
Enter

the
the
the
its

width of the triangular pulse


4
amplitude of the triangular pulse
5
impulse response h(t)
[2 0 0 0 1]
starting index
-2

27

Date:

Convolution of signals without using built-in functions continuous

RESULT:
The basic operations on continuous and discrete-time signals have been performed.

28

Date:

EXPERIMENT NO: 2
RANDOM SEQUENCE GENERATION
AIM:
To generate uniformly distributed, Gaussian distributed and Rayleigh distributed random
number sequences and to plot their histograms.

THEORY:
Uniform distribution:
Uniform deviates are just random numbers that lie within a specified range. Other
deviates are almost always generated by performing appropriate operations on one or more of
uniform deviates.
The probability density function of a random variable X, uniformly distributed in (a,b)
is given by
fX(x) = 1/(b-a), a x b
=

0, otherwise

MATLAB Code:

PROGRAM 2.1:
%Random Signal Generation using random functions
%Uniform Distribution
clc;
clear;
a= input('Enter the value of a in interval [a,b] ');
b= input('Enter the value of b in interval [a,b] ');
x= rand(1,100000);
y = a + (b-a).*x;
subplot(211);
plot(y);
xlabel('Index');
ylabel('Amplitude');
title('Uniform Random Signal');
subplot(212);
hist(y,10);
xlabel('Values');
ylabel('Frequency');
title('Histogram');
axis([0 8 0 12000]);
29

Date:
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the value of a in interval [a,b] 2
Enter the value of b in interval [a,b] 6

Figure 2.1: Uniform distribution

Gaussian distribution:
In probability theory, the normal (or Gaussian) distribution is a continuous probability
distribution that has a bell-shaped probability density function, known as the Gaussian
function or informally as the bell curve.

The parameter is the mean or expectation (location of the peak) and 2 is the variance. is
known as the standard deviation. The distribution with = 0 and 2 = 1 is called the standard
normal distribution or the unit normal distribution. A normal distribution is often used as a
first approximation to describe real-valued random variables that cluster around a single
mean value.

30

Date:

PROGRAM 2.2:
%Gaussian Distribution
clc;
clear;
mu= input('Enter the mean: ');
sd= input('Enter the standard deviation: ');
x= randn(1,100000);
y= mu + sd*x;
subplot(211);
plot(y);
xlabel('Index');
ylabel('Amplitude');
title('Gaussian Random Signal');
subplot(212);
histfit(y,500);
xlabel('Values');
ylabel('Frequency');
title('Histogram');
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the mean: 7
Enter the standard deviation: 1

Figure 2.2: Gaussian distribution


31

Date:

Rayleigh distribution:
In probability theory and statistics, the Rayleigh distribution is a continuous
probability distribution. A Rayleigh distribution is often observed when the overall
magnitude of a vector is related to its directional components. An example of the distribution
arises in the case of random complex numbers whose real and imaginary components are
i.i.d. (independently and identically distributed) Gaussian. In that case, the absolute value of
the complex number is Rayleigh-distributed. The distribution is named after Lord Rayleigh.
The Rayleigh probability density function is

for parameter

and cumulative distribution function

for

PROGRAM 2.3:
%Rayleigh Distribution
clc;
clear;
b=input('Enter the value of the parameter "b"');
x=random('rayl',b,1,100000);
subplot(211);
plot(x);
xlabel('Index');
ylabel('Amplitude');
title('Rayleigh Random Signal');
subplot(212);
histfit(x,50,'rayleigh');
xlabel('Values');
ylabel('Frequency');
title('Histogram');
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the value of the parameter "b"8
32

Date:

Figure 2.3: Rayleigh distribution

RESULT:
Uniformly distributed, Gaussian distributed and Rayleigh distributed random number
sequences have been generated and verified by plotting their histograms.

33

Date:

EXPERIMENT NO : 3
CONVOLUTION
AIM:
To implement linear and circular convolution of two finite length sequences using
elementary MATLAB commands and to demonstrate the implementation of linear
convolution via circular convolution.

THEORY:
3.1) Linear Convolution

In particular linear time invariant systems are characterized in time domain simply by their
response to a unit sample sequence. The general form of expression that relates the unit
sample response of the system and the arbitrary input signal to the output signal is called the
convolution formula (or sum) .
If x1(n) is an M-point sequence and x2(n) is an N-point sequence, then linear convolution
of x1(n) and x2(n) is defined as
( )

( )
=

( )

( )
(

X3(n) is an (M+N-1)-point sequence.


The process of computing convolution involves,
(1) Folding: fold x2(k) about k=0 to obtain x2(-k).
(2) Shifting: shift x2(-k) by n0 to the right (left) if n0 is positive (negative) to obtain
x2(n0-k).
(3) Multiplication: multiply x1(k) by x2(n0-k) to obtain the product sequence.
(4) Summation: sum of all values of the product sequence to obtain the value of output at
time n=n0.

34

Date:

Algorithm

X2(1)

X2(M)

X1(1)

X1(1)*x2(1)

X1(1)*X2(M)

X1(N)

X1(N)*X2(1) .

X1(N)*X2(M)

Take the sum of elements in each diagonal as shown by shaded cells, from left most
column to right. This gives the output sequence elements in order.

MATLAB code
PROGRAM 3.1:
%Linear Convolution
clc
clear all
close all
a=input('Enter the first sequence ');
b=input('Enter the second sequence ');
ma=length(a);
mb=length(b);
subplot(3,1,1)
stem(a)
title('Input signal a[n]')
xlabel('Time index')
ylabel('Amplitude')
subplot(3,1,2)
stem(b)
title('Input signal b[n]')
xlabel('Time index')
ylabel('Amplitude')
c=zeros(1,ma+mb-1);
35

Date:
for i=1:ma
j=i-1;
k=ma-i;
c=[zeros(1,j) b*a(i) zeros(1,k)]+c;
end
disp('Output Sequence ');c
subplot(3,1,3)
stem(c)
title('Output signal c[n]')
xlabel('Time index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the first sequence [1 1 1 1]
Enter the second sequence [1 0 2 3 1]
Output Sequence
c =
1

Figure 3.1: Input and output sequences

36

Date:

3.2) Circular Convolution

The N-point circular convolution of two sequences x1(n) and x2(n) of length N is given
by

( )

((

))

Circular convolution involves basically the same 4 steps as the ordinary linear convolution.
Folding (time reversing) of one sequence, shifting the folded sequence, multiplying the two
sequences to obtain a product sequence and finally summing the values of the product
sequence. The basic difference between these two types of convolution is that, in circular
convolution the folding and shifting operations are performed in a circular fashion by
computing the index of one of the sequences modulo N. In circular convolution there is no
modulo N operation. N is the max of length of the sequence

MATLAB code
PROGRAM 3.2:
%Circular Convolution
clc
clear all
close all
a=input('Enter the first sequence ');
b=input('Enter the second sequence ');
ma=length(a);
mb=length(b);
subplot(3,1,1)
stem(a)
title('Input signal a[n]')
xlabel('Time index')
ylabel('Amplitude')
subplot(3,1,2)
stem(b)
title('Input signal b[n]')
xlabel('Time index')
ylabel('Amplitude')
N=max(ma,mb);
a=[a zeros(1,N-ma)];
b=[b zeros(1,N-mb)];
for i=1:N
c(i)=0;
for j=1:N
k=mod(i-j,N);
37

Date:
c(i)=c(i)+a(j)*b(k+1);
end
end
disp('Output Sequence ');c
subplot(3,1,3)
stem(c)
title('Output signal c[n]')
xlabel('Time index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the first sequence [1 2 2 1]
Enter the second sequence [1 2 3 1]
Output Sequence
c =
11

10

12

Figure 3.2: Input and output sequences

38

Date:

3.3) Linear Convolution via Circular Convolution


If x1(n) is of length M and x2(n) is of length .Append (N-1) zeros to x1(n) and (M-1) zeros to
x2(n) to make their lengths equal. Then the M+N-1 point circular convolution is same as
their linear convolution. The method used for computation is same as that of circular
convolution above.

MATLAB code
PROGRAM 3.3:
%Linear Convolution via Circular Convolution
clc
clear all
close all
a=input('Enter the first sequence ');
b=input('Enter the second sequence ');
ma=length(a);
mb=length(b);
subplot(3,1,1)
stem(a)
title('Input signal a[n]')
xlabel('Time index')
ylabel('Amplitude')
subplot(3,1,2)
stem(b)
title('Input signal b[n]')
xlabel('Time index')
ylabel('Amplitude')
N=ma+mb-1;
a=[a zeros(1,N-ma)];
b=[b zeros(1,N-mb)];
for i=1:N
c(i)=0;
for j=1:N
k=mod(i-j,N);
c(i)=c(i)+a(j)*b(k+1);
end
end
disp('Output Sequence ');c
subplot(3,1,3)
stem(c)
title('Output signal c[n]')
xlabel('Time index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

39

Date:

SAMPLE OUTPUT
Enter the first sequence [1 1 0 1]
Enter the second sequence [1 2 3 1 2]
Output Sequence
c =
1

Figure 3.3: Input and output sequences

CONCLUSION :

(1) The MATLAB code linconv is used for implementing linear convolution without
matlab function.
This program can be used to verify the different properties of convolution sum
(commutative, distributive and assosiative laws) and also for polynomial
multiplication (algebraically convolution is the same operation as multiplying the
40

Date:
polynomials whose coefficients are the elements x1 and x2). But this approach is not
very efficient in speed for very long sequences.
(2) The MATLAB code cconv finds circular convolution by direct implementation of
equ. For circular convolution. It can be verified using the code that for two different
sequences, N-point, N+1 point...convolutions are different. This direct
implementation is inefficient in terms of speed for large sequences.
(3) The MATLAB code lin_circ finds linear convolution by padding the required number
of zeros to both input sequences and then finding circular convolution by the direct
method.

RESULT :

Linear convolution, Circular convolution and computation of Linear convolution via Circular
convolution of two finite length sequences were implemented using MATLAB commands.

41

Date:

EXPERIMENT NO : 4
MODULATED WAVEFORMS
AIM:
To generate AM, FM and PWM waveforms using MATLAB.

THEORY:
4.1 AMPLITUDE MODULATION
In the amplitude modulation (AM), the instantaneous amplitude of a carrier signal having
high frequency is varied by the instantaneous amplitude of a modulating voltage having low
frequency. Let the modulating signal be em(t)=Emsin(wmt) and the carrier signal be
ec(t)=Ecsin(wct).Then the modulating signal e(t) is expressed as
e(t)=[ Ec+ Emsin(wmt)]sin(wct).= Ec [1+msin(wmt)]sin(wct),
where m=Em/Ec is known as the modulation index. Emax and E min are the maximum and
minimum amplitudes of the signal in the positive side.

MATLAB code
PROGRAM 4.1 :
%Amplitude Modulation
clc;
clear all
close all
t=0:0.001:1;
set(0,'defaultlinelinewidth',2);
Ac=input('Enter carrier amplitude ');
fc=input('Enter carrier frequency ');
fm=input('Enter message frequency ');
m=input('Enter modulation index ');
s=Ac*m*sin(2*pi*fm*t);
subplot(3,1,1)
plot(t,s)
xlabel('Time')
ylabel('Amplitude')
title('Message Signal')
c=Ac*sin(2*pi*fc*t);
subplot(3,1,2)
plot(t,c)
xlabel('Time')
ylabel('Amplitude')
title('Carrier Signal')
am=(Ac+s).*sin(2*pi*fc*t);
42

Date:
subplot(3,1,3)
plot(t,am)
xlabel('Time')
ylabel('Amplitude')
title('AM Signal')
gtext('George Sebastian 12400026');
. SAMPLE OUTPUT
Enter
Enter
Enter
Enter

carrier amplitude 8
carrier frequency 25
message frequency 5
modulation index 0.5

Figure 4.1: Amplitude modulation

43

Date:
4.2 FREQUENCY MODULATION
In the frequency modulation (FM), the frequency of a carrier signal having high frequency is
varied by the instantaneous amplitude of a modulating voltage having low frequency. Let the
modulating signal be em(t)=Emsin(wmt) and the carrier signal be ec(t)=Ecsin(wct).Then the
modulating signal e(t) is expressed as
e(t)= Ec sin(wct+(m sin(wmt))),where m is known as the modulation index.

PROGRAM 4.2 :
%Frequency Modulation
clc;
clear all
close all
t=0:0.0001:0.1;
set(0,'defaultlinelinewidth',1);
fm=input('Enter message frequency ');
Ac=input('Enter carrier amplitude ');
fc=input('Enter carrier frequency ');
B=input('Enter the modulation index ');
s=sin(2*pi*fm*t);
subplot(3,1,1)
plot(t,s)
xlabel('Time')
ylabel('Amplitude')
title('Message Signal')
c=Ac*sin(2*pi*fc*t);
subplot(3,1,2)
plot(t,c)
xlabel('Time')
ylabel('Amplitude')
title('Carrier Signal')
fmod=Ac*sin((2*pi*fc*t)+(B*cos(2*pi*fm*t)));
subplot(3,1,3)
plot(t,fmod)
xlabel('Time')
ylabel('Amplitude')
title('FM Signal')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter
Enter
Enter
Enter

message frequency 10
carrier amplitude 6
carrier frequency 200
the modulation index 10
44

Date:

Figure 4.2: Frequency modulation


4.3 PULSE WIDTH MODULATION

PWM does the modulation of the duty cycle of the pulse. In addition of use in
communication systems. PWM is also used in voltage regulators such as Switched Mode
Power Supplies (SMPS) to control the power delivered to control the power delivered to load.
PWM can be generated using a comparator to which the modulating signal and a reference
ramp (sawtoooth) waveform are fed. The simplest way to generate a PWM signal is the
intersective method, which requires only a sawtooth or a triangle waveform (easily generated
using a simple oscillator ) and a comparator. When the value of the reference signal is more
than the modulation waveform , the PWM signal is in the high state, otherwise it is in the low
state.

45

Date:

PROGRAM 4.3 :
%Code for PWM wave
clc;
clear all;
close all;
F2=input('Enter the Message frequency = ');
F1=input('Enter the Carrier Sawtooth frequency = ');
A=5;
t=0:0.001:1;
c=A.*sawtooth(2*pi*F1*t);
m=0.75*A.*sin(2*pi*F2*t);
n=length(c);
for i=1:n
if (m(i)>=c(i))
pwm(i)=1;
else
pwm(i)=0;
end
end
plot(t,pwm,'-k',t,m,'--r',t,c,'--b');
title('PWM wave');
axis([0 1 -5 5]);
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the Message frequency = 2
Enter the Carrier Sawtooth frequency = 12

46

Date:

Figure 4.3: PWM waveform


RESULT
AM, FM and PWM waveforms are plotted in MATLAB.

47

Date:

EXPERIMENT NO : 5
DISCRETE FOURIER TRANSFORM (DFT)
AIM:
To implement the DFT and IDFT of input sequences and to plot and study the magnitude and
phase responses of common test signals.

5.1 Finding the N point DFT and IDFT


Let ( )be finite length sequence of length N, that is,
( )= 0

outside the range 0nN-1

The DFT of ( ), denoted as

( ) is defined by

( )=
where

( )

is the Nth root of unity given by


(

The inverse DFT (IDFT) is given by


( )=

( )

The MATLAB code to implement DFT and IDFT are as follows

PROGRAM 5.1.1
%Discrete Fourier Transform using matrix multiplication
clc
clear all
close all
x=input('Enter the input sequence ');
N=input('Enter the length of DFT ');
len=length(x);
if(N>len)
x=[x zeros(1,(N-len))];
else
x=x(1:N);
end;
W=exp(-j*2*pi/N);
n=0:1:(N-1);
k=0:1:(N-1);
nk=n'*k;
W=W.^nk;
X=x*W;
display(X)
48

Date:
display('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the input sequence [1 0 0 1]
Enter the length of DFT 4
X =
2.0000
1.0000 - 1.0000i

1.0000 + 1.0000i

0 - 0.0000i

George Sebastian 12400026

PROGRAM 5.1.2:
%Inverse Discrete Fourier Transform using matrix
multiplication
clc
clear all
close all
x=input('Enter the DFT sequence ');
N=input('Enter the length of DFT ');
len=length(x);
if(N>len)
x=[x zeros(1,(N-len))];
else
x=x(1:N);
end;
W=exp(-j*2*pi/N);
n=0:1:(N-1);
k=0:1:(N-1);
nk=n'*k;
W=W.^(-nk);
X=(x*W)/N;
display(X)
display('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the DFT sequence [2 1+i 0 1-i]
Enter the length of DFT 4
X =
1.0000
-0.0000 + 0.0000i
1.0000 - 0.0000i
George Sebastian 12400026
49

0.0000 + 0.0000i

Date:

5.2 MAGNITUDE AND PHASE PLOTS


AIM:
To find the magnitude and phase response of common test signals

THEORY:
The choice of N in this eqn is not fixed.

( )=

( )

If x(n) has length N1 < N , we want to assume that x(n) has length N by simply adding (NN1) samples with a value of 0.This addition of dummy samples is known as zero padding.
Then the resultant x(n) is often referred to as an N-point sequence, and X(k) defined in the
eqn(a) is referred to as an N-point DFT. By a judicious choice of N ,such as choosing it to be
a power of 2,computational efficiencies can be gained.
It is a common practice to represent the DFT by the plots of |X (k)| versus k and of the
phase angle (k) versus k. This may be done in terms of harmonics of or in terms of
frequency if is known. To find it is necessary to know the value of T, the sampling
interval. Then = 2/NT rad s-1.

An important property of the DFT is that X (k+N)=X(k),i.e., the DFT is periodic with period
N. This is the cyclical property of the DFT.T he values of the DFT components are repetitive.
The amplitude spectrum of an N-point DFT is symmetrical about harmonic N/2 when both
the zero and (N+1)th harmonics are included in the plot. Similarly ,the phase function being
odd exhibits anti-symmetry about harmonic N/2.if 2fmax samples per second are taken of the
signal for t seconds, then 2fmax = N, so 1/t =2fmax/N is the first harmonic frequency. The
symmetry at harmonic N/2 therefore occurs at the frequency (N/2)/(2fmax/N) = fmax, the
maximum frequency present in the signal. In this context, fmax is known as the folding
frequency, since the spectrum between harmonics N/2 and N may be folded about the axis of
symmetry at fmax to superimpose exactly the low frequency half of the spectrum. It is now
seen that N real data values transform to N/2 complex DFT values of practical significance.
The latter consist of N/2 real values and N/2 imaginary values giving a total of N values
derived from the initial N real data values.

50

Date:

PROGRAM 5.1.3:
%Magnitude and phase response of a rect signal
N = input('Enter the length of the sequence ');
m = floor(N/8);
rect = [ones(1,m) zeros(1,N-m)];
subplot(4,2,1:2),stem(rect);
title('INPUT SIGNAL');
xlabel('Time');
ylabel('Amplitude');
%Finding DFT
w = exp(-1i*2*pi/N);
n = 0:1:(N-1);
k = 0:1:(N-1);
nk = n'*k;
W = w.^nk;
X = rect*W;
%Magnitude and phase plots
subplot(423),stem(k,abs(X(1:N)));
title('MANITUDE PLOT');
xlabel('Discrete frequency');
ylabel('Amplitude');
subplot(424),stem(k,angle(X(1:N)));
title('PHASE PLOT');
xlabel('Discrete frequency');
ylabel('Phase angle');
%Unfolding the spectrum
y = X(floor(N/2)+1:N);
Y = [y X(1:floor(N/2))];
subplot(425),stem(k,abs(Y(1:N)));
title('MAGNITUDE PLOT(UNFOLDED SPECTRUM)');
xlabel('Discrete frequeny');
ylabel('Amplitude');
subplot(4,2,6),stem(k,angle(Y(1:N)));
title('PHASE PLOT(UNFOLDED SPECTRUM');
xlabel('Discrete frequeny');
ylabel('Phase angle');
%Labelling the frequency axis with normalised frequency values
if rem(N,2) == 0
t = 2*pi/N;
n = [-pi:t:(pi-t)];
else
t = pi/N;
n = [-pi+t:2*t:pi-t];
end
subplot(427);
stem((n/pi),abs(Y(1:N)));
51

Date:
xlabel('Frequency(pi units)');
ylabel('Amplitude');
title('MAGNITUDE PLOT');
subplot(428);
stem((n/pi),angle(Y(1:N)));
xlabel('Frequency(pi units)');
ylabel('Phase(radians)');
title('PHASE PLOT');
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the length of the sequence 28

Figure 5.1:Magnitude and phase plots


52

Date:

5.3 SPECTRAL ANALYSIS OF SIGNALS


AIM:
To draw the spectrum of sinusoids, sum of sinusoids, AM wave and random signal.

FREQUENCY SPECTRUM USING DFT:


When harmonic components of a signal are known, the signal can be presented in a different
way that highlights its frequency content rather than its time domain content. Introducing the
third axis of frequency perpendicular to the amplitude-time plane the harmonic components
can be plotted in the plane that corresponds to their frequencies. This is the frequency
domain spectrum. Components of this spectrum appear as lines to reflect the fact that they
are planes in which the cosines are placed. A spectrum however can be plotted showing only
the end points of each line connected together. For a spectrum with a large number of points
the gaps between the lines are barely visible and the spectrum appears continuous. Magnitude
spectrum is not sufficient to fully define the signal. The phase spectrum of each frequency
component must be known in order to unambiguously describe it. It is clear now that a
component of the spectrum at the given frequency must be described with two parameters.
In engineering practice signals are usually not described by mathematical functions but come
from measurement acquired with a selected sampling interval t (its inverse is the sampling
frequency or rate fs ). Thus the signal is not continuous but discrete. The duration of a signal
is finite and in most cases it will not be the same as the period required by the Fourier
Theorem. The signal may not be periodic at all. The purpose of frequency analysis is to
devise a method to extract an estimate of frequency components which are not known a
priori. The process is known as the Discrete Fourier Transform.
The choice of sampling frequency is arbitrary. The signal contains various frequency
components to be detected If the frequency to be detected is f and the sampling frequency is
too low, i.e. fs <= 2f , a lower erroneous frequency will be perceived. The phenomenon is
called the aliasing. Frequency equal to half of the sampling frequency is the highest
detectable frequency. It is called the Nyquist or folding frequency. The most effective way
of preventing the aliasing is by filtering it with a low pass filter with the cut-off frequency
less than half of the sampling rate.
The Fast Fourier Transform (FFT) is an algorithm for calculation of the DFT first published
in 1965 by J.W.Cooley and J.W.Tuckey. Its main advantage is that it significantly reduces the
computation time by a factor of the order m/log2m , i.e. more than 100 times for a sample of
1024 elements. The number of FFT elements is equal to the size of the time sample. The
second half of these complex numbers corresponds to negative frequencies and contains
complex conjugates of the first half for the positive frequencies, and does not carry any new
information.

53

Date:
The FFT does not directly give you the spectrum of a signal. The FFT can vary dramatically
depending on the number of points (N) of the FFT, and the number of periods of the signal
that are represented. There is another problem as well. The FFT contains information
between 0 and fs, however, we know that the sampling frequency must be at least twice the
highest frequency component. Therefore, the signal's spectrum should be entirely below fs/2 ,
the Nyquist frequency. A real signal should have a transform magnitude that is symmetrical
for for positive and negative frequencies. So instead of having a spectrum that goes from 0 to
fs, it would be more appropriate to show the spectrum from -fs/2 to fs/2.

PROGRAM 5.3.1:
%MATLAB CODE FOR SPECTRAL ANALYSIS
%Spectrum of a sinusoidal signal
clc;clear;
f = input('Enter the frequency of sine wave ');
fs=10*f;
t=0:(1/fs):.1;
x=sin(2*pi*f*t);
n= 2^(nextpow2(length(x)));
fftx=fft(x,n);
mx = abs(fftx);
mx=mx/(length(x))*2;
mx = fftshift(mx);
k=(-(n/2):(n/2)-1)/n*fs;
subplot(211);
plot(t,x);
title('Input signal');
xlabel('Time(s)')
ylabel('Amplitude')
subplot(212);
plot(k,mx);
title('Spectrum of input signal') ;
xlabel('Analog frequency (Hz)')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the frequency of sine wave 250

54

Date:

Figure 5.3.1: Spectrum of sinusoidal signal

PROGRAM 5.3.2:
%Spectrum analysis of a sum of sinusoids
clc;clear;
f1 = input('Enter the frequency of first sinewave ');
f2 = input('Enter the frequency of second sinewave ');
f=max(f1,f2)
fs=10*f;
%selecting sampling frequency
t=0:(1/fs):.1;
x=sin(2*pi*f1*t)+sin(2*pi*f2*t);
n= 2^(nextpow2(length(x)));
fftx=fft(x,n);
mx = abs(fftx);
mx=mx/(length(x))*2;
mx = fftshift(mx);
k=(-(n/2):(n/2)-1)/n*fs;
subplot(211);
plot(t,x);
title('Input signal') ;
xlabel('Time(s)')
ylabel('Amplitude')
subplot(212);
plot(k,mx);
55

Date:
title('Spectrum of input signal') ;
xlabel('Analog frequency (Hz)')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the frequency of first sinewave 250
Enter the frequency of second sinewave 500
f =
500

Figure 5.3.2: Spectrum of sum of sinusoids

PROGRAM 5.3.3:
%Spectrum analysis of a AM signal
clc;clear;
fc = input('Enter the frequency of carrier wave ');
fm = input('Enter the frequency of modulating wave ');
m=input('modulating index');
f=fm+fc;
fs=5*f;
%selecting sampling frequency
t=0:(1/fs):.1;
56

Date:
x=(1+m*sin(2*pi*fm*t)).*sin(2*pi*fc*t);
n= 2^(nextpow2(length(x)));
fftx=fft(x,n);
mx = abs(fftx);
mx=mx/(length(x))*2;
mx = fftshift(mx);
k=(-(n/2):(n/2)-1)/n*fs;
subplot(211);
plot(t,x);
title('Input signal') ;
xlabel('Time(s)')
ylabel('Amplitude')
subplot(212);
plot(k,mx);
title('Spectrum of input signal');
xlabel('Analog frequency (Hz)')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the frequency of carrier wave 500
Enter the frequency of modulating wave 250
modulating index0.5

Figure 5.3.3: Spectrum of AM signal


57

Date:

PROGRAM 5.3.4:
%Spectrum analysis of a random signal
%selecting sampling frequency
fs=100;
t=0:(1/fs):.1;
x=randn(1,100)
n= 2^(nextpow2(length(x)));
fftx=fft(x,n);
mx = abs(fftx);
mx=mx/(length(x))*2;
mx = fftshift(mx);
k=(-(n/2):(n/2)-1)/n*fs;
subplot(211);
plot(x);
title('Random signal')
xlabel('Time(s)')
ylabel('Amplitude')
subplot(212);
plot(k,mx);
title('Spectrum of random signal') ;
xlabel('Analog frequency (Hz)')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT

Figure 5.3.4: Spectrum of a random signal


58

Date:

CONCLUSION:
1.The amplitude spectrum of an N point DFT is symmetrical about harmonic N/2. The DFT
obtained by code DFT_matrix starts from 0 only and so, in order to satisfy this property as
well as the anti-symmetry of the phase function about harmonic N/2, the spectrum is folded
about the axis of symmetry. Then the discrete frequency N/2-1 corresponds to the normalized
frequency and -N/2 corresponds to .If 2fmax smples per second were taken of the signal
, then the discrete frequency N/2-1 corresponds to fmax and -N/2 corresponds to - fmax.. .All
these have been done in code ma_ph_rect.
2. The FFT of a signal can be used to obtain the spectrum of it. For that sampling frequency
(fs)selected such that fs >= 2fm,where fm is the maximum frequency in the signal otherwise
aliasing will happen.

RESULT:
The computation of DFT and IDFT using matrix multiplication is implemented. The
magnitude and phase response of a rect signal has been plotted. Spectral analysis of a
sinusoid, sum of sinusoids, AM wave and a random signal is done.

59

Date:

EXPERIMENT NO : 6
CONVOLUTION USING DFT

AIM:
To implement circular and linear convolution using DFT.

THEORY:

6.1 CIRCULAR CONVOLUTION USING DFT


Let x1(n) and x2(n) be two finite length sequence of length N and let y(n) be the N- point
circular convolution of x1(n) and x2(n).Let X1(k),X2(k) and Y(k) be the DFTs of x1(n),x2(n)
and y(n) respectively. Then,
Y(k)=X1(k)X2(k)
The IDFT of Y(k) will give the circular convolution of x1(n) and x2(n).
The matlab code for implementing circular convolution of two finite-length sequences using
DFT is as follows:

PROGRAM 6.1
% uses DFT to find circular convolution
% N- point circular convolution between x1 and x2
%-----------------------------------------------% y = output sequence containing the circular convolution
% x1 = input sequence of length N1<=N
% x2 = input sequence of length N2<=N
% N = size of circular buffer
% Method: x1 (*) x2 = idft(X1*X2)
% X1 = N-point DFT of x1
% X2 = N-point DFT of x2
x1=input('Enter the first sequence ');
x2=input('Enter the second sequence ');
N=input('Enter the size of the circular convolution ');
%Check for the length of x1
if length(x1)>N
error('N must be greater than length of x1')
end
%Check for the length of x2
60

Date:
if length(x2)>N
error('N must be greater than length of x2')
end
%Taking DFT
X1 = fft(x1,N);
X2 = fft(x2,N);
Y = X1.*X2;
y = ifft(Y,N);
stem(y);
title('Circular convolution using DFT')
xlabel('Time Index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the first sequence [0 1 0 0 0]
Enter the second sequence [0 1 2 3 4]
Enter the size of the circular convolution 5

Figure 6.1: Circular convolution using DFT

61

Date:
6.2 LINEAR CONVOLUTION USING DFT
Let x(n) be of the length n, h(n) be of length m. Let y(n) be the linear convolution of x(n)
And h(n). Append m-1 zeros to x(n) and n-1 zeros to h(n) to make their lengths equal. Now,
Y(k)=X(k)H(k)
Where Y(k),X(k) and H(k) are the DFTs of y(n),x(n) and h(n) respectively. Taking IDFT of
Y(k) will give linear convolution of x(n) and h(n).
The MATLAB code is as follows:

PROGRAM 6.2
%
%
%
%
%
%
%
%

MATLAB CODE
Linear convolution using DFT
----------------------------x1=input sequence of length n
x2=input sequence of length m
y= output sequence of length n+m-1
Method : Pad m-1 0s to x1 and n-1 0s to x2
and then perform circular convolution using DFT

x1=input('enter the first sequence ');


x2=input('enter the second sequence ');
m=length(x1);
n=length(x2);
% Taking n+m-1 point DFT
% fft(x,N) will automatically pad the necessary no. of zeros
N=n+m-1;
X1=fft(x1,N);
X2=fft(x2,N);
Y=X1.*X2;
y=ifft(Y,N);
stem(y);
title('Linear convolution using DFT')
xlabel('Time Index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
enter the first sequence [1 1 1]
enter the second sequence [1 2 3 1]
62

Date:

Figure 6.2: linear convolution using DFT

RESULT:
Implemented linear and circular convolution using DFT.

63

Date:

EXPERIMENT NO : 7
OVERLAP-SAVE METHOD
AIM:
To find the convolution of two sequences using overlap-save method.

THEORY:
Overlapsave is the traditional name for an efficient way to evaluate the discrete convolution
between a very long signal x[n] and a finite impulse response (FIR) filter h[n]:

Where h[m]=0 for m outside the region [1, M].


The concept is to compute short segments of y[n] of an arbitrary length L, and concatenate
the segments together. Consider a segment that begins at n = kL + M, for any integer k, and
define:

Then, for kL + M n kL + L + M 1, and equivalently M n kL L + M 1, we


can write:

The task is thereby reduced to computing yk[n], for M n L + M 1.


Now note that if we periodically extend xk[n] with period N L + M 1, according to:

64

Date:

the convolutions
and
are equivalent in the region
M n L + M 1. So it is sufficient to compute the
-point circular convolution of
with h[n] in the region [1, N]. The subregion [M, L + M 1] is appended to the output
stream, and the other values are discarded.
The advantage is that the circular convolution can be computed very efficiently as follows,
according to the circular convolution theorem:

where FFT and IFFT refer to the fast Fourier transform and inverse fast Fourier transform,
respectively, evaluated over N discrete points.

The overlap-save algorithm may be extended to include other common operations of a


system additional channels can be processed more cheaply than the first by reusing the
forward FFT

sampling rates can be changed by using different sized forward and inverse FFTs

frequency translation (mixing) can be accomplished by rearranging frequency bins

MATLAB CODE:
%Overlap Save method
clc
clear all
close all
h1=input('Enter the input sequence ');
Ls=length(h1);
h2=input('Enter the impulse sequence ');
M=length(h2);
L=input('Enter the length of each block ');
h=[h2 zeros(1,L-(M-1))];
x=[zeros(1,M-1) h1 zeros(1,L-1)];
N=Ls+M-1;
l1=length(x);
i=1;
j=1;
while (i<=N)
xk=[x(i:i+L-1)]
y(j,:)=cconv(xk,h,L)
i=i+L-M+1;
j=j+1;
end
[m n]=size(y)
65

Date:
y=y(:,M:n)'
y=y(1:N)
subplot(3,1,1)
stem(h1)
title('Input Sequence')
xlabel('Time Index')
ylabel('Amplitude')
subplot(3,1,2)
stem(h2)
title('Impulse Sequence')
xlabel('Time Index')
ylabel('Amplitude')
subplot(3,1,3)
stem(y)
title('Linear Convolved signal using Overlap Save Method')
xlabel('Time Index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the input sequence [1 2 -1 2 3 -2 -3 -1 1 1 2 -1]
Enter the impulse sequence [1 2]
Enter the length of each block 4

Figure 7 : Linear Convolution using overlap save method


66

Date:

RESULT:
The convolution of two sequences are obtained by using overlap-save method.

67

Date:

EXPERIMENT NO.8
OVERLAP-ADD METHOD

AIM:
To find the convolution of two sequences using overlap-add method.

THEORY:
The overlapadd method (OA, OLA) is an efficient way to evaluate the discrete
convolution of a very long signal x[n] with a finite impulse response (FIR) filter h[n]:

Where h[m] = 0 for m outside the region [1, M].


The concept is to divide the problem into multiple convolutions of h[n] with short segments
of x[n]:

Where L is an arbitrary segment length. Then:

And y[n] can be written as a sum of short convolutions:

is zero outside the region [1, L + M 1].

where
And for any parameter
convolution of

it is equivalent to the

with h[n] in the region [1, N].


68

-point circular

Date:
The advantage is that the circular convolution can be computed very efficiently as follows,
according to the circular convolution theorem:

where FFT and IFFT refer to the fast Fourier transform and inverse fast Fourier transform,
respectively, evaluated over
discrete points.

ALGORITHM:

Figure sketches the idea of the overlapadd method. The signal x[n] is first partitioned into
non-overlapping sequences, then the discrete Fourier transforms of the sequences
evaluated by multiplying the FFT of

with the FFT of

are

. After recovering of

by inverse FFT, the resulting output signal is reconstructed by overlapping and adding
the
as shown in the figure. The overlap arises from the fact that a linear convolution is
always longer than the original sequences. In the early days of development of the fast
Fourier transform, was often chosen to be a power of 2 for efficiency, but further
development has revealed efficient transforms for larger prime factorizations of L, reducing
computational sensitivity to this parameter.

MATLAB CODE :
%Overlap Add method
clc
clear all
69

Date:
close all
h1=input('Enter the input sequence ');
Ls=length(h1);
h2=input('Enter the impulse sequence ');
M=length(h2);
L=input('Enter the length of each block ');
h=[h2 zeros(1,L-1)];
x=[h1 zeros(1,L-1)];
N=Ls+M-1;
k=ceil(Ls/L);
j=1;
for i=1:1:k
xk=[x(j:j+L-1)];
xk=[xk zeros(1,M-1)];
y(i,:)=cconv(xk,h,length(h));
j=i*L+1;
end
y(i+1,1)=0;
[m n]=size(y);
for i=1:1:m-1
for j=1:1:M-1
y(i+1,j)=y(i,n-(M-1)+j)+y(i+1,j);
end
end
y=[y(:,1:L)]';
y=y(1:N);
subplot(3,1,1)
stem(h1)
title('Input Sequence')
xlabel('Time Index')
ylabel('Amplitude')
subplot(3,1,2)
stem(h2)
title('Impulse Sequence')
xlabel('Time Index')
ylabel('Amplitude')
subplot(3,1,3)
stem(y)
title('Linear Convolved signal using Overlap Add Method')
xlabel('Time Index')
ylabel('Amplitude')
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter the input sequence [1 2 -1 2 3 -2 -3 -1 1 1 2 -1]
Enter the impulse sequence [1 2]
Enter the length of each block 3

70

Date:

Figure 8: Linear convolution using overlap add method

RESULT:
The convolution of two sequences are obtained by using overlap-add method.

71

Date:

EXPERIMENT NO : 9
IIR FILTERS
AIM:
To realize IIR filters using matlab

THEORY:
9.1 BUTTERWORTH LOW PASS FLTER
This filter is characterized the property that its magnitude response is flat in both passband
and stopband the magnitude of an Nth order low pass filter is given by
Ha(j) = 1/1+(/c)^2N
Where N is the order of filter and c is the cutoff frequency
The analog filter is specified by Parameters p, Rp, s, and As
Filter order
N = [log[(10^(Rp/10)-1)/ (10^(As/10)-1)]/2log(p/s)]
To satisfy the specifications exactly at p
c = p/(10^(Rp/10)-1)^(1/2N)

PROGRAM 9.1:
% Butterworth Low pass filter
clc;
clear;
alphap=input('Enter the Passband attenuation in dB ');
alphas=input('Enter the Stopband attenuation in dB ');
fp=input('Enter the Passband frequency in hertz ');
fs=input('Enter the Stopband frequency in hertz ');
F=input('Enter the Sampling frequency in hertz ');
normfp=2*fp/F;
normfs=2*fs/F;
[n,normf]=buttord(normfp,normfs,alphap,alphas);
fn=normf*F/2;
display('The order of the filter is = ');n
display('The cut off frequency in hertz of the filter is =
');fn
[b,a]=butter(n,normf);
display('The Numerator coefficients of the filter is = ');b
display('The Denominator coefficients of the filter is = ');a
72

Date:
[h,f]=freqz(b,a,512,F);
Av=abs(h);
an=angle(h)*180/pi;
subplot(211);
plot(f,Av);
title('Magnitude Response');
xlabel('Frequency in hertz');
ylabel('Magnitude');
grid on;
subplot(212);
plot(f,an);
title('Phase Response');
xlabel('Frequency in hertz');
ylabel('Phase in degrees');
grid on;
gtext('George Sebastian 12400026');

SAMPLE OUTPUT
Enter the
Enter the
Enter the
Enter the
Enter the
The order

Passband attenuation in dB .4
Stopband attenuation in dB 30
Passband frequency in hertz 400
Stopband frequency in hertz 800
Sampling frequency in hertz 2000
of the filter is =

n =
4

73

Date:

Figure 9.1: Butterworth lowpass filter

PROGRAM 9.2:
% Butterworth High pass filter
clc;
clear;
alphap=input('Enter the Passband attenuation in dB ');
alphas=input('Enter the Stopband attenuation in dB ');
fp=input('Enter the Passband frequency in hertz ');
fs=input('Enter the Stopband frequency in hertz ');
F=input('Enter the Sampling frequency in hertz ');
normfp=2*fp/F;
normfs=2*fs/F;
[n,normf]=buttord(normfp,normfs,alphap,alphas);
fn=normf*F/2;
display('The order of the filter is = ');n
display('The cut off frequency in hertz of the filter is =
');fn
[b,a]=butter(n,normf,'high');
display('The Numerator coefficients of the filter is = ');b
display('The Denominator coefficients of the filter is = ');a
[h,f]=freqz(b,a,512,F);
Av=abs(h);
an=angle(h)*180/pi;
subplot(211);
plot(f,Av);
74

Date:
title('Magnitude Response');
xlabel('Frequency in hertz');
ylabel('Magnitude');
grid on;
subplot(212);
plot(f,an);
title('Phase Response');
xlabel('Frequency in hertz');
ylabel('Phase in degrees');
grid on;
gtext('George Sebastian 12400026');

SAMPLE OUTPUT
Enter the
Enter the
Enter the
Enter the
Enter the
The order

Passband attenuation in dB 0.4


Stopband attenuation in dB 50
Passband frequency in hertz 800
Stopband frequency in hertz 500
Sampling frequency in hertz 2000
of the filter is =

n =
7

Figure 9.2: Butterworth High Pass Filter

75

Date:

PROGRAM 9.3:
% Butterworth Band pass filter
clc;
clear;
alphap=input('Enter the Passband attenuation in dB ');
alphas=input('Enter the Stopband attenuation in dB ');
fp=input('Enter the Passband frequencies in hertz in an array
');
fs=input('Enter the Stopband frequencies in hertz in an array
');
F=input('Enter the Sampling frequency in hertz');
normfp=2*fp/F;
normfs=2*fs/F;
[n,normf]=buttord(normfp,normfs,alphap,alphas);
fn=normf*F/2;
display('The order of the filter is = ');n
display('The cut off frequencies in hertz of the filter are =
');fn
[b,a]=butter(n,normf);
display('The Numerator coefficients of the filter is = ');b
display('The Denominator coefficients of the filter is = ');a
[h,f]=freqz(b,a,512,F);
Av=abs(h);
an=angle(h)*180/pi;
subplot(211);
plot(f,Av);
title('Magnitude Response');
xlabel('Frequency in hertz');
ylabel('Magnitude');
grid on;
subplot(212);
plot(f,an);
title('Phase Response');
xlabel('Frequency in hertz');
ylabel('Phase in degrees');
grid on;
gtext('George Sebastian 12400026');

SAMPLE OUTPUT
Enter
Enter
Enter
Enter

the
the
the
the

Passband
Stopband
Passband
Stopband

attenuation
attenuation
frequencies
frequencies

in
in
in
in
76

dB 2
dB 30
hertz in an array [350 800]
hertz in an array [200 900]

Date:
Enter the Sampling frequency in hertz 5000
The order of the filter is =
n =
13

Figure 9.3: Butterworth Band pass filter

PROGRAM 9.4:
% Butterworth Band reject filter
clc;
clear;
alphap=input('Enter the Passband attenuation in dB ');
alphas=input('Enter the Stopband attenuation in dB ');
fp=input('Enter the Passband frequencies in hertz in an array
');
fs=input('Enter the Stopband frequencies in hertz in an array
');
F=input('Enter the Sampling frequency in hertz ');
normfp=2*fp/F;
normfs=2*fs/F;
[n,normf]=buttord(normfp,normfs,alphap,alphas);
fn=normf*F/2;
77

Date:

display('The order of the filter is = ');n


display('The cut off frequencies in hertz of the filter are =
');fn
[b,a]=butter(n,normf,'stop');
display('The Numerator coefficients of the filter is = ');b
display('The Denominator coefficients of the filter is = ');a
[h,f]=freqz(b,a,512,F);
Av=abs(h);
an=angle(h)*180/pi;
subplot(211);
plot(f,Av);
title('Magnitude Response');
xlabel('Frequency in hertz');
ylabel('Magnitude');
grid on;
subplot(212);
plot(f,an);
title('Phase Response');
xlabel('Frequency in hertz');
ylabel('Phase in degrees');
grid on;
gtext('George Sebastian 12400026');

SAMPLE OUTPUT
Enter the
Enter the
Enter the
Enter the
Enter the
The order

Passband attenuation in dB 2
Stopband attenuation in dB 30
Passband frequencies in hertz in an array [200 900]
Stopband frequencies in hertz in an array [350 750]
Sampling frequency in hertz 2000
of the filter is =

n =
5

78

Date:

Figure 9.4: Butterworth Band reject filter

CHEBYSHEV FILTERS
The chebyshev 1 filter is equiripple in the passband and monotonic in the stopband
The magnitude frequency response of a low pass Chebyshev 1 filter is given by
|H()| = [1 + 2TN 2(/P)]-1/2

TN = cos(Ncos-1x)

|x| 1

cos(Ncosh-1x)

|x| 1

Where is a parameter of the ffilter related to the ripple in the passband and TN(x) is th N th
order Chebyshev polynomial
The salient properties

We note that |H(j0)| = 1 for N odd and |H(j0)| = 1/[(

The filter has uniform ripples in the passband and is monotonic outside the passband

79

) ] for N even

Date:

The sum of the number of maxima and minima in the passband equal the order of
filter

The lowpass normalized Chebyshev 1 filter is characterized by following magnitude squared


frequency response
|HN()| 2 = [1 + 2TN 2()]-1

FILTER DESIGN EQUATIONS


=

100.1Rp -1]

A=10(As/20)
c= p
r= s/p
g=

(A2-1)/ 2]

N=[(log10 g+ (g2-1))/(log10r + ( r2-1))]

PROGRAM 9.5:
%Chebyshev Low Pass Filter
clc;
clear all;
close all;
format long;
pr=input('Enter the pass band ripple ');
sr=input('Enter the stop band ripple ');
pf=input('Enter the pass band frequency ');
sf=input('Enter the stop band frequency ');
fs=input('Enter the sampling frequency in hz ');
w1=2*pf/fs;
w2=2*sf/fs;
[n,wn]=cheb1ord(w1,w2,pr,sr,'s');
[b,a]=cheby1(n,pr,wn,'s');
w=0:0.01:pi;
[h,om]=freqs(b,a,w);
m=20*log10(abs(h));
ang=angle(h);
subplot(2,1,1);
plot(om/pi,m);
title('Magnitude Response of the low pass filter:');
xlabel('Normalized Frequency');
80

Date:
ylabel('Magnitude');
grid on;
subplot(2,1,2);
plot(om/pi,ang);
title('Phase Response of the low pass filter:');
xlabel('Normalized Frequency');
ylabel('Phase in degree');
grid on;
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter
Enter
Enter
Enter
Enter

the
the
the
the
the

pass band ripple 0.5


stop band ripple 40
pass band frequency 5000
stop band frequency 6000
sampling frequency in hz 10000

Figure 9.5: Chebyshev type I low pass filter

81

Date:

PROGRAM 9.6
%Chebyshev High Pass Filter
clc;
clear all;
close all;
format long;
pr=input('Enter the pass band ripple ');
sr=input('Enter the stop band ripple ');
pf=input('Enter the pass band frequency ');
sf=input('Enter the stop band frequency ');
fs=input('Enter the sampling frequency in hz ');
w1=2*pf/fs;
w2=2*sf/fs;
[n,wn]=cheb1ord(w1,w2,pr,sr,'s');
[b,a]=cheby1(n,pr,wn,'high','s');
w=0:0.01:pi;
[h,om]=freqs(b,a,w);
m=20*log10(abs(h));
ang=angle(h);
subplot(2,1,1);
plot(om/pi,m);
title('Magnitude Response of the High pass filter:');
xlabel('Normalized Frequency');
ylabel('Magnitude');
grid on;
subplot(2,1,2);
plot(om/pi,ang);
title('Phase Response of the High pass filter:');
xlabel('Normalized Frequency');
ylabel('Phase in degree');
grid on;
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter
Enter
Enter
Enter
Enter

the
the
the
the
the

pass band ripple 0.7


stop band ripple 30
pass band frequency 6000
stop band frequency 7000
sampling frequency in hz 10000

82

Date:

Figure 9.6: Chebyshev I High Pass Filter

PROGRAM 9.7:
%Chebyshev Band Pass Filter
clc;
clear all;
close all;
format long;
pr=input('Enter the pass band ripple ');
sr=input('Enter the stop band ripple ');
pf=input('Enter the pass band frequency as an interval ');
sf=input('Enter the stop band frequency as an interval ');
fs=input('Enter the sampling frequency in hz ');
w1=2*pf/fs;
w2=2*sf/fs;
[n,wn]=cheb1ord(w1,w2,pr,sr,'s');
[b,a]=cheby1(n,pr,wn,'bandpass','s');
w=0:0.01:pi;
[h,om]=freqs(b,a,w);
m=20*log10(abs(h));
ang=angle(h);
subplot(2,1,1);
plot(om/pi,m);
title('Magnitude Response of the Band pass filter:');
xlabel('Normalized Frequency');
83

Date:
ylabel('Magnitude');
grid on;
subplot(2,1,2);
plot(om/pi,ang);
title('Phase Response of the Band pass filter:');
xlabel('Normalized Frequency');
ylabel('Phase in degree');
grid on;
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter
Enter
Enter
Enter
Enter

the
the
the
the
the

pass band ripple 0.4


stop band ripple 30
pass band frequency as an interval [3000 5000]
stop band frequency as an interval [1000 8000]
sampling frequency in hz 10000

Figure 9.7: Chebyshev I Band pass filter

84

Date:

PROGRAM 9.8:
%Chebyshev Band Stop Filter
clc;
clear all;
close all;
format long;
pr=input('Enter the pass band ripple ');
sr=input('Enter the stop band ripple ');
pf=input('Enter the pass band frequency as an interval ');
sf=input('Enter the stop band frequency as an interval ');
fs=input('Enter the sampling frequency in hz ');
w1=2*pf/fs;
w2=2*sf/fs;
[n,wn]=cheb1ord(w1,w2,pr,sr,'s');
[b,a]=cheby1(n,pr,wn,'stop','s');
w=0:0.01:pi;
[h,om]=freqs(b,a,w);
m=20*log10(abs(h));
ang=angle(h);
subplot(2,1,1);
plot(om/pi,m);
title('Magnitude Response of the Band stop filter:');
xlabel('Normalized Frequency');
ylabel('Magnitude');
grid on;
subplot(2,1,2);
plot(om/pi,ang);
title('Phase Response of the Band stop filter:');
xlabel('Normalized Frequency');
ylabel('Phase in degree');
grid on;
gtext('George Sebastian 12400026')

SAMPLE OUTPUT
Enter
Enter
Enter
Enter
Enter

the
the
the
the
the

pass band ripple 0.4


stop band ripple 30
pass band frequency as an interval [1000 8000]
stop band frequency as an interval [3000 5000]
sampling frequency in hz 10000

85

Date:

Figure 9.8: Chebyshev Band stop filter

RESULT:
IIR filters are designed and implemented using MATLAB.

86

Date:

EXPERIMENT NO.10
FIR FILTER DESIGN
AIM:
To design FIR low pass filters using
i) Window method
a) Hamming Window
b) Hanning Window
ii) Frequency sampling method

THEORY:
1) Window method: The desired frequency response Hd(ejw) of a filter is periodic in
frequency and can be expanded in Fourier series is given by
Hd(ejw)
where

hd(n) =

( )
(

hd(n) e -jwn
1/2 Hd(ejw) e jwn d

and known as Fourier coefficients having infinite length. One possible way of obtaining FIR
filter is to truncate the infinite Fourier series at n= (

), where N is the length of the

desired sequence. The Fourier coefficients of the filter are modified by multiplying the
infinite impulse response with a finite sequence w(n) called window.
For an ideal low pass filter of cut off frequency wc and sample delay , the impulse response
is given by
hd(n) = sin(N/2)/sin(/2)
To obtain an FIR filter from hd(n), one has to truncate it on both sides. Thus
h(n)= hd(n)w(n) where w(n) represents the window.

Hamming and Hanning windows:


The hamming window is similar to a raised cosine window function, but with a small amount
of discontinuity and is given by
87

Date:

wham(n) = 0.54 0.46cos(2n/N-1)

, -(N-1)/2n(N-1)/2

, otherwise

The hanning window sequence is given by


whann(n) = 0.5 + 0.5cos(2n/N-1)
0

, -(N-1)/2n(N-1)/2

, otherwise

At higher frequencies, the stop band attenuation is low when compared to that of hanning
window. Since the hamming window generates lesser oscillations in the side lobes than the
hanning window for the same main lobe width, the Hamming window is generally
preferred.

2) Frequency sampling method: Transfer function H(z) of an FIR filter is given by


H(z) =
where h(n)=

( )

(n) z-n

( )

, n=0,1,2...N-1

The DFT samples H(k) for an FIR sequence can be regarded as samples of the filter Z
transform evaluated at N points equally spaced along the unit circle. That is
H(k)= H(z)|z=ej2k/N
Thus H(z) =

( )

H(k)/(1- ej2k/Nz-1)

That is H(k) is kth DFT component obtained by sampling the frequency response H(ejw). As
such this approach for designing FIR filter is called the frequency sampling method.

88

Date:

MATLAB CODE:

PROGRAM 10.1:
%Designing an FIR low pass filter using Hamming window
wc=0.5*pi;
N=60;
alpha=(N-1)/2;
eps=0.001;
n=0:1:N-1;
hd=sin(wc*(n-alpha + eps))./(pi*(n-alpha + eps));
wh=hamming(N);
hn=hd.*wh';
w=0:0.01:pi;
h=freqz(hn,1,w);
subplot(311);
stem(n,wh);
xlabel('n');
ylabel('wh(n)');
title('hamming window');
subplot(312);
stem(n,hn);
xlabel('n');
ylabel('hn');
title('ideal impulse response');
subplot(313);
plot(w/pi,abs(h));
grid;
xlabel('Normalized frequency');
ylabel('Magnitude');
title('Magitude response');
gtext('George Sebastian 12400026');

89

Date:

SAMPLE OUTPUT

Figure 10.1: Filter using hamming window

PROGRAM 10.2
%Designing an FIR low pass filter using Hanning window;
wc=0.5*pi;
N=120;
alpha=(N-1)/2;
eps=0.001;
n=0:1:N-1;
hd=sin(wc*(n-alpha + eps))./(pi*(n-alpha + eps));
wh=hanning(N);
hn=hd.*wh';
w=0:0.01:pi;
h=freqz(hn,1,w);
subplot(311);
stem(n,wh);
xlabel('n');
ylabel('wh(n)');
title('hanning window');
subplot(312);
90

Date:
stem(n,hn);
xlabel('n');
ylabel('hn');
title('ideal impulse response');
subplot(313);
plot(w/pi,abs(h));
grid;
xlabel('Normalized frequency');
ylabel('Magnitude');
title('magitude response');
gtext('George Sebastian 12400026');

SAMPLE OUTPUT

Figure 10.2: Filter using hanning window

PROGRAM 10.3:
% Designing a FIR low pass filter using Frequency sampling
method
% wc=0.5pi
N=33;
91

Date:
alpha=(N-1)/2;
Hrk=[ones(1,9),zeros(1,16),ones(1,8)];
%samples of magnitude response
k1=0:(N-1)/2;
k2=(N+1)/2:N-1;
theetak=[(-alpha*(2*pi)/N)*k1,(alpha*(2*pi)/N)*(N-k2)];
Hk=Hrk.*(exp(1i*theetak));
w=0:0.01:pi; hn=real(ifft(Hk,N));
H=freqz(hn,1,w);
plot(w/pi,20*log10(abs(H)));
ylabel('Magnitude in db');
xlabel('Normalized frequency \omega/\pi');
gtext('George Sebastian 12400026');

SAMPLE OUTPUT

Figure 10.3: Filter design using frequency sampling

92

Date:

CONCLUSION:
The rectangular windowing, being a direct truncation of the infinite length hd(n), suffers from
Gibbs phenomenon. If we increase N, the width of each side lobe will decrease but the area
under each lobe will remain constant. This implies that all ripples will bunch up near the band
edges.
For the Hamming window, the main lobe width is equal to 8/N and the peak side lobe level
is down about 41 dB from the main lobe peak.
It can be seen that for the same design specifications, the Hamming Window provides lower
filter order than the Blackman window, but the latter provides more stopband attenuation and
smaller passband ripple.
Frequency sampling method is attractive for narrow band frequency selective filters where
only a few of the samples of the frequency response are non zero.

RESULT:
FIR low pass filters have been designed by using, Hamming Window, Hanning Window, and
using Frequency sampling method. And the frequency responses in each case have been
plotted.

93

Date:

EXPERIMENT NO.11
SAMPLING RATE CONVERSION BY RATIONAL FACTOR
AIM:
To implement sampling rate conversion by rational factor.

THEORY:
Sample rate conversion is the process of converting a (usually digital) signal from
one sampling rate to another, while changing the information carried by the signal as little as
possible. Sampling rate conversion is a typical example where it is required to determine the
values between existing samples. The computation of a value between existing samples can
alternatively be regarded as delaying the underlying signal by a fractional sampling period.
The fractional-delay filters are used in this context to provide a fractional-delay adjustable to
any desired value and are therefore suitable for both integer and non-integer factors.

MATLAB CODE:
%Sampling rate conversion by rational factor
clc; clear all; close all;
disp('Sampling rate conversion by rational factor ');
f=input('Enter frequency of the signal ');
Fs=input('Enter sampling rate in samples/sec ');
N=input('Enter number of samples N = ');
L=input('Enter up-sampling factor L = ');
M=input('Enter down-sampling factor M(<L) = ');
%Time index
Ts=1/Fs;
n=0:Ts:(N-1)*Ts;
%Amplitude
A=2;
%Input sequence
x=A*sin(2*pi*f*n);
%Up-sampling
xi=interp(x,L);
%Down-sampling
xd=decimate(x,M);
%Re-sampling
y=resample(x,L,M);
%Plotting sequences
%Input sequence
n1=0:N-1;
subplot(4,1,1); stem(n1,x);
xlabel('Time index n'); ylabel('x(n)');
title(['Input signal with sampling rate Fs = ',num2str(Fs),
'Hz']);
%Up-sampled sequence
94

Date:
ni=0:length(xi)-1;
subplot(4,1,2); stem(ni,xi);
xlabel('Time index n'); ylabel('xi(n)');
Fsu=Fs*L;
title(['Up sampled signal with sampling rate Fs =
',num2str(Fsu),' Hz']);
%Down-sampled sequence
nd=0:length(xd)-1;
subplot(4,1,3); stem(nd,xd);
xlabel('Time index n'); ylabel('xd(n)');
Fsd=Fs/M;
title(['Down sampled signal with sampling rate Fs =
',num2str(Fsd),' Hz']);
%Re-sampled sequence
ny=0:length(y)-1;
subplot(4,1,4); stem(ny,y);
xlabel('Time index n'); ylabel('y(n)');
Fssc=Fs*L/M;
title(['Sampling rate converted signal with sampling rate L/M
= ',num2str(Fssc),' Hz']);
gtext('George Sebastian 12400026');

SAMPLE OUTPUT
Sampling rate conversion by rational factor
Enter frequency of the signal 20
Enter sampling rate in samples/sec 50
Enter number of samples N = 20
Enter up-sampling factor L = 2
Enter down-sampling factor M(<L) = 1

95

Date:

Figure 11: Sampling rate conversion by a rational number

RESULT:
Sampling rate conversion by a rational factor is implemented in MATLAB.

96

Date:

EXPERIMENT NO.12
OPTIMAL EQUIRIPPLE DESIGN TECHNIQUE FOR FIR
FILTERS

AIM:
To design FIR lowpass, bandpass and highpass filters using the optimal equiripple design
technique and to obtain the frequency response.

Optimal Design Method


The disadvantage of the window design are that (i) we cannot specify the band frequencies p
and s precisely in the design, (ii) we cannot specify both (1 = 2), and the approximation
error that is, the difference between the ideal response the actual response is not
uniformly distributed over the band intervals (higher near the band edges and smaller in the
regions away from band edges). The idea behind the optimal method is that by distributing
the error uniformly, we can obtain a lower order filter satisfying the same specifications. For
linear phase FIR filters it is possible to derive a set of conditions for which it can be proved
that the design solution is optimal in the sense of minimizing the maximum approximation
error (sometimes called the minimax or the Chebyshev error). Filters that have this property
are called equiripple filters because the approximation error is uniformly distributed in both
the passband and the stopband. This results in lower-order filters.
The MATLAB code to design the FIR lowpass filter using the Parks-McClellan algorithms is
as follows:

MATLAB CODE:
%Pgm to design FIR low-pass filter using Parks-McClellan
%algorithm to meet the desired specifications
wp=input('Enter the passband edge frequency ');
ws=input('Enter the stopband edge frequency ');
Rp=input('Enter the passband ripple in dB ');
As=input('Enter the stopband attenuation in dB ');
delta_w=2*pi/1000;
wsi=ws/delta_w+1;
delta1=(10^(Rp/20)-1)/(10^(Rp/20)+1);
delta2=(1+delta1)*(10^(-As/20));
deltaH=max(delta1,delta2);
97

Date:
deltaL=min(delta1,delta2);
weights=[delta2/delta1 1];
deltaf=(ws-wp)/(2*pi);
f=[0 wp/pi ws/pi 1];
m=[1 1 0 0];
M=ceil((-20*log10(sqrt(delta1*delta2))-13)/(14.6*deltaf)+1);
while(1);
h=firpm(M-1,f,m,weights);
[db,mag,pha,grd,w]=freqz_m(h,[1]);
Asd=-max(db(wsi:1:501));
if Asd >= As
break
else
M=M+1;
end
end
M
disp('Actual stopband attenuation');
Asd
%Plotting
n=0:1:(M-1);
subplot(211); stem(n,h);
axis([0 M-1 -0.1 0.3]);
title('Actual Impulse Response'); xlabel('n'); ylabel('h[n]');
subplot(212); plot(w/pi,db);grid
axis([0 1 -80 10]);
title('Magnitude Response in dB'); xlabel('Frequency in pi
units'); ylabel('Decibels');
gtext('George Sebastian 12400026');
figure,plot(w/pi,mag);grid
axis([0 1 -0.2 1.2]);
title('Amplitude Response'); xlabel('Frequency in pi units');
ylabel('Hr(w)');
gtext('George Sebastian 12400026');
%Error
L1=wp/delta_w + 1;
for l=1:1:L1
e1(l)=1-mag(l);
end
L2=ws/delta_w + 1;
L=501-L2+1;
for l=1:1:L
e2(l)=mag(L2+l-1);
end
w1=w(1:1:L1);
w2=w(L2:1:501);
figure,subplot(211); plot(w1/pi,e1);
title('Error response in passband');
xlabel('Frequency in pi units'); ylabel('E(w)');
subplot(212); plot(w2/pi,e2);
98

Date:
title('Error response in stopband');
xlabel('Frequency in pi units'); ylabel('E(w)');
gtext('George Sebastian 12400026');

SAMPLE OUTPUT
Enter the passband edge frequency 0.2*pi
Enter the stopband edge frequency 0.3*pi
Enter the passband ripple in dB 0.25
Enter the stopband attenuation in dB 50

M =

47

Actual stopband attenuation

Asd =

51.085735780764153

99

Date:

Figure 12.1.1: Response of FIR LPF designed using Parks-McClellan algorithm

100

Date:

Figure 12.1.2: Amplitude Response

101

Date:

Figure 12.1.3: Weighted Error Response

CONCLUSION:
1. Comparing with the results of window design technique, it can be seen that the filter order
resulting from the optimal method is lower for the same design specifications.
2. The equiripple behaviour is seen in the plots of the weighted response.

RESULT:
FIR lowpass filter have been designed using the Parks-McClellan algorithm and their
frequency and error responses have been obtained.

102

Date:

EXPERIMENT NO.13
INTODUCTION TO DSP DEVELOPMENT SYSTEM
AIM:
To study the tools available for digital signal processing, including Code Composer
Studio (CCS), this provides an integrated development environment (IDE), and the DSP
starter kit (DSK) with the TMS320C6713 floating-point processor on-board.

INTRODUCTION:

Components of a typical DSP system


Typical DSP systems consist of a DSP chip, Memory, possibly an analog-to-digital converter
(ADC), a digital-to-analog converter (DAC), and communication channels. Not all DSP
systems have the same architecture with the same components. The selection of components
in a DSP system depends on the application. For example, a sound system would probably
require A/D and D/A converters, whereas an image processing system may not.

103

Date:

DSP chip
A DSP chip can contain many hardware elements; some of the more common ones are listed
below.
1. Central Arithmetic Unit
This part of the DSP performs major arithmetic functions such as multiplication and addition.
It is the part that makes the DSP so fast in comparison with traditional processors.
2. Auxiliary Arithmetic Unit
DSPs frequently have an auxiliary arithmetic unit that performs pointer arithmetic,
mathematical calculations, or logical operations in parallel with the main arithmetic unit.
3. Serial Ports
DSPs normally have internal serial ports for high-speed communication with other DSPs and
data converters.
These serial ports are directly connected to the internal buses to improve performance, to
reduce external address decoding problems, and to reduce cost.
4. Memory
Memory holds information, data, and instructions for DSPs and is an essential part of any
DSP system.
Although DSPs are intelligent machines, they still need to be told what to do. Memory
devices hold a series of instructions that tell the DSP which operations to perform on the data
(i.e., information). In many cases, the DSP reads some data, operates on it, and writes it back.
Almost all DSP systems have some type of memory device, whether it is on-chip memory or
off-chip memory; however, on-chip memory operates faster.
5. A/D and D/A Converter
Converters provide the translator function for the DSP. Since the DSP can only operate on
digital data, analog signals from the outside world must be converted to digital signals. When
the DSP provides an output, it may need to be converted back to an analog signal to be
perceived by the outside world.
Analog-to-digital converters (ADCs) accept analog input and turn it into digital data that
consist of only 0s and 1s. Digital-to-analog converters (DACs) perform the reverse process;
they accept digital data and convert it to a continuous analog signal.
6. Ports
Communication ports are necessary for a DSP system. Raw information is received and
process information is transmitted to the outside world through these ports. For example, a
104

Date:
DSP system could output information to a printer through a port. The most common ports are
serial and parallel ports. A serial port accepts a serial (single) stream of data and converts it to
the processor format. When the processor wishes to output serial data, the port accepts
processor data and converts it to a serial stream (e.g., modem connections
On PCs). A parallel port does the same job, except the output and input are in parallel
(simultaneous)format. The most common example of a parallel port is a printer port on a PC.
Digital signal processors such as the TMS320C6x (C6x) family of processors are like fast
special-purpose microprocessors with a specialized type of architecture and an instruction set
appropriate for signal processing. The C6x notation is used to designate a member of Texas
Instruments (TI) TMS320C6000 family of digital signal processors. The architecture of the
C6x digital signal processor is very well suited for numerically intensive calculations. Based
on a very-long-instruction-word (VLIW) architecture, the C6x is considered to be TIs most
powerful processor.

DSK support tools


To perform the design of a program to implement a DSP application, the following tools are
to be used:
1. TIs DSP starter kit (DSK). The DSK package includes:
(a) Code Composer Studio (CCS), which provides the necessary software support
tools. CCS provides an integrated development environment (IDE), bringing
together the C compiler, assembler, linker, debugger, and so on.
(b) A board, that contains the TMS320C6713 (C6713) floating-point digital signal
processor as well as a 32-bit stereo codec for input and output (I/O) support.
(c) A universal synchronous bus (USB) cable that connects the DSK board to a PC.
(d) A 5V power supply for the DSK board.
2. An IBM-compatible PC. The DSK board connects to the USB port of the PC through the
USB cable included with the DSK package.
3. An oscilloscope, signal generator, and speakers. A signal/spectrum analyzer is optional.
Shareware utilities are available that utilize the PC and a sound card to create a virtual
instrument such as an oscilloscope, a function generator, or spectrum analyser.

The 6713 DSK is a low-cost standalone development platform that enables us to evaluate and
develop applications for the TI C67XX DSP family. The DSK also serves
as a hardware reference design for the TMS320C6713 DSP.

The DSK uses 2-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.
105

Date:

An onboard AIC23 codec allows the DSP to transmit and receive analog signals.
McBSP0 is used for the codec control interface and McBSP1 is used for the data.

Analog audio I/O is done through 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 use to implement the 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 a way to provide the user with interactive feedback. Both are
accessed by reading and writing to the CPLD registers.

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 external JTAG connector.

DSK Board
The DSK board includes the C6713 floating-point digital signal processor and a 32-bit stereo
codec TLV320AIC23 (AIC23) for input and output. The on-board codec AIC23 uses a
sigmadelta technology that provides ADC and DAC. It connects to a 12-MHz system clock.
Variable sampling rates from 8 to 96 kHz can be set readily. A daughter card expansion is
also provided on the DSK board. Two 80-pin connectors provide for external peripheral and
external memory interfaces. The DSK board includes 16MB of synchronous dynamic
random-access memory (SDRAM) and 256kB of flash memory. Four connectors on the
board provide input and output: MIC IN for microphone input, LINE IN for line input, LINE
OUT for line output, and HEADPHONE for a headphone output (multiplexed with line
output). The status of the four user dip switches on the DSK board can be read from a
program and provides the user with a feedback control interface. The DSK operates at
225MHz.Also on-board the DSK are voltage regulators that provide 1.26 V for the C6713
core and 3.3 V for its memory and peripherals.

106

Date:

TMS320C6713 Digital Signal Processor


The TMS320C6713 (C6713) is based on the VLIW architecture, which is very well suited for
numerically intensive algorithms. The internal program memory is structured so that a total of
eight instructions can be fetched every cycle. For example, with a clock rate of 225MHz, the
C6713 is capable of fetching eight 32-bit instructions every 1/ (225 MHz) or 4.44 ns.
Features of the C6713 include 264 kB of internal memory (8kB as L1P and L1D Cache and
256kB as L2 memory shared between program and data space), eight functional or execution
units composed of six arithmetic-logic units (ALUs) and two multiplier units, a 32-bit address
bus to address 4 GB and two sets of 32-bit general-purpose registers.
The C67xx (such as the C6701, C6711, and C6713) belong to the family of theC6x floatingpoint processors, whereas the C62xx and C64xx belong to the family of the C6x fixed-point
processors. The C6713 is capable of both fixed- and floating-point processing.

TMS 320C6713 DSP Features:

Highest-Performance Floating-Point Digital Signal Processors (DSPs):


C6713/C6713B

Eight 32-Bit Instructions/Cycle

32/64-Bit Data Word

300-, 225-, 200-MHz (GDP), and 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.


107

Date:

Advanced Very Long Instruction Word (VLIW) TMS320C67x DSP Core

Eight Independent Functional Units


1. Two ALUs (Fixed-Point)
2. Four ALUs (Floating- and Fixed-Point)
3. 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

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)

Glue less Interface to SRAM, EPROM, Flash, SBSRAM, and


SDRAM

512M-Byte Total Addressable External Memory Space

Enhanced Direct-Memory-Access (EDMA) Controller (16 Independent


Channels)
108

Date:

16-Bit Host-Port Interface (HPI)

Two Multichannel Audio Serial Ports (McASPs)

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


1. Programmable Clock Generator
2. Programmable Frame Sync Generator
3. Programmable Frame Sync Generator
4. TDM Streams From 2-32 Time Slots
5. Support for Slot Size:8, 12, 16, 20, 24, 28, 32 Bits
6. Data Formatter for Bit Manipulation

Wide Variety of I2S and Similar Bit Stream Formats

Integrated Digital Audio Interface

Transmitter (DIT) Supports:


1. S/PDIF, IEC60958-1, AES-3, CP-430 Formats
2. Up to 16 transmit pins
3. Enhanced Channel Status/User Data

Extensive Error Checking and Recovery

Two Inter-Integrated Circuit Bus (I2C Bus) Multi-Master and Slave Interfaces

Two Multichannel Buffered Serial Ports:

Serial-Peripheral-Interface (SPI)

High-Speed TDM Interface

AC97 Interface

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


109

Date:

Package Options:

208-Pin PowerPAD Plastic (Low-Profile) Quad Flatpack (PYP)

272-Ball, Ball Grid Array Package (GDP)

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

CODE COMPOSER STUDIO


CCS provides an IDE to incorporate the software tools. CCS includes tools for code
generation, such as a C compiler, an assembler, and a linker. It has graphical capabilities and
supports real-time debugging. It provides an easy-to-use software tool to build and debug
programs.

The C compiler compiles a C source program with extension .c to produce an assembly


source file with extension.asm. The assembler assembles an.asm source file to produce a
machine language object file with extension.obj. The linker combines object files and object
libraries as input to produce an executable file with extension. out. This executable file
represents a linked common object file format (COFF), popular in Unix-based systems and
adopted by several makers of digital signal processors. This executable file can be loaded and
run directly on the C6713 processor.

Types of files
There are a number of files with different extensions. They include:
1. file.pjt: to create and build a project named file
2. file.c: C source program
3. file.asm: assembly source program created by the user, by the C compiler,
110

Date:
or by the linear optimizer
4. file.sa: linear assembly source program. The linear optimizer uses file.sa
as input to produce an assembly program file.asm
5. file.h: header support file
6. file.lib: library file, such as the run-time support library file
rts6700.lib
7. file.cmd: linker command file that maps sections to memory
8. file.obj: object file created by the assembler
9. file.out: executable file created by the linker to be loaded and run on the
C6713 processor
10. file.cdb: configuration file when using DSP/BIOS

CREATING AND BUILDING PROJECTS IN CCS


Support files
The following support files are used for waveform generation and filtering
1. C6713dskinit.c: contains functions to initialize the DSK, the codec, the serial ports,
and for I/O. It is not included with CCS.
2. C6713dskinit.h: header files with function prototypes. Features such as those used
to select the mic input in lieu of line input (by default), input gain< and so on are
obtained from this header file.
3. C6713dsk.cmd: sample linker command file. This generic file can be changed
when using external memory in lieu of internal memory.
4. Vectors_intr.asm: a modified version of a vector file included with CCS to handle
interrupts. Twelve interrupts, INT4 through INT15, are available, and INT11 is
selected within this vector file. They are used for interrupt-driven programs.
5. Vectors_poll.asm: vector files for programs using polling.

111

Date:
6. Rts6700.lib, dsk6713bsl.lib, csl6713.lib: run time, board and chip support library
files, respectively. These files are included with CCS and are located in
C6000\cgtools\lib, c6000\dsk6713\lib, and c6000\bios\lib, respectively.
These files are available in the folder support.

Creating project
Consider creating project by the name myproj
1. First create a folder myproj in c:\c6713\myprojects.
2. To create a project file myproj.pjt, select Project

New. Type myproj for the

project name. This project file is saved in the folder myproj within
c:\c6713\myprojects.the .pjt file stores project information on build options, source
filenames, and dependencies.
3. Create the C source file myproj.c and save it in the folder myproj within
c:\c6713\myprojects.
4. To add files to the project. Select Project

Add files to the project. Look in the

folder support files of type C source files. Double click on the C source files.
C6713dskinit.c to add it to the project.
5. Repeat step 4, use the pull down menu for the files of type, and select ASM source
files. Double click on the assembly source vector file vectors.poll, asm to add it to
the project. Repeat again and select files of Type: Linker Command File, and
C6713dsk.cmd to the project.
6. To add the library support files to the project, repeat the previous steps, but select
files of type: Object and Library Files. Look in c:\c6713\c6000\cgtools\lib and select
the run time support library file rts6700.lib (which supports the C67x architecture)
to add to the project. Continue this process to add the BSL file dsk6713bsl.lib
located in c:\c6713\c6000\dsk6713\lib, and the chip support file (CSL)
C6713dsk.cmd located in c:\c6713\c6000\bios\lib.
7. Verify from the Files window that the project (.pjt) file, the linker command (.cmd)
file, the three library (.lib) files, the two C source (.c) files, and the assembly (.asm)
file have been added to the project. The GEL file dsk673.el is added automatically
when you create the project. It initialises the c6713 DSK invoking the BSL to use
the phase locked loop (PLL)

112

Date:
8. To set the central processing unit clock to 225MHz (Otherwise the C6713 runs
50MHZ by default).

Code generation and options


Various projects are associated with the code generation tools:C compiler and linker to build
a project.

Compiler option
Select Project Build options. Select the following for the 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),and (4) None (for Opt Level and
Program level Opt).select the Pre-processor category and type for definite symbolised:
CHIP_6713, and from the Feedback category, select for Interlisting: OPT/C and ASM-s. The
resulting compiler option is g s
The -g option is used in conjunction with the option s to interlist the C source file with the
assembly source file myproj.asm generated (an additional option,-k, can be used to retain the
assembly source file). The g options disables many code optimizations to facilitate the
debugging process, Press OK.
Selecting C621x andC64xx for Target Version invokes a fixed point implementation.
The C6713 based DSK can use either fixed or floating point processing. Selecting C671x as
Target version invokes a floating point implementation.
Linker option
Click on Linker option (from CCS Build option).The output filename myproj.out defaults to
the name of .pjt filename, and Run time Auto initialisations defaults for autoinit model. Press
OK.

Building and running the project


The project myproj can now be built and run.

1. Build this project as myproj. Select Project=>Rebuild All or press the toolbar with the
three down arrows. This compiles and assembles all the C files using cl6x and assembles the
assembly file vectors_poll.asm using asn6x.The resulting object files are then linked with the
library files using link6x.this creates an executable file myproj.out that can be loaded into the
C6713 processor and run. Note that the commands for compiling, assembling, and linking are
performed with the Build option. A log file cc_build_Debug.log is created that shows the
files that are compiled and assembled, along with the compiler options selected. It also lists
the support functions that are used. The building process causes all the dependant files to be
included(in case one forgets to scan for all the file dependencies).
113

Date:

2. Select File=>Load Program in order to load myproj.out by clicking on it(CCS includes an


option to load the program automatically after a build).It should be in the folder
myproj\Debug. Select Debug=Run or use the toolbar with the unning man.

Loop program using interrupt


This example illustrates input and output with the AIC23 codec.It is interrupt-driven.
//Loop_intr. c Loop program using interrupt.Output= delayed input
#include dsk^6713_aic23.h

//codec-DSK support file

Uint32 fs=DSK6713_AIC23_FREQ_8KHZ;

//set sampling rate

Interrupt void c_int11()

//interrupt service routine

{ short sample_data;
sample_data = input_sample();//input data
output_sample(sample_data);//output data
return;
}
void main()
{ comm_intr();
while(1);

//init DSK,codec,McBSP
//infinite loop

}
This program example can be used as a base program to build on. For example, to implement
a digital filter, one would need to insert the appropriate algorithm between the input and
output functions. The two functions input sample and output_sample,as well as the function
comm_intr, are included in the communication support file C6713dskinit.c.

RESULT:
The tools available for digital signal processing, including code composer Studio, and the
DSP starter kit with the TMS320C6713 floating point processor onboard have been studied.

114

Date:

EXPERIMENT NO.14
PROGRAMS USING CODE COMPOSER STUDIO
1.SINEWAVE GENERATION USING CCS
AIM:
To implement sinewave generation using lookup table with table values generated within the
program.

PROGRAM CODE:
#include DSK6713_AIC23.h //codec-DSK support file
Uint32fs=DSK6713_AIC23_FREQ_16KHZ; //set sampling rate
short sine_table[0,707,1000,707,0,-707,-1000,-707]; //sine table array
int i=0;
interrupt void c_int11() //interrupt service routine
{ output_sample( 32*sine_table[i]);
i++; //incr index until end of table
if(i>=8)
i=0;
return; //return from interrupt
}
main()
{
comm_intr(); //init DSK, codec, McBSP
while(1); //infinite loop
}
The project has been created and built using the above source file and debugged.

115

Date:
CONCLUSION:
This program creates one period of sine data values for a table. Then thesevalues are output
for generating a sinewave. The program sinusoid.c implements this project. This
project,which uses the transmit interrupt INT11 should be build and run as sinusoid.

RESULT:
Sinewave has been generated using the source program that uses lookup table with the table
values generated within the program.

116

Date:

2.FIR FILTERING USING CCS


AIM:
To implement an FIR filter using Code Composer Studio.

PROGRAM CODE:
//FIR.c FIR filter . Include coefficient file with length N
#include"lpcof.h"
#include DSK6713_aic23.h //codec-DSK support file
Uint32 fs=DSK6713_AIC23_FREQ_16KHZ; //set sampling rate
Int yn=0; //initialize filters output
Short dlx[N]; //delay samples
Interrupt void c_int11() //ISR
{ short i;
dlx[0]= input_sample(); //input newest sample
yn=0; //initialize filters output
for(i=0;i<N;i++)
yn+= (h[i]*dlx[i]); //y(n)+=h(i)*x(n-i)
for(i=N-1;i>0;i--) //starting @ end of buffer
dlx[i]=dlx[i-1]; //update delays with data move
output_sample(yn>>15); //scale output filter sample
return;
}
void main()
{ comm_intr(); //init DSK, codec, McBSP Date: 126
while(1); //infinite loop
}

117

Date:
The FIR filter coefficients are found using MATLAB and the coefficient file is included inthe
program before debugging.

Explanation: The C source program impliments an FIR filter.It is a generic FIR


program,since the coefficient file included ,BS2700.cof ,specifies the filters
charecteristics.The number of coefficients N is defined in the coefficient file.A buffer dly[N]
is created for the delay samples.

RESULT:
The audio signal input to the DSK has been lowpass filtered using FIR filter and the filtered
audio signal has been heard.

118

Date:

3.IIR FILTERING USING CCS


AIM:
To implement a generic IIR filter using the cascaded direct -II structure with the help of Code
Composer Studio.

PROGRAM CODE:
//IIR.c IIR filter using cascaded Direct Form II
//Coefficients as and bs correspond to bs and as from MATLAB
#include DSK6713_AIC23.h

//codec-DSK support file

Uint32 fs=DSK6713_AIC23_FREQ_8KHZ;

//set sampling rate

#include bs1750.cof

//BS @ 1750 Hz coefficient file

Short dly[stages][2] ={0};

//delay samples per stage

Interrupt void c_int11()

//ISR

{ short i, input;
int un,yn;
input= input_sample();

//input to 1st stage

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

//repeat for each stage

{ un=input-((b[i][0]*dly[i][0])>>15)-((b[i][1]*dly[i][1])>>15);
yn=((a[i][0]*un)>>15)+((a[i][1]*dly[i][0])>>15)+((a[i][2]*dly[i][1])>>15);
dly[i][1]=dly[i][0];

//update delays

dly[i][1]=un;

//update delays

input=yn;
nextstage

//intermediate output->input to

}
output_sample((short)yn);
return;

//return from ISR


119

Date:
}
void main()
{ comm_intr();

//init DSK,codec,McBSP

while(1);

//infinite loop

}
The IIR filter is designed in MATLAB using the fda tool and the b and a coefficient
files are included as the a and b arrays of the above source file. The project is built and
debugged.
Explanation:
Figure shows a listing of the program IIR.c that implements a generic IIR filter using
cascaded second-order stages(sections). The program uses the following two equations
associated with each stage:
u(n) = x(n) - b1u(n - 1) - b2u(n 2)
y(n) = a0 u(n) + a1u(n - 1) + a2u(n 2)
The loop section of code within the program is processed five times (the number of stages)
for each value of n, or sample period. For the first stage, x(n) is the newly acquired input
sample. However, for the other stages, the input x(n) is the output y(n) of the preceding
stage.The coefficients b[i][0] and b[i][1] correspond to b1 and b2, respectively; where i
represents each stage. The delays dly[i][0] and dly[i][1] correspond to u(n - 1) and u(n 2),
respectively.

RESULT:
The audio signal input to the DSK has been lowpass filtered using IIR filter and the filter
audio signal has been heard.

120

Date:

121

Você também pode gostar