Systems Lab
DATE: 08-02-2011 EXPERIMENT NO.1 FAMILIARISATION OF MATLAB AIM To familiarize with MATLAB and its functions. THEORY MATLAB is an ideal software tool for studying digital signal processing. The plotting capacity of MATLAB makes it possible to view the result of processing and gain understanding into complicated operations. The tool box support a wide range of signal processing from waveform generation to filter design and implementation, parametric modelling and spectral analysis. There are two categories of tools Signal processing functions Graphical interaction tools. The first category of tools is made of functions that we can call from the common line or from your own application. Many of the functions are MATLAB statements that implement specialized signal processing algorithm. (a) DEFINTION OF VARIABLES Variables are assigned numerical values by typing the expression directly Eg: a=1+2 yields a=3 The answer will not be displayed when semicolon is put at the end of an expression Eg: a=1+2 MATLAB utilizes the following arithmetic operations + Addition - Subtraction * Multiplication / Division ˆpower operation „Transpose A variable can be assigned using a formula that utilizes these operations and either numbers or previously defined variables. Eg: since „a‟ was defined previously the following expression is valid, B=z*a.To determine the value of a previously defined quantity type the quantity by b=6. If your expression does not fill on the line, use an ellipse and continue on the next line. C=1+2+3+. . . . . . . . . . . . ..+5+6+7. These are certain predefined variables which can be used at any time, in the same manner as user defined variables. i=sqrt(-1); j=sqrt(-1) Dept. Of ECE, SJCET, Palai
1
Systems Lab
pi=3.1416 Eg: y=2*(1+4*j)yields y=2.000+8.000y These are also a number of predefined functions that can be used when defining a variable. Some common functions that are used in this text are Abs- magnitude of a number Angle- angle of a complex numberCos- cosine function, assume arguments in radian. Exp-exponential functions For example with y defined as aboveE= abs(y), yields e=8.2462, c=angle(y) yields c=1.3258 with a=3 as defined previously c=cos(a)yields, c= -0.9900c = exp(a), yields c=20.0855.Note that exp can be used on complex numbers example with y = 2 + 8i as defined above c = -1.0751 + 7.3104i which can be verified by using Euler‟s formula c = c2cos(8) + jc2sin(8). (b) DEFINTION OF MATRICES MATLAB is based on matrix and vector algebra. Even scalars are treated 1x1 matrix. Therefore, vector and matrix operation are simple as common calculator operations. Vectors can be defined in two ways. The first method is used for arbitrary elements, v=[1 3 5 7] creates 1x4 vector elements with elements 1 3 5 &7. Note that commas would have been used in the place of spaces to separate the elements. Additional elements can be added to the vector v(5)=8 yields the vector v = [1357]. Previously defined vectors can be used to define a new vectors. For example with we defined above a= [910]; b = [v a]; creates the vector b = [1357910]. The second method is used for creating vector with equally spaced elements t=0:0.1:10; creates 1x101 vector with elements0,0.1,0.2. . . . . 10. Note that the middle number defines the increments is set to a default of 1k=0,10 creates 1x11 vector with the elements 0,1,2. . . .10. Matrices are defined by entering the element row by row. M = [124; 368] creates the matrix M= 1 2 43 6 8 There are number of special matrices that can be defined Null matrix: [ ]; Nxm matrixes of zero: M=zeros (m,m); Nxm matrix of ones: M= ones (n,m); Nxn matrix of identity: M=eye (n) A particular elements of matrix can e assigned M(1,2)=5 place the number 5 in the first row,2nd column. Operations and functions that were defined for scalars in the previous section can be used on vectors and matrices. For example a=[1 2 3]; b=[4 5 6]; c=a+b yield c=579. Functions are applied element by element. For example t=0:„0; x=cos(2*t) creates a vector „x‟ with elements equal to cos(2t) for t=0,1,2. . . ..10 (c) GENERAL INFORMATION MATLAB is case sensitive. So „a‟ and „A‟ are two different names. Comment statements are preceded by a %. Dept. Of ECE, SJCET, Palai
2
Systems Lab
1) M-files M-files are macros of MATLAB commands that are stored as ordinary text file with the extension „in‟ that is „filename.m‟. An m-file can be either a function with input and output variables or a set of commands. MATLAB requires that the m-file must be stored either in the working directory or in a directory that is specified in the MATLAB path list. The following commands typed from within MATLAB demonstrate how this m-file is used. X=2,y=3,z=y plusx(y,x) MATLAB m-files are most efficient when written in a way that utilizes matrix or vector operations, loops and if statements are available, but should be used sparingly since they are computationally inefficient. An examples is For k=1:10 x(k)=cos(k) end; This creates a 1x10vector „x‟ containing the cosine of the positive integers from 1 to 10. This operation is performed more efficiently with the commands k=1:10 x=cos(k) which utilizes a function of a vector instead of a for loop. An if statement can be used to define combinational statement. (d) REPRESENTATION OF SIGNALS A signal can be defined as function that conveys information, generally about or behaviour of physical system; signals are represented mathematically as functions of one or more independent variables. The independent variables is the mathematical expression of a signal may be either continuous is discrete. Continuous time signals are defined along a number of times and thus they are represented by a continuous independent variable. TheMATLAB is case sensitive. Discrete time signals are represented mathematically.Continuoustimesignals are often referred to as analog signals. Discrete time signals are defined at discrete times and thus the independent variable has discrete values. In a sequence of numbers x, the nthnumber in the sequence is denoted as x[n]. The basic signals used in digital signal processing are the unit impulse signal [U+0260](n), exponential of the form au[n], sine waves and their generalization to complex exponentials. Since the only numerical data type in MATLAB is the m x nmatrix, signals must be represented as vectors either mx1 matrix if column vector 1xn matrices if row vectors. A constant will be treated as 1x1 matrix. The signals are sampling frequency Fs,which is greater than twice the maximum frequency of the signal. In time domain, the signals are represented as time versus amplitude. In MATLAB you can generate time base for given signals T=t start: 1/Fs:t-stop,tstart is the starting time of the signal t-sto is the stop time of the signal and Fs sampling frequency. 1/Fs is the time period between the two samples. In signals like speech if the data secured length is too long, plotting of the whole signal will not be clean view. In that case we can use step function.
RESULT The familiarization of MATLAB was completed.
Dept. Of ECE, SJCET, Palai
3
Systems Lab
DATE: 08-02-2011 EXPERIMENT NO: 2 BASIC DISCRETE TIME SIGNALS AIM To plot the following waveforms 1. Step Function 2. Impulse Function 3. Exponential Function 4. Ramp Function 5. Sine Function
THEORY A digital signal can be either deterministic signal that can be predicted with certainty or random signal that is unpredictable. Due to ease in signal generation and need for predictability, deterministic signal can be used for system simulation studies.Standard forms of some deterministic signal that is frequently used in DSP are discussed below: 1. Impulse:the simplest signal is the unit impulse signal which is defined as δ (n) = 1 for n = 0 = 0 for n ≠ 0 2. Step:the general form of step function is u (n) = 1 for n ≥ 0 = 0 for n< 0 3. Exponential:the decaying exponential is a basic signal in DSP.Their general form is given by
x (n) = a n for all n. 4. Ramp:signal is given by ur (n) = n for n ≥ 0 = 0 for n < 0 5. Sine:A sinusoidal sequence is defined as x(n) = sin(n). ALGORITHM 1. Start 2. Generate the time axis 3. Define A as sine function 4. Plot the sine wave Dept. Of ECE, SJCET, Palai
4
Systems Lab
5. Define B as exponential signal 6. Plot the exponential signal 7. Define r(n) as ramp signal 8. Plot the ramp signal 9. Define unit impulse signal 10. Plot the signal 11. Define unit step signal 12. Plot the signal 13.Stop MATLAB FUNCTIONS USED • CLC: clc clears all input and output from the Command Window display, giving you a ”clean screen. “After using clc, you cannot use the scroll bar to see the history of functions, but you still can use the up arrow to recall statements from the command history. • CLEAR ALL: clear removes all variables from the workspace. This frees up system memory. • CLOSE ALL: Closes all the open figure windows • SUBPLOT: subplot divides the current figure into rectangular panes that are numberedrowwise. Each pane contains an axes object. Subsequent plots are output to the current pane. • STEM: A two-dimensional stem plot displays data as lines extending from a baseline along the xaxis. A circle (the default) or other marker whose y-position represents the data value terminates each stem. • TITLE: Each axes graphics object can have one title. The title is located at the top and in the centre of the axes. • XLABEL: Each axes graphics object can have one label for the x-, y-, and z-axis. The label appears beneath its respective axis in a two-dimensional plot and to the side or beneath the axis in a threedimensional plot. • YLABEL: Each axes graphics object can have one label for the x-, y-, and z-axis. The label appears beneath its respective axis in a two-dimensional plot and to the side or beneath the axis in a threedimensional plot. • ZEROS: Create array of all zeros • ONES: Create array of all ones • SIN: The sin function operates element-wise on arrays. The function‟s domains and ranges include complex values. All angles are in radians. • EXP: The exp function is an elementary function that operates element-wise on arrays. Its domain includes complex numbers.
Dept. Of ECE, SJCET, Palai
5
Systems Lab
PROGRAM %Generation of Basic Discrete Signals clear all clc close all %Generation of Sinusoidal signal n =0:0.5:10; y=sin(n); subplot(3,2,1); stem(n,y); xlabel(' Samples '); ylabel(' Amplitude'); title (' Sine'); %Generation of Exponential signal y=exp(n); subplot(3,2,2); stem(n,y); xlabel (' Samples '); ylabel(' Amplitude'); title (' Exponential'); %Generation of Ramp signal n =1:10; y=n; subplot(3,2,3); stem(n,y); xlabel (' Samples '); ylabel(' Amplitude'); title (' Ramp'); %Generation of Unit Impulse signal n =-10:10; y=[zeros(1,10) 1 zeros(1,10)]; subplot(3,2,4); stem(n,y); xlabel (' Samples '); ylabel (' Amplitude'); Dept. Of ECE, SJCET, Palai
6
Systems Lab
title(' Impulse'); %Generation of Unit Step signal n =-10:10; y=[zeros(1,10) 1 ones(1,10)]; subplot(3,2,5); stem(n,y); xlabel (' Samples '); ylabel(' Amplitude'); title (' Step');
OUTPUT
RESULT
The MATLAB program to generate basic discrete signals is executed and output
waveforms are obtained.
Dept. Of ECE, SJCET, Palai
7
Systems Lab
DATE: 17-02-2011 EXPERIMENT NO: 3 IMPULSE RESPONSE & STEP RESPONSE AIM Write a MATLAB program to find the impulse response and step response of the system given by y(n) = x(n) + x(n-1) – 0.7y(n-1) at -20 ≤ n ≤ 100. THEORY The impulse response of a given system is its response to impulse function input. We know that y[n]=impulse response h[n],when input x[n] is unit impulse function Step response of a system is its output for step function. ALGORITHM 1. Start 2. Input the coefficients of x(n). 3. Generate impulse signal. 4. Input the coefficients of y(n). 5. Obtain the impulse response using filter function 6. Plot the impulse response. 7. Generate step signal. 8. Obtain the step response using filter function. 9. Plot the step response. 10. Stop. MATLAB FUNCTIONS USED FILTER: One dimensional digital filter. Y=FILTER (B, A, X) filter the data in vector X with the filter described by vectors A and B to create the filtered data Y. The filter is a “Direct Form II Transposed” implementation of the standard difference equation: a(1) * y(n) = b(1) * x(n) +b(2) * x(n - 1) + .... + b(nb + 1) * x(n - nb) - a(2) * y(n - 1) - . . . a(na + 1) * y(n - na) If a(1) is not equal to 1, filter normalizes the filter coefficients by a(1).
Dept. Of ECE, SJCET, Palai
8
Systems Lab
PROGRAM clc clear all close all x = [ 1 1]; y = [1 0.7]; n = -20:1:10; imp = [zeros(1,20) 1 zeros(1,10)]; h = filter (x, y, imp); subplot (2, 1, 1); stem (n,h); title(' Impulse Response '); xlabel (' Samples '); ylabel (' Amplitude '); stp = [zeros(1,10 1 ones(1,20)]; h = filter(x,y,stp); subplot ( 2, 1, 2); stem(n,h); title (' Step Response '); xlabel (' Samples '); ylabel (' Amplitude ');
Dept. Of ECE, SJCET, Palai
9
Systems Lab
OUTPUT
RESULT The MATLAB program to find the impulse response and step response of the given system is executed and output waveform is obtained.
Dept. Of ECE, SJCET, Palai
10
Systems Lab
DATE: 24-02-2011 EXPERIMENT NO: 4
LINEARITY, STABILITY & CAUSALITY
AIM Write a MATLAB program to find whether the given systems are linear, stable and causal. 1. y(n) = x(n) – 0.9y(n-1) 2. y(n) = exp x(n) THEORY A system is linear if and only if T [a1x1[n] + a2x2n]] = a1T [x1[n]] + a2T [x2[n]], for any arbitrary constants a1 and a2. Let x[n] be bounded input sequence and h[n] be impulse response of the system and y[n], the output sequence. Necessary and sufficient boundary condition for stability is8n = -8|h[n]| < 8. Causal system is a system where the output depends on past or current inputs but not on the future inputs. The necessary condition is h[n] = 0; < 0, where h[n] is the impulse response. ALGORITHM 1. Start 2. Input the coefficients of x(n) and y(n) 3. Generate random signals x1 and x2. 4. Check for linearity using filter function of the given system and display 5. Generate impulse signal. 6. Check for causality using filter function of the given system and display 7. Obtain the absolute value of impulse response and check for the stability of the system and display. 8. Stop MATLAB FUNCTIONS USED • RAND: Uniformly distributed pseudo random numbers. R=RAND (N) returns an N-by-N matrix containing pseudo-random values drawn from a uniform distribution on the unit interval. RAND (M , N)or RAND([M, N]) returns an M-by-N matrix.
Dept. Of ECE, SJCET, Palai
11
Systems Lab
• DISP: Display array. DISP(X) displays the array, without printing the array name. In all other ways it‟s the same as leaving the semicolon of an expression except that empty arrays don‟t display. • ABS: Absolute value. ABS(X) is the absolute value of the elements of X. • SUM: Sum of elements. S=SUM(X) is the sum of the elements of the vector X.
PROGRAM %Program to find linearity of system 1 clc clear all close all
% System 1 % Linearity b = [1 0]; a = [1 0.9];
x1 = rand (1,10); x2 = rand (1,10); y2 = filter (b, a, 2.*x1); y5 = filter (b, a,2.* x2); y = filter (b, a, x1); y0 = filter (b, a, x2); y6 = y2+y5; y7 = y+y0; if (y6-y7 ~= 0) disp (' Linear ') else disp (' Non Linear ') end; % Causality--------%%%
n= -10:1:10; x = [zeros(1,10) 1 zeros(1,10)]; y1 = filter (a, b, x); Dept. Of ECE, SJCET, Palai
12
Systems Lab
subplot (2, 1, 1); stem (n1,y1); xlabel (' Samples '); ylabel (' Amplitude ');
% Stability T = abs (y1); t = sum (T); if (t < 1000) disp (' Stable ') else disp (' Unstable ') end;
%%%%%%%%%% % System 2%%%%%%%%%%%%%%%%%%%%% % 1 % Linearity
y8 = exp (x2); y9 = exp ( x3); y10 = 5*y8+5*y9; y11 = exp(5*x2+5*x3); if (y11-y10~=0) disp (' 2Linear ') else disp (' 2Non Linear ') end;
% 2 % Causality
Y8= exp (x); subplot (2, 1, 2); stem (n1,y8); xlabel (' Samples '); ylabel (' Amplitude ');
Dept. Of ECE, SJCET, Palai
13
Systems Lab
% 3 % Stability T1= abs (y8); t1 = sum (T1); if (t1 < 1000) disp (' 2Stable ') else disp (' 2Unstable ') end; OUTPUT
System 1 Linear. Stable. System 2 Non Linear. Stable. Dept. Of ECE, SJCET, Palai
14
Systems Lab
RESULT The MATLAB program to find the linearity, causality, and stability of 2 systems given is executed and output is obtained System 1 Linear Stable Causal
Dept. Of ECE, SJCET, Palai
System 2 Non Linear Stable Non Causal
15
Systems Lab
DATE: 15-03-2011 EXPERIMENT NO: 5
CONVOLUTION AIM Write a MATLAB program to obtain linear and circular convolution of the following sequences 1.
x(n) = [1 2 3 4] h(n) = [1 2 3]
2.
x(n) = u(n) h(n) = u(n-2)
THEORY Convolution is used to find the output response of a digital system. The linear convolution of two continuous time signals x[n] and h[n] is defined by y[n] = x[n] * h[n]. Circular Convolution of two sequences x1[n] and x2[n], each of length N is given by y[n] = If the length of sequence is not equal, zero padding is done. Convolution operation will result in the convolved signal be zero outside of the range n= 0,1,...,N-1. ALGORITHM 1. Start 2. Input the sequences 3. Input the length of sequences 4. Calculate the linear convolution. 5. Calculate the circular convolution. 6. Stop
MATLAB FUNCTIONS USED
• CONV: Convolution and polynomial multiplication. C = CONV (A,B) convolves vectors A and B. The resulting vector is length LENGTH(A) + LENGTH(B) – 1 .If A and Bare vectors of polynomial coefficients, convolving them is equivalent to multiplying the two polynomials. • LENGTH: Length of vector. LENGTH(X) returns the length of vector X.
Dept. Of ECE, SJCET, Palai
16
Systems Lab
• CCONV: Convolution and polynomial multiplication. C = CONV (A,B) convolves vectors A and B. The resulting vector is length LENGTH(A) + LENGTH(B) – 1 .If A and Bare vectors of polynomial coefficients, convolving them is equivalent to multiplying the two polynomials.
PROGRAM %program to find convolution of two sequences clc close all clear all n = -10:10; x1 = [1 2 3 4]; subplot(4,2,1); stem(x1); title('-----x1(n)----'); h1 = [1,2,3]; subplot(4,2,3); stem(h1); title('-----h1(n)----'); %%%%%linear convolution%%%%%% l1 = conv(x1,h1) subplot(4,2,5); stem(l1); title('-----linear convolution-1--'); %%%%%%%%%% circular convolution %%%%%%%%%%%5 x1 = [1 2 3 4]; h1 = [1 2 3 0]; c1 = cconv(x1,h1,4)
Dept. Of ECE, SJCET, Palai
17
Systems Lab
subplot(4,2,7); stem(c1); title('-----circular convolution-1---');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% x2 = [zeros(1,10) ones(1,11)]; subplot(4,2,2); stem(n,x2); title('-----x2(n)----'); h2 = [zeros(1,12) ones(1,9)]; subplot(4,2,4); stem(n,h2); title('-----h2(n)----'); %%%%%linear convolution%%%%%% l2= conv(x2,h2) subplot(4,2,6); stem(l2); title('-----linear convolution--2--'); %%%%%%%%%% circular convolution %%%%%%%%%%% c2 = cconv(x2,h2,8) subplot(4,2,8); stem(c2); title('-----circular convolution--2----');
Dept. Of ECE, SJCET, Palai
18
Systems Lab
OUTPUT
RESULT The MATLAB program to find the linear convolution and circular convolution of given sequences is executed and output is obtained.
Dept. Of ECE, SJCET, Palai
19
Systems Lab
DATE: 15-03-2011 EXPERIMENT NO: 6
CONVOLUTION USING DFT
AIM 1. Write a MATLAB program to obtain linear convolution of x(n) = [1 2 3 4] h(n) = [1 2 2 -1] using DFT. 2. Write a MATLAB program to obtain circular convolution of x(n) = u(n),
h(n) = u(n-3)
THEORY Convolution is used to find the output response of a digital system. The linear convolution of two continuous time signals x[n] and h[n] is defined by y[n] = x[n] * h[n] = Let X(k) and H(k) be the Fourier transforms of x[n] and h[n] respectively. Then by DFT method, convolution of x[n] and h[n] is given by: x[n]*h[n]= Inverse Fourier transform of X(k).H(k). Circular convolution of two sequences x1[n] and x2[n], each of length N is given by y[n] = If the length of sequence is not equal, zero padding is done. Convolution operation will result in the convolved signal be zero outside of the range n= 0,1,...,N-1.Then by DFT method, convolution of x[n] and h[n] is given by: x[n]*h[n]= Inverse Fourier transform of X(k).H(k). ALGORITHM 1. Start 2. Input the sequences 3. Input the length of the sequences. 4. Find the FFT of the sequences 5. Multiply the FFT of the sequences. 6. Calculate the IFFT 7. Stop
Dept. Of ECE, SJCET, Palai
20
Systems Lab
MATLAB FUNCTIONS USED • FFT: Discrete Fourier Transform. FFT(X) is the discrete Fourier transform(DFT) of vectorX. FFT(X,N) is the N-point FFT, padded with zeros if X has less than N points and truncated if it has more. • IFFT: Inverse discrete Fourier transform. IFFT(X) is the inverse discrete Fourier transform of X. IIF(X,N) is the N-point inverse transform.
PROGRAM clc; close all; clear all; x1 = [1 2 3 4]; subplot(4,2,1); stem(x1); title('-----x1(n)----'); h1 = [1 2 2 -1]; subplot(4,2,3); stem(h1); title('-----h1(n)----'); l = conv(x1,h1) subplot(4,2,5); stem(l); title('-----linear convolution----') dx1 = fft(x1,7); dh1 = fft(h1,7); dl = dx1.*dh1; k1 = ifft(dl) subplot(4,2,7); stem(k1);
Dept. Of ECE, SJCET, Palai
21
Systems Lab
title('-----linear convolution--dft--'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% x2 = ones(1,6); subplot(4,2,2); stem(x2); title('-----x2(n)----'); h2 = [zeros(1,3) ones(1,3)]; subplot(4,2,4); stem(h2); title('-----h2(n)----'); c = cconv(x2,h2,6) subplot(4,2,6); stem(c); title('-----circular convolution------'); dx2 = fft(x2,6); dh2 = fft(h2,6); dc = dx2.*dh2; k2 = ifft(dc) subplot(4,2,8); stem(k2); title('-----circular convolution--dft----');
Dept. Of ECE, SJCET, Palai
22
Systems Lab
OUTPUT
RESULT The MATLAB program to find linear convolution and circular convolution of given sequences using DFT is executed and output is obtained.
Dept. Of ECE, SJCET, Palai
23
Systems Lab
DATE: 22-03-2011 EXPERIMENT NO: 7
CORRELATION
AIM a) Write a MATLAB program to compute autocorrelation of sequence x(n) = 0.9 n , n= 0 to 20 and verify the property. b) Compute cross-correlation of sequences x(n) = {1,2,3,4,5,6} and y(n) = x(n-3) and verify the property.
THEORY Autocorrelation is the cross-correlation of a signal with itself. The autocorrelation sequence of x(n) is given by RXX[l] = ∑
( ) (
)
Cross correlation is a measure of similarity of two signals, commonly used to find features in an unknown signal by comparing it to a known one. The correlation sequence of x(n) and y(n) is given by RXY[l] = ∑
( ) (
)
l=0,±1,±2,…
ALGORITHM 1. Start 2. Input the sequences 3. Find the autocorrelation of the sequence 4. Check for the symmetry property of the sequence 5. Find the cross correlation of the sequences 6. Check for the symmetry property of the sequence 7. Stop
Dept. Of ECE, SJCET, Palai
24
Systems Lab
MATLAB FUNCTIONS USED XCORR(A): when A is a vector, is the auto-correlation sequence.XCORR(A), when A is an M-by-N matrix, is a large matrix with2*M-1 rows whose N^2 columns contain the cross-correlation sequences for all combinations of the columns of A. XCORR(A,B): where A and B are length M vectors (M>1), returns the length 2*M-1 crosscorrelation sequence C. If A and B are of different length, the shortest one is zero-padded. FLIPLR: Flip matrix in left/right direction. FLIPLR(X) returns X with row preserved and columns flipped in the left/right direction. PROGRAM clc; clear all; close all; %autocorrelation of x(n) n=0:20; x=0.9.^n;
% input sequence
y =xcorr(x);
% autocorrelation
subplot(2,2,1); stem (y); xlabel (' Samples ') ylabel ('Amplitude'); title(' Autocorrelation of x(n)'); %autocorrelation ofx(-n) z =fliplr (y);
% flip the matrix y
subplot(2,2,2); stem (z); xlabel (' Samples '); ylabel(' Amplitude'); title (' Autocorrelation of x(-n)'); %cross correlation of x(n) & y(n) x1= [1 2 3 4 5 6 0 0 0];
%input
h1 = [0 0 0 1 2 3 4 5 6];
% input
y1 =xcorr (x1, h1);
% cross correlation of e and f
subplot(2,2,3); stem (y1); Dept. Of ECE, SJCET, Palai
25
Systems Lab
xlabel (' Samples ') ;ylabel(' Amplitude'); title(' Cross correlation of x(n) and y(n)'); %cross correlation property z1= fliplr (y1); subplot(2,2,4); stem (z1); xlabel (' Samples '); ylabel(' Amplitude'); title (' Cross correlation of x(-n) and h(-n)'); OUTPUT
RESULT The MATLAB program to compute autocorrelation and cross correlation of the given sequences is executed and output is obtained.
Dept. Of ECE, SJCET, Palai
26
Systems Lab
DATE: 22-03-2011 EXPERIMENT NO: 8
SAMPLING THEOREM
AIM Write a MATLAB program to generate x(n) = sin 0.5πn for n to 50. Verify sampling theorem.
THEORY Sampling Theorem: A band limited signal can be reconstructed exactly if it is sampled at a rate at least twice the maximum frequency component in it.” Figure 1 shows a signal g(t) that is band limited.
Figure 1: Spectrum of band limited signal g(t)
The maximum frequency component of g(t) is fm. To recover the signal g(t) exactly from its samples it has to be sampled at a rate fs=2fm. The minimum required sampling rate fs = 2fm iscalled Nyquist rate.
Dept. Of ECE, SJCET, Palai
27
Systems Lab
ALGORITHM 1. Start 2. Generate the sine wave 3. Resample the signal at various values. 4. Obtain the output waveforms 5. Stop MATLAB FUNCTIONS USED RESAMPLE : Change the sampling rate of a signal. Y = RESAMPLE(X,P,Q) resamples the sequence in vector X at P/Q times the original sample rate using a polyphase implementation. Y is P/Q times the length of X (or the ceiling of this if P/Q is not an integer). P and Q must be positive integers. PROGRAM % Verification of sampling theorem clc; clear all; close all; n = 0:0.5:50; x = sin(0.5*pi*n); subplot(4,1,1); stem(x); title('original'); y = resample(x,2,1); subplot(4,1,2); stem(y); title('fs = 2fm'); y = resample(x,4,1); subplot(4,1,3); stem(y); title('fs > 2fm'); y = resample(x,1,2); subplot(4,1,4); stem(y); title('fs<2fm');
Dept. Of ECE, SJCET, Palai
28
Systems Lab
OUTPUT
RESULT The MATLAB program to generate sine wave and to verify sampling theorem is executed and output is obtained.
Dept. Of ECE, SJCET, Palai
29
Systems Lab
DATE: 22-03-2011 EXPERIMENT NO: 9
POLE-ZERO PLOT
AIM Write a MATLAB program to find poles and zeros of the system given by y(n) = x(n) + 2x(n-1) – 0.9y(n-1)
THEORY In mathematics, signal processing and control theory, a pole–zero plot is a graphical representation of a rational transfer function in the complex plane which helps to convey certain properties of the system such as:
Stability
Causal system / anticausal system
Region of convergence (ROC)
Minimum phase / non minimum phase
In general, a rational transfer function for a discrete LTI system has the form:
Where
zi such that P(zi) = 0 are the zeros of the system
zj such that Q(zj) = 0 are the poles of the system
In the plot, the poles of the system are indicated by an x while the zeroes are indicated by an o.
ALGORITHM 1. Start 2. Input the coefficients of the system Dept. Of ECE, SJCET, Palai
30
Systems Lab
3. Plot the zeros and poles of the system 4. Stop MATLAB FUNCTIONS USED ZPLANE: Z-plane zero-pole plot. ZPLANE (Z,P) plots the zeros Z and poles P (in column vectors) with the unit circle for reference. Each zero is represented with a 'o' and each pole with a 'x' on the plot. Multiple zeros and poles are indicated by the multiplicity number shown to the upper right of the zero or pole. PROGRAM clc ;close all;clear all; b = [1 2];
% coefficient of x
a = [1 0.9];
% coefficient of y
zplane (b, a); OUTPUT
RESULT The MATLAB program to find the poles and zeros of given system was executed and output obtained correctly.
Dept. Of ECE, SJCET, Palai
31
Systems Lab
DATE: 22-03-2011 EXPERIMENT NO: 10
FIR FILTER DESIGN
AIM
1. Write a MATLAB program to design FIR filter and to plot magnitude and phase response for the given specification using Kaiser window. a. Pass band Ripple = 0.087 dB b. Stop band attenuation = 60 dB c. Pass band edge frequency = 0.4π d. Stop band edge frequency = 0.6π
2. Design FIR filter using rectangular, hamming and hanning window a. Pass band Ripple = 0.4 dB b. Stop band attenuation = 44 dB c. Pass band edge frequency = 3000Hz d. Stop band edge frequency = 2000Hz e. Sampling Frequency = 8000 Hz
THEORY The basic idea behind the window design is to choose a proper ideal frequency selective filter (which always has a non-causal, infinite duration impulse response), and then truncate ( or window) its impulse response to obtain a linear phase and causal FIR filter. One possible way of obtaining FIR (
filter is to truncate the Fourier series at n= ±
)
, where N is the length of the desired sequence but
abrupt truncation of the Fourier series results in oscillation in the pass band and stop band. These oscillations are due to slow convergence of the Fourier series and this effect is known as Gibbs phenomenon. To reduce this oscillations the Fourier coefficients of the filter are modified by multiplying the infinite impulse response with a finite weighing sequence w(n) called a window.
Dept. Of ECE, SJCET, Palai
32
Systems Lab
Rectangular window is given by (
)
Wr (n) = 1; for n=± = 0;
otherwise )
Frequency response: H(
(
∫
)
(
(
)
)
The convolution of the desired response and the rectangular window response gives rise to ripples in both passband and stop band. This Gibbs phenomenon can be reduced by using a less abrupt truncation of filter coefficients. This can be achieved using a window function that tapers smoothly towards zero at both ends. Hamming window is given by, (
)
Wh(n) = 0.54+0.046cos(2πn/N-1); for n=± = 0; otherwise )
Frequency response: H(
(
∫
)
(
(
)
)
This window generates less oscillation in the side lobes than the hamming window. At higher frequencies the stop band attenuation is low when compared to the hanning window. Hanning window is given by, (
)
WHn(n) = .5+.5cos(2πn/N-1);for n=± = 0; otherwise
This window results in smaller ripples in both passband and stop band of the filter. At higher frequencies the stop band attenuation is even greater. Kaiser window is given by, (
WK(n) =
(( ( )
)
)
(
; for n=±
)
= 0; otherwise This is one of the most useful and optimum window. It provides large main lobe width for the given stop band attenuation, which implies the sharpest transition width. Α is the parameter that depends on N (window length) and that can be chosen to yield the various transmission widths and near optimum stop band attenuation. ALGORITHM 1. Start 2. Input the design parameters of the system. 3. Find the order of the 4. Design the FIR filter using Kaiser Window 5. Plot the magnitude and phase response. Dept. Of ECE, SJCET, Palai
33
Systems Lab
6. Design the FIR filter using Hanning window 7. Plot the magnitude and phase response 8. Design the FIR filter using Hamming window 9. Plot the magnitude and phase response. 10. Design the FIR filter using Rectangular window 11. Plot the magnitude and phase response. 12. Stop MATLAB FUNCTIONS USED
FIR1: FIR filters design using the window method. B = FIR1(N,Wn) designs an N'th order low pass FIR digital filter and returns the filter coefficients in length N+1 vector B
FREQZ: Digital filter frequency response. [H, W] = FREQZ(B,A,N) returns the N-point complex frequency response vector H and the N-point frequency vector W in radians/sample of the filter
ANGLE: Phase angle. ANGLE(H) returns the phase angles, in radians, of a matrix with complex elements.
HANN: Hanning window. HANN(N) returns the N-point symmetric Hanning window in a column vector.
GRID: Grid lines.
GRID ON: adds major grid lines to the current axes.
HAMMING: Hamming window. HAMMING(N) returns the N-point symmetric Hamming window in a column vector.
RECTWIN: Rectangular window. W = RECTWIN(N) returns the N-point rectangular window.
KAISERORD: FIR order estimator (lowpass, highpass, bandpass, and multiband). [N,Wn,BTA,FILTYPE] = KAISERORD(F,A,DEV,Fs) is the approximate order N, normalized frequency band edges Wn, Kaiser window beta parameter BTA and filter type FILTYPE to be used by the FIR1 function: B = FIR1(N, Wn, FILTYPE, kaiser( N+1,BTA ), 'noscale' ), F vector of band edge frequencies in Hz in ascending order between 0 and half the sampling frequency Fs, DEV is the vector of maximum deviation or ripples allowable for each band.
PLOT: Linear plot. PLOT(X, Y) plots vector Y versus vector X. If X or Y is a matrix then the vector is plotted versus the rows or columns of the matrix, whichever line up.
PROGRAM clear all; Dept. Of ECE, SJCET, Palai
34
Systems Lab
close all; clc ; % Kaiser Window %pass band ripple = 0.087dB %stop band attenuation = 60dB %pass band edge frequency = 0.4π rad/sec %stop band edge frequency = 0.6π rad/sec %sampling frequency = 100 rad/sec fs = 100;
%rad/sec, sampling frequency
pf = 0.4*pi;
%rad/sec, pass band frequency
sf = 0.6*pi;
%rad/sec, stop band frequency
fsamp = fs/(2*pi);
% fs into hertz
pf1 = pf/(2*pi);
% pf into hetz
sf1 = sf/(2*pi);
% sf into hertz
d1 = 10^(-0.05*60);
%stop band ripple
d2 = (10^(0.05*0.087)-1)/(10^(0.05*0.087)+1); %pass band ripple fcuts = [pf1 sf1]; mags = [1 0];
%pass and stop band cut off frequency %magnitude assigning
%d3 = min(d1,d2); devs = [d2 d1];
%setting deviation
w = 0:0.01:pi; %to get the order n, kaiser window beta parameter BTA and filter type [n,Wn,beta,ftype] = kaiserord(fcuts,mags,devs,fs); %filter design using windows h = fir1(n,Wn,ftype,kaiser(n+1,beta),'noscale'); [H,f] = freqz(h,1,w); % frequency response and frequency vector gain = 20*log10(abs(H)); a = angle(H); %PLOTTING THE GRAPHS subplot(2,1,1); plot(f/pi, gain); grid on; title(' Magnitude Response of Kaiser Window'); xlabel(' Normalised Frequency'); ylabel (' Gain in DB'); subplot(2,1,2); Dept. Of ECE, SJCET, Palai
35
Systems Lab
plot(f/pi, a); grid on; title(„ Phase Response of Kaiser Window „); xlabel(' Normalised Frequency'); ylabel(' Angle'); %hanning,hamming and rectangular window %pass band ripple = 0.4dB %stop band attenuation = 44dB %pass band edge frequency = 3000Hz %stop band edge frequency = 2000Hz %sampling frequency = 8000Hz fsamp = 8000;
%sampling frequency
fcuts = [2000 3000];
%pass band and stopband edge frequency
mags = [0 1];
%magnitude
d1 = 10^(-0.05*44);
%stop band ripple
d2 = (10^(0.05*0.1)-1)/(10^(0.05*0.1)+1); devs = [d2 d1];
%pass band ripple
%setting deviation
W = 0:0.01:pi; [n,Wn,beta,ftype] = kaiserord(fcuts,mags,devs,fsamp);
%to get the order
% hanning window h = hann(n+1); b = fir1(n,Wn,h); w = 0:0.01:pi; [H,f] = freqz(b,1,w); gain = 20*log10(abs(H)); an = angle(H); %plotting magnitude and phase response of hanning window figure; subplot(2,1,1); plot(f/pi, gain); grid on; title('Magnitude Response Hanning Window'); xlabel('Normalised Frequency'); ylabel('Gain in dB'); subplot(2,1,2); plot(f/pi, an); grid on; title('Phase Response of Hanning Window'); Dept. Of ECE, SJCET, Palai
36
Systems Lab
xlabel(' Normalised Frequency'); ylabel(' Angle'); % HAMMING WINDOW h = hamming(n+1); b = fir1(n,Wn,h); w = 0:0.01:pi; [H,f] = freqz(b,1,w); gain = 20*log10(abs(H)); an = angle(H); %plotting magnitude and phase response of hanning window figure; subplot(2,1,1); plot(f/pi, gain); grid on; title (' Magnitude Response of Hamming Window '); xlabel(' Normalised Frequency'); ylabel (' Gain in dB'); subplot(2,1,2); plot(f/pi, an); grid on; title(' Phase Response of Hamming Window '); xlabel (' Normalised Frequency'); ylabel(' Angle'); %RECTANGULAR WINDOW h = rectwin(n+1); b = fir1(n,Wn,h); w = 0:0.01:pi; [H,f] = freqz(b,1,w); gain = 20*log10(abs(H)); an = angle(H); %plotting magnitude and phase response of hanning window figure; subplot(2,1,1); plot(f/pi,gain); grid on; title (' Magnitude Response of Rectangular Window '); xlabel (' Normalised Frequency'); ylabel (' Gain in dB'); Dept. Of ECE, SJCET, Palai
37
Systems Lab
subplot(2,1,2); plot (f/pi, an); grid on; title ('Phase Response of Rectangular Window'); xlabel(' Normalised Frequency'); ylabel(' Angle');
OUTPUT
Dept. Of ECE, SJCET, Palai
38
Systems Lab
Dept. Of ECE, SJCET, Palai
39
Systems Lab
RESULT The MATLAB program to design FIR filter and to plot the responses are executed and output was verified.
Dept. Of ECE, SJCET, Palai
40
Systems Lab
DATE: 22-03-2011 EXPERIMENT NO: 11
IIR FILTER DESIGN
AIM
1. Write a MATLAB program to design Butterworth BPF with given specification and plot its response a. Pass band Ripple = 1.5 dB b. Stop band attenuation = 20 dB c. Pass band edge frequency = 800 Hz < f< 1000 Hz d. Stop band edge frequency = 0 to 400 Hz and 2000Hz to infinity e. Sampling Frequency = 8000 Hz
2. Write a MATLAB program to design Type -1 Chebyshev filter with given specification and plot its response a. Pass band Ripple = 0.5 dB b. Stop band attenuation = 20 dB c. Pass band edge frequency = 800Hz d. Stop band edge frequency = 300Hz e. Sampling Frequency = 3000 Hz
THEORY The Butterworth filter is a type of signal processing filter designed to have as flat a frequency response as possible in the pass band so that it is also termed a maximally flat magnitude filter.The frequency response of the Butterworth filter is maximally flat (has no ripples) in the pass band and rolls off towards zero in the stop band. When viewed on a logarithmic Bode plot the response slopes off linearly towards negative infinity. A first-order filter's response rolls off at −6 dB per octave (−20 dB per decade) (all first-order low pass filters have the same normalized frequency response). A second-order filter decreases at −12 Dept. Of ECE, SJCET, Palai
41
Systems Lab
dB per octave, a third-order at −18 dB and so on. Butterworth filters have a monotonically changing magnitude function with ω, unlike other filter types that have non-monotonic ripple in the pass band and/or the stop band. Chebyshev filters are analog or digital filters having a steeper roll-off and more pass band ripple (type I) or stop band ripple (type II) than Butterworth filters. Chebyshev filters have the property that they minimize the error between the idealized and the actual filter characteristic over the range of the filter, but with ripples in the pass band. Because of the pass band ripple inherent in Chebyshev filters, filters which have a smoother response in the passband but a more irregular response in the stop band are preferred for some applications. These are the most common Chebyshev filters. The gain (or amplitude) response as a function of angular frequency ω of the nth order low pass filter is
Where is the ripple factor, ω0 is the cut-off frequency and Tn() is a Chebyshev polynomial of the nth order.
ALGORITHM 1. Start 2. Input the system parameters 3. Calculate the cut-off and order. 4. Design the Butterworth filter 5. Plot the magnitude and phase response 6. Design the Type-1 Chebyshev filter 7. Plot the magnitude and phase response 8. Stop
MATLAB FUNCTIONS USED
BUTTORD Butterworth filter order selection.
[N, Wn] = BUTTORD (Wp, Ws, Rp, Rs) returns the order N of the lowest order digital Butterworth filter that loses no more than Rp dB in the passband and has at least Rs dB of attenuation in the stop band. Wp and Ws are the passband and stop band edge frequencies, normalized from 0 to 1 (where 1 corresponds to pi radians/sample) Dept. Of ECE, SJCET, Palai
42
Systems Lab
BUTTER Butterworth digital and analog filter design.
[B, A] = BUTTER (N, Wn) designs an Nth order low pass digital Butterworth filter and returns the filter coefficients in length N+1 vectors B (numerator) and A (denominator). The coefficients are listed in descending powers of z. The cutoff frequency Wn must be 0.0 < Wn < 1.0, with 1.0 corresponding to half the sample rate.
CHEBY1 Chebyshev Type I digital and analog filter design.
[B, A] = CHEBY1(N, R, Wp) designs an Nth order lowpass digital Chebyshev filter with R decibels of peak-to-peak ripple in the passband. CHEBY1returns the filter coefficients in length N+1 vectors B (numerator) andA (denominator). The passband-edge frequency Wp must be 0.0 < Wp < 1.0 with 1.0 corresponding to half the sample rate.
CHEB1ORD Chebyshev Type I filter order selection.
[N, Wp] = CHEB1ORD (Wp, Ws, Rp, Rs) returns the order N of the lowest order digital Chebyshev Type I filter that loses no more than Rp dB in the passband and has at least Rs dB of attenuation in the stopband. Wp and Ws are the passband and stopband edge frequencies, normalized from 0 to 1 (where 1 corresponds to pi radians/sample).
PROGRAM
%BUTTERWORTH BAND PASS FILTER %pass band ripple = 1.5dB %stop band attenuation = 20dB %pass band frequency = 800Hz<= f <=1000Hz %stop band frequency = 0 <= f <= 400Hz and 2000Hz <= f <= infinity %sampling frequency = 8000Hz clear all close all clc rp = 1.5;
% passband ripple
rs = 20;
%stop band ripple
ft = 8000;
%sampling frequency
wp1 = 2* 800/ft;
Dept. Of ECE, SJCET, Palai
%normalize passband edge frequencies
43
Systems Lab
wp2 = 2* 1000/ft; wp = [wp1 wp2];
%pass band corner frequencies
ws1 = 2* 400/ft;
%normalize stop band edge frequencies
ws2 = 2* 2000/ft; ws = [ws1 ws2];
%stop band corner frequency
[n,Wn] = buttord(wp, ws, rp,rs); %to calculate order and cut off [b,a] = butter (n, Wn); % to design bandpass filter coefficients w = 0:0.01:pi; freqz(b,a,w);
% to plot magnitude and phase response
%CHEBYSHEV HIGHPASS FILTER %pass band ripple = 0.5dB %stop band attenuation = 20dB %pass band edge frequency = 800Hz %stop band edge frequency = 300Hz %sampling frequency = 3000Hz rp = 0.5;
% passband ripple
rs = 20;
%stop band ripple
ft = 3000;
%sampling frequency
wp = 2* 800/ft;
%normalize passband frequency
ws = 2* 300/ft; %normalize stop band frequency [n,Wn] = cheb1ord(wp,ws,rp,rs);
%returns order N and cut off
[b,a] = cheby1(n,rp,Wn,'high');
%designs an nth order high pass digital Chebyshev filter
w = 0:0.01:pi; figure; freqz(b,a,w);
Dept. Of ECE, SJCET, Palai
% to plot magnitude and phase response
44
Systems Lab
OUTPUT Butterworth filter
Chebyshev filter
Dept. Of ECE, SJCET, Palai
45
Systems Lab
RESULT The MATLAB program to design a Butterworth band pass filter and type 1 Chebyshev high pass filter has been executed and the filter responses are plotted.
Dept. Of ECE, SJCET, Palai
46
Systems Lab
DATE: 30-03-2011 EXPERIMENT NO: 12
FAMILIARIZATION OF VHDL AIM To familiarize the VHDL programming. THEORY VHDL is a hardware description language. It describes the behaviour of an electronic circuit or system from which the physical circuit or system can then be attained (implemented). VHDL stands for VHSIC Hardware Description Language. VHSIC is itself an abbreviation for Very High Speed Integrated Circuits, an initiative funded by the United States Department of Defence in the 1980s that led to the creation of VHDL. Its first version was VHDL 87, later upgraded to the so called VHDL 93.vHDL was the original and first hardware description language to be standardized by the institute of electrical and Electronics Engineers through the IEEE 1076 standard. An additional standard, the IEEE 1164, was later added to introduce a multi-valued logic system. VHDL is intended for circuit synthesis as well as circuit simulation. However, though VHDL is, fully simulateable, not all constructs are synthesizable. A fundamental motivation to use VHDL (or its competitor, verilog) is that VHDL is a standard, technology/vendor independent language, and is therefore portable and reusable. The two main immediate applications of VHDL are in the field of programmable Logic Devices (including CPLDs and FPGAs) and in the field of ASICs (Application Specific Integrated Circuits). Once the VHDL code has been written, it can be used either to implement the circuit in a programmable device (from Atera, Xilinx, Atmel etc) or can be submitted to a foundry for fabrication of an ASIC chip. Currently, many complex commercial chips (microcontrollers, for example) are designed using such an approach. A final note regarding VHDL is that, contrary to regular computer programs which are sequential, its statements are inherently concurrent parallel 0. for that reason, VHDL is usually referred to as code rather than program. In VHDL, only statements placed inside a PROCESS, FUNCTION, or PROCEDURE are executed sequentially.
Dept. Of ECE, SJCET, Palai
47
Systems Lab
DESIGN FLOW
VHDL enter (RTD Level) ( RTD level) Computation Netlist (gate level)
(Gate Optimization level) Optimized Netlist (gatelevel)
Simulation
Physical Device
Stimulation
We start the design by writing the VHDL code, which is saved in a file with the extension .vhd and the same name as its ENTITY's name. The first step in the synthesis process is compilation. Compilation is the conversion of the high-level VHDL language, which describes the circuit at the register Transfer level (RTL) into a netlist at the gate. VHDL is a hardware description language that can be used to model a digital system. The digital system can be as simple as a logic gate or as complex as a complete electronic system. A hardware abstraction of this digital system is called an entity. This model specifies the external view of the device and one or more internal views. The internal view of the device specifies the functionality or structure, while the external view specifies the interface of the device through which it communicates with the other models in its environment. Figure I.I shows the hardware device and the corresponding software model. Figure 1.2 shows the VHDL view of a hardware device that has multiple device models, with each device model representing one entity.
Dept. Of ECE, SJCET, Palai
48
Systems Lab
To describe an entity, VHDL provides five different types of primary constructs, called" design units. They are 1. Entity declaration 2. Architecture body 3. Configuration declaration 4. Package declaration 5. Package body Entity declaration An entity is modelled using an entity declaration and at least one architecture body. The entity declaration describes the external view of the entity, for example, the input and output signal names. The entity' declaration specifies the name of the entity being modelled and lists the set of interface ports. Ports are signals through which the entity communicates with the other models in its external environment. Architecture body The architecture body contains the internal description of the entity, for example, as a set of interconnected components that represents the structure of the entity, or as a set of concurrent or sequential statements that represents the behavior of the entity. Each style of representation can be specified in a different architecture body or mixed within a single architecture body. The internal details of an entity are specified by an architecture body using any of the following modeling styles: 1. As a set of interconnected components (to represent structure), 2. As a set of concurrent assignment statements (to represent dataflow), Dept. Of ECE, SJCET, Palai
49
Systems Lab
3. As a set of sequential assignment statements (to represent behavior), 4. Any combination of the above three. The structural style of modelling describes only an interconnection of components without implying any behaviour of the components themselves, nor of the entity that they collectively represent. In data flow style of modelling , the flow of data through the entity is expressed primarily using concurrent signal assignment statements. The structure of the entity is not explicitly specified in this modelling style, but it can be implicitly deduced. The behavioural style of modelling specifies the behaviour of an entity as a set of statements that are executed sequentially in the specified order. This set of sequential statements, that are specified inside a process statement, do not explicitly specify the structure of the entity but merely specifies its functionality. A process statement is a concurrent statement that can appear within an architecture body. It is possible to mix the three modelling styles that we have seen so far in a single architecture body. That is, within an architecture body, we could use component instantiation statements (that represent structure), concurrent signal assignment statements (that represent dataflow), and process statements (that represent behaviour). Configuration declaration A configuration declaration is used to create a configuration for an entity. It specifies the binding of one architecture body from the many architecture bodies that may be associated with the entity. It may also specify the bindings of components used in the selected architecture body to other entities. An entity may have any number of different configurations.
Package declaration A package declaration encapsulates a set of related declarations such as type declarations, subtype declarations, and subprogram declarations that can be shared across two or more design units.
Package body A package body is primarily used to store the definitions of functions and procedures that were declared in the corresponding package declaration, and also the complete constant declarations for any deferred constants that appear in the package declaration. Therefore, a package body is always associated with a package declaration; furthermore, a package declaration can have at most one package body associated with it. Contrast this with an architecture body and an entity declaration where multiple architecture bodies may be associated with a single entity declaration. Library declaration In
Library,
the
various
definition
group
to
use
in
VHDL
is
declared.
Generally, the declaration of the standard logic which is prescribed in the IEEE is specified. There is various declaration but it seems OK if declaring the following 2 lines. Dept. Of ECE, SJCET, Palai
50
Systems Lab
library ieee; use
ieee.std_logic_1164.all;
The above declares all definitions which are prescribed in STD_LOGIC_1164 of the IEEE. When using Xilinx Project Navigator, these declare statements are already written when making a source file newly. When you design the more complicated circuit, more declaration must be done. When using an arithmetic operation in the processing STD_LOGIC_UNSIGNED must be specified. use ieee.std_logic_unsigned.all; Entity statements In Entity, a port declaration, an attribute declaration, a generic declaration and so on are written. When Entity ends, it writes END. The entity name behind end can be omitted. Below, I will explain a port declaration and an attribute declaration. Entity and architecture declaration entity entity-name is port (signal-names : mode signal-type; signal-names : mode signal-type; … signal-names : mode signal-type); end entity-names; architecture architecture-name of entity-name is type declarations signal declarations constant declarations function definitions procedure definitions component declarations begin concurrent-statement … concurrent-statement end architecture-name;
RESULT The VHDL programming is familiarized.
Dept. Of ECE, SJCET, Palai
51
Systems Lab
DATE: 30-03-2011 EXPERIMENT NO: 13
LOGIC GATES AIM Write a VHDL program for generating waveforms of various logic gates. THEORY AND gate An AND gate may have two or more inputs but only one output. The output of an AND gate is 1 if and only if all the inputs are 1. Its logical equation is given by C=A.B Truth Table
OR gate An OR gate may have two or more inputs but only one output. The output of an OR gate is one if and only if one or more inputs are 1. Its logical equation is given by C=A+B
Dept. Of ECE, SJCET, Palai
52
Systems Lab
Truth Table
NOT gate A NOT gate, also called an inverter, has only one input and only one output. The output of a NOT gate assumes the logic 1 state when its input is in logic 0 state and assumes the logic 0 state when its input is in logic 1 state.
Truth Table
NAND gate NAND gate is a combination of an AND gate and a NOT gate. The output is a logic 0 level, only when each of the inputs assumes logic 1 level. For any other combination of inputs, the output is logic 1 level.
Dept. Of ECE, SJCET, Palai
53
Systems Lab
Truth Table
NOR gate NOR gate is a combination of an OR gate and a NOT gate. The output is logic 1 level, only when each of its inputs assumes a logic 0 level. For any other combination of inputs, the output is logic 0 level.
Truth Table
XOR gate The XOR operation is widely used in digital circuits. The output of XOR gate is logic 0 when both the inputs are same and the output is logic 1 when the inputs are not same.
Dept. Of ECE, SJCET, Palai
54
Systems Lab
Truth Table
XNOR gate An XNOR gate is a combination of an XOR gate and a NOT gate. The XNOR gate is a two input, one output logic, whose output assumes a 1 state only when both the inputs assumes a logic 0 state and the other a 1 state.
Truth Table
Dept. Of ECE, SJCET, Palai
55
Systems Lab
PROCEDURE 1. Create a new work space. 2. Create new file 3. Choose vhdl source 4. Enter name of source file and name of entity 5. Enter inputs and outputs. 6. Enter the program 7. Compile 8. Initialize simulation 9. Add simulators and generate waveform 10. End simulation PROGRAM library IEEE; use IEEE.STD_LOGIC_1164.all;
entityentity_logicgate is port( a : in STD_LOGIC; b : in STD_LOGIC; c_or : out STD_LOGIC; c_and : out STD_LOGIC; c_nor : out STD_LOGIC; c_nand : out STD_LOGIC; c_xor : out STD_LOGIC; c_not : out STD_LOGIC ); endentity_logicgate;
architecturearch_logicgate of entity_logicgate is begin c_or <= a or b; c_and <= a and b; c_nor <= a nor b; c_nand <= a nand b; Dept. Of ECE, SJCET, Palai
56
Systems Lab
c_xor <= a xor b; c_not <= not b; endarch_logicgate;
WAVEFORMS:
RESULT The VHDL programs for logic gates are executed correctly and output waveforms are plotted.
Dept. Of ECE, SJCET, Palai
57
Systems Lab
DATE: 30-03-2011 EXPERIMENT NO: 14
HALF ADDER AND FULL ADDER
AIM To write a program for half adder and full adder in VHDL. THEORY 1. HALF ADDER A half adder is a circuit that adds two binary digits, giving a sum bit and a carry bit. Sum, S=A ̅ +B ̅=A B Carry, C =AB Truth table OUTPUTS A 0 0 1 1
B 0 1 0 1
SUM 0 1 1 1
CARRY 0 0 0 1
2. FULL ADDER A full adder is an arithmetic circuit that adds two bits and outputs a sum bit and a carry bit. When adding two binary numbers each having two or more bits the LSBs can be added using a half adder. The carry resulted from the addition of the LSBs is carried to the next significant column and added to the two bits in that column. The full adder adds the bits A and B and the carry from the previous column called carry_in, Cin and outputs the sum bit S and the carry bit called the carry_out Cout. Sum=A
B
C
Carry, Cout=AB+ACin+BCin
Dept. Of ECE, SJCET, Palai
58
Systems Lab
Truth table
A 0 0 0 0 1 1 1 1
B 0 0 1 1 0 0 1 1
C 0 1 0 1 0 1 0 1
OUTPUTS SUM CARRY 0 0 1 0 1 0 0 1 1 0 0 1 0 1 1 1
PROCEDURE 1. Create new workspace 2. Create new file 3. Choose vhdl source 4. Enter name of source file and name of entity 5. Enter inputs and outputs 6. Enter the program 7. Compile 8. Initialize simulation 9. Add simulators and generate waveform 10. End simulation PROGRAM library IEEE; use IEEE.STD_LOGIC_1164.all; entity adder is port( a : in STD_LOGIC; b : in STD_LOGIC; c : in STD_LOGIC; sum_half : out STD_LOGIC; sum_full : out STD_LOGIC; c_half : out STD_LOGIC; c_full : out STD_LOGIC ); Dept. Of ECE, SJCET, Palai
59
Systems Lab
end adder;
architecture behaviour of adder is begin sum_half <= a xor b; c_half <= a and b; sum_full <= a xor b xor c ; c_full <= (a and b) or ( a and c) or (b and c); end behaviour; WAVEFORMS
RESULT Half adder and full adder are implemented using VHDL and output waveforms are plotted.
Dept. Of ECE, SJCET, Palai
60
Systems Lab
DATE: 30-03-2011 EXPERIMENT NO.: 15
FLIP FLOPS AIM To write VHDL program for implementing the following flip flops.
D flip flop T flip flop JK flip flop SR flip flop
THEORY Flipflop, which is made up of an assembly of logic gates, is a memory element. A logic gate by itself has no storage capability, but when connected together in ways permits the information to be stored. A flipflop known as bistable multivibrator has two states. It can remain in either of the twp states indefinitely. Its state can be changed by applying the proper triggering signal. SR Flipflop S-R flipflop is the simplest type of flip flop. It has two outputs labelled Q and ̅ and two inputs labelled S and R. The state of the flipflop corresponds to the level of Q (high or low, 1 or 0) and ̅ the compliment of the state. Q0 represents the state of the flipflop before applying the inputs. The name S-R or SET- RESET is derived from the names of its inputs. Truth Table INPUTS S 0 0 1 1
R 0 1 0 1
OUTPUT Q Q0 0 1 U
COMMENTS No change RESET SET Invalid
JK Flipflop JK flipflop is very versatile and most widely used. The functioning of JK is similar to that of SR flipflop, except that it has no invalid state as in SR When J=K=1, the flipflop toggles. Dept. Of ECE, SJCET, Palai
61
Systems Lab
Truth table INPUTS J 0 0 1 1
K 0 1 0 1
OUTPUT Q Q0 0 1 ̅0
COMMENTS No Change RESET SET Toggle
D Flipflop The edge triggered D flip-flop has only one input terminal. The D flipflop may be obtained from SR by just putting one inverter between the S and R terminals. The single input to the D flipflop is called the data input. The level present at D will be stored in the flipflop at the instant the positive going transition occurs. Truth Table INPUT D 0 1
OUTPUT Q 0 1
COMMENTS RESET SET
T Flipflop A T flipflop has a single control input, labelled T for toggle. When T is HIGH, the flip-flop toggles on every new clock pulse. When T is LOW, the flip flop remains in whatever state it was before. T flipflop is obtained by connecting the J and K inputs to JK flipflop together. Truth Table INPUT T 0 1
Dept. Of ECE, SJCET, Palai
OUTPUT Q Q0 ̅0
COMMENTS No Change Toggle
62
Systems Lab
PROCEDURE 1. Create new workspace 2. Create new file 3. Choose VHDL source 4. Enter name of source file and name of entity 5. Enter inputs and outputs 6. Enter the program 7. Compile 8. Initialize simulation 9. Add simulators and generate waveform 10. End simulation
PROGRAM library IEEE; use IEEE.STD_LOGIC_1164.all;
entityff is port( d : in STD_LOGIC; t : in STD_LOGIC; s : in STD_LOGIC; r : in STD_LOGIC; j : in STD_LOGIC; k : in STD_LOGIC; clk : in STD_LOGIC; rst : in STD_LOGIC; dout : out STD_LOGIC; tout : inout STD_LOGIC; srout : inout STD_LOGIC; jkout : inout STD_LOGIC ); endff;
Dept. Of ECE, SJCET, Palai
63
Systems Lab
architecture behaviour of ff is begin process(clk,d,rst) begin caserst is when '0' => if (clk 'event and clk = '1') then dout<= d; end if; when '1' => dout <= '0'; when others => null; end case; end process; -- T FLIPFLOP process (t, clk) begin caserst is when '0' => if(clk' event and clk = '1' and t = '0')then tout<= tout; elsif ( clk' event and clk = '1' and t = '1') then tout<= not tout; end if; when '1' => tout <= '0'; when others => null; end case; end process; -- J K FLIPFLOP Process (j, k, clk,rst) begin caserst is when '0' => if(clk' event and clk = '1' and j = '0' and k = '0') then jkout<= jkout; elsif(clk' event and clk = '1' and j = '0' and k = '1') then Dept. Of ECE, SJCET, Palai
64
Systems Lab
jkout<= '0'; elsif(clk' event and clk = '1' and j = '1' and k = '0') then jkout<= '1'; elsif(clk' event and clk = '1' and j = '1' and k = '1') then jkout<= not jkout; end if; when '1' => jkout <= '0'; when others => null; end case; end process; -- S R FLIPFLOP process (s, r, clk,rst) begin caserst is when '0' => if (clk' event and clk = '1' and s = '0' and r = '0') then srout<= srout; elsif (clk' event and clk = '1' and s = '0' and r = '1') then srout<= '0'; elsif (clk' event and clk = '1' and s = '1' and r = '0') then srout<= '1'; elsif(clk' event and clk = '1' and s = '1' and r = '1') then srout<= '1'; end if; when '1' => srout <= '0'; when others => null; end case; end process; end behaviour;
Dept. Of ECE, SJCET, Palai
65
Systems Lab
WAVEFORMS
RESULT All the flipflops are implemented using VHDL and output waveforms are plotted.
Dept. Of ECE, SJCET, Palai
66
Systems Lab
DATE: 30-03-2011 EXPERIMENT NO: 16
COMPARATOR AIM To design a comparator using VHDL
THEORY A comparator is a logic circuit used to compare the magnitude of two binary numbers. Depending on the design, it may either simply provide an output that is active when the two numbers are equal or additionally provide outputs that signify which of the numbers is greater when equality does not hold. Two binary numbers are equal, if and only if all their corresponding bits coincide. For example, two 4-bit numbers, A3A2A1A0 and B3B2B1B0 are equal, if and only if A3= B3, A2= B2, A1= B1 and A0= B0.
PROCEDURE 1. Create new workspace. 2. Create new file. 3. Choose vhdl source. 4. Enter name of source file and name of entity. 5. Enter inputs and outputs. 6. Enter the program. 7. Compile. 8. Initialize simulation. 9. Add simulators and generate waveform. 10. End simulation. PROGRAM library IEEE; use IEEE.STD_LOGIC_1164.all;
entity comparator is port( a : in STD_LOGIC_VECTOR(2 downto 0); b : in STD_LOGIC_VECTOR(2 downto 0); Dept. Of ECE, SJCET, Palai
67
Systems Lab
c : out STD_LOGIC_VECTOR(1 downto 0) ); end comparator;
architecture behaviour of comparator is begin process(a,b) begin if(a>b)then c<="00"; elsif(a
RESULT The VHDL program for comparator is executed correctly and the waveform obtained while simulation is plotted.
Dept. Of ECE, SJCET, Palai
68