Sie sind auf Seite 1von 201

MATLAB – A Review

MATLAB – this name is derived from MATrix LABoratory.


MATLAB® is a high-performance language for technical computing. It integrates
computation, visualization, and programming in an easy-to-use environment where problems and
solutions are expressed in familiar mathematical notation. Typical uses include
 Math and computation
 Algorithm development
 Data acquisition
 Modeling, simulation, and prototyping
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including graphical user interface building

MATLAB is an interactive system whose basic data element is an array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time it would take to write a program in
a scalar non-interactive language such as C or FORTRAN.
MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses in
mathematics, engineering, and science. In industry, MATLAB is the tool of choice for high-
productivity research, development, and analysis.
MATLAB features a family of add-on application-specific solutions called toolboxes.
Very important to most users of MATLAB, toolboxes allow you to learn and apply specialized
technology. Toolboxes are comprehensive collections of MATLAB functions (M-files) that
extend the MATLAB environment to solve particular classes of problems. Areas in which
toolboxes are available include signal processing, control systems, communications, filter design,
neural networks, fuzzy logic, wavelets, simulation, and many others.

The MATLAB System


The MATLAB system consists of five main parts:
Development Environment.
This is the set of tools and facilities that help you use MATLAB functions and files. Many of
these tools are graphical user interfaces. It includes the MATLAB desktop and Command
Window, a command history, an editor and debugger, and browsers for viewing help, the
workspace, files, and the search path.
The MATLAB Mathematical Function Library.
This is a vast collection of computational algorithms ranging from elementary functions, like
sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse,
matrix eigenvalues, Bessel functions, and fast Fourier transforms
The MATLAB Language.
This is a high-level matrix/array language with control flow statements, functions, data
structures, input/output, and object-oriented programming features. It allows both "programming
in the small" to rapidly create quick and dirty throw-away programs, and "programming in the
large" to create large and complex application programs.
Graphics.
MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as
annotating and printing these graphs. It includes high-level functions for two-dimensional and
three-dimensional data visualization, image processing, animation, and presentation graphics. It
also includes low-level functions that allow you to fully customize the appearance of graphics as
well as to build complete graphical user interfaces on your MATLAB applications.
The MATLAB Application Program Interface (API).
This is a library that allows you to write C and FORTRAN programs that interact with
MATLAB. It includes facilities for calling routines from MATLAB (dynamic linking), calling
MATLAB as a computational engine, and for reading and writing MAT-files.

2
MATLAB Online Help
To view the online documentation, select MATLAB Help from the Help menu in
MATLAB. The MATLAB documentation is organized into these main topics:
 Desktop Tools and Development Environment -- Startup and shutdown, the desktop, and
other tools that help you use MATLAB
 Mathematics -- Mathematical operations and data analysis
 Programming -- The MATLAB language and how to develop MATLAB applications
 Graphics -- Tools and techniques for plotting, graph annotation, printing, and
programming with Handle Graphics®
 3-D Visualization -- Visualizing surface and volume data, transparency, and viewing and
lighting techniques
 Creating Graphical User Interfaces -- GUI-building tools and how to write callback
functions
 External Interfaces/API -- MEX-files, the MATLAB engine, and interfacing to Java,
COM, and the serial port
MATLAB also includes reference documentation for all MATLAB functions:
 Functions - By Category -- Lists all MATLAB functions grouped into categories
 Handle Graphics Property Browser -- Provides easy access to descriptions of graphics
object properties
 External Interfaces/API Reference -- Covers those functions used by the MATLAB
external interfaces, providing information on syntax in the calling language, description,
arguments, return values, and examples
The MATLAB online documentation also includes
 Examples -- An index of examples included in the documentation
 Release Notes -- New features and known problems in the current release
 Printable Documentation -- PDF versions of the documentation suitable for printing

3
Starting MATLAB
On Windows platforms, start MATLAB by double-clicking the MATLAB shortcut icon
on your Windows desktop.
On UNIX platforms, start MATLAB by typing matlab at the operating system prompt.
You can customize MATLAB startup. For example, you can change the directory in
which MATLAB starts or automatically execute MATLAB statements in a script file named
startup.m
Quitting MATLAB
To end your MATLAB session, select File -> Exit MATLAB in the desktop, or type quit
in the Command Window. You can run a script file named finish.m each time MATLAB quits
that, for example, executes functions to save the workspace, or displays a quit confirmation
dialog box.

4
MATLAB Desktop
When you start MATLAB, the MATLAB desktop appears, containing tools (graphical user
interfaces) for managing files, variables, and applications associated with MATLAB. The
following illustration shows the default desktop. You can customize the arrangement of tools and
documents to suit your needs.

5
M-files
MATLAB can execute a sequence of statements stored in disk files. Such files are called
"M-files" because they must have the file type of ".m" as the last part of their filename. M-files
are usually created using the local editor. There are two types of M-files:
1. Script files
A script file consists of a sequence of normal MATLAB statements. If the file has the filename,
say, rotate.m, then the MATLAB command rotate will cause the statements in the file to be
executed. Variables in a script file are global and will change the value of variables of the same
name in the environment of the current MATLAB session. Script files may be used to enter data
into a large matrix; in such a file, entry errors can be easily corrected
2. Function files.
Function files provide extensibility to MATLAB. We can create new functions specific to the
problem which will then have the same status as other MATLAB functions. Variables in a
function file are by default local.

6
MEX files

The MATLAB M-File is very good for putting together functions or scripts that run many
of MATLAB's fast Built-In functions. One nice thing about these files is that they are never
compiled and will run on any system that is already running MATLAB. MATLAB achieves this
by interpreting each line of the M-File every time it is run. This method of running the code can
make processing time very slow for large and complicated functions, especially those with many
loops because every line within the loop will be interpreted as a new line, each time through the
loop. Good MATLAB code avoids these things by using as many Built-In features and array
operations as possible (because these are fast and efficient).

MATLAB has the capability of running functions written in C. The files which hold the
source for these functions are called MEX-Files. The mex Functions are not intended to be a
substitute for MATLAB's built-in operations however if we need to code many loops and other
things that MATLAB is not very good at, this is a good option.

MAT files
A MAT file is a binary data file format created by MATLAB and similar programs.MAT
files can contain any number of program variables produced by a MATLAB interactive session
or automated script. These variables represent several MATLAB data types including strings,
arrays, cells and structures.

In MATLAB, we can create MAT-files by using the save command, which writes the
arrays currently in memory to a file as a continuous byte stream. By convention, this file has the
filename extension .mat; thus the name MAT-file. The load command reads the arrays from a
MAT-file into the MATLAB workspace.
Graphics Concepts
Matlab has outstanding graphics capabilities. Before looking at the plotting capabilities of
Matlab, we need to consider a graph which is a collection of points, in 2,3 or even 4 dimensions,
that may or may not be connected by lines or polygons.
Matlab is designed to work with matrices, rather than functions. Matrices are a
convenient way to store a collection of numbers - which is exactly what is needed when

7
graphing. Thus all graphing commands in Matlab accept matrices as their argument, rather than a
function.
On the other hand, Matlab's approach makes it very easy to visualize data and to create
graphics based on lists of points. Another unique feature of Matlab's graphics engine is the way
in which it displays graphical output. In Matlab, there is (usually) only one plotting window.
Subsequent plotting commands will add to the old plot, unless we request a new one be made.
Saving Graphs to Reload into MATLAB
There are two ways to save graphs that enable you to save the work we have invested in their
preparation:
 Save the graph as a FIG-file (select Save from the figure File menu).
 Generate MATLAB code that can recreate the graph (select Generate M-File from the
figure File menu).
FIGURE-Files.
FIG-files are a binary format that saves a figure in its current state. This means that all
graphics objects and property settings are stored in the file when we create it. We can reload the
file into a different MATLAB session, even if we are running MATLAB on a different type of
computer. When we load a FIG-file, MATLAB creates a new figure in the same state as the one
we saved. Note that the states of any figure tools (i.e., any items on the toolbars) are not saved in
a FIG-file; only the contents of the graph are saved.

8
CYCLE- I

9
Program – 1

Generation of Sinusoidal waveform based on recursive difference equations


Date:

Aim: To generate Sinusoidal waveform based on recursive difference equations.


Requirements: Personal Computer with MATLAB software v 8.5
Theory
Sine and cosine functions are very common in communications and DSP applications e.g.
modulation, demodulation, FFT, spectral analysis. Digital sinusoidal oscillators are essential
elements in many applications. They are used in communications, music synthesis, control,
radar, and digital signal processing. These digital oscillators exhibit the advantages of digital
techniques, namely, stability, flexibility, and low cost. Moreover, the parameters of a digitally
generated sinusoid are easy to control.
In Recursive Evaluation, we consider a place pole pair on unit circle giving rise to the
transfer function
1 z 2
H ( z)  
( z  e jT )( z  e  jT ) (1  2 cos(T ) z 1  z 2 )

Rewriting as the difference equation we get


y (n)  2 cos(T ). y (n  1)  y (n  2)  x(n  2)
This will oscillate at fixed frequency ω with x(n-2) = 0 or x(n) being an impulse signal.
 2f 
cos(T )  cos o  where fs is the sampling frequency, fo is the desired oscillating
,
 fs 
frequency
Let fo=300Hz and fs=1/T=8000Hz

10
Program
% Clearing and Closing Commands
clc; % To clear Command Window
clear all; % To clear the workspace
close all; % To close the previous Waveforms/Graphs if any
%difference equation approach
%Assumptions
y(1)=1;
y(2)=1;
x=[0 0 1 zeros(1,97)]
for n=3:100
y(n)=1.9447*y(n-1)-y(n-2);
end
plot(y)
xlabel('Time--->');
ylabel('Amplitude--->');
title('Sinusoidal waveform generation');

Waveforms/Graphs:

Fig 1.1: Sinusoidal signal generation based on recursive evaluation

11
Result: Sinusoidal signal has been generated using recursive evaluation approach and the
corresponding Waveforms/Graphs have been plotted.

Viva-voce:
1. Solving difference equations
2. Graph Plotting commands
3. Syntaxes of various Keywords used in the program

12
Program –2
Histogram of White Gaussian Noise and Uniformly Distributed Noise

Date:

Aim:To plot the histogram of white Gaussian noise and uniformly distributed noise.

Requirements: Personal Computer with MATLAB software v 8.5

Theory:

Gaussian noise is statistical noise that has its probability density function equal to that of
the normal distribution, which is also known as the Gaussian distribution. In other words, the
values that the noise can take on are Gaussian-distributed. A special case is white Gaussian
noise, in which the values at any pair of times are identically distributed and statistically
independent (and hence uncorrelated). In applications, Gaussian noise is most commonly used as
additive white noise to yield additive white Gaussian noise.
Uniformly distributed noise has uniform or constant probability density function throughout the
range it is defined.
Program

clc;
clear all;
close all;

% Generate first set of 50000 samples of Gaussian distributed random numbers


x1 = randn(1,50000);

%Generate first set of 50000 samples of uniformly distributed random numbers


x2 = rand(1,50000);

% Plot a histogram graph of x1 in the 1st portion of a new figure window


subplot(2,1,1);
hist(x1)
title('Histogram of White Gaussian Noise Distribution')
xlabel('Realization of random variable')
ylabel('Number of occurrences')

%Plot a histogram graph of y in the 2nd portion of the figure window


subplot(2,1,2);
hist(x2)
title('Histogram of Uniformly Distributed Noise')
xlabel('Realization of random variable')
ylabel('Number of occurrences')
Waveforms/Graphs:

13
Fig 2.1: a) Histogram of White Gaussian noise
b) Histogram of Uniformly Distributed noise
Result: Thus histograms of white Gaussian noise and uniformly distributed noise are plotted.
14
Viva-Voce:
1. What is white noise?
2. What is probability density function?
3. Syntaxes of various Keywords used in the program

15
Program –3
DFT / IDFT of given DT signal

Date:

Aim:a) To find Discrete Fourier Transform of a given signal/sequence


b) To recover the original sequence from DFT sequence using Inverse DFT

Requirements: Personal Computer with MATLAB software v 8.5

Theory:
The DFT of any sequence is the powerful computational tool for performing frequency analysis
of discrete-time signals .In this program the Discrete Fourier Transform (DFT) of a sequence
N 1  2 
 j  nk
x[n] is generated by using the formula, X (k )   x(n).e
n 0
 N 

where, X(k) DFT of sequence x[n], N represents the sequence length.


The Inverse DFT is performed on X(k)is obtained using the formula
 2 
 1  N 1 j  nk
x(n)    X (k ).e  N 

 N  k 0

Program

% Clearing and Closing Commands


clc; % To clear Command Window
clear all; % To clear the workspace
close all; % To close the previous Waveforms/Graphs if any
% To Compute DFT/IDFT
x=input('Enter the sequence:');
N=length(x);
X=[];
%DFT
for k=0:N-1
y1=0;
for n=0:N-1
y1=y1+x(n+1)*exp(-i*2*pi*n*k/N);
end
X=[X,y1];
end
disp('The result of DFT is:');X

% Inverse DFT
y=[];
16
for n=0:N-1
y2=0;
for k=0:N-1
y2=y2+X(k+1)*exp(i*2*pi*n*k/N);
end
y=[y,y2];
end
disp('The result of IDFT is:');y/N

Result:a) Thus DFT of a sequence is found


b) Original input sequence is obtained using Inverse DFT

Input Sequence x(n)=

DFT of the input sequence X(k) =

The original input sequence recovered using Inverse DFT is :

Viva-Voce:
1. Mathematical expressions to find DFT / IDFT
2. Applications of DFT
3. Syntaxes of various Keywords used in the program

17
Program –4
Frequency response of a system given in Transfer Function/ Differential
equation form

Date:

Aim:a) To find the frequency response of a continuous time system in Transfer function form.
b) To find the frequency response of a discrete time system in difference equation form.

Requirements: Personal Computer with MATLAB software v 8.5

Theory:
Frequency response of a system includes both Magnitude response and phase response.
The magnitude plot is the absolute value of magnitude versus the frequency and the phase plot is
the phase angle versus the frequency is plotted for different systems.

Program

% To compute frequency response of a continuous time system in transfer form

% Clearing and Closing Commands


clc; % To clear Command Window
clear all; % To clear the workspace
close all; % To close the previous Waveforms/Graphs if any

% Given 2nd order system


%H(s)=(s+4)/(s^2+3s+1)

a = input ('type the numerator vector:');


b = input ('type the denominator vector:');
[H,W]=freqs(a,b)
magR=abs(H);
phaseR=angle(H);
subplot(2,1,1);
plot(W/pi,magR);
xlabel ('Freq--->');
ylabel ('Magnitude---> ');
title ('Magnitude Response of 2nd order LTI system');
subplot(2,1,2);
plot(W/pi,phaseR);
xlabel ('Freq--->');
ylabel ('Phase---> ');
title ('Phase Response of 2nd order LTI system');

18
% To compute frequency response of a discrete time system in difference equation form

% Clearing and Closing Commands


clc; % To clear Command Window
clear all; % To clear the workspace
close all; % To close the previous Waveforms/Graphs if any

% Given 2nd order system


%y(n)=(3/8)y(n-1)+(2/3)y(n-2)+x(n)+(1/4)x(n-1)

a = input ('type the numerator vector for 2nd order system ');
b = input ('type the denominator vector for 2nd order system ');
[H,W]=freqz(a,b);
magR=abs(H);
phaseR=angle(H);
subplot(2,1,1);
plot(W/pi,magR);
xlabel ('Freq--->');
ylabel ('Magnitude---> ');
title ('Magnitude Response of 2nd order LTI system');
subplot(2,1,2);
plot(W/pi,phaseR);
xlabel ('Freq--->');
ylabel ('Phase---> ');
title ('Phase Response of 2nd order LTI system');

19
Waveforms/Graphs:

Fig 4.1: a) Frequency response of CT-LTI system


b) Frequency response of DT-LTI system
20
Result: Thus frequency response of continuous time and discrete time systems are found and
plotted

Viva-Voce:
1. What is frequency response?
2. What is transfer function?
3. Syntaxes of various Keywords used in the program

21
Program –5
Obtain Fourier series coefficients by formula and using FFT and compare for
half sine wave

Date:

Aim:To compare the fourier coefficients of half sine wave obtained using fourier series formula
and FFT

Requirements: Personal Computer with MATLAB software v 8.5

Theory:
A Fourier series is a representation of a function in terms of a summation of an infinite
number of harmonically-related sinusoids with different amplitudes and phases. The amplitude
and phase of a sinusoid can be combined into a single complex number, called a
Fourier coefficient.
𝑁−1
1 2𝜋
𝑋(𝑘) 𝑒 𝑗 𝑛𝑘
𝑥 𝑛 = 𝑁
𝑁
𝑘=0

A fast Fourier transform (FFT) is an algorithm that samples a signal over a period of time (or
space) and divides it into its frequency components.

Program

clc;
clear all;
close all;
stepsize=0.001;
t=0:stepsize:2;
x=sin(2*pi*t);
[~,idx]=findpeaks(x);
T=t(idx(2))-t(idx(1));
disp(['Time Period =' num2str(T),'seconds']);
N=T/stepsize;
X1=[];
for k=0:(N/2)-1
y=0;
for(n=0:N-1)
y=y+x(n+1)*exp(-1i*2*pi*n*k/N);
22
end
X1=[X1,y];
end

%USING FFT

X2=fft(x,N);
subplot(3,1,1)
stem(x(1:N/2));
xlabel('n--->');
ylabel('x(n)--->');
title('Half cycle of sine wave');
subplot(3,1,2);
stem(abs(X1));
xlabel('K--->');
ylabel('X(k)--->');
title('Absolute plot of Fourier series coefficients');
subplot(3,1,3);
stem(abs(X2(1:N/2)));
xlabel('K--->');
ylabel('X(k)--->');
title('Absolute plot of coefficients using FFT');

23
Waveforms/Graphs:

Fig 5.1: a) Half cycle of sinewave b) magnitude plot of fourier series coefficients
c) magnitude plot using FFT
24
Result: Thus Fourier coefficients of half cycle of a sinewave are found using fourier series and
FFT and are compared using magnitude plot.

Viva-Voce:
1. What is the importance of Fourier series?
2. What is FFT?
3. Syntaxes of various Keywords used in the program

25
Program – 6
Fast Fourier Transform
Date:

Aim:To Compute the DFT of a sequence using Fast Fourier Transform.


Requirements: Personal Computer with MATLAB software v 8.5
Theory:
The Fast Fourier Transform is useful to map the time-domain sequence into a continuous
function of a frequency variable. The FFT of a sequence {x(n)} of length N is given by a
complex-valued sequence X(k).
 2 
M  j  nk
X (k )   xn e  N 
;0  k  N  1
k 0
The above equation is the mathematical representation of the DFT. As the number of
computations involved in transforming a N point time domain signal into its corresponding
frequency domain signal was found to be N2 complex multiplications, an alternative algorithm
involving lesser number of computations is opted.
The time burden created by this large number of computations limits the use of DFT in
many applications. Tremendous efforts devoted to develop more efficient ways of computing
DFT resulted in the above explained Fast Fourier Transform algorithm. This mathematical
shortcut reduces the number of calculations the DFT requires drastically.
Radix-2 FFT:
The Decimation-in-time FFT algorithm is based on splitting (decimating) x(n) into
smaller sequences and finding X ( k ) from the DFTs of these decimated sequences.
Consider x(2n) be the even sample sequences and x(2n+1) be the odd sample sequence
derived from x(n). Both these individually result in (N/2)2multiplication’s, totally (N2/4)
computations.
Further dividing the sequence x(2n) into further 2 odd and even sequences would reduce
the computations.
 2 
 j 
 N 
WN is the twiddle factor which is defined as e

26
The above shown mathematical representation forms the basis of N point FFT and is called the
Butterfly Structure.

A complete eight-point radix-2 decimation-in-time FFT.

27
Shuffled Inputs

To perform the computations in place, however, the input sequence x(n) must be stored
(or accessed) in non-sequential order as seen in Figure below for N=8.

The shuffling of the input sequence that takes place is due to the successive decimations
of x(n). The ordering that results corresponds to a bit-reversed indexing of the original sequence.
In other words, if the index n is written in binary form, the order in which in the input sequence
must be accessed is found by reading the binary representation for n in reverse order

28
Another class of FFT algorithms may be derived by decimating the output sequence X(k)
into smaller and smaller subsequences. These algorithms are called Decimation-in-frequency
FFTs

A complete eight-point radix-2 decimation-in-frequency FFT

Program

clc;
clear all;
close all;
x=input('Enter the sequence:');
N=length(x);
X=fft(x,N);
disp('The result of fft is :'); X
y=ifft(X,N);
disp('The inverse fft is :'); y

Result:The discrete fourier transform of a given sequence is found using FFT

Input Sequence:

FFT output:

IFFT output:

29
Viva-voce:

1. Fast Fourier Transform


2. Computations required for DFT and FFT
3. Syntaxes of various Keywords used in the program

30
Program – 7
Power Spectrum of a given Signal
Date:

Aim: To plot the power spectrum of a given signal.


Requirements: Personal Computer with MATLAB software v 8.5
Theory:
The total or the average power in a signal is often not of as great an interest. We are most
often interested in the PSD or the Power Spectrum. We often want to see how the input power
has been redistributed by the channel and in this frequency-based redistribution of power where
most of the interesting information lies. The total area under the Power Spectrum or PSD is equal
to the total avg. power of the signal. The PSD is an even function of frequency.
This can be accomplished by finding the FFT of the sequence and then the result is
obtained by the formula
FFT{xn }
2 2
X (k )
P 
N N
The Wiener-Khinchine theorem states that for power signals (Energy = infinity and PAvg=finite)
Power Spectral Density (PSD)and the autocorrelation function of the signal form the fourier
transform pair.

Program
clc
clear all
close all
F1=input('enter the frequency of first signal in hz=') %F1=15Hz
F2=input('enter the frequency of second signal in hz=') %F1=30Hz
Fs=input('enter the sampling frequency in hz=') %Fs=100Hz
t=0:1/Fs:1;
x=2*sin(2*pi*F1*t)+3*sin(2*pi*F2*t);
Px1=abs(fft(x).^2);
Px2=abs(fft(xcorr(x)));
subplot(2,1,1);
plot(10*log10(Px1));
xlabel('Frequency in hz')
ylabel('magnitude in db')
title('PSD using Square magnitude method')
subplot(2,1,2)
plot(10*log10(Px2))
xlabel('Frequency in hz')
ylabel('magnitude in db')
title('PSD using autocorrelation method')

Waveforms/Graphs:

31
Fig 7.1:a) Input Signal b) PSD using FFT c) PSD using Wiener Khinchine relation

32
Result: Magnitude and Phase Spectrum of the given Signal has been calculated and
corresponding Waveforms/Graphs have been plotted.

Viva-Voce:

1. Define Power signal.


2. PSD
3. Syntaxes of various Keywords used in the program

33
Implementation of FIR filter for a given sequence

Theory:
A Finite Impulse Response (FIR) filter is a discrete linear time-invariant system whose
output is based on the weighted summation of a finite number of past inputs.
M
H ( z )   bk z k
k 0
The difference equation for such a system is described by the following:
M
y n    bk xn  k 
k 0
M is the Length of the Filter, and bk represents the filter coefficients.
These coefficients are generated by using FDS (Filter Design Software or Digital filter
design package). FIR – filter is a finite impulse response filter. Order of the filter should be
specified. Infinite response is truncated to get finite impulse response. Placing a window of finite
length does this. Types of windows available are Rectangular, Bartlett, Hamming, Hanning,
Blackmann, Kaiser window etc.
There are a number of standard windows functions which provide differing properties.
The following are the ones used most often:

(a) Rectangularwindow – the simplest window specified by saying:

w(n) =1 when 0≤n≤N-1 where N is the total length.

(b) BartlettWindow – In this case

w(n) = 2n/(N-1) if 0 ≤ n ≤ (N-1)/2 and,


w(n) = 2 – 2n/(N-1) if (N-1)/2 ≤ n ≤ N-1

(c) HanningWindow – In this case

w(n) = (½)[1 – cos({2πn}/{N-1})] if 0 ≤ n ≤ N – 1.

(d) HammingWindow – In this case

w(n) = 0.54 – 0.46cos({2πn}/{N-1}) if 0 ≤ n ≤ N – 1.

(e) Blackman Window – In this case

w(n) = 0.42 – 0.5cos({2πn}/{N-1}) + 0.08cos({4πn}/{N-1})


if 0 ≤ n ≤ N – 1.

34
Program – 8.1
Implementation of LP FIR filter for a given sequence
Date:

Aim: To design LP FIR filter using Hamming window technique and implement it for a given
sequence
Requirements: Personal Computer with MATLAB software v 8.5

Program
clc;
clear all;
close all;

% Taking inputs
fp = input('Enter Passband Frequency:');
fs = input('Enter Stopband Frequency:');
f = input('Enter Sampling Frequency:');
rp = input('Enter Passband ripple:');
rs = input('Enter Stopband ripple:');

% Normalisation
ws = 2*fs/f;
wp = 2*fp/f;

% For finding the filter Order


N = ((-20*log10(sqrt(rp*rs)))-13)/(14.6*((fs-fp)/f));
N = ceil (N);

% Filter Order must be even


if rem(N,2)~= 0
N1 = N;
N = N1-1;
else
N1 = N+1;
end

disp('Order of the filter is')


disp(N)

% Windowing Technique
y = hamming(N1);
wc = (wp+ws)/2;
b = fir1(N,wc,y)
[h,w] = freqz(b);

% Frequency Response

35
M = 20*log10(abs(h));
th = angle(h);

subplot(2,1,1)
plot(w/pi,M);
title('Frequency Response of Low Pass Filter');
xlabel('Normalised Frequency --->');
ylabel('Magnitude(dB)');
subplot(2,1,2)
plot(w/pi,th);
xlabel('Normalised Frequency --->');
ylabel('Phase(radians)');

%implementation of LP Hamming window FIR filter for a given sequence


t=0:0.01:4;
x=sin(4*pi*t)+rand(size(t));
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,1,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

Given Data

Enter Passband Frequency:1200


Enter Stopband Frequency:1700
Enter Sampling Frequency:8000
Enter Passband ripple:0.01
Enter Stopband ripple:0.02

36
Waveforms/Graphs:

Figure 8.1.1: i) Frequency response of LP FIR filter (Hamming)


ii) Input signal
iii)Filtered output
37
Result: Hence Lowpass FIR filter has been designed using Hamming window technique and is
implemented on a given signal. The corresponding plots are shown.

38
Program – 8.2
Implementation of HP FIR filter for a given sequence
Date:

Aim: To design HP FIR filter using Hanning window technique and implement it for a given
sequence
Requirements: Personal Computer with MATLAB software v 8.5

Program
clc;
clear all;
close all;

% Taking inputs
fs = input('Enter Stopband Frequency:');
fp = input('Enter Passband Frequency:');
f = input('Enter Sampling Frequency:');
rs = input('Enter Stopband ripple:');
rp = input('Enter Passband ripple:');

% Normalisation
ws = 2*fs/f;
wp = 2*fp/f;

% For finding the filter Order


N = ((-20*log10(sqrt(rp*rs)))-13)/(14.6*((fp-fs)/f));
N = ceil (N);

% Filter Order must be even


if rem(N,2)~= 0
N1 = N;
N = N1-1;
else
N1 = N+1;
end
disp('Order of the filter is')
disp(N)

% Windowing Technique
y = hann(N1);
wc = (wp+ws)/2;
b = fir1(N,wc,'high',y)
[h,w] = freqz(b);

% Frequency Response
M = 20*log10(abs(h));

39
th = angle(h);

subplot(2,1,1)
plot(w/pi,M);
title('Frequency Response of High Pass Filter');
xlabel('Normalised Frequency --->');
ylabel('Magnitude(dB)');
subplot(2,1,2)
plot(w/pi,th);
xlabel('Normalised Frequency --->');
ylabel('Phase(radians)');

%implementation of HP Hanning window FIR filter for a given sequence


t=0:0.01:4;
x=sin(4*pi*t)+sin(40*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,1,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

Given Data

Enter Stopband Frequency:1200


Enter Passband Frequency:1700
Enter Sampling Frequency:8000
Enter Stopband ripple:0.01
Enter Passband ripple:0.02

40
Waveforms/Graphs:

Figure 8.2.1: i) Frequency response of HP FIR filter (Hanning)


ii) Input signal
iii)Filtered output
41
Result: Hence Highpass FIR filter has been designed using Hanning window technique and is
implemented on a given signal. The corresponding plots are shown.

42
Program – 8.3
Implementation of BP FIR filter for a given sequence
Date:

Aim: To design BP FIR filter using Blackmann window technique and implement it for a given
sequence
Requirements: Personal Computer with MATLAB software v 8.5

Program
clc;
clear all;
close all;

% Taking inputs
fs1 = input('Enter Lower Stopband Frequency:');
fp1 = input('Enter Lower Passband Frequency:');
fp2 = input('Enter Higher Passband Frequency:');
fs2 = input('Enter Higher Stopband Frequency:');
f = input('Enter Sampling Frequency:');
rp = input('Enter Passband ripple:');
rs = input('Enter Stopband ripple:');

% Normalisation
ws1 = 2*fs1/f;
wp1 = 2*fp1/f;
ws2 = 2*fs2/f;
wp2 = 2*fp2/f;

% For finding the filter Order


TBW = min(abs(fp1-fs1), abs(fs2-fp2));
N = ((-20*log10(sqrt(rp*rs)))-13)/(14.6*(TBW/f));
N = ceil (N);

% Filter Order must be even


if rem(N,2)~= 0
N1 = N;
N = N1-1;
else
N1 = N+1;
end
disp('Order of the filter is')
disp(N)

% Windowing Technique
y = blackman(N1);
wc1 = wp1-TBW/(2*f);

43
wc2 = wp2+TBW/(2*f);
wc = [wc1 wc2];
b = fir1(N,wc,'bandpass',y)
[h,w] = freqz(b);

% Frequency Response
M = 20*log10(abs(h));
th = angle(h);

subplot(2,1,1)
plot(w/pi,M);
title('Frequency Response of Band Pass Filter');
xlabel('Normalised Frequency --->');
ylabel('Magnitude(dB)');
subplot(212)
plot(w/pi,th);
xlabel('Normalised Frequency --->');
ylabel('Phase');

%implementation of BP Blackmann window FIR filter for a given sequence


t=0:0.01:4;
x=sin(4*pi*t)+sin(40*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,1,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

Given Data

Enter Lower Stopband Frequency:1200


Enter Lower Passband Frequency:1700
Enter Higher Passband Frequency:2200
Enter Higher Stopband Frequency:2700
Enter Sampling Frequency:8000
Enter Passband ripple:0.01
Enter Stopband ripple:0.02

44
Waveforms/Graphs:

Figure 8.3.1: i) Frequency response of BP FIR filter (Blackmann)


ii) Input signal
iii)Filtered output
45
Result: Hence Bandpass FIR filter has been designed using Blackmann window technique and is
implemented on a given signal. The corresponding plots are shown.

46
Program – 8.4
Implementation of BS FIR filter for a given sequence
Date:

Aim: To design BS FIR filter using Kaiser window technique and implement it for a given
sequence
Requirements: Personal Computer with MATLAB software v 8.5

Program
clc;
clear all;
close all;

% Taking inputs
fp1 = input('Enter Lower Passband Frequency:');
fs1 = input('Enter Lower Stopband Frequency:');
fs2 = input('Enter Higher Stopband Frequency:');
fp2 = input('Enter Higher Passband Frequency:');
f = input('Enter Sampling Frequency:');
rs = input('Enter Stopband ripple:');
rp = input('Enter Passband ripple:');

% Normalisation
ws1 = 2*fs1/f;
wp1 = 2*fp1/f;
ws2 = 2*fs2/f;
wp2 = 2*fp2/f;

% For finding the filter Order


TBW = min(abs(fs1-fp1), abs(fp2-fs2));
N = ((-20*log10(sqrt(rp*rs)))-13)/(14.6*(TBW/f));
N = ceil (N);

% Filter Order must be even


if rem(N,2)~= 0
N1 = N;
N = N1-1;
else
N1 = N+1;
end
disp('Order of the filter is')
disp(N)

% Windowing Technique
y = kaiser(N1,0.5);
wc1 = ws1-TBW/(f);

47
wc2 = ws2+TBW/(f);
wc = [wc1 wc2];
b = fir1(N,wc,'stop',y)
[h,w] = freqz(b);

% Frequency Response
M = 20*log10(abs(h));
th = angle(h);

subplot(2,1,1)
plot(w/pi,M);
title('Frequency Response of Band Stop Filter');
xlabel('Normalised Frequency --->');
ylabel('Magnitude(dB)');
subplot(2,1,2)
plot(w/pi,th);
xlabel('Normalised Frequency --->');
ylabel('Phase');

%implementation of BSKaiser window FIR filter for a given sequence


t=0:0.01:4;
x=sin(4*pi*t)+sin(40*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,1,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

Given Data

Enter Lower Passband Frequency:1200


Enter Lower Stopband Frequency:1700
Enter Higher Stopband Frequency:2200
Enter Higher Passband Frequency:2700
Enter Sampling Frequency:8000
Enter Stopband ripple:0.01
Enter Passband ripple:0.02

48
Waveforms/Graphs:

Figure 8.4.1: i) Frequency response of BS FIR filter (Kaiser)


ii) Input signal
iii)Filtered output
49
Result: Hence Bandstop FIR filter has been designed using Kaiser window technique and is
implemented on a given signal. The corresponding plots are shown.

Viva-Voce:
1. FIR filter.
2. Window techniques
3. Filter design and response
4. Syntaxes of various Keywords used in the program

50
Implementation of IIR filter for a given sequence

Theory:
The three most commonly used analog low-pass filters are the Butterworth,
and Chebyshev filters. These filters are described below.
Butterworth Filter:
Alow-pass Butterworth filter is an all-pole filter with a magnitude response given
by:
1
H a ( j )  1
   2N  2
1    

  c  
where  c is the 3-dB cut-off frequency and N is the Filter order.
 The magnitude response has a maximally flat pass and stop bands.

FIGURE 1. THE MAGNITUDE RESPONSE FOR BUTTERWORTH FILTERS


OF ORDERS N = 2.4, 8.

Chebyshev Type –I Filter


The Chebyshev type - I low-pass filter has a magnitude response given by:
1
H a ( j )  1
 2   2

1   2
C 
N 

  c 
51
where  c is the 3-dB cut-off frequency and  is a constant.
Chebyshev filters are defined in terms of the Chebyshev polynomial of the I kind
of Nth order is given by:

C N ( x)  cos( N cos1 x) for x  1


C N ( x)  cosh(N cosh 1 x) for x  1

 The magnitude response has equiripple pass band and maximally flat stop
band

FIGURE 2. THE MAGNITUDE RESPONSE FOR CHEBYSHEV TYPE-1


FILTER FOR ORDERS N=5 AND N=6
Chebyshev Type –II Filter
The Chebyshev type – II low-pass filter has a magnitude response given by

H a ( j )  1
   s  
2 2

 CN   p   
1   2   
  C   s   
  N    
  
where N is the order of the filter,  s is the passband edge frequency,  p is the
stopband edge frequency, and  is the parameter that controls the stopband ripple
amplitude.

52
 The magnitude response has maximally flat pass band and equiripple stop
band

FIGURE 3. THE MAGNITUDE RESPONSE FOR CHEBYSHEV TYPE-2


FILTER FOR ORDERS N=5 AND N=6

53
Program – 9.1
Implementation of LP IIR filter for a given sequence
Date:

Aim: To design
i)Butterworth Lowpass IIR filter and implement it for a given sequence
ii)Chebyshev-I Lowpass IIR filter and implement it for a given sequence
iii) Chebyshev-II Lowpass IIR filter and implement it for a given sequence
Requirements: Personal Computer with MATLAB software v 8.5

Program

%BUTTERWORTH LP FILTER
clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Finding the filter order


[n,wc]=buttord(wp,ws,rp,rs);

%Finding the filter coefficients


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

%Finding the frequency response


[h,w]=freqz(b,a);

%plotting Magnitude and Phase responses


mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
ylabel('magnitude');
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);

54
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of LP BUTTERWORTH IIR filter for a given sequence


t=0:0.01:5;
x=sin(400*pi*t)+rand(size(t));
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

%CHEBYSHEV-I LP FILTER
clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Finding the filter order


[n,wc]=cheb1ord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=cheby1(n,rp,wc);

%Finding the frequency response


[h,w]=freqz(b,a);

%plotting Magnitude and Phase responses


mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
55
xlabel('normalised frequency');
ylabel('magnitude');
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of LP Chebyshev-I IIR filter for a given sequence


t=0:0.01:4;
x=sin(4*pi*t)+rand(size(t));
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

%CHEBYSHEV-II LP FILTER

clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Finding the filter order


[n,wc]=cheb2ord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=cheby2(n,rs,wc);

56
%Finding the frequency response
[h,w]=freqz(b,a);

%plotting Magnitude and Phase responses


mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
ylabel('magnitude');
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of LP Chebyshev-II IIR filter for a given sequence


t=0:0.01:4;
x=sin(4*pi*t)+rand(size(t));
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

Given Data:

passband ripple:3dB
stopband ripple:60dB
passband frequency:40Hz
stopband frequency:150Hz
sampling frequency:500Hz

57
Waveforms/Graphs:

Figure 9.1.1: i) Frequency response of LP IIR Butterworth filter


ii) Input signal
iii)Filtered output
58
Figure 9.1..2: i) Frequency response of LP IIR Chebyshev-I filter
ii) Input signal
iii)Filtered output

59
Figure 9.1.3: i) Frequency response of LP IIR Chebyshev-II filter
ii) Input signal
iii)Filtered output

60
Result: Hence Lowpass IIR filter has been designed using Butterworth, Chebyshev-I and
Chebyshev-II approximation s and are implemented on a given signal. The corresponding plots
are shown.

61
Program – 9.2
Implementation of HP IIR filter for a given sequence
Date:

Aim: To design
i)Butterworth Highpass IIR filter and implement it for a given sequence
ii)Chebyshev-I Highpass IIR filter and implement it for a given sequence
iii) Chebyshev-II Highpass IIR filter and implement it for a given sequence
Requirements: Personal Computer with MATLAB software v 8.5

Program

%BUTTERWORTH HP FILTER
clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Finding the filter order


[n,wc]=buttord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=butter(n,wc,'high');

%Finding the frequency response


[h,w]=freqz(b,a);

%plotting Magnitude and Phase responses


mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
ylabel('magnitude');
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');

62
ylabel('Phase in radians');

%implementation of HP BUTTERWORTH IIR filter for a given sequence


t=0:0.01:2;
x=sin(4*pi*t)+sin(400*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

%CHEBYSHEV-I HP FILTER
clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Finding the filter order


[n,wc]=cheb1ord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=cheby1(n,rp,wc,'high');

%Finding the frequency response


[h,w]=freqz(b,a);

%plotting Magnitude and Phase responses


mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
63
ylabel('magnitude');
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of HP CHEBYSHEV-I IIR filter for a given sequence


t=0:0.01:2;
x=sin(4*pi*t)+sin(400*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

%CHEBYSHEV-II HP FILTER
clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Finding the filter order


[n,wc]=cheb2ord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=cheby2(n,rs,wc,'high');

%Finding the frequency response


[h,w]=freqz(b,a);
64
%plotting Magnitude and Phase responses
mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
ylabel('magnitude');
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of HP CHEBYSHEV-II IIR filter for a given sequence


t=0:0.01:2;
x=sin(4*pi*t)+sin(400*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

Given Data:

passband ripple:3dB
stopband ripple:60dB
passband frequency:150Hz
stopband frequency:40Hz
sampling frequency:500Hz

65
Waveforms/Graphs:

Figure 9.2.1: i) Frequency response of HP IIR Butterworth filter


ii) Input signal
iii)Filtered output
66
Figure 9.2.2: i) Frequency response of HP IIR Chebyshev-Ifilter
ii) Input signal
iii)Filtered output

67
Figure 9.2.3: i) Frequency response of HP IIR Chebyshev-II filter
ii) Input signal
iii)Filtered output

68
Result: Hence Highpass IIR filter has been designed using Butterworth, Chebyshev-I and
Chebyshev-II approximations and are implemented on a given signal. The corresponding plots
are shown.

69
Program – 9.3
Implementation of BP IIR filter for a given sequence
Date:

Aim: To design
i)Butterworth Bandpass IIR filter and implement it for a given sequence
ii)Chebyshev-I Bandpass IIR filter and implement it for a given sequence
iii) Chebyshev-II Bandpass IIR filter and implement it for a given sequence
Requirements: Personal Computer with MATLAB software v 8.5

Program

%BUTTERWORTH BP FILTER
clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Defining the specific passband


w=[wp,ws];

%Finding the filter order


n=buttord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=butter(n,w,'bandpass');

%Finding the frequency response


[h,w]=freqz(b,a);

%plotting Magnitude and Phase responses


mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
ylabel('magnitude');

70
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of BP BUTTERWORTH IIR filter for a given sequence


t=0:0.01:2;
x=sin(4*pi*t)+sin(400*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

%CHEBYSHEV-I BP FILTER
clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Defining the specific passband


w=[wp,ws];

%Finding the filter order


n=cheb1ord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=cheby1(n,rp,w,’bandpass’);

%Finding the frequency response


71
[h,w]=freqz(b,a);
%plotting Magnitude and Phase responses
mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
ylabel('magnitude');
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of BP Chebyshev-I IIR filter for a given sequence


t=0:0.01:2;
x=sin(4*pi*t)+sin(400*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

%CHEBYSHEV-II LP FILTER

clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Defining the specific passband


72
w=[wp,ws];

%Finding the filter order


n=cheb2ord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=cheby2(n,rs,w,’bandpass’);

%Finding the frequency response


[h,w]=freqz(b,a);

%plotting Magnitude and Phase responses


mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
ylabel('magnitude');
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of BP Chebyshev-II IIR filter for a given sequence


t=0:0.01:2;
x=sin(4*pi*t)+sin(400*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

Given Data:

passband ripple:3dB
stopband ripple:60dB
passband frequency:40Hz
stopband frequency:150Hz
sampling frequency:500Hz

73
Waveforms/Graphs:

Figure 9.3.1: i) Frequency response of BP IIR Butterworth filter


ii) Input signal
iii)Filtered output
74
Figure 9.3.2: i) Frequency response of BP IIR Chebyshev-I filter
ii) Input signal
iii)Filtered output

75
Figure 9.3.3: i) Frequency response of BP IIR Chebyshev-II filter
ii) Input signal
iii)Filtered output

76
Result: Hence Bandpass IIR filter has been designed using Butterworth, Chebyshev-I and
Chebyshev-II approximation s and are implemented on a given signal. The corresponding plots
are shown.

77
Program – 9.4
Implementation of BS IIR filter for a given sequence
Date:

Aim: To design
i)Butterworth Bandstop IIR filter and implement it for a given sequence
ii)Chebyshev-I Bandstop IIR filter and implement it for a given sequence
iii) Chebyshev-II Bandstop IIR filter and implement it for a given sequence
Requirements: Personal Computer with MATLAB software v 8.5

Program

%BUTTERWORTH BSFILTER
clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Defining specific stopband


w=[wp,ws];

%Finding the filter order


[n,wc]=buttord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=butter(n,w,'stop');

%Finding the frequency response


[h,w]=freqz(b,a);

%plotting Magnitude and Phase responses


mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
ylabel('magnitude');
an=angle(h);

78
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of BS BUTTERWORTH IIR filter for a given sequence


t=0:0.01:2;
x=sin(4*pi*t)+sin(400*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

%CHEBYSHEV-I BS FILTER
clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Defining specific stopband


w=[wp,ws];

%Finding the filter order


[n,wc]=cheb1ord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=cheby1(n,rp,w,'stop');

%Finding the frequency response


[h,w]=freqz(b,a);
79
%plotting Magnitude and Phase responses
mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
ylabel('magnitude');
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of BSCHEBYSHEV-I IIR filter for a given sequence


t=0:0.01:2;
x=sin(4*pi*t)+sin(400*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

%CHEBYSHEV-II BS FILTER
clc;
close all;
clear all;

%Filter Specifications
rp=input('enter passband ripple');
rs=input('enter stopband ripple');
fp=input('enter passband frequency');
fs=input('enter stopband frequency');
F=input('enter sampling frequency');

%Normalization of frequencies
wp=2*fp/F;
ws=2*fs/F;

%Defining specific stopband


w=[wp,ws];
80
%Finding the filter order
[n,wc]=cheb2ord(wp,ws,rp,rs);

%Finding the filter coefficients


[b,a]=cheby2(n,rs,w,'stop');

%Finding the frequency response


[h,w]=freqz(b,a);

%plotting Magnitude and Phase responses


mag=20*log10(abs(h));
subplot(2,1,1);
plot(w/pi,mag);
xlabel('normalised frequency');
ylabel('magnitude');
an=angle(h);
subplot(2,1,2);
plot(w/pi,an);
xlabel('normalised frequency');
ylabel('Phase in radians');

%implementation of BSCHEBYSHEV-II IIR filter for a given sequence


t=0:0.01:2;
x=sin(4*pi*t)+sin(400*pi*t);
figure,
subplot(2,1,1);
plot(t,x);
xlabel('t--->');
ylabel('Amplitude--->');
title('Input signal');
result=filter(b,a,x);
subplot(2,1,2);
plot(t,result);
xlabel('t--->');
ylabel('Amplitude--->');
title('Filtered signal');

Given Data:

passband ripple:3dB
stopband ripple:60dB
passband frequency:150Hz
stopband frequency:40Hz
sampling frequency:500Hz

81
Waveforms/Graphs:

Figure 9.4.1: i) Frequency response of BS IIR Butterworth filter


ii) Input signal
iii)Filtered output

82
Figure 9.4.2: i) Frequency response of BS IIR Chebyshev-Ifilter
ii) Input signal
iii)Filtered output

83
Figure 9.4.3: i) Frequency response of BS IIR Chebyshev-II filter
ii) Input signal
iii)Filtered output

84
Result: Hence Bandstop IIR filter has been designed using Butterworth, Chebyshev-I and
Chebyshev-II approximations and are implemented on a given signal. The corresponding plots
are shown.

Viva-Voce:
1. IIR filter.
2. Butterworth, Chebyshev type1&2 approximation
3. Filter design
4. Syntaxes of various Keywords used in the program

85
Program – 10
Generation of Narrowband signal through filtering
Date:

Aim: To generate a narrowband signal through filtering

Requirements: Personal Computer with MATLAB software v 8.5

Theory:

Narrowband communication uses a narrow bandwidth.

 Narrowband signals are used in a slower form of communication where mainly voice or
slow data streams have to be transmitted
 Narrowband signals usually have a far greater range of reception as narrower filters can
be used and therefore cancel out unwanted wideband noise. The transmitted energy also
concentrates on a smaller portion of the spectrum.
 Common uses are FM radio, AM radio, satellite downlinks, morse code (CW), GPS
signals and NOAA weather transmissions.
For generating narrowband signals, we consider a place pole pair on unit circle giving rise to the
transfer function
1 z 2
H ( z)  
( z  e jT )( z  e  jT ) (1  2 cos(T ) z 1  z 2 )

Rewriting as the difference equation we get


y (n)  2 cos(T ). y (n  1)  y (n  2)  x(n  2)
This will oscillate at fixed frequency ω with x(n-2) = 0 or x(n) being an impulse signal.
 2f 
cos(T )  cos o  where fsis the sampling frequency, fois the desired oscillating
,
 fs 
frequency
Let fo=300Hz and fs=1/T=8000Hz

86
Program

% Clearing and Closing Commands

clc; % To clear Command Window


clear all; % To clear the workspace
close all; % To close the previous Waveforms/Graphs if any

%filtering
x=[1 zeros(1,200)];
num=[0 0 1];
den=[1 -1.9447,1];
z=filter(num,den,x)
subplot(2,1,1);
plot(z);
xlabel('Time--->');
ylabel('Amplitude--->');
title('Narrowband signal generation');
s=fft(z)
subplot(2,1,2);
plot(abs(s));
xlabel('Frequency--->');
ylabel('Magnitude--->');
title('Narrowband signal spectrum');

87
Waveforms/Graphs:

Fig 10.1: Narrowband signal generation through filtering

Result: Narrowband signal generation through filtering is performed and Waveforms/Graphs


have been plotted.

Viva-voce:
1. Direct form realization of IIR filter.
2. Narrowband Vs Broadband signals and their applications
3. Syntaxes of various Keywords used in the program

88
Program – 11

Generation of DTMF signals

Date:

Aim: To generate DTMF signal tones.

Requirements: Personal Computer with MATLAB software v 8.5

Theory
DTMF stands for Dual-Tone Multi-Frequency. The DTMF is a popular signaling method
between telephones and switching centers. This method is also used for signaling between the
Telephone network and computer networks. The DTMF signals are transmitted over a telephone
line and uses speech frequency signals. These signals are the superposition of two sine waves
with different frequencies.
When we press the buttons on the keypad, a connection is made that generates two tones
at the same time. A "Row" tone and a "Column" tone. These two tones identify the key you
pressed to any equipment you are controlling. If the keypad is on your phone, the telephone
company's "Central Office" equipment knows what numbers you are dialing by these tones, and
will switch your call accordingly. If you are using a DTMF keypad to remotely control
equipment, the tones can identify what unit you want to control, as well as which unique function
you want it to perform.
A DTMF signal consists of the sum of two sinusoids - or tones - with frequencies taken
from two mutually exclusive groups. These frequencies were chosen to prevent any harmonics
from being incorrectly detected by the receiver as some other DTMF frequency. Each pair of
tones contains one frequency of the low group (697 Hz, 770 Hz, 852 Hz, 941 Hz) and one
frequency of the high group (1209 Hz, 1336 Hz, 1477Hz) and represents a unique symbol. The
frequencies allocated to the push-buttons of the telephone pad are shown below:

Program

89
clc;
clear all;
close all;

number=input('enter a phone number with no spaces:','s');


fs=8192;
T=0.5;
x=2*pi*[697 770 852 941];
y=2*pi*[1209 1336 1477 1602];
t=[0:1/fs:T]';
tx=[sin(x(1)*t),sin(x(2)*t),sin(x(3)*t),sin(x(4)*t)]/2;
ty=[sin(y(1)*t),sin(y(2)*t),sin(y(3)*t),sin(y(4)*t)]/2;
for k=1:length(number)

switch number(k)

case'1'
tone=tx(:,1)+ty(:,1);
sound(tone);

case'2'
tone=tx(:,1)+ty(:,2);
sound(tone);

case'3'
tone=tx(:,1)+ty(:,3);
sound(tone);

case'A'
tone=tx(:,1)+ty(:,4);
sound(tone);

case'4'
tone=tx(:,2)+ty(:,1);
sound(tone);

case'5'
tone=tx(:,2)+ty(:,2);
sound(tone);

case'6'
tone=tx(:,2)+ty(:,3);
sound(tone);

case'B'
tone=tx(:,2)+ty(:,4);
sound(tone);

90
case'7'
tone=tx(:,3)+ty(:,1);
sound(tone);

case'8'
tone=tx(:,3)+ty(:,2);
sound(tone);

case'9'
tone=tx(:,3)+ty(:,3);
sound(tone);

case'C'
tone=tx(:,3)+ty(:,4);
sound(tone);

case'#'
tone=tx(:,4)+ty(:,1);
sound(tone);

case'0'
tone=tx(:,4)+ty(:,2);
sound(tone);

case'*'
tone=tx(:,4)+ty(:,3);
sound(tone);

case'D'
tone=tx(:,4)+ty(:,4);
sound(tone);

otherwise
disp('invalid number');
end;
pause(0.75);
end;

Result: DTMF signal tones are generated.

Viva-voce:
1. DTMF signal frequencies
2. Syntaxes of various Keywords used in the program

91
Multirate Sampling

Theory

Multirate simply means "multiple sampling rates". A multirate DSP system uses multiple
sampling rates within the system. Whenever a signal at one rate has to be used by a system that
expects a different rate, the rate has to be increased or decreased, and some processing is
required to do so. Therefore "Multirate DSP" really refers to the art or science
of changing sampling rates.

The most immediate reason is when we need to pass data between two systems which use
incompatible sampling rates. For example, professional audio systems use 48 kHz rate, but
consumer CD players use 44.1 kHz; when audio professionals transfer their recorded music to
CDs, they need to do a rate conversion.

But the most common reason is that multirate DSP can greatly increase processing
efficiency (even by orders of magnitude!), which reduces DSP system cost.

The two basic operations in a multirate system are decreasing (decimation) and increasing
(interpolation) the sampling-rate of a signal. Multirate systems are sometimes used for sampling-
rate conversion, which involves both decimation and interpolation.

Decimation

For decreasing sampling rate downsampling alone may cause aliasing, therefore, it is desirable to
introduce an anti-aliasing filter Hd (ωx)

Interpolation

For increasing sampling rate making use upsamling alone may serve the purpose but due to
compression of spectrum of the desired signal the resultant signal spectra contains repititions of
the original spectra called images. Therefore, it is desirable to introduce an anti-aliasing filter
Hu(ωy)

92
Multirate sampling by rational factor

For variation in sampling rate by a rational factor there is a need for using both interpolator and
decimator in cascade.

93
Program – 12

Implementation of Decimation Process

Date:

Aim: To implement Decimation process on a given sequence.

Requirements: Personal Computer with MATLAB software v 8.5

Program

clc
clear all
close all

D=input('Enter the factor by which the signal is to be decimated:');

%Illustration of Downsampling
x=[1 2 3 4 4 3 2 1];
xd=downsample(x,D);
subplot(2,1,1);
stem(x);
xlabel('n-->');
ylabel('Amplitude');
title('Input signal');
subplot(2,1,2);
stem(xd);
xlabel('n-->');
ylabel('Amplitude');
title(['Downsampled version of input signal by a factor ',num2str(D)]);

%input signal for decimator


t=0:0.00025:1;
x=sin(2*pi*30*t)+sin(2*pi*60*t);

%decimation
y=decimate(x, D,'fir');

%view the original and decimated signals


figure,subplot(2,1,1)
stem(x(1:60));
title('original signal');
subplot(2,1,2)
stem(y(1:60/D))
title(['decimated signal by a factor',num2str(D)]);
94
Waveforms/Graphs:

Fig 12.1: a) Input signal for decimator b) Decimated signal

Result: Decimated signal is obtained and is plotted.

95
Program – 13

Implementation of Interpolation Process

Date:

Aim: To implement Interpolation process on a given sequence.

Requirements: Personal Computer with MATLAB software v 8.5

Program

clc
clear all
close all

I=input('Enter the factor by which the signal is to be interpolated:');

%Illustration of upsampling
x=[1 2 3 4 4 3 2 1];
xu=upsample(x,I);
subplot(2,1,1);
stem(x);
xlabel('n-->');;
ylabel('Amplitude');
title('Input signal');
subplot(2,1,2);
stem(xu);
xlabel('n-->');
ylabel('Amplitude');
title(['Upsampled version of input signal by a factor ',num2str(I)]);

%input signal for decimator


t=0:0.00025:1;
x=sin(2*pi*30*t)+sin(2*pi*60*t);

%Interpolation
y=interp(x, I);

%view the original and Interpolated signals


figure,subplot(2,1,1)
stem(x(1:60));
title('original signal')
subplot(2,1,2)
stem(y(1:60*I))
title(['Interpolated signal by a factor ' ,num2str(I)]);
96
Waveforms/Graphs:

Fig 13.1: a) Input signal for Interpolator b) Interpolated signal

Result: Interpolated signal is obtained and is plotted.


97
Program – 14

Implementation of I/D sampling rate converters

Date:

Aim: To implement sampling rate conversion by a rational factor on a given sequence.

Requirements: Personal Computer with MATLAB software v 8.5

Program

clc
clear all
close all

t=0:0.00025:1;
x=sin(2*pi*30*t)+sin(2*pi*60*t);

%Sampling rate conversion by a rational factor I/D


I=input('Enter the integer factor ‘I’:');
D=input('Enter the integer factor ‘D’:');

y=resample(x, I,D);

%view the original and sample rate converted signals


subplot(2,1,1)
stem(x(1:60));
title('original signal')
subplot(2,1,2)
stem(y(1:60*I/D))
title(['Sampling rate converted signal by a factor ' ,num2str(I),'/',num2str(D)]);

98
Waveforms/Graphs:

Fig 14.1: a) Input signal b) Sampling rate converter output

Result: Hence the sampling rate of the signal has been changed by a rational factor and the
corresponding waveform is plotted.
99
Viva-voce:
1. Upsampling and Downsampling
2. Anti-imaging and anti-aliasing filters
3. Interpolation and Decimation
4. Multirate sampling
5. Syntaxes of various Keywords used in the program

100
Program – 15
Impulse response of first order and second order systems
Date:

Aim: To Calculate Unit Impulse Response (Unit Sample) of the given LTI system.
Requirements: Personal Computer with MATLAB software v 8.5
Theory:

The response of an LTI system for any input signal is obtained by performing the convolution
between the input and the impulse response of the signal

Program

clc;
clear all;
close all;

% Given 1st order system


%y(n)=(3/8)y(n-1)+x(n)

num = input ('type the numerator vector for 1st order system ');
den = input ('type the denominator vector for 1st order system ');
N = input ('type the desired length of the output sequence N ');
n = 0 : N-1;
h=impz(num,den);
disp('The impulse response of 1st order LTI system is'); disp(h(1:N));
figure(1);
stem(n,h(1:N))
xlabel ('time index n');
ylabel ('Amplitude ');
title ('Impulse Response of 1st order LTI system');

% Given 2nd order system


%y(n)=(3/8)y(n-1)+(2/3)y(n-2)+x(n)+(1/4)x(n-1)

a = input ('type the numerator vector for 2nd order system ');
b = input ('type the denominator vector for 2nd order system ');
M = input ('type the desired length of the output sequence M ');
m = 0 : M-1;
r=impz(a,b);
disp('The impulse response of 2nd order LTI system is'); disp(r(1:M));
figure(2);
stem(m,r(1:M))
xlabel ('time index n');
ylabel ('Amplitude ');
title ('Impulse Response of 2nd order LTI system');
101
Waveforms/Graphs:

Fig 15.1: a) Impulse response of First order system


b) Impulse response of Second order system
102
Result: Thus the Impulse response of given first and second order systems is computed and
plotted.

Viva-voce:

1. Define Impulse response.


2. Transfer Function
3. Order of the system
4. Syntaxes of various Keywords used in the program

103
Introduction to Digital Signal Processors

A Digital Signal Processor (DSP) is an integrated circuit designed for high-speed data
manipulations, and is used in audio, communications, image manipulation, and other data-
acquisition and data-control applications.

Digital signals are those that are transmitted within or between computers, in which
information is represented by discrete states – for example, high voltages and low voltages –
rather than by continuously variable levels in a continuous stream, as in an analog signal.

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.

DSP Chip
A DSP chip can contain many hardware elements; some of the more common ones are
listed below:

110
5. 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.

6. 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.

7. 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.

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.

A/D and D/A Converters:


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 0sand 1s. Digital-to-analog converters (DACs) perform the
reverse process; they accept digital data and convert it to a continuous analog signal.

Ports:
Communication ports are necessary for a DSP system. Raw information is received and
processed; then that information is transmitted to the outside world through these ports. For
example, a 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.

Why Convert From Analog to Digital?


Some applications require analog designs, and some require digital designs. To process
signals digitally, they must be converted from analog to digital numbers. After a signal is
processed, it is then often converted back to analog form. Considering the overhead, digital
processing must offer some clear advantages that include:
i) Programmability
ii) Stability
iii) Repeatability
iv) Special Applications

111
 Programmability:
A single piece of digital DSP hardware can perform many functions. For example, a
multimedia PC can play music and also function as a word processor if it is loaded with suitable
programs. This ability to use the same hardware for many functions provides important
flexibility. You can implement any new function you think of, as long as you can program it.

1) Upgradability
Once you have designed and implemented your system, you may want to upgrade
or add new functions. Perhaps you would like to adapt your system to a new
environment. With a digital system, this means modifying your code. With an
analog system, this could involve obtaining and soldering in new components, or
even a complete redesign.
2) Flexibility
A single DSP board can be made to perform many functions by simply loading
new programs into it. In our demonstrations, we are using the same DSK board as
a tone generator and as a low-pass filter by simply loading it with different
software. This flexibility reduces design time and complexity. With analog
circuits, a new circuit has to be designed for each new function.

 Stability:
The stability of analog circuits depends upon several factors. Analog circuits are affected
by temperature and aging, among other things. Also, two analog systems using the same
design and components may differ in performance.

i) Temperature
Analog components such as resistors, capacitors, diodes, and operational
amplifiers are affected by temperature, humidity, and aging. A temperature-
sensitive analog circuit may perform quite differently in the UK than in Egypt,
where the temperatures are different. This could prove disastrous for a company

112
that sells its products worldwide. Digital circuits do not gradually change their
characteristics over time, temperature, or humidity. They either work or they
don’t work. In other words, digital circuits are repeatable as long as they are
designed with enough tolerance to operate properly over the range of expected
conditions.

ii) Ageing
The effects of component aging can be detrimental to analog circuits as
characteristics and performance change. These effects can sometimes be
anticipated, or their effect may not be critical. Analog designers must be aware of
these effects.

iii) Tolerances
Components such as resistors and capacitors have tolerances. If a
component tolerance is only accurate to within 10%, two apparently identical
analog circuits could perform differently enough to cause operational problems.
This can make design, manufacturing, and support expensive.

 Digital Repeatability:
A properly designed digital circuit will produce the same result every time, in
addition to being identical from unit to unit. If the same multiplication is performed on
500 computers, all 500 computers should produce the same result. Component tolerances,
aging, and temperature drifts also do not affect digital circuits nearly as much.

A properly designed digital circuit will produce the same results in the UK as in
Egypt, even when the temperatures are different. On the other hand, 500 analog circuits
could produce a range of results.

In digital circuitry, logical 1s and 0s are defined when an analog voltage is above
or below an analog voltage threshold. For a digital circuit to be repeatable, the analog
voltage which represents the logical 1s and 0sneeds to be sufficiently greater or less than
the threshold so as not to be affected by circuit variations or noise. The only concern is
that timing restrictions and maximum device ratings should not be exceeded. If proper
digital inputs are not maintained, the 1s and 0s can be corrupted, making a normally
repeatable digital circuit suddenly fail. On the other hand, analog circuit characteristics
will tend to gradually drift.

Digital accuracy is determined by the number of bits used and is guaranteed to


remain the same. With analog circuits, the number of bits is effectively infinite, but the
effects of noise, tolerances, and linearity can rapidly diminish performance.

 Special Functions and Performance:


Some special functions are best implemented digitally like Lossless Compression,
Adaptive Filters, Linear Phase Filters etc.

113
DSP Development

i) The Program
The DSP chip is a piece of hardware that cannot function without the intelligence of a
program. A program is a series of instructions that perform certain functions.

ii) Assemblers
Assemblers generate machine-level code from text instructions. Assemblers take our text
instructions and convert them into machine language. This relieves us of the burden of having to
remember binary instructions for DSP.

iii)High-Level Language
High-level languages are like assembly languages, but much friendlier. Assembly
languages have very basic instructions, such as multiply, add, and compare. High-level
languages have higher-level instructions, such as print, and repeat until equal to zero. Therefore,
it is easier to write programs in high-level languages. While it is easier to write in high-level
languages, assembly language can produce programs that are able to execute faster. For this
reason, both have their uses in DSPs. Sometimes it is necessary to write time-critical sections of
a program in assembly. A complete program may have sections of code in assembly and sections
in a high-level language. It is easy to combine both types of code into a single executable
program. Assembly and high-level programming languages make it possible to program DSPs to
perform a variety of functions.

114
iv)Simulators
DSP simulator is a software implementation of a DSP chip. A simulator typically runs on
a computer (PC or workstation), simulating almost all of the functionality of the DSP. They are
used to analyze the feasibility of designs before the designs are committed to hardware. They are
also very useful in determining whether or not a particular design will work.

v)Emulators
An emulator allows us to directly control and debug the results of instructions executing
on the DSP. Modern emulators do not replace the DSP chip on the board but exert their control
through a serial emulation scan path. Using these devices, it is possible to see all of the internal
changes in the device at each step. Developers can execute the instructions one step at a time,
check voltage levels for correct operation, and check each result in their own time. Emulators are
invaluable tools in development environments.

vi)Debugger
A debugger interface is used to display program execution information in a useable
format for the programmer. The data displayed in the debugger windows is essentially a
formatted data print of the contents of the DSP memory. This memory is simply loaded into the
PC using either an emulator or a communications link with the PC using appropriate software.

Debuggers consist of a user interface on the host PC computer, which can control and
modify the contents and execution of the chip. The user interface displays the contents of RAM,
registers, and the disassembly of the currently loaded program. The major advantage of
debuggers over simulators is that they operate in real-time, allowing the designer to assess the
performance of the system in a real-time environment.

vii)Development Cycle
After the feasibility of the design is established through simulation, program design can
begin. First, the software is designed. This stage determines the complexity and the modules of
the code. The modules of software are written and tested, and then the full system is put together
and tested. If everything works as required, the result is version 1.0 of the product on the market.
If it does not work as required, the process is repeated until it does. When new requirements and
improvements emerge as a result of user feedback, a new version is produced via the same
process.

115
About PL-DSPTMS320C6745 DSP Trainer

A Digital Signal Processor (DSP) is a specialized microprocessor with an architecture


optimized for the fast-operational needs of digital signal processing.

Based on VLSI technology

i) VLSI (very Large Scale Integration), is the process


of creating an Integrated Circuit by combining
thousands of transistors into a single chip.
ii) VLSI is the Platform that you use to implement
various domains such as DSP/networking/TCP IP,
etc.
iii) An electronic circuit might consist of
a CPU, ROM, RAM and other glue logic. VLSI
lets IC makers add these into one chip.
iv) Thus, a VLSI technique creates a system on chip
design.

PL-DSP Trainer board& Features

116
 Uses TMS-320C6745 DSP processor from Texas Instruments
 Exclusively designed for education in a user friendly format with onboard Noise
generator block, RTC block, LCD display, Speech processing block, etc.
 Supports Fixed and floating point operation.
 Embedded JTAG supported via USB.
 Onboard Peripherals

 For Easily interfacing with PC

 Facilitates to apply a 8-bit digital data

 Facilitates to indicate the 8 digital output

 Codec allows the DSP to transmit and receive


analog signals.
 Codec allows the DSP to transmit andreceive audio
signals.

 Keypad to generate DTMF tone as we press the buttons

117
o Manually generate a noise and can be added with
information signal
o Now this noisy signal can be removed/suppressed by
executing a filter program via a CODEC

118
TECHNICAL SPECIFICATIONS

TMS320C6745 PL-DSP Features

The PL-DSP features the TMS320C6745 PL-DSP, a 375 MHz device delivering up to
3648 million instructions per second (MIPs) and 2736 MFLOPS. This PL-DSP generation is
designed for applications that require high precision accuracy. The C6745 is based on the
TMS320C6000 DSP platform designed to needs of high-performing high-precision applications
such as pro-audio, medical and diagnostic. Other hardware features of the TMS320C6745 DSK
board include:

• Embedded JTAG supported via USB


• TLV320AIC23B programmable stereo codec
• Two 3.5mm audio jacks for microphone and speaker
• Expansion for port connector for plug-in modules
• Power supply: +5V, ±12V, GND
• 8 DIP switches for inputs
• 8 LED indication for output
• Provision for manual Reset
• 4x4 LED matrix
• Noise generator: White noise generator
: Amplitude 0 ~ 5Vpp
• 20*2 character LCD display.
• 2 No. 7 segment displays.
• RTC interface: I2C based RTC section
• Phone keypad: 0 to 9 digits and *, # characters

Software - Designers can readily target the TMS32C6745 PL-DSP through TI´s robust and
comprehensive Code Composer Studio v5™ PL-DSP development platform. The tools, which
run on Windows 98, Windows 2000, Windows XPand Windows 7, allow developers to
seamlessly manage projects of any complexity. Code Composer Studio features for the
TMS320C6745 PL-DSP includes:
 A complete Integrated Development Environment (IDE), an efficient optimizing C/C++
compiler assembler, linker, debugger, an a advance deditor with Code Maestro™
technology for faster code creation, data visualization, a profiler and a flexible project
manager
 DSP/BIOS™ real-time kernel
 Target error recovery software
 PL-DSP diagnostic tool
 "Plug-in" ability for third-party software for additional functionality

119
INTRODUCTION TO PL-DSP

The 6745 PL-DSP is a low-cost standalone development platform that enables users to
evaluate and develop applications for the TI C67XX DSP family. The DSP also serves as a
hardware reference design for the TMS320C6745 DSP. Schematics, logic equations and
application notes are available to ease hardware development and reduce time to market.

An on-board AIC23 codec allows the DSP to transmit and receive analog signals.SPI is
used for the codec control interface and McASP0 is used for data. Analog audio I/O is done
through two 3.5mm audio jacks that correspond to microphone input, and headphone output and
also line input, line 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.

The PL-DSP includes 8 LEDs, 8 DIP switches, 4*4 LED matrix, LCD and Seven
segment as a simple way to provide the user with interactive feedback. It also includes phone
keypad to study DTMF signals.

The PL-DSP includes Real time clock displayed on LCD to learn RTC and I2Cprotocol.
Code Composer communicates with the DSP through an embedded JTAG emulator with a USB
host interface.

HARDWARE SETTING

Connect the DSP- 320 to Your PC


 Connect the supplied USB cable to your PC or laptop.

 If you plan to connect a microphone, speaker, function generator, Digital Storage


Oscilloscope, or expansion card these must be plugged in properly before you connect
power to the PL-DSP board.

 JTAG cable must be connected to PC and kit before power ON the PL-DSP board. The
required driver for the emulator is automatically installed by computer.

 Connect the power supply to PL-DSP and switch it ON

120
INTRODUCTION TO CODE COMPOSER STUDIO

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

CODE COMPOSER FEATURES INCLUDE:

1. IDE
2. Debug IDE
3. Advanced watch windows
4. Integrated editor
5. File I/O, Probe Points, and graphical algorithm scope probes
6. Advanced graphical signal analysis
7. Interactive profiling
8. Automated testing and customization via scripting
9. Visual project management system
10. Compile in the background while editing and debugging
11. Multi-processor debugging
12. Help on the target DSP

PROCEDURE TO WORK ON CODE COMPOSER STUDIO:

 Double click on Code Composer Studio v5 icon which is on desktop.

 It will ask for selection of workspace opening Workspace Launcher

121
Click OK to open workspace window.

 It will open the workspace window as follows.

122
 To create a new project, go to Project→New CCS Project. Give name to project with
location to save project or use default location. Project type must be Executable.
Following window should appear. Device family is C6000.The Variant is C674x
Floating-point DSP and next to this you have to selectEVMC6747. In device
connection, select Texas Instruments XDS100v2USB Emulator. In project templates
and example section, you have to select an Empty project. As per shown in below
window.

Click on ‘Finish’ button. It starts creating an empty project.

 After finishing project creation. Empty Project will appear in left window of software, as
shown below

123
 To create a source file. Go to File → New → source file.

124
The new source file popup window should appear containing source folder, In Source file
section save the file name with extension .c, Select template as a Default C++ source
template as shown below:

Click on ‘Finish’ button. It will create a new source file.

 The next window will appear where you can write your code and save it. Or you can add
existing source file as shown below.

125
1. Now write your c program, as follows

2. For testing your connection with board, Double click on EVMC6747.ccxml so


following window will appear

126
3. Then click on Test connection in above window, so testing window will appear as
follows

If above window will appear with this message then your connection is correct, then you
can close this window and proceed further.

If following window appears, then connection may be incorrect. So power off PL-DSP
board and power it again, and do all processes again till scan- test will be succeeded.

127
4. After that build your program from Project → Build ALL. Following console window
will appear. It shows if any error present or not.

5. To debug the program, double click on Debug icon shown in above window or press
F11. Debug process starts as follows.

128
6. After few seconds, loading of program is completed that is shown in following
Window

7. Run program by clicking on RUN icon in above window, program will run
completely and give output in console window as follows.

129
8. After completion of the program, close debug session by clicking on disconnecticon
shown in above window. It will come to previous edit window

9. After completion of one program close project by right clicking on project name and
delete as shown below.

10. A dialog box appears as follows

11. Only click on OK. It will delete project from project explorer only. Don’t tick on
Delete project content on disk. It will delete all program from computer.

130
HOW TO IMPORT EXISTING PROJECT
12. Open CCStudio v5

13. Then Go to Project→ Import Existing CCS Eclipse Project as per shown
below.

131
14. Selection of Existing CCS Eclipse project window should appear. As shown
below.

15. Browse to select directory. Selected project will appear in discovered projects section.
Asshown below

132
16. Select and click on ok, in above window, so following window will appear

17. Click on ‘Finish’ button. Selected project will automatically import into project
explorer window present at the left side of software window. As shown below

133
For debugging and downloading follow the procedure from 11 to 14.
Viewing the Graphs/ Plots using CCS v5.0

8. Click on View menu and select Memory Browser


9. Type the variable, for example ‘y’, as shown in the figure below and click on ‘Go’

10. Now open Graph in Tools menu by selecting the required type of graph

134
11. Modify the graph properties according to the requirement and enter the start address of
the variable to be plotted and click OK

12. View the graph in the viewer

135
Program – 1

Generation of Sinusoidal waveform based on recursive difference equations


Date:

Aim: To generate Sinusoidal waveform based on recursive difference equations.


Software Requirements: Personal Computer with Code Composer Studio v 5.0,
Hardware Requirements: TMS320C6745 DSK
Theory
In Recursive Evaluation, we consider a place pole pair on unit circle giving rise to the
transfer function
1 z 2
H ( z)  
( z  e jT )( z  e  jT ) (1  2 cos(T ) z 1  z 2 )

Rewriting as the difference equation we get


y (n)  2 cos(T ). y (n  1)  y (n  2)  x(n  2)
This will oscillate at fixed frequency ω with x(n-2) = 0 or x(n) being an impulse signal.
 2f 
cos(T )  cos o  where fsis the sampling frequency, fois the desired oscillating
 fs  ,
frequency
Let fo=300Hz and fs=1/T=8000Hz

136
Program

//Sinusoidal signal generation using recursive equations

#include<stdio.h>
#include<math.h>
float y[200],x[200];
int n,m;
voidmain()
{
y[1]=1;
y[2]=1;
for (m=1;m<=150;m++)
{
if (m==3)
x[m]=1;
else
x[m]=0;
}
for (n=3;n<=150;n++)
{
y[n]=1.9447*y[n-1]-y[n-2];
}
}

137
Waveforms/Graphs:

Fig 1.1: Sinusoidal signal generation based on recursive evaluation


Result: Sinusoidal signal has been generated using recursive evaluation approach and the
corresponding Waveforms/Graphs have been plotted.

Viva-voce:
1. Solving difference equations
2. Graph Plotting using CCS
3. Syntaxes of various Keywords used in the program

138
Program –2
DFT / IDFT of given DT signal

Date:

Aim:a) To find Discrete Fourier Transform of a given signal/sequence


b) To recover the original sequence from DFT sequence using Inverse DFT

Software Requirements: Personal Computer with Code Composer Studio v 5.0,


Hardware Requirements: TMS320C6745 DSK

Program

//To Compute DFT

#include<stdio.h>
#include<math.h>
int N,x[15],i,k,n;
float w,yR,yI,XR[15],XI[15];
voidmain()
{
printf("Enter the length of the sequence:");
scanf("%d",&N);
w=(2*3.1415)/N;
printf("Enter the sequence:");
for(i=0;i<N;i++)
{
scanf("%d",&x[i]);
}
for (k=0;k<N;k++)
{
yR=0;
yI=0;
for(n=0;n<N;n++)
{
yR=yR+x[n]*(cos(w*n*k));
yI=yI+x[n]*(-sin(w*n*k));
}
XR[k]=yR;
XI[k]=yI;
}
printf("The result of DFT of the given sequence is X(k)=\n");
for (k=0;k<N;k++)
printf("%f+j%f\n",XR[k],XI[k]);
}

139
Input Sequence x(n)=[1 2 3 4 4 3 2 1]

DFT of the input sequence X(k) =

//To Compute IDFT

#include<stdio.h>
#include<math.h>
int N,i,k,n;
float w,yR,yI,XR[15],XI[15],yR1,yR2,yI1,yI2,xR[15],xI[15];
voidmain()
{
printf("Enter the length of the sequence:");
scanf("%d",&N);
w=(2*3.1415)/N;
printf("Enter the real part of complex coefficient sequence:");
for(i=0;i<N;i++)
{
scanf("%f",&XR[i]);
}
printf("Enter the imaginary part of complex coefficient
sequence:");
for(i=0;i<N;i++)
{
scanf("%f",&XI[i]);
}
for (n=0;n<N;n++)
{
yR=0;
140
yI=0;
for(k=0;k<N;k++)
{
yR1=XR[k]*(cos(w*n*k));
yR2=-XI[k]*(sin(w*n*k));
yR=yR+yR1+yR2;
yI1=XI[k]*(cos(w*n*k));
yI2=XR[k]*(sin(w*n*k));
yI=yI+yI1+yI2;
}
xR[n]=yR/N;
xI[n]=yI/N;
}
printf("The result of IDFT of the given complex coefficient
sequence is x(n)=\n");
for (n=0;n<N;n++)
printf("%f+j%f\n",xR[n],xI[n]);
}

Input Sequence x(n)=


[ 20, -5.8284 - 2.4142i , 0, -0.1716 - 0.4142i, 0, -0.1716 + 0.4142i, 0, -5.8284 + 2.4142i]

DFT of the input sequence X(k) =

Result:Hence DFT and IDFT of a sequence are found.

141
Viva-Voce:
1. Mathematical expressions to find DFT / IDFT
2. Applications of DFT
3. Syntaxes of various Keywords used in the program

142
Program – 3
Frequency response of a second order system
Date:
Aim: To plot the frequency response of a second order system.
Software Requirements: Personal Computer with Code Composer Studio v 5.0,
Hardware Requirements: TMS320C6745 DSK
Program :
#include <stdio.h>
#include <math.h>
int i,n;
float x[10],y[10];
void main()
{
for(i=-2;i<=9;i++)
{
y[i]=0;
x[i]=0;
}
x[0]=1;
for(n=0;n<=9;n++)
{
y[n]=0.375*y[n-1]+0.667*y[n-2]+x[n]+0.25*x[n-1];
}
printf("The impulse response of the given second order system is:");
for(n=0;n<=9;n++)
printf("%f\n",y[n]);
}

143
144
Waveforms/Graphs:

Fig 3.1: Frequency response of second order system


Result: Frequency response of a second order system is plotted
Viva-Voce:
1. Define Frequency response.

145
Program – 4
Fast Fourier Transform
Date:

Aim:To Compute the DFT of a sequence using Fast Fourier Transform.


Software Requirements: Personal Computer with Code Composer Studio v 5.0,
Hardware Requirements: TMS320C6745 DSK

Program

#include<stdio.h>
#include<math.h>
voidmain()
{
int n,i,j,k,n1,n2;
double m,x[30],y[30],c,s,e,a,t1,t2;

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


scanf("%d",&n);

m=(log(n)/log(2));
printf("The total no. of stages %lf\n",m);

printf("Enter the sequence\n");


for(i=0;i<n;i++)
scanf("%lf",&x[i]);
for(i=0;i<n;i++)
y[i]=0;

j = 0; /* bit-reverse */
n2 = n/2;
for (i=1; i < n - 1; i++)
{
n1 = n2;
while ( j >= n1 )
{
j = j - n1;
n1 = n1/2;
}
j = j + n1;
if (i < j)
{
t1 = x[i];
x[i] = x[j];
x[j] = t1;
t1 = y[i];
146
y[i] = y[j];
y[j] = t1;
}
}

n1 = 0; /* FFT */
n2 = 1;
for (i=0; i < m; i++)
{
n1 = n2;
n2 = n2 + n2;
e = -6.283185307179586/n2;
a = 0.0;
for (j=0; j < n1; j++)
{
c = cos(a);
s = sin(a);
a = a + e;
for (k=j; k < n; k=k+n2)
{
t1 = c*x[k+n1] - s*y[k+n1];
t2 = s*x[k+n1] + c*y[k+n1];
x[k+n1] = x[k] - t1;
y[k+n1] = y[k] - t2;
x[k] = x[k] + t1;
y[k] = y[k] + t2;
}
}
}

printf("The FFT of the given sequence is\n");


for(i=0;i<n;i++)
printf("(%lf)+j(%lf)\n",x[i],y[i]);
}

Input Sequence x(n)= [ 1 2 3 4 4 3 2 1]

FFT of the input sequence X(k) =

147
Result: Hence FFT of a sequence is found.

148
Program – 5
Power Spectrum of a given Signal
Date:

Aim: To plot the power spectrum of a given signal.


Software Requirements: Personal Computer with Code Composer Studio v 5.0,
Hardware Requirements: TMS320C6745 DSK

Program

#include<stdio.h>
#include<math.h>

int n,i,j,k,n1,n2;
float m,x[10],y[10],psd[10],c,s,e,a,t1,t2;
voidmain()
{

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


scanf("%d",&n);

for(i=0;i<n;i++)
{
psd[i]=0;
x[i]=0;
}
m=(log(n)/log(2));
printf("The total no. of stages %lf\n",m);

printf("Enter the sequence\n");


for(i=0;i<n;i++)
scanf("%f",&x[i]);
for(i=0;i<n;i++)
y[i]=0;

j = 0; /* bit-reverse */
n2 = n/2;
for (i=1; i < n - 1; i++)
{
n1 = n2;
while ( j >= n1 )
{
j = j - n1;
n1 = n1/2;
}
j = j + n1;
if (i < j)
149
{
t1 = x[i];
x[i] = x[j];
x[j] = t1;
t1 = y[i];
y[i] = y[j];
y[j] = t1;
}
}

n1 = 0; /* FFT */
n2 = 1;
for (i=0; i < m; i++)
{
n1 = n2;
n2 = n2 + n2;
e = -6.283185307179586/n2;
a = 0.0;
for (j=0; j < n1; j++)
{
c = cos(a);
s = sin(a);
a = a + e;
for (k=j; k < n; k=k+n2)
{
t1 = c*x[k+n1] - s*y[k+n1];
t2 = s*x[k+n1] + c*y[k+n1];
x[k+n1] = x[k] - t1;
y[k+n1] = y[k] - t2;
x[k] = x[k] + t1;
y[k] = y[k] + t2;
}
}
}

printf("The FFT of the given sequence is\n");


for(i=0;i<n;i++)
printf("(%f)+j(%f)\n",x[i],y[i]);

for(i=0;i<n;i++)
psd[i]=(x[i]*x[i]+y[i]*y[i])/n;
printf("The PSD of the given sequence is\n");
for(i=0;i<n;i++)
printf("%f\n",psd[i]);
}

150
151
Waveforms/Graphs:

Fig 5.1:a) Input Signal b) PSD


Result: PSD of a sequence is calculated using square magnitude approach and is plotted

Viva-Voce:

1. Define Power signal.


2. PSD
3. Syntaxes of various Keywords used in the program

152
Program – 6
Implementation of LP/HP FIR filter on a sequence
Date:
Aim: To implement LP FIR filter on a sequence.
Software Requirements: Personal Computer with Code Composer Studio v 5.0, Matlab v8.5
Hardware Requirements: TMS320C6745 DSK
Program:
Filter Type: Lowpass
Window Type: Hamming
Order: 10
Fs=1000Hz
Fc=1Hz

Matlab support:
clc;
clear all;
close all;

%Generation of sine wave


t=0:0.01:0.5;
x=sin(2*pi*t);
%Generation of noise
noise=rand(size(x));
sn=x+noise;%Signal + noise
plot(x);
figure,plot(sn);
%Coefficients of FIR filter
h=[0.014596556252797903
0.030627611554787409
0.07259853985055098
0.12447981176888186

153
0.16645399578198858
0.18248696958198654
0.16645399578198858
0.12447981176888186
0.07259853985055098
0.030627611554787409
0.014596556252797903];
h=h';
%Finding the output of FIR filter
y=conv(x,h);
figure,plot(y);

C program

#include<stdio.h>
#include <math.h>
// random sequence values
float n[51]={ 0.576053456321354, 0.810628105007939 ,
0.403843368384066, 0.988439267199745 , 0.0899988149868883 ,
0.320941032647761 , 0.511408938819178 , 0.0606063665682423
, 0.725687923545844 , 0.556555748561992 , 0.529359902481257
, 0.829982432033195 , 0.858759034071804 ,
0.789028923313949, 0.317833053726229 , 0.452207453762982 ,
0.752227970049942 , 0.109861705750686 , 0.109742368593904 ,
0.269883663704401 , 0.524637345396311 , 0.972651076977497 ,
0.710408685278170 , 0.311859945147533 , 0.291457127647727
, 0.850357337374621 , 0.911647424007853 , 0.639276147276064
, 0.255370297944443 , 0.0886658400322831 ,
0.838255587537226 , 0.584718619263320 , 0.948108735396022 ,
0.0610289291925092 , 0.584641303355111 , 0.285108085658642
, 0.827732173448263 , 0.190986440697398 , 0.442529962202884
, 0.393411506367576 , 0.826573979042765 ,
0.676871093438419 , 0.207603034379981 , 0.318104726150263
, 0.133810985356126 , 0.671462889478031 , 0.570991075462406
, 0.169767066026489, 0.147655777151737 , 0.476079718267456
, 0.908102416506950};
// FIR HAMMING WINDOW LOWPASS filter coefficients
float
h[51]={0.014596556252797903,0.030627611554787409,0.0725985398505
5098,0.12447981176888186 ,0.16645399578198858,
,0.18248696958198654 ,0.16645399578198858 ,0.12447981176888186
,0.07259853985055098,0.030627611554787409,0.014596556252797903};

float t[51],x[51],xn[51],y[61];
int i,j,m,k,p;
int main()
{
// defining time variable
t[0]=0;
for(i==0;(i+1)<51;i++)
{
154
t[i+1]=t[i]+0.01;
printf("%f\n",t[i]);
}
// defining half cycle of sinewave
printf("The input signal is");
for(j==0;j<51;j++)
{
x[j]=sin(2*3.1415*t[j]);
printf("%f\n",x[j]);
}
// generating signal plus noise
printf("The input plus noise is:");
for(p==0;p<51;p++)
{
xn[p]=x[p]+n[p];
printf("%f\n",xn[p]);
}
//initializing output variable
for (i=0;i<61;i++)
y[i]=0;

// finding the output of LP FIR Hamming window filter


//(SMOOTHING)
for (m=0; m < 61; m++)
{
for(k=0;k<51;k++)
{
if((m-k)>=0)
{
y[m]+=xn[k]*h[m-k];

}
}
}
printf("\nThe resultant sequence y is :");
for (i=0;i<51;i++)
{
printf("\n%f",y[i]);
}

155
INPUT SIGNAL PLOT SIGNAL PLUS RANDOM NOISE PLOT

FILTERED OUTPUT FROM LOWPASS HAMMING WINDOW FILTER

156
Waveforms/Graphs:

Fig 6.1:a) Input Signal b) Signal + noise c) Smoothened or Lowpass filtered output

157
Result: Thus Lowpass FIR filter is implemented on a sinewave corrupted with random noise and
the result observed is smoothened.

158
Program – 7
Implementation of Decimation Process
Date:
Aim: To implement Decimation process on a sequence.
Software Requirements: Personal Computer with Code Composer Studio v 5.0, Matlabv8.5
Hardware Requirements: TMS320C6745 DSK
Program:
Down sampling:
#include<stdio.h>
#include<math.h>
int x[100],y[100];
float z,d;
float a,b;
int i,j;
void main()
{
printf(“\n Enter the length of input sequence”);
scanf(“%f”,&a);
printf(“\n Enter sampling value:”);
scanf(“%f”,&b);
printf(“Enter values for input x(n):\n”);
for(i=0;i<=a;i++)
scanf(“%d”,&x[i]);
j=0;
for(i=1;i<=a;i++)
{
y[i]=x[j];
j=j+b;
}
d=a/b;
z=ceilf(d);
for(i=1;i<=z;i++)
printf(“\n The Down sampled version is y[%d]=%d”,i,y[i]);
}

159
PROCEDURE FOR SELECTING ANTI-ALIASING FIR FILTER COEFFICIENTS

160
MATLAB SUPPORT:
DECIMATION
clc;
clear all;
close all;
%decimation
Fs=50;
t=0:1/Fs:2*pi;
D=3
x1 = sin(t);
h1=[
0
-0.000043020495399987069
-0.000076013438760316076
0
0.00018487124619081242
0.00026753581008901812
0
-0.00050970783426300664
-0.00067879593558529917
0
0.0011407690199314677
0.0014464278234642166
0
-0.0022436979078414884
-0.0027521260481395641
0

161
0.0040375134195622716
0.0048376681337442612
0
-0.0068240527838610019
-0.0080464176413262388
0
0.011070838087278455
0.012941029950154342
0
-0.017654667293030096
-0.020661234151834809
0
0.028687013916059163
0.034237591369701031
0
-0.051349505150856727
-0.065855675339352465
0
0.1362791750483513
0.27488503838177852
0.33333333333333331
0.27488503838177852
0.1362791750483513
0
-0.065855675339352465
-0.051349505150856727
0
0.034237591369701031
0.028687013916059163
0
-0.020661234151834809
-0.017654667293030096
0
0.012941029950154342
0.011070838087278455
0
-0.0080464176413262388
-0.0068240527838610019
0
0.0048376681337442612
0.0040375134195622716
0
-0.0027521260481395641
-0.0022436979078414884
0
0.0014464278234642166
0.0011407690199314677
0
-0.00067879593558529917
162
-0.00050970783426300664
0
0.00026753581008901812
0.00018487124619081242
0
-0.000076013438760316076
-0.000043020495399987069
];
h1=h1';
x_antialiasing=conv(x1,h1);
decim_output=downsample(x_antialiasing,D);
n=length(decim_output);
figure,
subplot(2,1,1);
stem(x1);
subplot(2,1,2);
stem(decim_output(13:118));
grid
Convolution ‘c’ program - Support

#include<stdio.h>
#include<math.h>
float x[100],y[100],h[100];
int l,k,i,j,n,m;
voidmain()
{

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


scanf("%d",&l);

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


scanf("%d",&m);

for(i=0;i<l+m-1;i++)
{
x[i]=0;
h[i]=0;
}
printf("\nEnter the sequence x:");
for (i=0;i<l;i++)
scanf("%f",&x[i]);
printf("\nEnter the sequence h:");
for (j=0;j<m;j++)
scanf("%f",&h[j]);
163
for (i=0;i<100;i++)
y[i]=0;

for (n=0; n < l+m-1; n++)


{
for(k=0;k<l;k++)
{
if((n-k)>=0)
{
y[n]+=x[k]*h[n-k];

}
}
}
printf("\nThe resultant sequence y is :");
for (i=0;i<l+m-1;i++)
printf("\n%f",y[i]);

}
DECIMATION ‘C’ PROGRAM
#include<stdio.h>
#include<math.h>
double x[315],y[315],t[315],h[500],xd[105];
float z,d;
float a,b,D;
int i,j,Fs=50,n,k;
int main()
{
/*defining a input wave*/
for (i=0;i<315;i++)
{
t[i]=i/Fs;
x[i]=sin(Fs*t[i]);
}
printf("The input wave is:\n");
for(i=0;i<315;i++)
{
printf("\n%lf",x[i]);

}
for(i=0;i<500;i++)
{
h[i]=0;
}
/*Passing input wave through anti-aliasing filter*/
h[0]= 0.000000000 ;
h[1]= -0.000043020 ;
h[2]= -0.000076013 ;
h[3]= 0.000000000 ;
164
h[4]= 0.000184871 ;
h[5]= 0.000267536 ;
h[6]= 0.000000000 ;
h[7]= -0.000509708 ;
h[8]= -0.000678796 ;
h[9]= 0.000000000 ;
h[10]= 0.001140769 ;
h[11]= 0.001446428 ;
h[12]= 0.000000000 ;
h[13]= -0.002243698 ;
h[14]= -0.002752126 ;
h[15]= 0.000000000 ;
h[16]= 0.004037513 ;
h[17]= 0.004837668 ;
h[18]= 0.000000000 ;
h[19]= -0.006824053 ;
h[20]= -0.008046418 ;
h[21]= 0.000000000 ;
h[22]= 0.011070838 ;
h[23]= 0.012941030 ;
h[24]= 0.000000000 ;
h[25]= -0.017654667 ;
h[26]= -0.020661234 ;
h[27]= 0.000000000 ;
h[28]= 0.028687014 ;
h[29]= 0.034237591 ;
h[30]= 0.000000000 ;
h[31]= -0.051349505 ;
h[32]= -0.065855675 ;
h[33]= 0.000000000 ;
h[34]= 0.136279175 ;
h[35]= 0.274885038 ;
h[36]= 0.333333333 ;
h[37]= 0.274885038 ;
h[38]= 0.136279175 ;
h[39]= 0.000000000 ;
h[40]= -0.065855675 ;
h[41]= -0.051349505 ;
h[42]= 0.000000000 ;
h[43]= 0.034237591 ;
h[44]= 0.028687014 ;
h[45]= 0.000000000 ;
h[46]= -0.020661234 ;
h[47]= -0.017654667 ;
h[48]= 0.000000000 ;
h[49]= 0.012941030 ;
h[50]= 0.011070838 ;
h[51]= 0.000000000 ;
h[52]= -0.008046418 ;
165
h[53]= -0.006824053 ;
h[54]= 0.000000000 ;
h[55]= 0.004837668 ;
h[56]= 0.004037513 ;
h[57]= 0.000000000 ;
h[58]= -0.002752126 ;
h[59]= -0.002243698 ;
h[60]= 0.000000000 ;
h[61]= 0.001446428 ;
h[62]= 0.001140769 ;
h[63]= 0.000000000 ;
h[64]= -0.000678796 ;
h[65]= -0.000509708 ;
h[66]= 0.000000000 ;
h[67]= 0.000267536 ;
h[68]= 0.000184871 ;
h[69]= 0.000000000 ;
h[70]= -0.000076013 ;
h[71]= -0.000043020 ;

for (i=0;i<388;i++)
{
y[i]=0;
}
for (n=0; n < 388; n++)
{
for(k=0;k<315;k++)
{
if((n-k)>=0)
{
y[n]+=x[k]*h[n-k];
}
}
}
printf("\nThe resultant filtered sequence y is :");
for (i=0;i<388;i++)
{
printf("\n%lf",y[i]);
}
a=315;/* length of the inputwave*/
b=3;/*decimation factor*/
/*performing downsampling*/
j=0;
for(i=0;i<105;i++)
{
xd[i]=y[j];
j=j+b;
}
d=a/b;
166
z=ceilf(d);
printf("\n The Down sampled version is:\n");
for(i=0;i<z;i++)
{
printf("\n%lf",xd[i]);
}
}
INPUT SEQUENCE PLOT

FINAL DECIMATED OUTUPT

167
Waveforms/Graphs:

Fig 7.1: a) Input signal for decimator b) Decimated signal

Result: Decimated signal is obtained and is plotted.

168
Program – 8
Implementation of Interpolation Process
Date:
Aim: To implement Interpolation process on a sequence.
Software Requirements: Personal Computer with Code Composer Studio v 5.0, Matlab v 8.5
Hardware Requirements: TMS320C6745 DSK
Program:
Upsampling:
#include<stdio.h>
#include<math.h>
void main()
{
int x[100],xu[100],N,i,I,n,R;
printf(“\n Enter the length of input sequence”);
scanf(“%f”,&N);
printf(“\n Enter Interpolation factor:”);
scanf(“%f”,&I);
printf(“Enter values for input x(n):\n”);
for(i=0;i<=N;i++)
scanf(“%d”,&x[i]);
for(n=0;n<(N*I)-(I-1);n++)
{
R=n%I;
If(R==0)
xu[n]=x[n/I];
else
xu[n]=0;
}
printf(“\n Interpolated sequence is:”);
for(i=0;i<(N*I)-(I-1);i++)
printf(“%d”,xu[i]);
}

169
PROCEDURE FOR SELECTING ANTI-IMAGING FIR FILTER COEFFICIENTS

MATLAB SUPPORT
INTERPOLATION
clc ; clear all ; close all;
Fs=2;
t=0:1/Fs:6*pi;
%interpolation
I=2
x = sin(t);
subplot(2,1,1);
stem(x);
xu=upsample(x,2);
h=[0.5,1,0.5,0];
interp_output=conv(xu,2*h);
m=length(interp_output);
subplot(2,1,2);
stem(interp_output);
grid

170
Convolution ‘c’ program - Support

#include<stdio.h>
#include<math.h>
float x[100],y[100],h[100];
int l,k,i,j,n,m;
voidmain()
{

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


scanf("%d",&l);

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


scanf("%d",&m);

for(i=0;i<l+m-1;i++)
{
x[i]=0;
h[i]=0;
}
printf("\nEnter the sequence x:");
for (i=0;i<l;i++)
scanf("%f",&x[i]);
printf("\nEnter the sequence h:");
for (j=0;j<m;j++)
scanf("%f",&h[j]);
for (i=0;i<100;i++)
y[i]=0;

for (n=0; n < l+m-1; n++)


{
for(k=0;k<l;k++)
{
if((n-k)>=0)
{
y[n]+=x[k]*h[n-k];

}
}
}
printf("\nThe resultant sequence y is :");
for (i=0;i<l+m-1;i++)
printf("\n%f",y[i]);

171
INTERPOLATION ‘C’ PROGRAM
#include<stdio.h>
#include<math.h>
int main()
{
float x[38],xu[76],h[76],y[78],t[38];
int i,I,n,R,k;
float m=0,Fs=2;
/*input sinewave*/
for (i=0;i<38;i++)
{
t[i]=m/Fs;
x[i]=sin(t[i]);
m=m+1;
}

printf("The input sinewave is:\n");


for (i=0;i<38;i++)
{
printf("\n%f",x[i]);
}
for(i=0;i<76;i++)
{
h[i]=0;
}
h[0]=0.5;
h[1]=1;
h[2]=0.5;
h[3]=0;
/*Interpolation factor*/
I=2;
/* Upsampling*/
for(n=0;n<(38*2)-(2-1);n++)
{
R=n%I;
if(R==0)
{
xu[n]=x[n/I];
}
else
{
xu[n]=0;
}
}
printf("\n Upsampled sequence is:");
for(i=0;i<(38*2)-(2-1);i++)
{
printf("\n%f",xu[i]);
172
}
/*passing upsampled sinewave through anti-imaging filter*/
for (i=0;i<78;i++)
{
y[i]=0;
}
for (n=0; n < 78; n++)
{
for(k=0;k<75;k++)
{
if((n-k)>=0)
{
y[n]+=xu[k]*h[n-k];

}
}
}
printf("\nThe resultant sequence y is :");
for (i=0;i<78;i++)
{
printf("\n%f",y[i]);
}
}
INPUT SEQUENCE PLOT

173
RESULT OF ANTI-IMAGING FILTER : INTERPOLATED SEQUENCE PLOT

174
Waveforms/Graphs:

Fig 8.1: a) Input signal for Interpolator b) Interpolated signal

Result: Interpolated signal is obtained and is plotted.

175
Program – 9
Implementation of I/D Sampling rate Converter
Date:
Aim: To implement sampling rate conversion by a rational factor I/D on a sequence.
Software Requirements: Personal Computer with Code Composer Studio v 5.0, Matlab v 8.2
Hardware Requirements: TMS320C6745 DSK
Program:
Procedure for selecting Lowpass filter coefficients for I/D sampling rate conversion

MATLAB SUPPORT
MULTIRATE SAMPLING BY RATIONAL FACTOR - I/D
clc
clear all
close all
Fs=10;
t=0:1/Fs:2*pi;
%interpolation
I=2;D=3;
x = sin(t);
subplot(2,1,1);
stem(x);
xu=upsample(x,I);
h=[
0
-0.000086040990799974139
-0.00015202687752063215
176
0
0.00036974249238162484
0.00053507162017803623
0
-0.0010194156685260133
-0.0013575918711705983
0
0.0022815380398629355
0.0028928556469284333
0
-0.0044873958156829768
-0.0055042520962791282
0
0.0080750268391245432
0.0096753362674885223
0
-0.013648105567722004
-0.016092835282652478
0
0.02214167617455691
0.025882059900308684
0
-0.035309334586060191
-0.041322468303669618
0
0.057374027832118327
0.068475182739402063
0
-0.10269901030171345
-0.13171135067870493
0
0.2725583500967026
0.54977007676355705
0.66666666666666663
0.54977007676355705
0.2725583500967026
0
-0.13171135067870493
-0.10269901030171345
0
0.068475182739402063
0.057374027832118327
0
-0.041322468303669618
-0.035309334586060191
0
0.025882059900308684
0.02214167617455691
0
177
-0.016092835282652478
-0.013648105567722004
0
0.0096753362674885223
0.0080750268391245432
0
-0.0055042520962791282
-0.0044873958156829768
0
0.0028928556469284333
0.0022815380398629355
0
-0.0013575918711705983
-0.0010194156685260133
0
0.00053507162017803623
0.00036974249238162484
0
-0.00015202687752063215
-0.000086040990799974139
];
h=h';
interp_output=conv(xu,2*h);
subplot(2,1,2);
%decimation
multirate_output=downsample(interp_output,D);
subplot(2,1,2);
stem(multirate_output(14:54));
grid
Convolution ‘c’ program - Support

#include<stdio.h>
#include<math.h>
float x[100],y[100],h[100];
int l,k,i,j,n,m;
voidmain()
{

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


scanf("%d",&l);

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


scanf("%d",&m);

for(i=0;i<l+m-1;i++)
{
x[i]=0;
h[i]=0;
178
}
printf("\nEnter the sequence x:");
for (i=0;i<l;i++)
scanf("%f",&x[i]);
printf("\nEnter the sequence h:");
for (j=0;j<m;j++)
scanf("%f",&h[j]);
for (i=0;i<100;i++)
y[i]=0;

for (n=0; n < l+m-1; n++)


{
for(k=0;k<l;k++)
{
if((n-k)>=0)
{
y[n]+=x[k]*h[n-k];

}
}
}
printf("\nThe resultant sequence y is :");
for (i=0;i<l+m-1;i++)
printf("\n%f",y[i]);

}
MULTIRATE SAMPLING BY RATIONAL FACTOR - I/D - C-PROGRAM
#include<stdio.h>
#include<math.h>
void main ()
{
float x[38], xu[76], h[72], y[147], xd[47], t[38];
int i, j, I, n, R, k, l, p, q;
float m = 0, Fs = 2, a,b, d, z;
/*input sinewave */
for (i = 0; i < 38; i++)
{
t[i] = m / Fs;
x[i] = sin (t[i]);
m = m + 1;
}

printf ("The input sinewave is:\n");


for (i = 0; i < 38; i++)
printf ("\n%f", x[i]);

q = sizeof (x);
h[0] = 0;
h[1] = -0.000086040990799974139;
179
h[2] = -0.00015202687752063215;
h[3] = 0;
h[4] = 0.00036974249238162489;
h[5] = 0.00053507162017803623;
h[6] = 0;
h[7] = -0.0010194156685260133;
h[8] = -0.0013575918711705983,
h[9] = 0;
h[10] = 0.0022815380398629355;
h[11] = 0.0028928556469284333;
h[12] = 0;
h[13] = -0.0044873958156829742;
h[14] = -0.0055042520962791282;
h[15] = 0;
h[16] = 0.0080750268391245432;
h[17] = 0.009675336267488524;
h[18] = 0;
h[19] = -0.013648105567722004;
h[20] = -0.016092835282652478;
h[21] = 0;
h[22] = 0.02214167617455691;
h[23] = 0.025882059900308684;
h[24] = 0;
h[25] = -0.035309334586060191;
h[26] = -0.041322468303669618;
h[27] = 0;
h[28] = 0.057374027832118327;
h[29] = 0.068475182739402063;
h[30] = 0;
h[31] = -0.10269901030171345;
h[32] = -0.13171135067870493;
h[33] = 0;
h[34] = 0.2725583500967026;
h[35] = 0.54977007676355705;
h[36] = 0.66666666666666663;
h[37] = 0.54977007676355705;
h[38] = 0.2725583500967026;
h[39] = 0;
h[40] = -0.13171135067870493;
h[41] = -0.10269901030171345;
h[42] = 0;
h[43] = 0.068475182739402063;
h[44] = 0.057374027832118327;
h[45] = 0;
h[46] = -0.041322468303669618;
h[47] = -0.035309334586060191;
h[48] = 0;
h[49] = 0.025882059900308684;
h[50] = 0.02214167617455691;
180
h[51] = 0;
h[52] = -0.016092835282652478;
h[53] = -0.013648105567722004;
h[54] = 0;
h[55] = 0.009675336267488524;
h[56] = 0.0080750268391245432;
h[57] = 0;
h[58] = -0.0055042520962791282;
h[59] = -0.0044873958156829742;
h[60] = 0;
h[61] = 0.0028928556469284333;
h[62] = 0.0022815380398629355;
h[63] = 0;
h[64] = -0.0013575918711705983;
h[65] = -0.0010194156685260133;
h[66] = 0;
h[67] = 0.00053507162017803623;
h[68] = 0.00036974249238162489;
h[69] = 0;
h[70] = -0.00015202687752063215;
h[71] = -0.000086040990799974139;

/*Interpolation factor*/
I = 2;
/* Upsampling*/
for (n = 0; n < (q*I)-(I-1); n++)
{
R = n % I;
if (R == 0)
xu[n] = x[n / I];
else
xu[n] = 0;
}

l = sizeof (xu);
p = sizeof (h);

/*passing upsampled sinewave through anti-imaging and anti-


aliasing filter*/
for (i = 0; i < l + p - 1; i++)
y[i] = 0;

for (n = 0; n < l + p - 1; n++)

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

181
{

if ((n - k) >= 0)

y[n] += xu[k] * h[n - k];

a = sizeof (y);
b = 3; /*decimation factor */
/*performing downsampling*/
j = 0;

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


{
xd[i] = y[j];
j = j + b;
}

d = a / b;
z = ceilf (d);

printf ("\n The Down sampled version is:\n");


for (i = 0; i < z; i++)
{
printf ("%f\n", xd[i]);
}
}

182
Waveforms/Graphs:

Fig 9.1: a) Input signal b) I/D sample rate converter output

Result: Sample rate converter by a rational factor I/D is obtained and is plotted.

183
Program – 10
Implementation of HP IIR filter for a given sequence
Date:

Aim: To implement Highpass IIR filter


Software Requirements: Personal Computer with Code Composer Studio v 5.0,
Hardware Requirements: TMS320C6745 DSK
Program

#include "stdio.h"
#include "math.h"

int i,w,wc,c;
float H[100],ap,as,fp,fs,wp,ws,epsilon,lambda,N,a,b;

void main()
{
printf("\n Enter Passband attenuation in dB: ");
scanf("%f",&ap);

printf("\n Enter minimum stopbad attenuation in dB: ");


scanf("%f",&as);

//fs<fp for highpass filter

printf("\n Enter stopband edge frequency in Hz: ");


scanf("%f",&fs);

printf("\n Enter Passband edge frequency in Hz: ");


scanf("%f",&fp);

wp=2*3.1415*fs;
ws=2*3.1415*fp;

a=pow(10,(0.1*ap));
b=pow(10,(0.1*as));

epsilon=sqrt(a-1);
lambda=sqrt(b-1);

//filter order

N=(log10(lambda/epsilon))/(log10(ws/wp));
N=ceilf(N);
printf("The order is :\n");
printf("%f",N);

184
wc=wp;

printf("the cutoff freq is \n");


printf("%f",wc);

for(w=0;w<=100;w++)
{
H[w]=1/sqrt(1+pow((float)wc/w,2*N));
printf("H[%d]=%f\n",w,H[w]);
}

Input:
Enter Passband attenuation in dB: 3

Enter minimum stopbad attenuation in dB: 15

Enter stopband edge frequency in Hz: 10

Enter Passband edge frequency in Hz: 30

185
Waveforms/Graphs:

Fig 10.1: Frequency response – Magnitude plot

Result: Hence the Magnitude plot of IIR Highpass filter is plotted

186
Program – 11
Impulse response of a second order system
Date:
Aim: To plot the impulse response of a second order system.
Software Requirements: Personal Computer with Code Composer Studio v 5.0
Hardware Requirements: TMS320C6745 DSK
Program :
#include <stdio.h>
#include <math.h>
int i,n;
float x[10],y[10];
void main()
{
for(i=-2;i<=9;i++)
{
y[i]=0;
x[i]=0;
}
x[0]=1;
for(n=0;n<=9;n++)
{
y[n]=0.375*y[n-1]+0.667*y[n-2]+x[n]+0.25*x[n-1];
}
printf("The impulse response of the given second order system
is:");
for(n=0;n<=9;n++)
printf("%f\n",y[n]);
}

187
188
Waveforms/Graphs:

Fig 11.1:a) Input impulse signal b) Impulse response of second order system
Result: Impulse response of a second order system is calculated and is plotted
Viva-Voce:
1. Define unit impulse.
2. What is impulse response?

189
SIGNAL PROCESSING
USING SCILAB
INTRODUCTION TO SCILAB
Scilab is free and open source software for numerical computation providing a
powerful computing environment for engineering and scientific applications
From the software point of view, Scilab is an interpreted language. This generally
allows to get faster development processes, because the user directly accesses a high-level
language, with a rich set of features provided by the library. The Scilab language is meant to
be extended so that user-defined data types can be defined with possibly overloaded
operations. Scilab users can develop their own modules so that they can solve their particular
problems.
Scilab includes hundreds of mathematical functions. It has a high-level programming
language allowing access to advanced data structures, 2-D and 3-D graphical
functions. A large number of functionalities is included in Scilab:
 Maths& Simulation
For usual engineering and science applications including mathematical operations and
data analysis.
 2-D & 3-D Visualization
Graphics functions to visualize, annotate and export data and many ways to create and
customize various types of plots and charts.
 Optimization
Algorithms to solve constrained and unconstrained continuous and discrete
optimization problems.
 Statistics
Tools to perform data analysis and modeling
 Control System Design & Analysis
Standard algorithms and tools for control system study
 Signal Processing
Visualize, analyze and filter signals in time and frequency domains.
 Application Development
Increase Scilab native functionalities and manage data exchanges with external tools.
 Xcos - Hybrid dynamic systems modeler and simulator
Modeling mechanical systems, hydraulic circuits, control systems, etc.
Whatever our platform is (i.e. Windows, Linux or Mac), Scilab binaries can be
downloaded directly from the Scilab homepage http://www.scilab.org or from the Download

193
area http://www.scilab.org/download. Scilab binaries are provided for both 32 and 64-bit
platforms so that they match the target installation machine.

Getting startedwith Scilab


We can start using Scilab by clicking the icon shown below on the desktop

There are several ways of using Scilab and the basic two methods are:
 Using the console in the interactive mode
 Using the exec function against a file

The console
The first way is to use Scilab interactively, by typing commands in the console, analyzing
the results and continuing this process until the final result is computed.

The editor
Scilab,from version 5.2 provides a new editor which allows to edit scripts easily.The
editor can be accessed from the menu of the console, under the Applications > Editor menu,
or from the console, as presented below.

--> editor ()

194
This editor allows to manage several files at the same time, as presented in figure below

There are many features but commonly used features are under the Execute menu.
 Load into Scilab allows to execute the statements in the current file, as if wedid a
copy and paste. This implies that the statements which do not end withthe semicolon
";" character will produce an output in the console.
 Evaluate Selection allows to execute the statements which are currently selected.
 Execute File into Scilab allows to execute the file, as if we used the execfunction. The
results which are produced in the console are only those whichare associated with
printing functions, such as disp for example.

We can also select a few lines in the script, by right clicking and get the context menu as
presented below:

195
Using exec
When several commands are to be executed, it may be more convenient to writethese
statements into a file with Scilab editor. To execute the commands located in such a file, the
exec function can be used, followed by the name of the script. This file generally has the
extension.sce or .sci, depending on its content:
 Files having the .sci extension contain Scilab functions and executing themloads the
functions into Scilab environment (but does not execute them)
 Files having the .sce extension contain both Scilab functions and
executablestatements.

Executing a .scefile has generally an effect such as computing several variables and
displaying the results in the console, creating 2D plots, reading or writing into a file, etc.

Signal Processing using Scilab


Scilab provides tools to visualize, analyze and filter signals in time and frequency domains:
 Signal generation
 Data windowing
 Power spectral density estimation
 Digital IIR and FIR filter design
 Analog filter design
 Signal transforms including fftw

196
Program – 1
Fast Fourier Transform
Date:

Aim:To Compute the DFT of a sequence using Fast Fourier Transform.


Requirements: Personal Computer with SCILAB5.5.2 software

Program:
clear all;
clc ;
close ;

//Taking the input sequence from the user


x = input('Enter the input sequence:x=') ;
X = fft (x , -1)
disp(x,' The input sequence is x=');

//Inverse FFT
x_inv = real (fft(X ,1) )
disp(X,'The DFT of the input is X=');

//Alternate Inverse FFT


disp(x_inv,'The inverse DFT is x=');
k=fft(X,1);
disp(k,'the inverse is ');

INPUT:
Enter the input sequence:x=[1 2 3 4 4 3 2 1]
OUTPUT:
The input sequence is x= 1. 2. 3. 4. 4. 3. 2. 1.
The DFT of the input is X= 20. - 5.8284271 - 2.4142136i 0 - 0.1715729 - 0.4142136i
0 - 0.1715729 + 0.4142136i 0 - 5.8284271 + 2.4142136i
The inverse DFT is x= 1. 2. 3. 4. 4. 3. 2. 1.
The inverse is 1. 2. 3. 4. 4. 3. 2. 1.
Result: The DFT of a sequence using Fast Fourier Transform is computed

197
Program – 2
Implementation of I/D sampling rate converters
Date:

Aim: To implement sampling rate conversion by a rational factor on a given sequence.

Requirements: Personal Computer with SCILAB 5.5.2 software

Program
clc;
clear all;
close;
t=0:0.05:1;
x=sin(10*t);
I=input('Enter the Interpolation factor:');
D=input('Enter the Decimation factor:');

scf(0);
plot2d3(x);
xlabel("$0\le t\le 1$","fontsize",4,"color","red");
ylabel("$x(t)={sin(10t)}$","fontsize",4,"color","red");
title("Input signal","color","red","fontsize",4);

y=intdec(x,I/D);
scf(1);
plot2d3(y);
xlabel("$0\le t\le 1$","fontsize",4,"color","red");
ylabel("$y(t)={x(2t/3)}$","fontsize",4,"color","red");
title("I/D sampled signal","color","red","fontsize",4);

INPUT:
Enter the Interpolation factor:2
Enter the Decimation factor:3
PLOTS:
INPUT SIGNAL

198
I/D SAMPLE RATE CONVERSION OUTPUT

199
Waveforms/Graphs:

Result:Henceimplementation of sampling rate conversion by a rational factor on a given


sequence is performed

200
Program – 3
Impulse response of first order and second order systems
Date:

Aim: To Calculate Unit Impulse Response (Unit Sample) of the givenLTI system.
Requirements: Personal Computer with SCILAB 5.5.2 software
Program:
// Continuous time System
clc;
close;
clear all;
s=%s; // first create a variable
num=36;
den=36+3*s+s^2;
//create a scilab continuous system LTI object
TF=syslin('c',num,den);
//TF = 36/ (36 + 3s + s^2);
ty=typeof(TF);// type of object is rational
t=linspace(0,5,500);
imp_res=csim('imp',t,TF);
plot(t,imp_res);
xgrid();
xtitle('Impulse response','time','response');

201
// Discrete time System

clc;
clear all;
close;
//Given 2nd order system
//y(n)=(3/8)y(n-1)+(2/3)y(n-2)+x(n)+(1/4)x(n-1)

z=%z; // first create a variable


a=((z^2)+(1/4)*z);
b=(z^(2)-(3/8)*z-(2/3))
h = ldiv (a ,b ,10) ;
disp (h ,"h(n)=") ;
plot2d3(h);
xtitle('Impulse response','n-->','response');

OUTPUT:
h(n)=

1.
0.625
0.9010417
0.7545573
0.8836534
0.8344082
0.9020054
0.8945242
0.9367835
0.9476432

202
Waveforms/Graphs:

Result:Henceimpulse response of second order continuous and discrete time LTI systems are
found and plotted.

203
Program – 4
Implementation of LP/HP IIR filter
Date:

Aim: To design
i)Butterworth Lowpass IIR filter
ii)Chebyshev-I Highpass IIR filter

Requirements: Personal Computer with SCILAB 5.5.2 software


Program:

// Low pass filter


clc;
clear all;
close;
fp=input('Enter the cutoff frequency in Hz fp=');
n=input('Enter the order of the filter n=');
F=input('Enter sampling frequency in Hz F=');
wc=fp/F;
hz=iir(n,'lp','butt',[wc 0],[0 0]);// for Butterworth design LP
//hz=iir(n,'hp','butt',[wc 0],[0 0]);// for Butterworth design HP
//hz=iir(n,'lp','cheb1',[wc 0],[.08 .03]); // for Chebyshev-1 design
//hz=iir(n,'lp','cheb2',[wc 0],[.08 .03]); // for Chebyshev-2 design
[hzm,fr]=frmag(hz,256);
plot2d(fr',hzm');
a=gca();
a.x_label.text="Frequency";
a.y_label.text="Magnitude";
xtitle('Discrete IIR filter low pass');
z=poly(0,'z'); //to express the result in terms of the delay operator q=z^-1
hzd=horner(hz,1/z); // delay operator q=z^1
disp(hzd,'The transfer function is');
INPUT:
Enter the cutoff frequency in Hz --fp=400Hz
Enter the order of the filter --n=10
Enter sampling frequency in Hz --F=5000Hz
OUTPUT:

204
205
Waveforms/Graphs:

Result:HenceLP/HP digital IIR filters are designed and frequency response is plotted.

206
Program – 5

Generation of DTMF signals

Date:

Aim: To generate DTMF signal tones.

Requirements: Personal Computer with SCILAB 5.5.2 software

Program:

row_f1 =[697 770 852 941]; // Row F r e q u e n c y


colum_f1 =[1209 1336 1477]; // Column F r e q u e n c y
fs =8192; // Sampling F r e q u e n c y
N =1:4000; // T o t al No . of Sample
mobile =[9 8 4 9 4 0 7 9 6 5];
temp =[]; // A r ray t h a t Co n tai n t o t a l s i g n a l f o r ea c h D i g i t

figure ;

for i =1: length ( mobile )


select mobile (i )
case 1
row_f =1;
colum_f =1;
case 2
row_f =1;
colum_f =2;
case 3
row_f =1;
colum_f =3;
case 4
row_f =2;
colum_f =1;
case 5
row_f =2;
colum_f =2;
case 6
row_f =2;
colum_f =3;
case 7
row_f =3;
colum_f =1;
case 8
row_f =3;
colum_f =2;
case 9

207
row_f =3;
colum_f =3;
case 0
row_f =4;
colum_f =2;
else
row_f =4;
colum_f =1;
end

y = sin (2*3.14*( row_f1 ( row_f )/ fs ) * N) +sin (2*3.14*(colum_f1 ( colum_f ) / fs ) * N) ;

temp =[temp y zeros(1 ,4000)];


end
sound ( temp , fs ) ;

Result: DTMF signal tones are generated.

208

Das könnte Ihnen auch gefallen