Você está na página 1de 147

Department of Electronics and Communication

VCET,Hyderabad.

DIGITAL SIGNAL PROCESSING


LAB MANUAL

III YEAR II SEMESTER (ECE )

Prepared by: K. Ashok Kumar Reddy

Department of Electronics & Communications Engineering,

Visvesvaraya College of Engineering & Technology,


Ibrahimpatnam.

Digital Signal Processing Lab Manual

Page 1

Department of Electronics and Communication

VCET,Hyderabad.

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD III Year B.Tech. ECE - II Sem L T/P/D C 0 -/3/2

DIGITAL SIGNAL PROCESSING LAB The programs shall be implemented in software (Using MATLAB / Lab view / C programming/ Equivalent) and hardware (Using TI / Analog devices / Motorola / Equivalent DSP processors). 1. Generation of Sinusoidal waveform / signal based on recursive difference equations 2. To find DFT / IDFT of given DT signal 3. To find frequency response of a given system given in (Transfer Function/ Differential equation form). 4. Implementation of FFT of given sequence 5. Determination of Power Spectrum of a given signal(s). 6. Implementation of LP FIR filter for a given sequence 7. Implementation of HP FIR filter for a given sequence 8. Implementation of LP IIR filter for a given sequence 9. Implementation of HP IIR filter for a given sequence 10. Generation of Sinusoidal signal through filtering 11. Generation of DTMF signals 12. Implementation of Decimation Process 13. Implementation of Interpolation Process 14. Implementation of I/D sampling rate converters 15. Audio application such as to plot a time and frequency display of microphone plus a cosine using DSP. Read a .wav file and match with their respective spectrograms. 16. Noise removal: Add noise above 3 KHz and then remove, interference suppression using 400 Hz tone. 17. Impulse response of first order and second order systems. Note: - Minimum of 12 experiments has to be conducted.

Digital Signal Processing Lab Manual

Page 2

Department of Electronics and Communication

VCET,Hyderabad.

CONTENTS
List of experiments using Mat lab Introduction to MATLAB 1) Generation of Basic Signals 2) Sum of sinusoidal signals 3) Impulse response of the difference equation 4) Frequency response of a system given in Difference equation form 5) Determination of Power Spectrum 6) FIR Low pass Filter design 7) FIR High pass Filter design 8) IIR Low pass Filter design 9) IIR High pass Filter design 10) Fast Fourier Transform 11) DFT / IDFT of given DT signal 12) Implementation of Decimation Process 13) Implementation of Interpolation Process 14) Implementation of I/D sampling rate converters Page No. 4 10 18 20 22 24 26 30 34 37 40 43 46 49 52

List of experiments using CC Studio Introduction to DSP processors, TMS 320C6713 DSK Introduction to CC STUDIO 1) Generation of Sine wave and Square wave 2) Linear Convolution 3) Impulse response of first order and second order systems 4) Generation of Real time sine wave 5) Real time FIR (LP/HP) Filter Design 6) Real time IIR (LP/HP) Filter Design 7) Audio application 8) Noise removal Mini project DTMF (Touch Tone) Signaling 55 63 68 72 75

Digital Signal Processing Lab Manual

Page 3

Department of Electronics and Communication

VCET,Hyderabad.

INRODUCTION
MATLAB: MATLAB is a software package for high performance numerical computation and visualization provides an interactive environment with hundreds of built in functions for technical computation, graphics and animation. The MATLAB name stands for MATrix Laboratory

At its core ,MATLAB is essentially a set (a toolbox) of routines (called m files or mex files) that sit on your computer and a window that allows you to create new variables with names (e.g. voltage and time) and process those variables with any of those routines (e.g. plot voltage against time, find the largest voltage, etc). It also allows you to put a list of your processing requests together in a file and save that combined list with a name so that you can run all of those commands in the same order at some later time. Furthermore, it allows you to run such lists of commands such that you pass in data
Digital Signal Processing Lab Manual Page 4

Department of Electronics and Communication

VCET,Hyderabad.

and/or get data back out (i.e. the list of commands is like a function in most programming languages). Once you save a function, it becomes part of your toolbox (i.e. it now looks to you as if it were part of the basic toolbox that you started with). For those with computer programming backgrounds: Note that MATLAB runs as an interpretive language (like the old BASIC). That is, it does not need to be compiled. It simply reads through each line of the function, executes it, and then goes on to the next line. (In practice, a form of compilation occurs when you first run a function, so that it can run faster the next time you run it.) MATLAB Windows : MATLAB works with through three basic windows Command Window : This is the main window .it is characterized by MATLAB command prompt >> when you launch the application program MATLAB puts you in this window all commands including those for user-written programs ,are typed in this window at the MATLAB prompt Graphics window: the output of all graphics commands typed in the command window are flushed to the graphics or figure window, a separate gray window with white background color the user can create as many windows as the system memory will allow Edit window: This is where you write edit, create and save your own programs in files called M files. Input-output: MATLAB supports interactive computation taking the input from the screen and flushing, the output to the screen. In addition it can read input files and write output files Data Type: the fundamental data type in MATLAB is the array. It encompasses several distinct data objects- integers, real numbers, matrices, charcter strings, structures and cells.There is no need to declare variables as real or complex, MATLAB automatically sets the variable to be real. Dimensioning: Dimensioning is automatic in MATLAB. No dimension statements are required for vectors or arrays .we can find the dimensions of an existing matrix or a vector with the size and length commands.

Digital Signal Processing Lab Manual

Page 5

Department of Electronics and Communication

VCET,Hyderabad.

Where to work in MATLAB? All programs and commands can be entered either in the a)Command window b) As an M file using Matlab editor Note : Save all M files in the folder 'work' in the current directory. Otherwise you have to locate the file during compiling. Typing quit in the command prompt>> quit, will close MATLAB Matlab Development Environment. For any clarification regarding plot etc, which are built in functions type help topic i.e. help plot

Basic Instructions in Mat lab 1. T = 0: 1:10 This instruction indicates a vector T which as initial value 0 and final value 10 with an increment of 1 Therefore T = [0 1 2 3 4 5 6 7 8 9 10] 2. F= 20: 1: 100 Therefore F = [20 21 22 23 24 100] 3. T= 0:1/pi: 1 Therefore T= [0, 0.3183, 0.6366, 0.9549] 4. zeros (1, 3) The above instruction creates a vector of one row and three columns whose values are zero Output= [0 0 0] 5. zeros( 2,4) Output = 0000 0000 6. ones (5,2)
Digital Signal Processing Lab Manual Page 6

Department of Electronics and Communication

VCET,Hyderabad.

The above instruction creates a vector of five rows and two columns Output = 11 11 11 11 11 7. a = [ 1 2 3] a.*b = [4 10 18] 8 if C= [2 2 2] b.*C results in [8 10 12] b = [4 5 6]

9. plot (t, x) If x = [6 7 8 9] t = [1 2 3 4]

This instruction will display a figure window which indicates the plot of x versus t

10. stem (t,x) :-

This instruction will display a figure window as shown

Digital Signal Processing Lab Manual

Page 7

Department of Electronics and Communication

VCET,Hyderabad.

11. Subplot: This function divides the figure window into rows and columns. Subplot (2 2 1) divides the figure window into 2 rows and 2 columns 1 represent number of the figure

Subplot (3 1 2) divides the figure window into 3 rows and 1 column 2 represent number of the figure 12. Conv Syntax: w = conv(u,v) Description: w = conv(u,v) convolves vectors u and v. Algebraically, convolution is the same operation as multiplying the polynomials whose coefficients are the elements of u and v. 13.Disp Syntax: disp(X) Description: disp(X) displays an array, without printing the array name. If X contains a text string, the string is displayed.Another way to display an array on the screen is to type its name, but this prints a leading "X=," which is not always desirable.Note that disp does not display empty arrays. 14.xlabel Syntax: xlabel('string') Description: xlabel('string') labels the x-axis of the current axes. 15. ylabel Syntax : ylabel('string') Description: ylabel('string') labels the y-axis of the current axes.
Digital Signal Processing Lab Manual Page 8

Department of Electronics and Communication

VCET,Hyderabad.

16.Title Syntax : title('string') Description: title('string') outputs the string at the top and in the center of the current axes. 17.grid on Syntax : grid on Description: grid on adds major grid lines to the current axes. 18.FFT Discrete Fourier transform. FFT(X) is the discrete Fourier transform (DFT) of vector X. For matrices, the FFT operation is applied to each column. For N-D arrays, the FFT operation operates on the first non-singleton dimension. FFT(X,N) is the N-point FFT, padded with zeros if X has less than N points and truncated if it has more.

19. ABS Absolute value. ABS(X) is the absolute value of the elements of X. When X is complex, ABS(X) is the complex modulus (magnitude) of the elements of X.

20. ANGLE Phase angle. ANGLE(H) returns the phase angles, in radians, of a matrix with complex elements.

21.INTERP Resample data at a higher rate using lowpass interpolation. Y = INTERP(X,L) resamples the sequence in vector X at L times the original sample rate. The resulting resampled vector Y is L times longer, LENGTH(Y) = L*LENGTH(X).

22. DECIMATE Resample data at a lower rate after lowpass filtering. Y = DECIMATE(X,M) resamples the sequence in vector X at 1/M times the original sample rate. The resulting resampled vector Y is M times shorter, i.e., LENGTH(Y) = CEIL(LENGTH(X)/M). By default, DECIMATE filters the data with an 8th order Chebyshev Type I lowpass filter with cutoff frequency .8*(Fs/2)/R, before resampling.
Digital Signal Processing Lab Manual Page 9

Department of Electronics and Communication

VCET,Hyderabad.

1. Generation of signals
Aim:- To ge nera te the following signals using MAT L A B 6. 5 1. Unit im pulse signal 2. Unit ste p signa l 3. Unit ra m p signa l 4. E xpone ntia l growing signal 5. E xpone ntia l deca ying signa l 6. Sine signal 7. Cosine s ignal Apparatus Required:- Syste m with MAT L A B 6. 5. Algorithm:1. Get the num ber of sa m ples. 2. Ge nera te the unit im pulse, unit s te p using ones, zeros m atrix c om ma nd. 3. Ge nera te ra m p, s ine, cosine a nd e xpone ntia l signals using c orres ponding ge nera l form ula. 4. Plot the graph.

Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window

Digital Signal Processing Lab Manual

Page 10

Department of Electronics and Communication

VCET,Hyderabad.

P rogram: 1. Unit impulse signal clc; clear all; close all; dis p('UNIT I MPUL SE SIGNAL '); N=input(' E nter Num ber of Sa m ples: '); n=-N:1:N x=[zeros(1, N) 1 ze ros(1, N)] ste m(n, x); xla be l('T ime'); yla be l('Am plitude'); title('Im pulse Res ponse');

Output:UNIT I MP UL SE SIGNAL Enter Number of Samples: 6

Digital Signal Processing Lab Manual

Page 11

Department of Electronics and Communication

VCET,Hyderabad.

2. Unit step signal

clc; clear all; close all; dis p('UNIT STE P SIGN AL'); N=input(' E nter Num ber of Sa m ples : '); n=-N:1:N x=[zeros(1, N) 1 ones (1, N)] ste m(n, x); xla be l('T ime'); yla be l('Am plitude'); title('Unit Ste p Res ponse');

Output:UNIT ST E P SIGNAL E nter Num ber of Sa m ples : 6

Digital Signal Processing Lab Manual

Page 12

Department of Electronics and Communication

VCET,Hyderabad.

3. Unit ramp signal clc; clear all; close all;

dis p('UNIT RA MP SIGN AL'); N=input(' E nter Num ber of Sa m ples : '); a=input('E nter Am plitude : ') n=0:1:N x=a *n ste m(n, x); xla be l('T ime'); yla be l('Am plitude'); title('Unit Ra m p Res ponse');

Output:UNIT RA MP SIGNAL E nter Num ber of Sa m ples : 6 E nter Am plitude : 20

Digital Signal Processing Lab Manual

Page 13

Department of Electronics and Communication

VCET,Hyderabad.

4. Exponential decaying signal clc; clear all; close all; dis p('E XPONE NT IAL DE C AYING SIGNAL '); N=input(' E nter Num ber of Sa m ples : '); a=0. 5 n=0:. 1:N x=a.^ n ste m(n, x); xla be l('T ime'); yla be l('Am plitude'); title('E xpone ntial Deca ying Signal Res ponse'); Output: E XPONE NT IAL DE CAYIN G SIGNAL Enter Number of Samples : 6

Digital Signal Processing Lab Manual

Page 14

Department of Electronics and Communication

VCET,Hyderabad.

5. Exponential growing signal clc; clear all; close all; dis p('E XPONE NT IAL GR O WING SIGNAL ');

N=input(' E nter Num ber of Sa m ples : '); a=0. 5 n=0:. 1:N x=a.^ -n ste m(n, x); xla be l('T ime'); yla be l('Am plitude'); title('E xpone ntial Growing Signal Re s ponse');

Output:E XPONE NT IAL GRO WING SIGN AL E nter Num ber of Sa m ples : 6

Digital Signal Processing Lab Manual

Page 15

Department of Electronics and Communication

VCET,Hyderabad.

6. Cosine signal clc; clear all; close all;

dis p('COSINE SIGNAL '); N=input(' E nter Num ber of Sa m ples : '); n=0:. 1:N x=c os(n) ste m(n, x); xla be l('T ime'); yla be l('Am plitude'); title('Cos ine Signal');

Output:COSINE SIGN AL E nter Num ber of Sa m ples : 16

Digital Signal Processing Lab Manual

Page 16

Department of Electronics and Communication

VCET,Hyderabad.

7. Sine signal clc; clear all; close all;

dis p('SINE SIGNAL '); N=input(' E nter Num ber of Sa m ples : '); n=0:. 1:N x=sin(n) ste m(n, x); xla be l('T ime'); yla be l('Am plitude'); title('sine Signa l'); Output:SINE SIGN AL Enter Number of Samples : 16

Result:- Thus the MATLAB program for generation of all basic signals was performed and the output was verified.
Digital Signal Processing Lab Manual Page 17

Department of Electronics and Communication

VCET,Hyderabad.

2. Sum of sinusoidal signals


Aim: - To write a MATLAB program to find the sum of sinusoidal signals. Apparatus required: Sys te m with M AT L AB 6. 5. Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window Program:% sum of sinusoidal signals clc; clear all; close all; tic; t=0:.01:pi; %generation of sine signals y1=sin(t); y2=sin(3*t)/3; y3=sin(5*t)/5; y4=sin(7*t)/7; y5=sin(9*t)/9; y = sin(t) + sin(3*t)/3 + sin(5*t)/5 + sin(7*t)/7 + sin(9*t)/9; plot(t,y,t,y1,t,y2,t,y3,t,y4,t,y5); legend('y','y1','y2','y3','y4',' y5'); title('generation of sum of sinusoidal signals');grid; ylabel('---> Amplitude'); xlabel('---> t'); toc;

Digital Signal Processing Lab Manual

Page 18

Department of Electronics and Communication

VCET,Hyderabad.

Output:-

Result:- Thus the MATLAB program for sum of sinusoidal signals was performed and the output was verified.

Digital Signal Processing Lab Manual

Page 19

Department of Electronics and Communication

VCET,Hyderabad.

3.Impulse response of the difference equation


Aim :- To find the impulse response of the following difference equation y(n)-y(n-1)+0.9y(n-2)= x(n) Apparatus Used:- Syste m with MAT L A B 6.5. Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window Program:clc; clear all; close all; disp('Difference Equation of a digital system'); N=input('Desired Impulse response length = '); b=input('Coefficients of x[n] terms = '); a=input('Coefficients of y[n] terms = '); h=impz(b,a,N); disp('Impulse response of the system is h = '); disp(h); n=0:1:N-1; figure(1); stem(n,h); xlabel('time index'); ylabel('h[n]'); title('Impulse response'); figure(2); zplane(b,a); xlabel('Real part');
Digital Signal Processing Lab Manual Page 20

Department of Electronics and Communication

VCET,Hyderabad.

ylabel('Imaginary part'); title('Poles and Zeros of H[z] in Z-plane'); Output:Difference Equation of a digital system Desired Impulse response length = 100 Coefficients of x[n] terms = 1 Coefficients of y[n] terms = [1 -1 0.9]

Result:- Thus the MATLAB program for Impulse Response of Difference Equation was performed and the output was verified
Digital Signal Processing Lab Manual Page 21

Department of Electronics and Communication

VCET,Hyderabad.

4.

Frequency response of a given system given in (Transfer Function/ Difference equation form)

Aim :- To find the frequency response of the following difference equation y(n) 5 y(n1) = x(n) + 4 x(n1) Apparatus Used:- Syste m with MAT L A B 6.5. Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window

Program:b = [1, 4]; %Numerator coefficients a = [1, -5]; %Denominator coefficients w = -2*pi: pi/256: 2*pi; [h] = freqz(b, a, w); subplot(2, 1, 1), plot(w, abs(h)); xlabel('Frequency \omega'), ylabel('Magnitude'); grid subplot(2, 1, 2), plot(w, angle(h)); xlabel('Frequency \omega'), ylabel('Phase - Radians'); grid

Digital Signal Processing Lab Manual

Page 22

Department of Electronics and Communication

VCET,Hyderabad.

Output:-

Result:- Thus the MATLAB program for Frequency Response of Difference Equation was performed and the output was verified.

Note:- If the transfer function is given instead of difference equation the n perform the inverse ZTransform and obtain the difference equation and then find the frequency response for the difference equation using Matlab.

Digital Signal Processing Lab Manual

Page 23

Department of Electronics and Communication

VCET,Hyderabad.

5. Determination of Power Spectrum


Aim: To obtain power spectrum of given signal using MATLAB. Apparatus Used:- Sys te m with M AT L AB 6. 5. Theory: In statistical signal processing the power spectral density is a positive real function of a frequency variable associated with a stationary stochastic process, or a deterministic function of time, which has dimensions of power per Hz, or energy pe r Hz. It is often called simply the spectrum of the signal. Intuitively, the spectral density captures the frequency content of a stochastic process and helps identify periodicities. The PSD is the FT of autocorrelation function, R() of the signal if the signal can be treated as a wide-sense stationary random process. Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window

Program:%Power spectral density t = 0:0.001:0.6; x = sin(2*pi*50*t)+sin(2*pi*120*t); y = x + 2*randn(size(t)); figure,plot(1000*t(1:50),y(1:50)) title('Signal Corrupted with Zero-Mean Random Noise') xlabel('time (milliseconds)'); Y = fft(y,512); %The power spectral density, a measurement of the energy at various frequencies, is: Pyy = Y.* conj(Y) / 512; f = 1000*(0:256)/512; figure,plot(f,Pyy(1:257)) title('Frequency content of y'); xlabel('frequency (Hz)');
Digital Signal Processing Lab Manual Page 24

Department of Electronics and Communication

VCET,Hyderabad.

Output:-

Result:- Thus the MATLAB program for Power Spectral Density was performed and the output was verified.

Digital Signal Processing Lab Manual

Page 25

Department of Electronics and Communication

VCET,Hyderabad.

6. FIR Low pass Filter design Aim :- To Design FIR LP Filter using Rectangular/Triangular/kaiser Windowing Technique. Apparatus Used:- Syste m with MAT L A B 6.5. Algorithm:1) Enter the pass band ripple (rp) and stop band ripple (rs). 2) Enter the pass band frequency (fp) and stop band frequency (fs). 3) Get the sampling frequency (f), beta value. 4) Calculate the analog pass band edge frequencies, w1 and w2. w1 = 2*fp/f w2 = 2*fs/f 5) calculate the numerator and denominator 6)Use an If condition and ask the user to choose either Rectangular Window or Triangular window or Kaiser window.. 7)use rectwin,triang,kaiser commands 8) Calculate the magnitude of the frequency response in decibels (dB m=20*log10(abs(h)) 9) Plot the magnitude response [magnitude in dB Vs normalized frequency (om/pi)] 10)Give relevant names to x and y axes and give an appropriate title for the plot. 11)Plot all the responses in a single figure window.[Make use of subplot]

Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window

Digital Signal Processing Lab Manual

Page 26

Department of Electronics and Communication

VCET,Hyderabad.

Program:%FIR Filter design window techniques clc; clear all; close all; rp=input('enter passband ripple'); rs=input('enter the stopband ripple'); fp=input('enter passband freq'); fs=input('enter stopband freq'); f=input('enter sampling freq '); beta=input('enter beta value); wp=2*fp/f; ws=2*fs/f; num=-20*log10(sqrt(rp*rs))-13; dem=14.6*(fs- fp)/f; n=ceil(num/dem); n1=n+1; if(rem(n,2)~=0) n1=n; n=n-1; end c=input('enter your choice of window function 1. rectangular 2. triangular 3.kaiser: \n '); if(c==1) y=rectwin(n1); disp('Rectangular window filter response'); end if (c==2) y=triang(n1); disp('Triangular window filter response'); end if(c==3) y=kaiser(n1,beta); disp('kaiser window filter response'); end

Digital Signal Processing Lab Manual

Page 27

Department of Electronics and Communication

VCET,Hyderabad.

%LPF b=fir1(n,wp,y); [h,o]=freqz(b,1,256); m=20*log10(abs(h)); plot(o/pi,m); title('LPF'); ylabel('Gain in dB-->'); xlabel('(a) Normalized frequency-->'); Output:enter passband ripple 0.02 enter the stopband ripple 0.01 enter passband freq 1000 enter stopband freq 1500 enter sampling freq 10000 enter beta value enter your choice of window function 1. rectangular 2. triangular 3.kaiser: 1 Rectangular window filter response

Digital Signal Processing Lab Manual

Page 28

Department of Electronics and Communication

VCET,Hyderabad.

enter your choice of window function 1. rectangular 2. triangular 3.kaiser: 2 triangular window filter response

enter beta value 5 enter your choice of window function 1. rectangular 2. triangular 3.kaiser: 3 kaiser window filter response

Result:- Thus FIR LP Filter is designed for Rectangular/triangular/kaiser windowing techniques using MATLAB.
Digital Signal Processing Lab Manual Page 29

Department of Electronics and Communication

VCET,Hyderabad.

7. FIR High pass Filter design Aim :- To Design FIR HP Filter using Rectangular/Triangular/kaiser Windowing Technique. Apparatus Used:- Syste m with MAT L A B 6.5. Algorithm:1) Enter the pass band ripple (rp) and stop band ripple (rs). 2) Enter the pass band frequency (fp) and stop band frequency (fs). 3) Get the sampling frequency (f), beta value. 4) Calculate the analog pass band edge frequencies, w1 and w2. w1 = 2*fp/f w2 = 2*fs/f 5) calculate the numerator and denominator 6)Use an If condition and ask the user to choose either Rectangular Window or Triangular window or Kaiser window.. 7)use rectwin,triang,kaiser commands 8) Calculate the magnitude of the frequency response in decibels (dB m=20*log10(abs(h)) 9) Plot the magnitude response [magnitude in dB Vs normalized frequency (om/pi)] 10)Give relevant names to x and y axes and give an appropriate title for the plot. 11)Plot all the responses in a single figure window.[Make use of subplot] Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window

Digital Signal Processing Lab Manual

Page 30

Department of Electronics and Communication

VCET,Hyderabad.

Program:%FIR Filter design window techniques clc; clear all; close all; rp=input('enter passband ripple'); rs=input('enter the stopband ripple'); fp=input('enter passband freq'); fs=input('enter stopband freq'); f=input('enter sampling freq '); beta=input('enter beta value'); wp=2*fp/f; ws=2*fs/f; num=-20*log10(sqrt(rp*rs))-13; dem=14.6*(fs- fp)/f; n=ceil(num/dem); n1=n+1; if(rem(n,2)~=0) n1=n; n=n-1; end c=input('enter your choice of window function 1. rectangular 2. triangular 3.kaiser: \n '); if(c==1) y=rectwin(n1); disp('Rectangular window filter response'); end if (c==2) y=triang(n1); disp('Triangular window filter response'); end if(c==3) y=kaiser(n1,beta); disp('kaiser window filter response'); end

Digital Signal Processing Lab Manual

Page 31

Department of Electronics and Communication

VCET,Hyderabad.

%HPF b=fir1(n,wp,'high',y); [h,o]=freqz(b,1,256); m=20*log10(abs(h)); plot(o/pi,m); title('HPF'); ylabel('Gain in dB-->'); xlabel('(b) Normalized frequency-->');

Output:enter passband ripple 0.02 enter the stopband ripple 0.01 enter passband freq 1000 enter stopband freq 1500 enter sampling freq 10000 enter beta value enter your choice of window function 1. rectangular 2. triangular 3.kaiser: 1 Rectangular window filter response

enter your choice of window function 1. rectangular 2. triangular 3.kaiser: 2 triangular window filter response

Digital Signal Processing Lab Manual

Page 32

Department of Electronics and Communication

VCET,Hyderabad.

enter beta value 5 enter your choice of window function 1. rectangular 2. triangular 3.kaiser: 3 kaiser window filter response

Result:- Thus FIR HP Filter is designed for Rectangular/triangular/kaiser windowing techniques using MATLAB.

Digital Signal Processing Lab Manual

Page 33

Department of Electronics and Communication

VCET,Hyderabad.

8. IIR Low pass Filter design Aim: - To Design and generate IIR Butterworth Analog LP Filter using MATLAB Apparatus Required:- Syste m with MAT L A B 6. 5. Algorithm:1) Enter the pass band ripple (rp) and stop band ripple (rs). 2) Enter the pass band frequency (fp) and stop band frequency (fs). 3) Get the sampling frequency (f). 4) Calculate the analog pass band edge frequencies, w1 and w2. w1 = 2*fp/f w2 = 2*fs/f 5) Calculate the order and 3dB cutoff frequency of the analog filter. [Make use of the following function] [n,wn]=buttord(w1,w2,rp,rs,s) 6) Design an nth order analog lowpass Butter worth filter using the following statement. [b,a]=butter(n,wn,s) 7) Find the complex frequency response of the filter by using freqs( ) function [h,om]=freqs(b,a,w) where, w = 0:.01:pi

This function returns complex frequency response vector h and frequency vector om in radians/samples of the filter. 8) Calculate the magnitude of the frequency response in decibels (dB m=20*log10(abs(h)) 9) Plot the magnitude response [magnitude in dB Vs normalized frequency (om/pi)] 10) Calculate the phase response using an = angle(h) 11) Plot the phase response [phase in radians Vs normalized frequency (om/pi)] 12)Give relevant names to x and y axes and give an appropriate title for the plot. 13)Plot all the responses in a single figure window.[Make use of subplot]
Digital Signal Processing Lab Manual Page 34

Department of Electronics and Communication

VCET,Hyderabad.

Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window

P rogram:% IIR filters clc; clear all; close all; warning off; disp('enter the IIR filter design specifications'); rp=input('enter the passband ripple'); rs=input('enter the stopband ripple'); wp=input('enter the passband freq'); ws=input('enter the stopband freq'); fs=input('enter the sampling freq'); w1=2*wp/fs;w2=2*ws/fs; [n,wn]=buttord(w1,w2,rp,rs,'s'); disp('Frequency response of IIR HPF is:'); [b,a]=butter(n,wn,'low','s'); w=0:.01:pi; [h,om]=freqs(b,a,w);

% Find the order n and cutt off frequency

% Find the filter co-efficients of LPF

% Plot the frequency response

m=20*log10(abs(h)); subplot(2,1,1); plot(om/pi,m); title('magnitude response of IIR Low Pass filter is:'); xlabel('(a) Normalized freq. -->');
Digital Signal Processing Lab Manual Page 35

Department of Electronics and Communication

VCET,Hyderabad.

ylabel('Gain in dB-->'); an=angle(h); subplot(2,1,2); plot(om/pi,an); title('phase response of IIR Low Pass filter is:'); xlabel('(b) Normalized freq. -->'); ylabel('Phase in radians-->');

Output:ente r the IIR filte r design s pec ifica tions ente r the pass ba nd ripple 0. 15 ente r the stopba nd ripple 60 ente r the pass ba nd fre q1500 ente r the stopba nd fre q3000 ente r the sa m pling fre q7000 Fre que nc y res ponse of IIR L PF is :

Result:- Thus IIR Low Pass Filter is designed using MATLAB.

Digital Signal Processing Lab Manual

Page 36

Department of Electronics and Communication

VCET,Hyderabad.

9. IIR High pass Filter design Aim: - To Design and generate IIR Butterworth Analog HP Filter using MATLAB Apparatus Required:- Syste m with MAT L A B 6. 5. Algorithm:1) Enter the pass band ripple (rp) and stop band ripple (rs). 2) Enter the pass band frequency (fp) and stop band frequency (fs). 3) Get the sampling frequency (f). 4) Calculate the analog pass band edge frequencies, w1 and w2. w1 = 2*fp/f w2 = 2*fs/f 5) Calculate the order and 3dB cutoff frequency of the analog filter. [Make use of the following function] [n,wn]=buttord(w1,w2,rp,rs,s) 6) Design an nth order analog high pass Butter worth filter using the following statement. [b,a]=butter(n,wn,high,s) 7) Find the complex frequency response of the filter by using freqs( ) function [h,om]=freqs(b,a,w) where, w = 0:.01:pi This function returns complex frequency response vector h and frequency vector om in radians/samples of the filter. 8) Calculate the magnitude of the frequency response in decibels (dB m=20*log10(abs(h)) 9) Plot the magnitude response [magnitude in dB Vs normalized frequency (om/pi)] 10) Calculate the phase response using an = angle(h) 11) Plot the phase response [phase in radians Vs normalized frequency (om/pi)] 12) Give relevant names to x and y axes and give an appropriate title for the plot. 13)Plot all the responses in a single figure window.[Make use of subplot]

Digital Signal Processing Lab Manual

Page 37

Department of Electronics and Communication

VCET,Hyderabad.

Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window

P rogram:% IIR filters clc; clear all; close all; warning off; disp('enter the IIR filter design specifications'); rp=input('enter the passband ripple'); rs=input('enter the stopband ripple'); wp=input('enter the passband freq'); ws=input('enter the stopband freq'); fs=input('enter the sampling freq'); w1=2*wp/fs;w2=2*ws/fs; [n,wn]=buttord(w1,w2,rp,rs,'s'); disp('Frequency response of IIR HPF is:'); [b,a]=butter(n,wn,'high','s');

% Find the order n and cutt off frequency

% Find the filter co-efficients of HPF

w=0:.01:pi; [h,om]=freqs(b,a,w);

% Plot the frequency response

m=20*log10(abs(h)); subplot(2,1,1); plot(om/pi,m); title('magnitude response of IIR High Pass filter is:');
Digital Signal Processing Lab Manual Page 38

Department of Electronics and Communication

VCET,Hyderabad.

xlabel('(a) Normalized freq. -->'); ylabel('Gain in dB-->'); an=angle(h); subplot(2,1,2); plot(om/pi,an); title('phase response of IIR High Pass filter is:'); xlabel('(b) Normalized freq. -->'); ylabel('Phase in radians-->');

Output:ente r the IIR filte r design s pec ifica tions ente r the pass ba nd ripple 0. 15 ente r the stopba nd ripple 60 ente r the pass ba nd fre q1500 ente r the stopba nd fre q3000 ente r the sa m pling fre q7000 Fre que nc y res ponse of IIR HPF is:

Result:- Thus IIR High Pass Filter is designed using MATLAB.


Digital Signal Processing Lab Manual Page 39

Department of Electronics and Communication

VCET,Hyderabad.

10. Implementation of FFT


Aim: To perform the FFT of signal x(n) using Mat lab. Apparatus require d: Syste m with MAT L AB 6. 5. Theory:- A fast Fourier transform (FFT) is an efficient algorithm to compute the discrete Fourier transform (DFT) and its inverse. FFTs are of great importance to a wide variety of applications, from digital signal processing and solving partial differential equations to algorithms for quick multiplication of large integers. Evaluating the sums of DFT directly would take O(N 2) arithmetical operations. An FFT is an algorithm to compute the same result in only O(N log N) operations. In general, such algorithms depend upon the factorization of N, but there are FFTs with O(N log N) complexity for all N, even for prime N. Since the inverse DFT is the same as the DFT, but with the opposite sign in the exponent and a 1/N factor, any FFT algorithm can easily be adapted for it as well.

Algorithm: 1) Get the input sequence 2) Number of DFT point(m) is 8 3) Find out the FFT function using MATLAB function. 4) Display the input & outputs sequence using stem function Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory
Digital Signal Processing Lab Manual Page 40

Department of Electronics and Communication

VCET,Hyderabad.

5)Compile and Run the program 6)For the output see command window\ Figure window Program: clear all; N=8; m=8; a=input('Enter the input sequence'); n=0:1:N-1; subplot(2,2,1); stem(n,a); xlabel('Time Index n'); ylabel('Amplitude'); title('Sequence'); x=fft(a,m); k=0:1:N-1; subplot(2,2,2); stem(k,abs(x)); ylabel('magnitude'); xlabel('Frequency Index K'); title('Magnitude of the DFT sample'); subplot(2,2,3); stem(k,angle(x)); xlabel('Frequency Index K'); ylabel('Phase'); title('Phase of DFT sample'); ylabel('Convolution');

Output:Enter the input sequence[1 1 1 1 0 0 0 0]

Digital Signal Processing Lab Manual

Page 41

Department of Electronics and Communication

VCET,Hyderabad.

Result:- Thus Fast Fourier Transform is Performed using Matlab.

Digital Signal Processing Lab Manual

Page 42

Department of Electronics and Communication

VCET,Hyderabad.

11.Discrete Fourier Transform(DFT)


Aim:- To perform the DFT of signal x(n) using Mat lab. Apparatus require d: A PC with Mat lab version 6.5. Theory:- Discrete Fourier Transform (DFT) is used for performing frequency analysis of discrete time signals. DFT gives a discrete frequency domain representation whereas the other transforms are continuous in frequency domain.
The N point DFT of discrete time signal x[n] is given by the equation

The inverse DFT allows us to recover the sequence x[n] from the frequency samples.

X(k) is a complex number (remember ejw=cosw + jsinw). It has both magnitude and phase which are plotted versus k. These plots are magnitude and phase spectrum of x[n]. The k gives us the frequency information. Here k=N in the frequency domain corresponds to sampling frequency (fs). Increasing N, increases the frequency resolution, i.e., it improves the spectral characteristics of the sequence. For example if fs=8kHz and N=8 point DFT, then in the resulting spectrum, k=1 corresponds to 1kHz frequency. For the same fs and x[n], if N=80 point DFT is computed, then in the resulting spectrum, k=1 corresponds to 100Hz frequency. Hence, the resolution in frequency is increased. Since N L , increasing N to 8 from 80 for the same x[n] implies x[n] is still the same sequence (<8), the rest of x[n] is padded with zeros. This implies that there is no further information in time domain, but the resulting spectrum has higher frequency resolution. This spectrum is known as high density spectrum (resulting from zero padding x[n]). Instead of zero padding, for higher N, if more number of points of x[n] are taken (more data in time domain), then the resulting spectrum is called a high resolution spectrum. Procedure:1)Open MATLAB 2)Open new M- file
Digital Signal Processing Lab Manual Page 43

Department of Electronics and Communication

VCET,Hyderabad.

3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window clc; x1 = input('Enter the sequence:'); n = input('Enter the length:'); m = fft(x1,n); disp('N-point DFT of a given sequence:'); disp(m); N = 0:1:n-1; subplot(2,2,1); stem(N,m); xlabel('Length'); ylabel('Magnitude of X(k)'); title('Magnitude spectrum:'); an = angle(m); subplot(2,2,2); stem(N, an); xlabel('Length'); ylabel('Phase of X(k)'); title('Phase spectrum:');

Output:Enter the sequence:[1 1 0 0] Enter the length:4 N-point DFT of a given sequence: Columns 1 through 3 2.0000 Column 4 1.0000 + 1.0000i 1.0000 - 1.0000i 0

Digital Signal Processing Lab Manual

Page 44

Department of Electronics and Communication

VCET,Hyderabad.

Result:- Thus Discrete Fourier Transform is Performed using Matlab.

Digital Signal Processing Lab Manual

Page 45

Department of Electronics and Communication

VCET,Hyderabad.

12.

Implementation of Decimation Process

Aim:- To perform Decimation process using Mat lab. Apparatus require d: Syste m with MAT L AB 6. 5. Theory :Sampling rate conversion (SRC) is a process of converting a discrete-time signal at a given rate to a different rate. This technique is encountered in many application areas such as: Digital Audio Communications systems Speech Processing Antenna Systems Radar Systems etc Sampling rates may be changed upward or downward. Increasing the sampling rate is called interpolation, and decreasing the sampling rate is called decimation. Reducing the sampling rate by a factor of M is achieved by discarding every M-1 samples, or, equivalently keeping every Mth sample. Increasing the sampling rate by a factor of L (interpolation by factor L) is achieved by inserting L-1 zeros into the output stream after every sample from the input stream of samples. This system can perform SRC for the following cases: Decimation by a factor of M Interpolation by a factor of L SRC by a rational factor of L/M. Decimator : To reduce the sampling rate by an integer factor M, assume a new sampling period The re-sampled signal is The system for performing this operation, called down-sampler, is shown below:

Digital Signal Processing Lab Manual

Page 46

Department of Electronics and Communication

VCET,Hyderabad.

Down-sampling generally results in aliasing. Therefore, in order to prevent aliasing, x(n) should be filtered prior to down-sampling with a low-pass filter that has a cutoff frequency The cascade of a low-pass filter with a down-sampler illustrated below and is called decimator.

Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window

Program:% Illustration of Decimation Process clc; close all; clear all; M = input('enter Down-sampling factor : '); N = input('enter number of samples :'); n = 0:N-1; x = sin(2*pi*0.043*n) + sin(2*pi*0.031*n); y = decimate(x,M,'fir'); subplot(2,1,1); stem(n,x(1:N)); title('Input Sequence'); xlabel('Time index n'); ylabel('Amplitude'); subplot(2,1,2); m = 0:(N/M)-1;
Digital Signal Processing Lab Manual Page 47

Department of Electronics and Communication

VCET,Hyderabad.

stem(m,y(1:N/M)); title('Output Sequence'); xlabel('Time index n');ylabel('Amplitude'); Output:enter Down-sampling factor : 3 enter number of samples :100

Result :- Thus Decimation Process is implemented using Mat lab.

Note:- Observe the Output Sequence for Different values of M.

Digital Signal Processing Lab Manual

Page 48

Department of Electronics and Communication

VCET,Hyderabad.

13. Implementation of Interpolation Process Aim:- To perform interpolation process using Mat lab. Apparatus require d:- Syste m with MAT L A B 6.5. Theory:- To increase the sampling rate by an integer factor L. If xa(t) is sampled with a sampling frequency fs = 1/Ts, then

To increase the sampling rate by an integer factor L, it is necessary to extract the samples

from x(n). The samples of xi(n) for values of n that are integer multiples of L are easily extracted from x(n) as follows:

The system performing the operation is called up-sampler and is shown below:

After up-sampling, it is necessary to remove the frequency scaled images in xi(n), except those that are at intege r multiples of 2. This is accomplished by filtering xi(n) with a low-pass filter that has a cutoff frequency of /L and a gain of L. In the time domain, the low-pass filter inter polates between the samples at integer multiples of L as shown below and is called interpolator.

Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program
Digital Signal Processing Lab Manual Page 49

Department of Electronics and Communication

VCET,Hyderabad.

6)For the output see command window\ Figure window Program:% Illustration of Interpolation Process clc; close all; clear all; L = input('Up-sampling factor = '); N = input('enter number of samples :'); n = 0:N-1; x = sin(2*pi*0.043*n) + sin(2*pi*0.031*n); y = interp(x,L); subplot(2,1,1); stem(n,x(1:N)); title('Input Sequence'); xlabel('Time index n'); ylabel('Amplitude'); subplot(2,1,2); m = 0:(N*L)-1; stem(m,y(1:N*L)); title('Output Sequence'); xlabel('Time index n'); ylabel('Amplitude');

Output:-

Digital Signal Processing Lab Manual

Page 50

Department of Electronics and Communication

VCET,Hyderabad.

Result:- Thus Interpolation Process is implemented using Mat lab. Note:- Observe the Output Sequence for Different values of L.

Digital Signal Processing Lab Manual

Page 51

Department of Electronics and Communication

VCET,Hyderabad.

14. Implementation of I/D sampling rate converters


Aim:- To study sampling rate conversion by a rational form using MATLAB Apparatus require d: Syste m with MAT L AB 6. 5. Theory:SRC by rational factor:

SRC by L/M requires performing an interpolation to a sampling rate which is divisible by both L and M. The final output is then achieved by decimating by a factor of M. The need for a noninteger sampling rate conversion appears when the two systems operating at different sampling rates have to be connected, or when there is a need to convert the sampling rate of the recorded data into another sampling rate for further processing or reproduction. Such applications are very common in telecommunications, digital audio, multimedia and others. An example is transferring data from compact disc (CD) system at a rate of 44.1 kHz to a digital audio tape at 48 kHz. This can be achieved by increasing the data rate of the CD by a factor of 48/44.1, a non-integer.

Illustration for sampling rate converter is:

If M>L, the resulting operation is a decimation process by a non- integer, and when M<L it is interpolation. If M=1, the generalized system reduces to the simple integer interpolation and if L=1 it reduces to integer decimation.

Digital Signal Processing Lab Manual

Page 52

Department of Electronics and Communication

VCET,Hyderabad.

Procedure:1)Open MATLAB 2)Open new M- file 3)Type the program 4)Save in current directory 5)Compile and Run the program 6)For the output see command window\ Figure window Program:clc; close all; clear all; L = input('Enter Up-sampling factor :'); M = input('Enter Down-sampling factor :'); N = input('Enter number of samples :'); n = 0:N-1; x = sin(2*pi*0.43*n) + sin(2*pi*0.31*n); y = resample(x,L,M); subplot(2,1,1); stem(n,x(1:N)); axis([0 29 -2.2 2.2]); title('Input Sequence'); xlabel('Time index n'); ylabel('Amplitude'); subplot(2,1,2); m = 0:(N*L/M)-1; stem(m,y(1:N*L/M)); axis([0 (N*L/M)-1 -2.2 2.2]); title('Output Sequence'); xlabel('Time index n'); ylabel('Amplitude'); Output:Enter Up-sampling factor :7 Enter Down-sampling factor :2 Enter number of samples :30
Digital Signal Processing Lab Manual Page 53

Department of Electronics and Communication

VCET,Hyderabad.

Result:- Thus sampling rate conversion by a rational form is performed using MATLAB

Note:- Observe the Output Sequence for Different values of L & M.

Digital Signal Processing Lab Manual

Page 54

Department of Electronics and Communication

VCET,Hyderabad.

INTRODUCTION TO DSP PROCESSORS


A digital signal processor (DSP) is an integrated circuit designed for highspeed data manipulations, and is used in audio, communications, image manipulation, and other data-acquisition and data-control applications. The microprocessors used in personal computers are optimized for tasks involving data movement and inequality testing. The typical applications requiring such capabilities are word processing, database management, spread sheets, etc. When it comes to mathematical computations the traditional microprocessor are deficient particularly where real-time performance is required. Digital signal processors are microprocessors optimized for basic mathematical calculations such as additions and multiplications.
Fixed versus Floating Point:

Digital Signal Processing can be divided into two categories, fixed po int and floating point which refer to the format used to store and manipulate numbers within the devices. Fixed point DSPs usually represent each number with a minimum of 16 bits, although a different length can be used. There are four common ways that these 216 i,e., 65,536 possible bit patterns can represent a number. In unsigned integer, the stored number can take on any integer value from 0 to 65,535, signed integer uses two's complement to include negative numbers from 32,768 to 32,767. With unsigned fraction notation, the 65,536 levels are spread uniformly between 0 and 1 and the signed fraction format allows negative numbers, equally spaced between -1 and 1. The floating point DSPs typically use a minimum of 32 bits to store each value. This results in many more bit patterns than for fixed point, 232 i,e., 4,294,967,296 to be exact. All floating point DSPs can also handle fixed point numbers, a necessity to implement counters, loops, and signals coming from the ADC and going to the DAC. However, this doesn't mean that fixed point math will be carried out as quickly as the floating point operations; it depends on the internal architecture.

C versus Assembly:

Digital Signal Processing Lab Manual

Page 55

Department of Electronics and Communication

VCET,Hyderabad.

DSPs are programmed in the same languages as other scientific and engineering applications, usually assembly or C. Programs written in assembly can execute faster, while programs written in C are easier to develop and maintain. In traditional applications, such as programs run on PCs and mainframes, C is almost always the first choice. If assembly is used at all, it is restricted to short subroutines that must run with the utmost speed. How fast are DSPs? The primary reason for using a DSP instead of a traditional microprocessor is speed: the ability to move samples into the device and carry out the needed mathematical operations, and output the processed data. The usual way of specifying the fastness of a DSP is: fixed point systems are often quoted in MIPS (million integer operations per second). Likewise, floating point devices can be specified in MFLOPS (million floating point operations per second). TMS320 Family: The Texas Instruments TMS320 family of DSP devices covers a wide range, from a 16-bit fixedpoint device to a single-chip parallel-processor device. In the past, DSPs were used only in specialized applications. Now they are in many mass- market consumer products that are continuously entering new market segments. The Texas Instruments TMS320 family of DSP devices and their typical applications are mentioned below. C1x, C2x, C2xx, C5x, and C54x: The width of the data bus on these devices is 16 bits. All have modified Harvard architectures. They have been used in toys, hard disk drives, modems, cellular phones, and active car suspensions. C3x: The width of the data bus in the C3x series is 32 bits. Because of the reasonable cost and floating-point performance, these are suitable for many applica tions. These include almost any filters, analyzers, hi- fi systems, voice- mail, imaging, bar-code readers, motor control, 3D graphics, or scientific processing. C4x: This range is designed for parallel processing. The C4x devices have a 32-bit data bus and are floating-point. They have an optimized on-chip communication channel, which enables a number of them to be put together to form a parallel-processing cluster. The C4x range devices have been used in virtual reality, image recognition, telecom routing, and parallel-processing systems. C6x: The C6x devices feature VelociTI , an advanced very long instruction word (VLIW) architecture developed by Texas Instruments. Eight functional units, including two multipliers
Digital Signal Processing Lab Manual Page 56

Department of Electronics and Communication

VCET,Hyderabad.

and six arithmetic logic units (ALUs), provide 1600 MIPS of cost-effective performance. The C6x DSPs are optimized for multi-channel, multifunction applications, including wireless base stations, pooled modems, remote-access servers, digital subscriber loop systems, cable modems, and multi-channel telephone systems.

Typical Applications for the TMS320 Family The TMS320 DSPs offer adaptable approaches to traditional signal-processing problems and support complex applications that often require multiple operations to be performed simultaneously.

Digital Signal Processing Lab Manual

Page 57

Department of Electronics and Communication

VCET,Hyderabad.

INTRODUCTION TO TMS 320 C6713 DSK


The highperformance board features the TMS320C6713 floating-point DSP. Capable of performing 1350 million floating point operations per second, the C6713 DSK the most powerful DSK development board.

Digital Signal Processing Lab Manual

Page 58

Department of Electronics and Communication

VCET,Hyderabad.

The DSK is USB port interfaced platform that allows to efficiently develop and test applications for the C6713. With extensive host PC and target DSP software support, the DSK provides ease-of- use and capabilities that are attractive to DSP engineers. The 6713 DSP Starter K it (DSK) is a low-cost platform which lets customers evaluate and develop applications for the Texas Instruments C67X DSP family. The primary features of the DSK are: 225 MHz TMS320C6713 Floating Point DSP AIC23 Stereo Codec Four Position User DIP Switch and Four User LEDs On-board Flash and SDRAM TIs Code Composer Studio development tools are bundled with the 6713DSK providing the user with an industrial-strength integrated development environment for C and assembly programming. Code Composer Studio communicates with the DSP using an on-board JTAG emulator through a USB interface. The TMS320C6713 DSP is the heart of the system. It is a core member of Texas Instruments C64X line of fixed point DSPs whose distinguishing features are an extremely high performance 225MHz VLIW DSP core and 256Kbytes of internal memory. On-chip peripherals include a 32bit external memory interface (EMIF) with integrated SDRAM controller, 2 multi-channel buffered serial ports (McBSPs), two on-board timers and an enhanced DMA controller (EDMA). The 6713 represents the high end of TIs C6700 floating point DSP line both in terms of computational performance and on-chip resources. The 6713 has a significant amount of internal memory so many applications will have all code
Digital Signal Processing Lab Manual Page 59

Department of Electronics and Communication

VCET,Hyderabad.

and data on-chip. External accesses are done through the EMIF which can connect to both synchronous and asynchronous memories. The EMIF signals are also brought out to standard TI expansion bus connectors so additional functionality can be added on daughter card modules.

DSPs are frequently used in audio processing applications so the DSK includes an on-board codec called the AIC23. Codec stands for coder/decoder,the job of the AIC23 is to code analog input samples into a digital format for the DSP to process, then decode data coming out of the DSP to generate the processed analog output. Digitial data is sent to and from the codec on McBSP1. TMS320C6713 DSK Overview Block Diagram

Digital Signal Processing Lab Manual

Page 60

Department of Electronics and Communication

VCET,Hyderabad.

The DSK has 4 light emitting diodes (LEDs) and 4 DIP switches that allow users to interact with programs through simple LED displays and user input on the switches. Many of the included examples make use of these user interfaces Options.

The DSK implements the logic necessary to tie board components together in a programmable logic device called a CPLD. In addition to random glue logic, the CPLD implements a set of 4 software programmable registers that can be used to access the on-board LEDs and DIP switches as well as control the daughter card interface.

Digital Signal Processing Lab Manual

Page 61

Department of Electronics and Communication

VCET,Hyderabad.

DSK hardware installation Shut down and power off the PC Connect the supplied USB port cable to the board Connect the other end of the cable to the USB port of PC Plug the other end of the power cable into a power outlet Plug the power cable into the board The user LEDs should flash several times to indicate board is operational When you connect your DSK through USB for the first time on a Windows loaded PC the new hardware found wizard will come up. So, Install the drivers (The CCS CD contains the require drivers for C6713 DSK). Install the CCS software for C6713 DSK. Troubleshooting DSK Connectivity If Code Composer Studio IDE fails to configure your port correctly, perform the following steps: Test the USB port by running DSK Port test from the start menu Use Start Programs Texas Instruments Code Composer Studio Code Composer Studio C6713 DSK Tools C6713 DSK Diagnostic Utilities The below Screen will appear Select 6713 DSK Diagnostic Utility Icon from Desktop The Screen Look like as below Select Start Option Utility Program will test the board After testing Diagnostic Status you will get PASS

Digital Signal Processing Lab Manual

Page 62

Department of Electronics and Communication

VCET,Hyderabad.

If the board still fails to detect Go to CM OS setup Enable the USB Port Option (The required Device drivers will load along with CCS Installation) SOFTWARE INSTALLATION You must install the hardware before you install the software on your system. The requirements for the operating platform are; Insert the installation CD into the CD-ROM drive An install screen appears; if not, goes to the windows Explorer and run setup.exe Choose the option to install Code Composer Studio If you already have C6000 CC Studio IDE installed on your PC,do not install DSK software. CC Studio IDE full tools supports the DSK platform Respond to the dialog boxes as the installation program runs The Installation program automatically configures CC Studio IDE for operation with your DSK and creates a CCStudio IDE DSK icon on your desktop. To install, follow these instructions:

Digital Signal Processing Lab Manual

Page 63

Department of Electronics and Communication

VCET,Hyderabad.

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 Cinterpretive scripting language and much more.

CODE COMPOSER FEATURES INCLUDE: IDE Debug IDE Advanced watch windows Integrated editor File I/O, Probe Points, and graphical algorithm scope probes Advanced graphical signal analysis Interactive profiling Automated testing and customization via scripting Visual project management system Compile in the background while editing and debugging Multi-processor debugging Help on the target DSP Useful Types of Files You will be working with a number of files with different extensions. They include: 1. file.pjt: to create and build a project named file. 2. file.c: C source program.

3. file.asm: assembly source program created by the user, by the C compiler,or by the linear optimizer. 4. file.sa: linear assembly source program. The linear optimizer uses file.sa as input to produce an assembly program file.asm . 5. file.h: header support file.
Digital Signal Processing Lab Manual Page 64

Department of Electronics and Communication

VCET,Hyderabad.

6. file.lib: library file, such as the run-time support library file rts6701.lib. 7. file.cmd: linker command file that maps sections to memory. 8. file.obj: object file created by the assembler. 9. file.out: executable file created by the linker to be loaded and run on the processor. Procedure to work on code composer studio
1.Click on CCStudio 3.1 on the desktop

Now the target is not connected in order to connect Debug connect

2. To create project, Project New

Digital Signal Processing Lab Manual

Page 65

Department of Electronics and Communication

VCET,Hyderabad.

3. Give project name and click on finish.

4. Click on File New Source File, To write the Source Code

Enter the source code and save the file with .C extension. 5. To add the c program to the project Project Add files to project <source file>

6. To add rts6700.lib to the project

Project Add files to project rts6700.lib Path : C:\CCstudio\c6000\lib\rts6700.lib Note: Select Object & library files (*.o, *.l) in Type of file

Digital Signal Processing Lab Manual

Page 66

Department of Electronics and Communication

VCET,Hyderabad.

7. To add hello.cmd to the project

Project Add files to project hello.cmd Path: C:\CCstudio\tutorial\dsk6713\hello1\hello.cmd Note: Select Linker command file (*.cmd) in Type of file

8. To compile Project Compile file ( or use icon or ctrl+F7 )

9. To build or link Project build (or use F7 ) (which will create a .out file in project folder)
Digital Signal Processing Lab Manual Page 67

Department of Electronics and Communication

VCET,Hyderabad.

10. To load the program: File Load Program <select the .out file in debug folder in project folder> This will load our program into the board. 11.To run the program Debug Run 12. Observe the output in output window. 11. To see the Graph go to View and select time/frequency in the Graph, And give the correct Start address provided in the program, Display data can be taken as per user

Digital Signal Processing Lab Manual

Page 68

Department of Electronics and Communication

VCET,Hyderabad.

1. Generation of sine wave and square wave


Aim:- To generate a sine wave and square wave using C6713 simulator Equipments: Operating System - Windows XP Software - CC STUDIO 3 DSK 6713 DSP Trainer kit. USB Cable Power supply Procedure:1. Open Code Composer Setup and select C6713 simulator, click save and quit 2. Start a new project using Project New pull down menu, save it in a separate directory (C:\My projects) with file name sine wave.pjt 3. Create a new source file using File New Source file menu and save it in the project folder(sinewave.c) 4. Add the source file (sinewave.c) to the project Project Add files to Project Select sinewave.c 5. Add the linker command file hello.cmd Project Add files to Project (path: C:\CCstudio\tutorial\dsk6713\hello\hello.cmd) 6. Add the run time support library file rts6700.lib Project Add files to Project (path: C\CCStudio\cgtools\lib\rts6700.lib) 7. Compile the program using project Compile menu or by Ctrl+F7 8. Build the program using project Build menu or by F7 9. Load the sinewave.out file (from project folder lcconv\Debug) using File Load Program 10. Run the program using Debug Run or F5 11. To view the output graphically Select View Graph Time and Frequency 12. Repeat the steps 2 to 11 for square wave
Digital Signal Processing Lab Manual Page 69

Department of Electronics and Communication

VCET,Hyderabad.

Program Sine Wave #include <stdio.h> #include <math.h> float a[500]; void main() { int i=0; for(i=0;i<500;i++) { a[i]=sin(2*3.14*10000*i); } }

Square wave #include <stdio.h> #include <math.h> int a[1000]; void main() { int i,j=0; int b=5; for(i=0;i<10;i++) { for (j=0;j<=50;j++) { a[(50*i)+j]=b; } b=b*(-1) ; } }

Digital Signal Processing Lab Manual

Page 70

Department of Electronics and Communication

VCET,Hyderabad.

Output:Sine wave

Digital Signal Processing Lab Manual

Page 71

Department of Electronics and Communication

VCET,Hyderabad.

Square wave:-

Result:- The sine wave and square wave has been obtained.

Digital Signal Processing Lab Manual

Page 72

Department of Electronics and Communication

VCET,Hyderabad.

2. Linear Convolution Aim: -To verify Linear Convolution. Equipments: Operating System - Windows XP Software - CC STUDIO 3

DSK 6713 DSP Trainer kit. USB Cable Power supply Procedure:1. Open Code Composer Setup and select C6713 simulator, click save and quit 2. Start a new project using Project New pull down menu, save it in a separate directory (C:\My projects) with file name linearconv.pjt 3. Create a new source file using File New Source file menu and save it in the project folder (linearconv.c) 4. Add the source file (linearconv.c) to the project Project Add files to Project Select linearconv.c 5. Add the linker command file hello.cmd Project Add files to Project (path: C:\CCstudio\tutorial\dsk6713\hello\hello.cmd) 6. Add the run time support library file rts6700.lib Project Add files to Project (Path: C\CCStudio\cgtools\lib\rts6700.lib) 7. Compile the program usingproject Compile menu or by Ctrl+F7 8. Build the program using project Build menu or by F7 9. Load the linearconv.out file (from project folder impulse response\Debug) using File Load Program 10. Run the program using Debug Run or F5 11. To view the output graphically Select View Graph Time and Frequency 12. observe the values in the output window.
Digital Signal Processing Lab Manual Page 73

Department of Electronics and Communication

VCET,Hyderabad.

Program:
// Linear convolution program in c language using CC Studio #include<stdio.h> int x[15],h[15],y[15]; main() { int i,j,m,n; printf("\n enter value for m"); scanf("%d",&m); printf("\n enter value for n"); scanf("%d",&n); printf("Enter values for i/p x(n):\n"); for(i=0;i<m;i++) scanf("%d",&x[i]); printf("Enter Values for i/p h(n) \n"); for(i=0;i<n; i++) scanf("%d",&h[i]); // padding of zeros for(i=m;i<=m+n-1;i++) x[i]=0; for(i=n;i<=m+n-1;i++) h[i]=0; /* convolution operation */ for(i=0;i<m+n-1;i++) { y[i]=0; for(j=0;j<=i;j++) { y[i]=y[i]+(x[j]*h[i-j]); } } //displaying the o/p for(i=0;i<m+n-1;i++) printf("\n The Value of output y[%d]=%d",i,y[i]); }

Digital Signal Processing Lab Manual

Page 74

Department of Electronics and Communication

VCET,Hyderabad.

Output:enter value for m 4 enter value for n 4 Enter values for i/p 1234 Enter Values for n 1234 The Value of output y[0]=1 The Value of output y[1]=4 The Value of output y[2]=10 The Value of output y[3]=20 The Value of output y[4]=25 The Value of output y[5]=24 The Value of output y[6]=16

Precautions: 1) Switch ON the computer only after connecting USB cable and make sure the DSP kit is ON. 2) Perform the diagnostic check before opening code composer studio. 3) All the connections must be tight.
Result:- Thus linear convolution of 2 sequences is verified using CC Studio.

Digital Signal Processing Lab Manual

Page 75

Department of Electronics and Communication

VCET,Hyderabad.

3. Impulse response of first order and second order systems


Aim:- To find Impulse response of a first order and second order system. Equipments: Operating System - Windows XP Software - CC STUDIO 3 DSK 6713 DSP Trainer kit. USB Cable Power supply Procedure:1. Open Code Composer Setup and select C6713 simulator, click save and quit 2. Start a new project using Project New pull down menu, save it in a separate directory (C:\My projects) with file name impulseresponse.pjt 3. Create a new source file using File New Source file menu and save it in the project folder (firstorder.c) 4. Add the source file (firstorder.c) to the project Project Add files to Project Select firstorder.c 5. Add the linker command file hello.cmd Project Add files to Project (path: C:\CCstudio\tutorial\dsk6713\hello\hello.cmd) 6. Add the run time support library file rts6700.lib Project Add files to Project (Path: C\CCStudio\cgtools\lib\rts6700.lib) 7. Compile the program using project Compile menu or by Ctrl+F7 8. Build the program using project Build menu or by F7 9. Load the firstorder.out file (from project folder impulse response\Debug) using File Load Program 10. Run the program using DebugRun or F5 11. To view the output graphically Select View Graph Time and Frequency 12. Repeat the steps 2 to 11 for secondorder

Digital Signal Processing Lab Manual

Page 76

Department of Electronics and Communication

VCET,Hyderabad.

For first order difference equation. Program: #include<stdio.h> #define Order 1 #define Len 5 float h[Len] = {0.0,0.0,0.0,0.0,0.0},sum;

void main() { int j, k; float a[Order+1] = {0.1311, 0.2622}; float b[Order+1] = {1, -0.7478}; for(j=0; j<Len; j++) { sum = 0.0; for(k=1; k<=Order; k++) { if((j-k)>=0) sum = sum+(b[k]*h[j-k]); } if(j<=Order) h[j] = a[j]-sum; else h[j] = -sum; printf("%f", j, h[j]); } }

Output: 0.131100 0.360237 0.269385 0.201446 0.150641.

Digital Signal Processing Lab Manual

Page 77

Department of Electronics and Communication

VCET,Hyderabad.

Find out the impulse response of second order difference equation. Program: #include<stdio.h> #define Order 2 #define Len 5 float h[Len] = {0.0,0.0,0.0,0.0,0.0},sum; void main() { int j, k; float a[Order+1] = {0.1311, 0.2622, 0.1311}; float b[Order+1] = {1, -0.7478, 0.2722}; for(j=0; j<Len; j++) { sum = 0.0; for(k=1; k<=Order; k++) { if ((j-k) >= 0) sum = sum+(b[k]*h[j-k]); } if (j <= Order) h[j] = a[j]-sum; else h[j] = -sum; printf (" %f ,h[j]); } } Output: 0.131100 0.360237 0.364799 0.174741 0.031373 Result:- Impulse response of a first order and second order system is performed using CC Studio
Digital Signal Processing Lab Manual Page 78

Department of Electronics and Communication

VCET,Hyderabad.

Real time experiments


Procedure for Real time Programs : 1. Connect a Signal Generator/audio input to the LINE IN Socket or connect a microphone to the MIC IN Socket. Note:- To use microphone input change the analog audio path control register value (Register no. 4) in Codec Configuration settings of the Source file ( Codec.c) from 0x0011 to 0x0015.

2. Connect CRO/Desktop Speakers to the Socket Provided for LINE OUT or connect a headphone to the Headphone out Socket. 3. Now Switch on the DSK and Bring Up Code Composer Studio on the PC. 4. Use the Debug Connect menu option to open a debug connection to the DSK Board

Digital Signal Processing Lab Manual

Page 79

Department of Electronics and Communication

VCET,Hyderabad.

5. Create a new project with name codec.pjt. 6. Open the File new DSP/BIOS Configuration select dsk6713.cdb and save it as xyz.cdb

7. Add xyz.cdb to the current project. Project Add files to project xyz.cdb

8. Automatically three files are added in the Gene rated file folder in project pane xyzcfg.cmd Command and linking file xyzcfg.s62 optimized assembly code for configuration xyzcfg_c.c Chip support initialization 9. Open the File Menu ne w Source file 10. Type the code in editor window. Save the file in project folder. (Eg: Codec.c). Important note: Save your source code with preferred language extension. For ASM codes save the file as code(.asm) For C and C++ codes code (*.c,*.cpp) respectively.
Digital Signal Processing Lab Manual Page 80

Department of Electronics and Communication

VCET,Hyderabad.

11. Add the saved Codec.c file to the current project which has the main function and calls all the other necessary routines. Project Add files to Project Codec.c 12. Add the library file dsk6713bsl.lib to the current project Path : C:\CCStudio_v3.1\C6000\dsk6713\lib\dsk6713bsl.lib Files of type : Object and library files (*.o*, *.l*) 13. Copy header files dsk6713.h and dsk6713_aic23.h from and paste it in current project folder. C:\CCStudio_v3.1\C6000\dsk6713\include . 14. Add the header file generated within xyzcfg_c.c to codec.c Note:- Double click on xyzcfg_c.c. Copy the first line header ( eg.#include xyzcfg.h) and paste that in source file (eg.codec.c). 15. Compile the program using the Project-compile pull down menu or by Clicking the shortcut icon on the left side of program window. 16. Build the program using the Project-Build pull down menu or by clicking the shortcut icon on the left side of program window. 17. Load the program (Codec. Out) in program memory of DSP chip using the File-load program pull down menu. 18. Debug Run 19. You can notice the input signal of 500 Hz. appearing on the CRO verifying the codec configuration. 20. You can also pass an audio input and hear the output signal through the speakers. 21. You can also vary the sampling frequency using the DSK6713_AIC23_setFreq Function in the codec.c file and repeat the above steps.

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

Digital Signal Processing Lab Manual

Page 81

Department of Electronics and Communication

VCET,Hyderabad.

4. Generation of Real Time Sine Wave


Aim:- To generate a real time sine wave using TMS320C6713 DSK Equipments:1) Operating System - Windows XP 2) Software - CC STUDIO 3 3) DSK 6713 DSP Trainer kit. 4) USB Cable 5) Power supply 6) Speaker Procedure:1.Connect Speaker to the LINE OUT socket. 2.Now switch ON the DSK and bring up Code Composer Studio on PC 3.Create a new project with name sinewave.pjt 4.From File menu New DSP/BIOS Configuration Select dsk6713.cdb and save it as xyz.cdb 5. Add xyz.cdb to the current project 6. Create a new source file and save it as sinewave.c 7. Add the source file sinewave.c to the project 8. Add the library file dsk6713bsl.lib to the project ( Path: C:\CCStudio\C6000\dsk6713\lib\dsk6713bsl.lib) 9. Copy files dsk6713.h and dsk6713_aic23.h to the Project folder 10. Build (F7) and load the program to the DSP Chip ( File Load Program) 11. Run the program (F5) 12. Give an audio output from the PC and notice the output in the speaker Program:-

Sinewave.c
#include "xyzcfg.h" #include "dsk6713.h" #include "dsk6713_aic23.h" #include <stdio.h>
Digital Signal Processing Lab Manual Page 82

Department of Electronics and Communication

VCET,Hyderabad.

#include <math.h> float a[500],b; DSK6713_AIC23_Config config= DSK6713_AIC23_DEFAULTCONFIG;

void main() { int i=0; DSK6713_AIC23_CodecHandle hCodec; Int l_output,r_output; DSK6713_init(); hCodec=DSK6713_AIC23_openCodec(0,&config); DSK6713_AIC23_setFreq=DSK6713_AIC23_FREQ_48KHZ; for(i=0;i<500;i++) { a[i]=sin(2*3.14*10000*i); } while(1) { for(i=0;i<500;i++) { b=400*a[i]; while(!DSK6713_AIC23_write(hCodec,b)); } } DSK6713_AIC23_closeCodec(hCodec); }

Result:- The sine wave tone have been successfully generated and obtained through speaker

Digital Signal Processing Lab Manual

Page 83

Department of Electronics and Communication

VCET,Hyderabad.

5.Real time FIR (LP/HP) Filter Design


Aim:- To design FIR filter (LP/HP) using windowing technique and verify using the DSP processor i. Using rectangular window ii. Using triangular window iii. Using Kaiser Window Equipments:1) Operating System - Windows XP 2) Software - CC STUDIO 3 3) Software Matlab 6.5 4) DSK 6713 DSP Trainer kit. 5) USB Cable 6) Power supply 7) CRO 8) Function Generator Procedure:1) Switch on the DSP board. 2) Open the Code Composer Studio. 3) Create a new project 4) Project New (File Name. pjt , Eg: FIR.pjt) 5) Initialize on board codec. Kindly refer the Topic Configuration of 6713 Codec using BSL 6) Add the given above C source file to the current project (remove codec.c source file from the project if you have already added). 7) Connect the speaker jack to the input of the CRO. 8) Build the program. 9) Load the generated object file(*.out) on to Target board. 10) Run the program using F5. 11) Observe the waveform that appears on the CRO screen.

Digital Signal Processing Lab Manual

Page 84

Department of Electronics and Communication

VCET,Hyderabad.

Matlab Program to gene rate FIR Filter-Low Pass Coefficients using FIR1 % FIR Low pass filters using rectangular, triangular and kaiser windows

% sampling rate - 8000 order = 30; cf=[500/4000,1000/4000,1500/4000]; cf--> contains set of cut-off frequencies[Wc ]

% cutoff frequency - 500 b_rect1=fir1(order,cf(1),boxcar(31)); Rectangular b_tri1=fir1(order,cf(1),bartlett(31)); Triangular b_kai1=fir1(order,cf(1),kaiser(31,8)); Kaisar [Where 8-->Beta Co-efficient]

% cutoff frequency - 1000 b_rect2=fir1(order,cf(2),boxcar(31)); b_tri2=fir1(order,cf(2),bartlett(31)); b_kai2=fir1(order,cf(2),kaiser(31,8)); % cutoff frequency 1500 b_rect3=fir1(order,cf(3),boxcar(31)); b_tri3=fir1(order,cf(3),bartlett(31)); b_kai3=fir1(order,cf(3),kaiser(31,8));

fid=fopen('FIR_lowpass_rectangular.txt','wt'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -400Hz'); fprintf(fid,'\nfloat b_rect1[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect1); fseek(fid,-1,0); fprintf(fid,'};'); fprintf(fid,'\n\n\n\n'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -800Hz');
Digital Signal Processing Lab Manual Page 85

Department of Electronics and Communication

VCET,Hyderabad.

fprintf(fid,'\nfloat b_rect2[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect2); fseek(fid,-1,0); fprintf(fid,'};'); fprintf(fid,'\n\n\n\n'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -1200Hz'); fprintf(fid,'\nfloat b_rect3[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect3); fseek(fid,-1,0); fprintf(fid,'};'); fclose(fid); winopen('FIR_highpass_rectangular.txt');

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

Digital Signal Processing Lab Manual

Page 86

Department of Electronics and Communication

VCET,Hyderabad.

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

T.3 : Matlab generated Coefficients for FIR Low Pass Triangular filter

Digital Signal Processing Lab Manual

Page 87

Department of Electronics and Communication

VCET,Hyderabad.

MATLAB Program to generate FIR Filter-High Pass Coefficients using FIR1 % FIR High pass filters using rectangular, triangular and kaiser windows

% sampling rate - 8000 order = 30; cf=[400/4000,800/4000,1200/4000]; ;cf--> contains set of cut-off frequencies[Wc]

% cutoff frequency - 400 b_rect1=fir1(order,cf(1),'high',boxcar(31)); b_tri1=fir1(order,cf(1),'high',bartlett(31)); b_kai1=fir1(order,cf(1),'high',kaiser(31,8)); Where Kaiser(31,8)--> '8'defines the value of 'beta'.

% cutoff frequency - 800 b_rect2=fir1(order,cf(2),'high',boxcar(31)); b_tri2=fir1(order,cf(2),'high',bartlett(31)); b_kai2=fir1(order,cf(2),'high',kaiser(31,8));

% cutoff frequency - 1200 b_rect3=fir1(order,cf(3),'high',boxcar(31)); b_tri3=fir1(order,cf(3),'high',bartlett(31)); b_kai3=fir1(order,cf(3),'high',kaiser(31,8));

fid=fopen('FIR_highpass_rectangular.txt','wt'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -400Hz'); fprintf(fid,'\nfloat b_rect1[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect1); fseek(fid,-1,0); fprintf(fid,'};');


Digital Signal Processing Lab Manual Page 88

Department of Electronics and Communication

VCET,Hyderabad.

fprintf(fid,'\n\n\n\n'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -800Hz'); fprintf(fid,'\nfloat b_rect2[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect2); fseek(fid,-1,0); fprintf(fid,'};'); fprintf(fid,'\n\n\n\n'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -1200Hz'); fprintf(fid,'\nfloat b_rect3[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect3); fseek(fid,-1,0); fprintf(fid,'};'); fclose(fid); winopen('FIR_highpass_rectangular.txt');

T.1: MATLAB generated Coefficients for FIR High Pass Kaiser filter:

Digital Signal Processing Lab Manual

Page 89

Department of Electronics and Communication

VCET,Hyderabad.

T.2 :MATLAB generated Coefficients for FIR High Pass Rectangular filter

T.3 : MATLAB generated Coefficients for FIR High Pass Triangular filter

Digital Signal Processing Lab Manual

Page 90

Department of Electronics and Communication

VCET,Hyderabad.

C PROGRAM TO IMPLEMENT FIR FILTER( fir.c):-

#include "filtercfg.h" #include "dsk6713.h" #include "dsk6713_aic23.h" float filter_Coeff[] ={0.000000,-0.001591,-0.002423,0.000000,0.005728, 0.011139,0.010502,-0.000000,-0.018003,-0.033416,-0.031505,0.000000, 0.063010,0.144802,0.220534,0.262448,0.220534,0.144802,0.063010,0.000000, -0.031505,-0.033416,-0.018003,-0.000000,0.010502,0.011139,0.005728, 0.000000,-0.002423,-0.001591,0.000000 }; static short in_buffer[100]; DSK6713_AIC23_Config config = {\ 0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Leftline input channel volume */\ 0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume*/\ 0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */\ 0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */\ 0x0011, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */\ 0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */\ 0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */\ 0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */\ 0x0081, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */\ 0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \ }; /* * main() - Main code routine, initializes BSL and generates tone */ void main() { DSK6713_AIC23_CodecHandle hCodec; Uint32 l_input, r_input,l_output, r_output;
Digital Signal Processing Lab Manual Page 91

Department of Electronics and Communication

VCET,Hyderabad.

/* Initialize the board support library, must be called first */ DSK6713_init(); /* Start the codec */ hCodec = DSK6713_AIC23_openCodec(0, &config); DSK6713_AIC23_setFreq(hCodec, 1); while(1) { /* Read a sample to the left channel */ while (!DSK6713_AIC23_read(hCodec, &l_input)); /* Read a sample to the right channel */ while (!DSK6713_AIC23_read(hCodec, &r_input)); l_output=(Int16)FIR_FILTER(&filter_Coeff ,l_input); r_output=l_output; /* Send a sample to the left channel */ while (!DSK6713_AIC23_write(hCodec, l_output)); /* Send a sample to the right channel */ while (!DSK6713_AIC23_write(hCodec, r_output)); } /* Close the codec */ DSK6713_AIC23_closeCodec(hCodec); } signed int FIR_FILTER(float * h, signed int x) {i nt i=0; signed long output=0; in_buffer[0] = x; /* new input at buffer[0] */ for(i=30;i>0;i--) in_buffer[i] = in_buffer[i-1]; /* shuffle the buffer */ for(i=0;i<32;i++) output = output + h[i] * in_buffer[i]; return(output); }
Digital Signal Processing Lab Manual Page 92

Department of Electronics and Communication

VCET,Hyderabad.

PROCEDURE : #include "dsk6713.h" #include "dsk6713_aic23.h" /* Codec configuration settings */ DSK6713_AIC23_Config config = { \ 0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Left line input channel volume */ \ 0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume */\ 0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */ \ 0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */ \ 0x0011, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */ \ 0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */ \ 0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */ \ 0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */ \ 0x0081, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */ \ 0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \ }; /* main() - Main code routine, initializes BSL and generates tone */ void main() { DSK6713_AIC23_CodecHandle hCodec; int l_input, r_input,l_output, r_output; /* Initialize the board support library, must be called first */ DSK6713_init(); /* Start the codec */ hCodec = DSK6713_AIC23_openCodec(0, &config); /*set codec sampling frequency*/ DSK6713_AIC23_setFreq(hCodec, 3); while(1) { /* Read a sample to the left channel */
Digital Signal Processing Lab Manual Page 93

Department of Electronics and Communication

VCET,Hyderabad.

while (!DSK6713_AIC23_read(hCodec, &l_input)); /* Read a sample to the right channel */ while (!DSK6713_AIC23_read(hCodec, &r_input)); /* Send a sample to the left channel */ while (!DSK6713_AIC23_write(hCodec, l_input)); /* Send a sample to the right channel */ while (!DSK6713_AIC23_write(hCodec, l_input)); } /* Close the codec */ DSK6713_AIC23_closeCodec(hCodec); }

Output:-

MATLAB GENERATED FREQUENCY RESPONSE High Pass FIR filter(Fc= 800Hz).

Digital Signal Processing Lab Manual

Page 94

Department of Electronics and Communication

VCET,Hyderabad.

Low Pass FIR filter (Fc=1000Hz)

Result:- Thus FIR (LP/HP) filter is designed using windowing technique and verified using the DSP Processor.

Digital Signal Processing Lab Manual

Page 95

Department of Electronics and Communication

VCET,Hyderabad.

6. Real Time IIR (LP/HP) Filter Design


Aim: To design IIR filter (LP/HP) using Low pass Butterworth and Chebyshev filters technique and verify using the DSP processor Equipments:1) Operating System - Windows XP 2) Software - CC STUDIO 3 3) Software Mat lab 6.5 4) DSK 6713 DSP Trainer kit. 5) USB Cable 6) Power supply 7) CRO 8) Function Generator Algorithm:We need to realize the Butter worth band pass IIR filter by implementing the difference equation y[n] = b0x[n] + b1x[n-1]+b2x[n-2]-a1y[n-1]-a2y[n-2] where b0 b2, a0-a2 are feed forward and feedback word coefficients respectively [Assume 2nd order of filter].These coefficients are calculated using MATLAB.A direct form I implementation approach is taken. Step 1 - Initialize the McBSP, the DSP board and the on board codec. Kindly refer the Topic Configuration of 6713Codec using BSL Step 2 - Initialize the discrete time system , that is , specify the initial conditions. Generally zero initial conditions are assumed. Step 3 - Take sampled data from codec while input is fed to DSP kit from the signal generator. Since Codec is stereo , take average of input data read from left and right channel . Store sampled data at a memory location. Step 4 - Perform filter operation using above said difference equation and store filter Output at a memory location. Step 5 - Output the value to codec (left channel and right channel) and view the output at Oscilloscope. Step 6 - Go to step 3.

Digital Signal Processing Lab Manual

Page 96

Department of Electronics and Communication

VCET,Hyderabad.

Program:(Matlab program to generate Filter Coefficients) % IIR Low pass Butterworth and Chebyshev filters % sampling rate - 24000 order = 2; cf=[2500/12000,8000/12000,1600/12000]; % cutoff frequency - 2500 [num_bw1,den_bw1]=butter(order,cf(1)); [num_cb1,den_cb1]=cheby1(order,3,cf(1)); % cutoff frequency - 8000 [num_bw2,den_bw2]=butter(order,cf(2)); [num_cb2,den_cb2]=cheby1(order,3,cf(2)); fid=fopen('IIR_LP_BW.txt','wt'); fprintf(fid,'\t\t-----------Pass band range: 0-2500Hz----------\n'); fprintf(fid,'\t\t-----------Magnitude response: Monotonic-----\n\n\'); fprintf(fid,'\n float num_bw1[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',num_bw1); fprintf(fid,'\nfloat den_bw1[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',den_bw1); fprintf(fid,'\n\n\n\t\t-----------Pass band range: 0-8000Hz----------\n'); fprintf(fid,'\t\t-----------Magnitude response: Monotonic-----\n\n'); fprintf(fid,'\nfloat num_bw2[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',num_bw2); fprintf(fid,'\nfloat den_bw2[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',den_bw2); fclose(fid); winopen('IIR_LP_BW.txt'); fid=fopen('IIR_LP_CHEB Type1.txt','wt'); fprintf(fid,'\t\t-----------Pass band range: 2500Hz----------\n'); fprintf(fid,'\t\t-----------Magnitude response: Rippled (3dB) -----\n\n\'); fprintf(fid,'\nfloat num_cb1[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',num_cb1); fprintf(fid,'\nfloat den_cb1[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',den_cb1);
Digital Signal Processing Lab Manual Page 97

Department of Electronics and Communication

VCET,Hyderabad.

fprintf(fid,'\n\n\n\t\t-----------Pass band range: 8000Hz----------\n'); fprintf(fid,'\t\t-----------Magnitude response: Rippled (3dB)-----\n\n'); fprintf(fid,'\nfloat num_cb2[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',num_cb2); fprintf(fid,'\nfloat den_cb2[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',den_cb2); fclose(fid); winopen('IIR_LP_CHEB Type1.txt'); %%%%%%%%%%%%%%%%%% figure(1); [h,w]=freqz(num_bw1,den_bw1); w=(w/max(w))*12000; plot(w,20*log10(abs(h)),'linewidth',2) hold on [h,w]=freqz(num_cb1,den_cb1); w=(w/max(w))*12000; plot(w,20*log10(abs(h)),'linewidth',2,'color','r') grid on legend('Butterworth','Chebyshev Type-1'); xlabel('Frequency in Hertz'); ylabel('Magnitude in Decibels'); title('Magnitude response of Low pass IIR filters (Fc=2500Hz)');

figure(2); [h,w]=freqz(num_bw2,den_bw2); w=(w/max(w))*12000; plot(w,20*log10(abs(h)),'linewidth',2) hold on [h,w]=freqz(num_cb2,den_cb2); w=(w/max(w))*12000; plot(w,20*log10(abs(h)),'linewidth',2,'color','r') grid on legend('Butterworth','Chebyshev Type-1 (Ripple: 3dB)'); xlabel('Frequency in Hertz'); ylabel('Magnitude in Decibels'); title('Magnitude response in the passband'); axis([0 12000 -20 20]);
Digital Signal Processing Lab Manual Page 98

Department of Electronics and Communication

VCET,Hyderabad.

IIR_cheb_lp filter co-efficients:

IIR_butterworth_hp filter co-efficients:

IIR_cheb_hp filter co-efficients:

IIR_butterworth_hp filter co-efficients:

Digital Signal Processing Lab Manual

Page 99

Department of Electronics and Communication

VCET,Hyderabad.

C PROGRAM TO IMPLEMENT IIR FILTER #include "filtercfg.h" #include "dsk6713.h" #include "dsk6713_aic23.h" const signed int filter_Coeff[] = { //12730,-12730,12730,2767,-18324,21137 /*HP 2500 */ //312,312,312,32767,-27943,24367 /*LP 800 */ //1455,1455,1455,32767,-23140,21735 /*LP 2500 */ //9268,-9268,9268,32767,-7395,18367 /*HP 4000*/ 7215,-7215,7215,32767,5039,6171, /*HP 7000*/ }; /* Codec configuration settings */ DSK6713_AIC23_Config config = { \ 0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Left line input channel volume */ \ 0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume */\ 0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */ \ 0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */ \ 0x0011, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */ \ 0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */ \ 0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */ \ 0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */ \ 0x0081, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */ \ 0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \ }; /* * main() - Main code routine, initializes BSL and generates tone */ void main() { DSK6713_AIC23_CodecHandle hCodec; int l_input, r_input, l_output, r_output; /* Initialize the board support library, must be called first */ DSK6713_init(); /* Start the codec */ hCodec = DSK6713_AIC23_openCodec(0, &config); DSK6713_AIC23_setFreq(hCodec, 3); while(1) { /* Read a sample to the left channel */
Digital Signal Processing Lab Manual Page 100

Department of Electronics and Communication

VCET,Hyderabad.

while (!DSK6713_AIC23_read(hCodec, &l_input)); /* Read a sample to the right channel */ while (!DSK6713_AIC23_read(hCodec, &r_input)); l_output=IIR_FILTER(&filter_Coeff ,l_input); r_output=l_output; /* Send a sample to the left channel */ while (!DSK6713_AIC23_write(hCodec, l_output)); /* Send a sample to the right channel */ while (!DSK6713_AIC23_write(hCodec, r_output)); } /* Close the codec */ DSK6713_AIC23_closeCodec(hCodec); } signed int IIR_FILTER(const signed int * h, signed int x1) { static signed int x[6] = { 0, 0, 0, 0, 0, 0 }; /* x(n), x(n-1), x(n-2). Must be static */ static signed int y[6] = { 0, 0, 0, 0, 0, 0 }; /* y(n), y(n-1), y(n-2). Must be static */ int temp=0; temp = (short int)x1; /* Copy input to temp */ x[0] = (signed int) temp; /* Copy input to x[stages][0] */ temp = ( (int)h[0] * x[0]) ; /* B0 * x(n) */ temp += ( (int)h[1] * x[1]); /* B1/2 * x(n-1) */ temp += ( (int)h[1] * x[1]); /* B1/2 * x(n-1) */ temp += ( (int)h[2] * x[2]); /* B2 * x(n-2) */ temp -= ( (int)h[4] * y[1]); /* A1/2 * y(n-1) */ temp -= ( (int)h[4] * y[1]); /* A1/2 * y(n-1) */ temp -= ( (int)h[5] * y[2]); /* A2 * y(n-2) */ /* Divide temp by coefficients[A0] */ temp >>= 15; if ( temp > 32767 ) { temp = 32767; } else if ( temp < -32767) { temp = -32767; } y[0] = temp ; /* Shuffle values along one place for next time */
Digital Signal Processing Lab Manual Page 101

Department of Electronics and Communication

VCET,Hyderabad.

y[2] = y[1] = x[2] = x[1] =

y[1]; y[0]; x[1]; x[0];

/* y(n-2) = y(n-1) */ /* y(n-1) = y(n) */ /* x(n-2) = x(n-1) */ /* x(n-1) = x(n) */ /* temp is used as input next time through */

return (temp<<2); } Procedure: 1) Switch on the DSP board. 2) Open the Code Composer Studio. 3) Create a new project Project New (File Name. pjt , Eg: IIR.pjt) 4) Initialize on board codec. Kindly refer the Topic Configuration of 6713 Codec using BSL 5) Add the given above C source file to the current project (re move codec.c source file from the project if you have already added). 6) Connect the speaker jack to the input of the CRO. 7) Build the program. 8) Load the generated object file(*.out) on to Target board. 9) Run the program using F5. 10) Observe the waveform that appears on the CRO screen.

Digital Signal Processing Lab Manual

Page 102

Department of Electronics and Communication

VCET,Hyderabad.

Result:- Thus IIR (LP/HP) filter is designed using Low pass Butterworth and Chebyshev filters technique and verified using the DSP processor

Digital Signal Processing Lab Manual

Page 103

Department of Electronics and Communication

VCET,Hyderabad.

7.

Audio applications
respective

Aim: - To Perform Audio applications such as to plot a time and frequency display of microphone plus a cosine using DSP. Read a wav file and match with their spectrograms. Equipments:1) Operating System - Windows XP 2) Software - CC STUDIO 3 3) Software Matlab 6.5 4) DSK 6713 DSP Trainer kit. 5) USB Cable 6) Power supply Theory: Spectrogram with RTDX using MATLAB This version of project makes use of RTDX with MATLAB for transferring data from the DSK to the PC host. This section introduces configuration file(.CDB) file and RTDX with MATLAB. This project uses source program spectrogram_rtdx_mtl.c that runs on the DSK which computes 256 point FFT and enables an RTDX output channel to write/send the resulting FFT data to the PC running MATLAB for finding the spectrogram. A total o f N/2 (128 points )are sent. The (.CDB) configuration file is used to set interrupt INT11. From this configuration file select Input/Output RTDX. Right click on properties and change the RTDX buffer size to 8200. Within CCS, select tools RTDX Configure to set the host buffer size to 2048(from 1024). An input signal is read in blocks of 256 samples. Each block of data is then multiplied with a hamming window of length 256 points. The FFT of the windowed data is calculated and squared. Half of the resulting FFT of each block of 256 points is then transferred to the PC running MATLAB to find the specrtrogram.

Digital Signal Processing Lab Manual

Page 104

Department of Electronics and Communication

VCET,Hyderabad.

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

main() { for (i = 0 ; i<PTS ; i++) {


Digital Signal Processing Lab Manual Page 105

//set up twiddle constants in w

Department of Electronics and Communication

VCET,Hyderabad.

w[i].real = cos(2*PI*i/512.0); w[i].imag =-sin(2*PI*i/512.0); } comm_intr();

//Re component of twiddle constants //Im component of twiddle constants

//init DSK, codec, McBSP

while(!RTDX_isOutputEnabled(&ochan)) puts("\n\n Waiting . . . "); for(l=0;l<256;l++) a[l]=cos(2*3.14*1500*l/8000); for(k=0;k<5000;k++) { while (flag == 0) ; flag = 0; for (i = 0 ; i < PTS ; i++) { iobuffer1[i]=iobuffer[i]+a[i];

//wait for PC to enable RTDX

//while waiting

//infinite loop

//wait until iobuffer is full //reset flag //swap buffers

samples[i].real=h[i]*iobuffer1[i]; //multiply by Hamming window coeffs iobuffer1[i] = x1[i]; } for (i = 0 ; i < PTS ; i++) samples[i].imag = 0.0; FFT(samples,PTS); for (i = 0 ; i < PTS ; i++) { x1[i] = (samples[i].real*samples[i].real + samples[i].imag*samples[i].imag)/16; //FFT data scaling
Digital Signal Processing Lab Manual Page 106

//process frame to iobuffer

//imag components = 0 //call C-coded FFT function //compute square of FFT magnitude

Department of Electronics and Communication

VCET,Hyderabad.

} RTDX_write(&ochan, x1, sizeof(x1)/2); } } //send 128 samples to PC //end of infinite loop //end of main

interrupt void c_int11() {

//ISR

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

FFT.c C callable FFT function in C #define PTS 256 //# of points for FFT

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

void FFT(COMPLEX *Y, int N) { COMPLEX temp1,temp2; int i,j,k;

//input sample array, # of points

//temporary storage variables

//loop counter variables


Page 107

Digital Signal Processing Lab Manual

Department of Electronics and Communication

VCET,Hyderabad.

int upper_leg, lower_leg; int leg_diff; int num_stages = 0; int index, step; i = 1; do { num_stages +=1; i = i*2; }while (i!=N); leg_diff = N/2; step = 512/N;

//index of upper/lower butterfly leg

//difference between upper/lower leg //number of FFT stages (iterations) //index/step through twiddle constant //log(base2) of N points= # of stages

//difference between upper&lower legs //step between values in twiddle.h

for (i = 0;i < num_stages; i++) //for N-point FFT { index = 0; for (j = 0; j < leg_diff; j++) { for (upper_leg = j; upper_leg < N; upper_leg += (2*leg_diff)) { lower_leg = upper_leg+leg_diff; temp1.real = (Y[upper_leg]).real + (Y[lower_leg]).real; temp1.imag = (Y[upper_leg]).imag + (Y[lower_leg]).imag; temp2.real = (Y[upper_leg]).real - (Y[lower_leg]).real; temp2.imag = (Y[upper_leg]).imag - (Y[lower_leg]).imag; (Y[lower_leg]).real = temp2.real*(w[index]).real
Digital Signal Processing Lab Manual Page 108

Department of Electronics and Communication

VCET,Hyderabad.

-temp2.imag*(w[index]).imag; (Y[lower_leg]).imag = temp2.real*(w[index]).imag +temp2.imag*(w[index]).real; (Y[upper_leg]).real = temp1.real; (Y[upper_leg]).imag = temp1.imag; } index += step; } leg_diff = leg_diff/2; step *= 2; } j = 0; for (i = 1; i < (N-1); i++) { k = N/2; while (k <= j) { j = j - k; k = k/2; } j = j + k; if (i<j) { temp1.real = (Y[j]).real; temp1.imag = (Y[j]).imag;
Digital Signal Processing Lab Manual Page 109

//bit reversal for resequencing data

Department of Electronics and Communication

VCET,Hyderabad.

(Y[j]).real = (Y[i]).real; (Y[j]).imag = (Y[i]).imag; (Y[i]).real = temp1.real; (Y[i]).imag = temp1.imag; } } return; } Spectrogram_RTDX.m For spectrogram plot using RTDX with MATLAB

clc; ccsboardinfo cc=ccsdsp('boardnum',0); reset(cc); visible(cc,1); enable(cc.rtdx); if ~isenabled(cc.rtdx); error('RTDX is not enabled') end cc.rtdx.set('timeout',50); open(cc,'spectrogram1.pjt'); load(cc,'./debug/spectrogram1.out'); run(cc); configure(cc.rtdx,2048,1); open(cc.rtdx,'ochan','r');
Digital Signal Processing Lab Manual

%board info %set up CCS object %reset board %for CCS window %enable RTDX

%set 50sec timeout for RTDX %open CCS project %load executable file %run program %configure one RTDX channel %open output channel
Page 110

Department of Electronics and Communication

VCET,Hyderabad.

pause(3) enable(cc.rtdx,'ochan'); isenabled(cc.rtdx,'ochan'); M = 256; N = round(M/2); B = 128; fs = 8000; t=(1:B)*(M/fs); f=((0:(M-1)/2)/(M-1))*fs; set(gcf,'DoubleBuffer','on'); y = ones(N,B); column = 1; set(gca,'NextPlot','add'); axes_handle = get(gcf,'CurrentAxes'); set(get(axes_handle,'XLabel'),'String','Time (s)');

%wait for RTDX channel to open %enable channel from DSK

%window size

%No. of blocks (128) %sampling rate %spectrogram axes generation

set(get(axes_handle,'YLabel'),'String','Frequency (Hz)'); set(get(axes_handle,'Title'),'String','\fontname{times}\bf Real-Time Spectrogram'); set(gca,'XLim', [0 4.096]); set(gca,'YLim', [0 4000]); set(gca,'XLimMode','manual'); set(gca,'YLimMode','manual'); for i = 1:32768 w=readmsg(cc.rtdx,'ochan','single'); w=double(w(1:N)); y(:, column) = w';
Digital Signal Processing Lab Manual Page 111

%read FFT data from DSK

Department of Electronics and Communication

VCET,Hyderabad.

imagesc(t,f,dB(y)); column = mod(column, B) + 1; end halt(cc);

%plot spectrogram

%halt processor

close(cc.rtdx,'ochan'); clear cc Procedure:

%close channel
%clear object

1. Create a new project with name spectrogram.pjt. 2. Open spectrogram.cdb from given CD and save it in your new project folder. 3. Copy the following files from the CD to your new project folder 1) c6713dskinit . c 2) FFT.c 3) spectrogram_rtdx_mtl.c 4) c6713dskinit . h 5) hamming.cof 6) spectrogram_RTDX.m 4. Add spectrogram.cdb, c6713dskinit.c and spectrogram_rtdx_mtl.c to the current project. 5. Add the library file dsk6713bsl.lib to the current project Path C:\CCStudio\C6000\dsk6713\lib\dsk6713bsl.lib 5. Set the following compiler options. Select Project Build options . Select the following for compiler option with Basic ( for category): (1) c671x{mv6710} (for target version) (2) Full symbolic debug (for Generate Debug info) (3) Speed most critical(for Opt Speed vs. Size) (4) None (for Opt Level and Program Level Opt)
Digital Signal Processing Lab Manual Page 112

Department of Electronics and Communication

VCET,Hyderabad.

Select The Preprocessor Category and Type for Define Symbols{d}: CHIP_6713, and from Feedback category, select for Interlisting: OPT / C and ASM{-s} 6 Build project. 7. Close CCS 8. Open MATLAB and Run spectrogram_RTDX.m . within MATLAB ,CCS will enable RTDX and will load and run the COFF(.out) executable file. Then MATLAB will plot the spectrogram of an input signal .

Result:- Thus Audio application is performed and spectrogram of an input signal is plotted using Matlab.

Digital Signal Processing Lab Manual

Page 113

Department of Electronics and Communication

VCET,Hyderabad.

8. Noise removal
Aim:- To 1) Add noise above 3kHz and then remove (using adaptive filters) 2) Interference suppression using 400 Hz tone Equipments:1) Operating System - Windows XP 2) Software - CC STUDIO 3 3) DSK 6713 DSP Trainer kit. 4) USB Cable 5) Power supply 6) CRO 7) Function Generator

Theory:- Adaptive filters are best used in cases where signal conditions or system parameters are slowly changing and the filter is to be adjusted to compensate for this change. The least mean squares (LMS) criterion is a search algorithm that can be used to provide the strategy for adjusting the filter coefficients.

Fig 1 Basic adaptive filter structure . In conventional FIR and IIR digital filters, it is assumed that the process parameters to determine the filter characteristics are known. They may vary with time, but the nature of the variation is assumed to be known. In many practical problems, there may be a large uncertainty in some parameters because of inadequate prior test data about the process. Some parameters might be expected to change with time, but the exact nature of the change is not predictable. In such cases it is highly desirable to design the filter to be self- learning, so that it can adapt itself to the situation at hand. The coefficients of an adaptive filter are adjusted to compensate for changes in input signal, output signal, or system parameters. Instead of being rigid, an adaptive system can learn the signal characteristics and track slow changes. An adaptive filter can be very useful when there is uncertainty about the characteristics of a signal or when these characteristics change.
Digital Signal Processing Lab Manual Page 114

Department of Electronics and Communication

VCET,Hyderabad.

Figure 1 shows a basic adaptive filter structure in which the adaptive filters output y is compared with a desired signal d to yield an error signal e, which is fed back to the adaptive filter. The coefficients of the adaptive filter are adjusted, or optimized, using a least mean squares (LMS) algorithm based on the error signal. We discuss here only the LMS searching algorithm with a linear combiner (FIR filter), although there are several strategies for performing adaptive filtering. The output of the adaptive filter in Figure 1 is

---------------------------------(1)

where wk (n) represent N weights or coefficients for a specific time n. The convolution equation 1 is in conjunction with FIR filtering. It is common practice to use the terminology of weights w for the coefficients associated with topics in adaptive filtering and neural networks.A performance measure is needed to determine how good the filter is. This measure is based on the error signal,

----------------------------------(2)

which is the difference between the desired signal d(n ) and the adaptive filters output y(n).The weights or coefficients wk (n) are adjusted such that a mean squared error function is minimized. This mean squared error function is E [e2(n)], where E represents the expected value. Since there are k weights or coefficients, a gradient of the mean squared error function is required. An estimate can be found instead using the gradient of e2(n), yielding

--------------------------------(3) which represents the LMS algorithm [13]. Equation 3 provides a simple but powerful and efficient means of updating the weights, or coefficients, without the need for averaging or differentiating, and will be used for implementing adaptive filters. The input to the adaptive filter is x (n), and the rate of convergence and accuracy of the adaptation process (adaptive step size) is b.

For each specific time n, each coefficient, or weight, wk (n) is updated or replaced by a new coefficient, based on 3, unless the error signal e(n) is zero. After the filters output y(n), the error signal e(n) and each of the coefficients wk (n) are updated for a specific time n, a new

Digital Signal Processing Lab Manual

Page 115

Department of Electronics and Communication

VCET,Hyderabad.

sample is acquired (from an ADC) and the adaptation process is repeated for a different time. Note that from equation 3, the weights are not updated when e (n) becomes zero. The linear adaptive combiner is one of the most useful adaptive filter structures and is an adjustable FIR filter.Whereas the coefficients of the frequency-selective FIR filter are fixed, the coefficients, or weights, of the adaptive FIR filter can be adjusted based on a changing environment such as an input signal. Adaptive IIR filters (not discussed here) can also be used. A major problem with an adaptive IIR filter is that its poles may be updated during the adaptatio n process to values outside the unit circle, making the filter unstable. ADAPTIVE STRUCTURES A number of adaptive structures have been used for different applications in adaptive ltering. 1. For noise cancellation. Figure 2 shows the adaptive structure in Figure 1 modied for a noise cancellation application. The desired signal d is corrupted by uncorrelated additive noise n. The input to the adaptive lter is a noise n that is correlated with the noise n. The noise n could come from the same source as n but modied by the environment. The adaptive lters output y is adapted to the noise n. When this happens, the error signal approaches the desired signal d. The overall output is this error signal and not the adaptive lters output y. This structure will be further illustrated with programming examples using C code. 2. For system identication. Figure 3 shows an adaptive lter structure that can be used for system identication or modeling. The same input is to an unknown system in parallel with an adaptive lter. The error signal e is the difference between the response of the unknown system d and the response of the adaptive lter y. This error signal is fed back to the adaptive lter and is used to update the adaptive lters coefcients until the overall output y d. When this happens, the adaptation process is nished, and e approaches zero. In this scheme, the adaptive lter models the unknown system. This structure is illustrated later with three programming examples. 3. Adaptive predictor. Figure 4 shows an adaptive predictor structure which can provide an estimate of an input. This structure is illustrated later with a programming example. 4. Additional structures have been implemented, such as: (a) Notch with two weights, which can be used to notch or cancel/reduce a sinusoidal noise signal. This structure has only two weights or coefcients.This structure is shown in Figure 5 .
Digital Signal Processing Lab Manual Page 116

Department of Electronics and Communication

VCET,Hyderabad.

(b) Adaptive channel equalization, used in a modem to reduce channel distortion resulting from the high speed of data transmission over telephone channels.

Fig 2 Adaptive filter structure for noise cancellation.

Fig 3 Adaptive filter structure for system identification.

Fig 4 Adaptive pre dictor structure.

Fig 5 Adaptive notch structure with two weights.

Digital Signal Processing Lab Manual

Page 117

Department of Electronics and Communication

VCET,Hyderabad.

The LMS is well suited for a number of applications, including adaptive echo and noise cancellation, equalization, and prediction. Other variants of the LMS algorithm have been employed, such as the sign-error LMS, the sign-data LMS, and the sign-sign LMS. 1. For the sign-error LMS algorithm, eqn 3 becomes

where sgn is the signum function,

2. For the sign-data LMS algorithm, eqn 3 becomes 3.For the sign-sign LMS algorithm,eqn 3 becomes

which reduces to

which is more concise from a mathematical viewpoint because no multiplication operation is required for this algorithm. The LMS algorithm has been quite useful in adaptive equalizers, telepho ne cancelers, and so forth. Other methods, such as the recursive least squares (RLS) algorithm [4], can offer faster convergence than the basic LMS but at the expense of more computations. The RLS is based on starting with the optimal solution and then using each input sample to update the impulse response in order to maintain that optimality. The right step size and direction are dened over each time sample. Such algorithms become useful when an appropriate reference signal is not avail- able. The lter is adapted in such a way as to restore some property of the signal lost before reaching the adaptive lter. Instead o f the desired waveform as a template, as in the LMS or RLS algorithms, this property is used for the adaptation of the lter. When the desir ed signal is available, the conventional approach such as the LMS can be used; otherwise, a priori knowledge about the signal is used.
Digital Signal Processing Lab Manual Page 118

Department of Electronics and Communication

VCET,Hyderabad.

Program:#include "NCcfg.h" #include "dsk6713.h" #include "dsk6713_aic23.h" #define beta 1E-13 #define N 30 //rate of convergence //adaptive FIR filter length- vary this parameter & observe

float delay[N]; float w[N];

DSK6713_AIC23_Config config = { \ 0x0017, 0x0017, 0x00d8, 0x00d8, 0x0011, 0x0000, 0x0000, 0x0043, 0x0081, 0x0001 }; /* main() - Main code routine, initializes BSL and generates tone*/ void main() {
Digital Signal Processing Lab Manual Page 119

/* 0 DSK6713_AIC23_LEFTINVOL Left line input channel volume */ \ /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume */\ /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */ \ /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */ \ /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */ /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */ \ \ \

/* 6 DSK6713_AIC23_POWERDOWN Power down control */ /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */ \ \

/* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */ /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \

Department of Electronics and Communication

VCET,Hyderabad.

DSK6713_AIC23_CodecHandle hCodec; int l_input, r_input,l_output, r_output,T; /* Initialize the board support library, must be called first */ DSK6713_init(); hCodec = DSK6713_AIC23_openCodec(0, &config); DSK6713_AIC23_setFreq(hCodec, 1); /* Start the codec */

for (T = 0; T < 30; T++) { w[T] = 0; delay[T] = 0; }

//Initialize the adaptive FIR coeffs=0 //init buffer for weights //init buffer for delay samples

while(1) { /* Read a sample to the left channel */ while (!DSK6713_AIC23_read(hCodec,&l_input)); /* Read a sample to the right channel */ while (!DSK6713_AIC23_read(hCodec, &r_input)); l_output=(short int)adaptive_filter(l_input,r_input); r_output=l_output; while (!DSK6713_AIC23_write(hCodec, l_output)); while (!DSK6713_AIC23_write(hCodec, r_output)); } DSK6713_AIC23_closeCodec(hCodec); } /* Close the codec */ /* Send o/p to the left channel */ /* Send o/p to the right channel*/

Digital Signal Processing Lab Manual

Page 120

Department of Electronics and Communication

VCET,Hyderabad.

signed int adaptive_filter(int l_input,int r_input) { short i,output; float yn=0, E=0, dplusn=0,desired,noise; desired = l_input; noise = r_input; dplusn = (short)(desired + noise); delay[0] = noise; //desired+noise

//ISR

//noise as input to adapt FIR

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

//to calculate out of adapt FIR //output of adaptive filter //"error" signal=(d+n)- yn //to update weights and delays

yn += (w[i] * delay[i]); E = (desired + noise) - yn; for (i = N-1; i >= 0; i--) {

w[i] = w[i] + beta*E*delay[i]; //update weights delay[i] = delay[i-1]; } //update delay samples

//output=((short)E); output=((short)dplusn);

//error signal as overall output //output (desired+noise)

//overall output result return(output); }

Digital Signal Processing Lab Manual

Page 121

Department of Electronics and Communication

VCET,Hyderabad.

Procedure :1. Switch on the DSP Board. 2. Open the code composer studio 3. Create a new project Project New 4. Initialise on board codec 5. Add the above c source file to the project 6. Desired signal 400Hz Noise 3KHz Input a desired sinusoidal signal into the left channel and noise signal of 3KHz into the right channel 7. Build the project 8. Load the generated object file onto the target board 9. Run the program 10. Observe the waveform that appears on the CRO screen Verify that the 3KHz noise signal is being cancelled gradually.

Result :- Thus noise signal cancellation using adaptive filters is verified.

Digital Signal Processing Lab Manual

Page 122

Department of Electronics and Communication

VCET,Hyderabad.

A MINI PROJECT ON
DTMF (Touch Tone) SIGNALLING Tone Generation and Detection Using MATLAB

Digital Signal Processing Lab Manual

Page 123

Department of Electronics and Communication

VCET,Hyderabad.

CONTENTS

Abstract Chapter 1: Dual Tone Multi Frequency (DTMF) 1.1. Introduction 1.2. History 1.3. #, *, A, B, C, and D 1.4. Keypad 1.5. DTMF event frequencies 1.6. Sample Code for DTMF Tone generation

Chapter 2: Goertzel Algorithm 2.1. Introduction 2.2. Explanation of algorithm 2.3. Computational complexity 2.4. Practical considerations

Chapter 3: MATLAB Simulation Codes 3.1. Matlab Code for DTMF Tone Generator 3.2. Matlab code for DTMF decoder (Geortzel Algorithm)

Chapter 4: Comparison of Goertzel Algorithm and FFT Chapter 5: Conclusion Chapter 6: References

Digital Signal Processing Lab Manual

Page 124

Department of Electronics and Communication

VCET,Hyderabad.

Abstract
Most engineers are familiar with the Fast Fourier Transform (FFT) and would have little trouble using a "canned" FFT routine to detect one or more tones in an audio signal.What many don't know, however, is that if you only need to detect a few frequencies, a much faster method is available. It's called the Goertzel algorithm. The Goertzel algorithm can perform tone detection using much less CPU horsepower than the Fast Fourier Transform.

The objective of this project is to gain an understanding of the DTMF tone generation software and the DTMF decoding algorithm (The GOERTZEL algorithm) using MATLAB.

This project includes design of the following MATLAB modules. 1.A tone generation function that produces a signal containg appropriate tones of a given digit. 2.A decoding function to implement the Geortzel Equation, that accepts a DTMF signal and produces an array of tones that corresponds to a digit.

In this project DTMF tone for a digit (seven - 7) was generated and it was detected using Goertzel algorithm.

Chapter 1 Dual Tone Multi-Frequency (DTMF)


Digital Signal Processing Lab Manual Page 125

Department of Electronics and Communication

VCET,Hyderabad.

1.1. Introduction
DTMF is the generic name for push button telephone signaling that is equivalent to the Touch Tone system in use within the BELL SYSTEM. DTMF also finds widespread use in electronic mail systems and telephone banking systems in which the user can select options from a menu by sending DTMF signals from a telephone. Dual-tone multi-frequency (DTMF) signaling is used for telephone signaling over the line in the voice-frequency band to the call switching center. The version of DTMF used for telephone tone dialing is known by the trademarked term Touch-Tone (canceled March 13, 1984), and is standardized by ITU-T Recomme ndation Q.23.Other multi- frequency systems are used for signaling internal to the telephone network. In a DTMF signalling system, a combination of a high- frequency and a lowfrequency tone represent a specific digit or the characters *, #, A, B, C and D . [1] As a method of in-band signaling, DTMF tones were also used by cable television broadcasters to indicate the start and stop times of local commercial insertion points during station breaks for the benefit of cable companies. Until better out-of-band signaling equipment was developed in the 1990s, fast, unacknowledged, and loud DTMF tone sequences could be heard during the commercial breaks of cable channels in the United States and elsewhere. 1.2. History In the time preceding the development of DTMF, telephone systems employed a system commonly referred to as pulse ( Dial Pulse or DP in the U.S.) or loop disconnect (LD) signaling to dial numbers, which functions by rapidly disconnecting and connecting the calling party's telephone line, similar to flicking a light switch on and off. The repeated connection and disconnection, as the dial spins, sounds like a series of clicks. The exchange equipment counts those clicks or dial pulses to determine the called number. Loop disconnect range was restricted by telegraphic distortion and other technical problems, and placing calls over longer distances required either operator assistance (operators used an earlier kind of multi- frequency dial) or the provision of subscriber trunk dialing equipment. Dual Tone Multi-Frequency, or DTMF, is a method for instructing a telephone switching system of the telephone number to be dialed, or to issue commands to switching systems or related telephony equipment.
Digital Signal Processing Lab Manual Page 126

Department of Electronics and Communication

VCET,Hyderabad.

The DTMF dialing system traces its roots to a technique developed by Bell Labs in the 1950s called MF (Multi-Frequency) which was deployed within the AT&T telephone network to direct calls between switching facilities using in-band signaling. In the early 1960s, a derivative technique was offered by AT&T through its Bell System telephone companies as a "modern" way for network customers to place calls. In AT&Ts Compatibility Bulletin No. 105, AT&T described the product as "a method for pushbutton signaling from customer stations using the voice transmission path." The consumer product was marketed by AT&T under the re gistered trade name Touch-Tone. Other vendors of compatible telephone equipment called this same system "Tone" dialing or "DTMF," or used their own registered trade names such as the "Digitone" of Northern Electric (now known as Nortel Networks).The DTMF system uses eight different frequency signals transmitted in pairs to represent sixteen different numbers, symbols and letters - as detailed below.

1.3. #, *, A, B, C, and D The engineers had envisioned phones being used to access computers, and surveyed a number of companies to see what they would need for this role. This led to the addition of the octothorpe number sign (#) and star (*) keys as well as a group of keys for menu selection: A, B, C and D. In the end, the lettered keys were dropped from most phones, and it was many years before these keys became widely used for vertical service codes such as *67 in the United States and Canada to suppress caller ID. Public payphones that accept credit cards use these additional codes to send the information from the magnetic strip. The U.S. military also used the letters, relabeled, in their now defunct Autovon phone system. Here they were used before dialing the phone in order to give some calls priority, cutting in over existing calls if need be. The idea was to allow important traffic to get through every time. The levels of priority available were Flash Override (A), Flash (B), Immediate (C), and Priority (D), with Flash Override being the highest priority.Pressing one of these keys gave your call priority, overriding other conversations on the network. Pressing C, Immediate, before dialing would make the switch first look for any free lines, and if all lines were in use, it would disconnect any non-priority calls, and then any priority calls. Flash Override will kick every
Digital Signal Processing Lab Manual Page 127

Department of Electronics and Communication

VCET,Hyderabad.

other call off the trunks between the origin and destination. Consequently, it is limited to the White House Communications Agency. Precedence dialing is still done on the military phone networks, but using number combinations (Example: Entering 93 before a number is a priority call) rather than the separate tones and the Government Emergency Telecommunications Service has superseded Autovon for any civilian priority telco access.

Present-day uses of the A, B, C and D keys on telephone networks are few, and exclusive to network control. For example, the A key is used on some networks to cycle through different carriers at will (thereby listening in on calls). Their use is probably prohibited by most carriers. The A, B, C and D tones are used in amateur radio phone patch and repeater operations to allow, among other uses, control of the repeater while connected to an active phone line.DTMF tones are also used by some cable television networks and radio networks to signal the local cable company/network station to insert a local advertisement or station identification. These tones were often heard during a station ID preceding a local ad insert. Previously, terrestrial television stations also used DTMF tones to shut off and turn on remote transmitters. DTMF tones are also sometimes used in caller ID systems to transfer the caller ID information, however in the USA only Bell 202 modulated FSK signaling is used to transfer the data.

1.4. Keypad The DTMF keypad is laid out in a 44 matrix, with each row representing a low frequency, and each column representing a high frequency. Pressing a single key (such as '1' ) will send a sinusoidal tone of the two frequencies (697 and 1209 hertz (Hz)). The original keypads had levers inside, so each button activated two contacts. The multiple tones are the reason for calling the system multi frequency. These tones are then decoded by the switching center to determine which key was pressed.

Digital Signal Processing Lab Manual

Page 128

Department of Electronics and Communication

VCET,Hyderabad.

1.5. DTMF event frequencies

The tone frequencies, as defined by the Precise Tone Plan, are selected such that harmonics and inter modulation products will not cause an unreliable signal. No frequency is a multiple of another, the difference between any two frequencies does not equal any of the
Digital Signal Processing Lab Manual Page 129

Department of Electronics and Communication

VCET,Hyderabad.

frequencies, and the sum of any two frequencies does not equal any of the frequencies. The frequencies were initially designed with a ratio of 21/19, which is slightly less than a whole tone. The frequencies may not vary more than 1.8% from their nominal frequency, or the switching center will ignore the signal. The high frequencies may be the same volume or louder as the low frequencies when sent across the line. The loudness difference between the high and low requencies can be as large as 3 decibels (dB) and is referred to as "twist." The minimum duration of the tone should be at least 70 msec, although in some countries and applications DTMF receivers must be able to reliably detect DTMF tones as short as 45ms.

1.6. Sample MATLAB code for DTMF Tone Generator


A=10; f0=567; fs=8000; n=62; temp = zeros(1,n+2); bb = zeros(1,n); temp(1) = -A*sin(2*pi*f0/fs); temp(2) = 0; a = 2*cos(2*pi*f0/fs); for k=3:n+2 temp(k) = a*temp(k-1) - temp(k-2); end bb = temp(3:n+2); Generated tone:

Figure 1.4. DTMF generated tone


Digital Signal Processing Lab Manual Page 130

Department of Electronics and Communication

VCET,Hyderabad.

Chapter 2 Goertzel algorithm 2.1. Introduction


The Goe rtzel algorithm is a digital signal processing (DSP) technique for identifying frequency components of a signal, published by Dr. Gerald Goertzel in 1958.While the general Fast Fourier transform (FFT) algorithm computes evenly across the bandwidth of the incoming signal, the Goertzel algorithm looks at specific, predetermined frequency. The basic Goertzel gives you real and imaginary frequency components as a regular Discrete Fourier Transform (DFT) or FFT would. If you need them, magnitude and phase can then be computed from the real/imaginary pair. The optimized Goertzel is even faster (and simpler) than the basic Goertzel, but doesn't give you the real and imaginary frequency components. Instead, it gives you the relative magnitude squared. You can take the square root of this result to get the relative magnitude (if needed), but there's no way to obtain the phase.

Before you can do the actual Goertzel, you must do some preliminary calculations: 1. Decide on the sampling rate. 2. Choose the block size, N. 3. Precompute one cosine and one sine term. 4. Precompute one coefficient. These can all be precomputed once and then hardcoded in your program, saving RAM and ROM space; or you can compute them on-the-fly. (i) Sampling rate Your sampling rate may already be determined by the application. For example, in telecom applications, it's common to use a sampling rate of 8kHz (8,000 samples per second). Alternatively, your analog-to-digital converter (or CODEC) may be running from an external clock or crystal over which you have no control. If you can choose the sampling rate, the usual Nyquist rules apply: the sampling rate will have to be at least twice your highest frequency of interest. I say "at least" because if you are
Digital Signal Processing Lab Manual Page 131

Department of Electronics and Communication

VCET,Hyderabad.

detecting multiple frequencies, it's possible that an even higher sampling frequency will give better results. What you really want is for every frequency of interest to be an integer factor of the sampling rate. (ii) Block size Goertzel block size N is like the number of points in an equivalent FFT. It controls the frequency resolution (also called bin width). For example, if your sampling rate is 8kHz and N is 100 samples, then your bin width is 80Hz. This would steer you towards making N as high as possible, to get the highest frequency resolution. The catch is that the higher N gets, the longer it takes to detect each tone, simply because you have to wait longer for all the samples to come in. For example, at 8kHz sampling, it will take 100ms for 800 samples to be accumulated. If you're trying to detect tones of short duration, you will have to use compatible values of N. The third factor influencing your choice of N is the relationship between the sampling rate and the target frequencies. Ideally you want the frequencies to be centered in their respective bins. In other words, you want the target frequencies to be integer multiples of sample rate/N . The good news is that, unlike the FFT, N doesn't have to be a power of two. (iii) Pre computed constants Once you've selected your sampling rate and block size, it's a simple five-step process to compute the constants you'll need during processing: w = (2*/N)*k cosine = cos w sine = sin w coeff = 2 * cosine For the per-sample processing you're going to need three variables. Let's call them Q0,Q1, and Q2. Q1 is just the value of Q0 last time. Q2 is just the value of Q0 two times ago (or Q1 last time).

Q1 and Q2 must be initialized to zero at the beginning of each block of samples. For every sample, you need to run the following three equations: Q0 = coeff * Q1 - Q2 + sample Q2 = Q1
Digital Signal Processing Lab Manual Page 132

Department of Electronics and Communication

VCET,Hyderabad.

Q1 = Q0

After running the per-sample equations N times, it's time to see if the tone is present or not. real = (Q1 - Q2 * cosine) imag = (Q2 * sine) magnitude2 = real2 + imag2

A simple threshold test of the magnitude will tell you if the tone was present or not. Reset Q2 and Q1 to zero and start the next block.

2.2. Explanation of algorithm


The Goertzel algorithm computes a sequence, s(n), given an input sequence, x (n): s(n) = x (n) + 2cos(2)s(n 1) s(n 2) where s( 2) = s( 1) = 0 and is some frequency of interest, in cycles per sample,which should be less than 1/2. This effectively implements a second-order IIR filter with poles at e and e
2 i , + 2i

and requires only one multiplication (assuming 2 cos (2) is pre-computed), one

addition and one subtraction per input sample. For real inputs, these operations are real.

Digital Signal Processing Lab Manual

Page 133

Department of Electronics and Communication

VCET,Hyderabad.

Note that applying the additional transform Y(z)/S(z) only requires the last two samples of the s sequence. Consequently, upon processing N samples x (0)...x (N 1), the last two samples from the s sequence can be used to compute the value of a DFT bin which corresponds to the chosen frequency as X() = y(N 1)e 2i(N 1) = ( s(N 1) e 2 is(N 2))e 2 i(N 1) For the special case often found when computing DFT bins, where N = k for some integer, k , this simplifies to X() = (s(N 1) e 2 i s(N 2))e + 2 i = e + 2i s(N 1) s (N 2)
Digital Signal Processing Lab Manual Page 134

Department of Electronics and Communication

VCET,Hyderabad.

In either case, the corresponding power can be computed using the same cosine term required to compute s as X()X'() = s(N 2)2 + s(N 1)2 2cos(2)s(N 2) s(N 1) When implemented in a general-purpose processor, values for s(n 1) and s(n 2) can be retained in variables and new values of s can be shifted through as they are computed, assuming that only the final two values of the s sequence are required. The code may then be as follows:

Sample C code for GEORTZEL Algorithm : s_prev = 0 s_prev2 = 0 coeff = 2*cos(2*PI*normalized_frequency); for each sample, x[n], s = x[n] + coeff*s_prev - s_prev2; s_prev2 = s_prev; s_prev = s; end power = s_prev2*s_prev2 + s_prev*s_prev - coeff*s_prev2*s_prev;

2.3. Computational complexity


In order to compute a single DFT bin for a complex sequence of length N, this algorithm requires 2N multiplies and 4N add/subtract operations within the loop, as well as 4 multiplies and 4 add/subtract operations to compute X(), for a total of 2N+4 multiplies and 4N+4 add/subtract operations (for real sequences, the required operations are half that amount). In contrast, the Fast Fourier transform (FFT) requires 2log2 N multiplies and 3log2 N add/subtract operations per DFT bin, but must compute all N bins simultaneously (similar optimizations are available to halve the number of operations in an FFT when the input sequence is real). When the number of desired DFT bins, M, is small (e.g., when detecting DTMF tones), it is computationally advantageous to implement the Goertzel algorithm, rather than the FFT. Approximately, this occurs when
Digital Signal Processing Lab Manual Page 135

Department of Electronics and Communication

VCET,Hyderabad.

or if, for some reason, N is not an integral power of 2 while you stick to a simple FFT algorithm like the 2-radix Cooley-Tukey FFT algorithm, and zero-padding the samples out to an integral power of 2 would violate

Moreover, the Goertzel algorithm can be computed as samples come in, and the FFTalgorithm may require a large table of N pre-computed sines and cosines in order to be efficient. If multiplications are not considered as difficult as additions, or vice versa, the 5/6 ratio can shift between anything from 3/4 (additions dominate) to 1/1 (multiplications dominate).

2.4. Practical considerations


The term DTMF or Dual-Tone Multi Frequency is the official name of the tones generated from a telephone keypad. (AT&T used the trademark "Touch-Tone" for its DTMF dialing service The original keypads were mechanical switches triggering RC controlled oscillators. The digit detectors were also tuned circuits. The interest in decoding DTMF is high because of the large numbers of phones generating these types of tones. At present, DTMF detectors are most often implemented as numerical algorithms on either general purpose computers or on fast digital signal processors. The algorithm shown below is an example of such a detector. However, this algorithm needs an additional post-processing step to completely implement a functional DTMF tone detector. DTMF tone bursts can be as short as 50 milliseconds or as long as several seconds. The tone burst can have noise or dropouts within it which must be ignored. The Goertzel algorithm produces multiple outputs; a post-processing step needs to smooth these outputs into one output per tone burst.

Digital Signal Processing Lab Manual

Page 136

Department of Electronics and Communication

VCET,Hyderabad.

One additional problem is that the algorithm will sometimes produce spurious outputs because of a window period that is not completely filled with samples. Imagine a DTMF tone burst and then imagine the window superimposed over this tone burst.Obviously, the detector is running at a fixed rate and the tone burst is not guaranteed to arrive aligned with the timing of the detector. So some window intervals on the leading and trailing edges of the tone burst will not be entirely filled with valid tone samples.Worse, RC-based tone generators will often have voltage sag/surge related anomalies at the leading and trailing edges of the tone burst. These also can contribute to spurious outputs.

It is highly likely that this detector will report false or incorrect results at the leading and trailing edges of the tone burst due to a lack of sufficient valid samples within the window. In addition, the tone detector must be able to tolerate tone dropouts within the tone burst and these can produce additional false reports due to the same windowing effects. The post-processing system can be implemented as a statistical aggregator which will examine a series of outputs of the algorithm below. There should be a counter for each possible output. These all start out at zero. The detector starts producing outputs and depending on the output, the appropriate counter is incremented. Finally, the detector stops generating outputs for long enough that the tone burst can be considered to be over. The counter with the highest value wins and should be considered to be the DTMF digit signaled by the tone burst.While it is true that there are eight possible frequencies in a DTMF tone, the algorithm as originally entered on this page was computing a few more frequencies so as to help reject false tones (talk off). Notice the peak tone counter loop. This checks to see that only two tones are active. If more than this are found then the tone is rejected.

Digital Signal Processing Lab Manual

Page 137

Department of Electronics and Communication

VCET,Hyderabad.

Chapter 3 MATLAB Simulation Codes 3.1. Matlab Code for DTMF Tone Generator :
close all; clear all figure(1) % DTMF tone generator fs=8000; t=[0:1:204]/fs; x=zeros(1,length(t)); x(1)=1; y852=filter([0 sin(2*pi*852/fs) ],[1 -2*cos(2*pi*852/fs) 1],x); y1209=filter([0 sin(2*pi*1209/fs) ],[1 -2*cos(2*pi*1209/fs) 1],x); y7=y852+y1209; subplot(2,1,1);plot(t,y7);grid ylabel('y(n) DTMF: number 7'); xlabel('time (second)') Ak=2*abs(fft(y7))/length(y7);Ak(1)=Ak(1)/2; f=[0:1:(length(y7)-1)/2]*fs/length(y7); subplot(2,1,2); plot(f,Ak(1:(length(y7)+1)/2));grid ylabel('Spectrum for y7(n)'); xlabel('frequency (Hz)');

Digital Signal Processing Lab Manual

Page 138

Department of Electronics and Communication

VCET,Hyderabad.

Figure 3.1. DTMF signal of digit 7 and its frequency spectrum

3.2. Matlab code for DTMF decoder :


% DTMF detector (use Goertzel algorithm) b697=[1]; a697=[1 -2*cos(2*pi*18/205) 1]; b770=[1]; a770=[1 -2*cos(2*pi*20/205) 1]; b852=[1]; a852=[1 -2*cos(2*pi*22/205) 1]; b941=[1]; a941=[1 -2*cos(2*pi*24/205) 1]; b1209=[1]; a1209=[1 -2*cos(2*pi*31/205) 1]; b1336=[1]; a1336=[1 -2*cos(2*pi*34/205) 1]; b1477=[1]; a1477=[1 -2*cos(2*pi*38/205) 1]; [w1, f]=freqz([1 exp(-2*pi*18/205)],a697,512,8000); [w2, f]=freqz([1 exp(-2*pi*20/205)],a770,512,8000);
Digital Signal Processing Lab Manual Page 139

Department of Electronics and Communication

VCET,Hyderabad.

[w3, f]=freqz([1 exp(-2*pi*22/205)],a852,512,8000); [w4, f]=freqz([1 exp(-2*pi*24/205)],a941,512,8000); [w5, f]=freqz([1 exp(-2*pi*31/205)],a1209,512,8000); [w6, f]=freqz([1 exp(-2*pi*34/205)],a1336,512,8000); [w7, f]=freqz([1 exp(-2*pi*38/205)],a1477,512,8000); subplot(2,1,1); plot(f,abs(w1),f,abs(w2),f,abs(w3),f,abs(w4),f,abs(w5),f,abs(w6),f,abs(w7));grid xlabel( Frequency (Hz)); ylabel( BPF frequency responses); 24 yDTMF=[y7 0]; y697=filter(1,a697,yDTMF); y770=filter(1,a770,yDTMF); y852=filter(1,a852,yDTMF); y941=filter(1,a941,yDTMF); y1209=filter(1,a1209,yDTMF); y1336=filter(1,a1336,yDTMF); y1477=filter(1,a1477,yDTMF); m(1)=sqrt(y697(206)^2+y697(205)^2- 2*cos(2*pi*18/205)*y697(206)*y697(205)); m(2)=sqrt(y770(206)^2+y770(205)^2- 2*cos(2*pi*20/205)*y770(206)*y770(205)); m(3)=sqrt(y852(206)^2+y852(205)^2- 2*cos(2*pi*22/205)*y852(206)*y852(205)); m(4)=sqrt(y941(206)^2+y941(205)^2- 2*cos(2*pi*24/205)*y941(206)*y941(205)); m(5)=sqrt(y1209(206)^2+y1209(205)^22*cos(2*pi*31/205)*y1209(206)*y1209(205)); m(6)=sqrt(y1336(206)^2+y1336(205)^22*cos(2*pi*34/205)*y1336(206)*y1336(205)); m(7)=sqrt(y1477(206)^2+y1477(205)^22*cos(2*pi*38/205)*y1477(206)*y1477(205)); m=2*m/205; th=sum(m)/4; %based on empirical measurement f=[ 697 770 852 941 1209 1336 1477]; f1=[0 4000]; th=[ th th]; x subplot(2,1,2);stem(f,m);grid hold; plot(f1,th); xlabel( Frequency (Hz)); ylabel( Absolute output values);

Digital Signal Processing Lab Manual

Page 140

Department of Electronics and Communication

VCET,Hyderabad.

Digital Signal Processing Lab Manual

Page 141

Department of Electronics and Communication

VCET,Hyderabad.

Chapter 4 Comparison of Goertzel Algorithm and FFT


While the general Fast Fourier transform (FFT) algorithm computes evenly across the bandwidth of the incoming signal, the Goertzel algorithm looks at specific,predetermined frequency 4.1. Matlab Code: %++++++++++++++++++++++++++++++++++++++++++++++++++++++ % Filename: Goertz.m % % Compares the Goertzel algorithm with % a standard FFT. (That is, the final output of % the Goertzel filter should be equal to a % single FFT-bin result.) % % NSSV Prasad - May, 2008 %++++++++++++++++++++++++++++++++++++++++++++++++++++++ Fsub_i = 30; % Tone freq to be detected, in Hz. Fsub_s = 128; % Sample rate in samples/second. N =64; % Define the Goertzel filter coefficients B = [1,-exp(-j*2*pi*Fsub_i/Fsub_s)]; % Feed forward A = [1,-2*cos(2*pi*Fsub_i/Fsub_s),1]; % Feedback [H,W] = freqz(B,A,N,Fsub_s); % Freq resp. vs omega MAG = abs(H); PHASE = angle(H).*(180/pi); % Phase in degrees % Plot the Goertzel filters freq response figure(1) subplot(2,1,1), plot(W,MAG,W,MAG,o,markersize,4), grid title( Filter Magnitude Resp.) xlabel( Hz) subplot(2,1,2), plot(W,PHASE,W,PHASE,o, markersize,4), grid title( Filter Phase Resp. in Deg.) xlabel( Hz)
Digital Signal Processing Lab Manual Page 142

Department of Electronics and Communication

VCET,Hyderabad.

% Generate & filter some time-domain data TIME = 0:1/Fsub_s N-1)/Fsub_s; X = cos(2*pi*Fsub_i*TIME+pi/4); % Sinewave were trying to detect X(65) = 0; % Add an extra zero so that your % Goertzel cycles through one extra % sample. This makes the final phase % results correct !!!! Y = filter(B,A,X); % Filter output sequence (complex) MAG = abs(Y); % Magnitude of filter output % Plot filters input & output (magnitude) figure(2) subplot(2,1,1), plot(TIME,X(1:64),TIME,X(1:64), o, markersize,4), grid title( Original Time Signal) xlabel( Seconds ) subplot(2,1,2), plot(TIME,MAG(1:64),TIME,MAG(1:64), o,markersize,4), grid title( Filter Output Magnitude ) xlabel( Seconds ) % Plot filters real & imaginary parts figure(3) subplot(2,1,1), plot(TIME, real(Y(1:64)),TIME, real(Y(1:64)), o,markersize,4), grid title( Real Part of Filter Output ) xlabel( Seconds ) subplot(2,1,2), plot(TIME,imag(Y(1:64)),TIME,imag(Y(1:64)), o,markersize,4), grid title( Imag Part of Filter Output) xlabel( Seconds ) % Calc the max FFT Coefficient for % comparison to Goertzel result. X = X(1:N); % Return X to correct length (a power of 2) SPEC = fft(X); disp( ), disp( )
Digital Signal Processing Lab Manual Page 143

Department of Electronics and Communication

VCET,Hyderabad.

disp([ Last filt output = num2str(Y(N+1)) (Final Goertzel filter output.)]) disp([ FFT- bin result = num2str(max(SPEC)) (FFT output for test tone.)]) disp([ k = num2str(N*Fsub_i/Fsub_s,Y(N+1)) (Indicates frequency of input tone.) ]) disp( ) 4.2. Result : Last filt output = 22.6274+22.6274i (Final Goertzel filter output.) FFT-bin result = 22.6274+22.6274i (FFT output for test tone.) k = 15(Indicates frequency of input tone.)

FFT computes all DFT values at all indices, while GOERTZEL computes DFT values at a specified subset of indices (i.e., a portion of the signals frequency range). If less than log2 (N) points are required, GOERTZEL is more efficient than the Fast
Digital Signal Processing Lab Manual Page 144

Department of Electronics and Communication

VCET,Hyderabad.

Fourier Transform (fft).

Digital Signal Processing Lab Manual

Page 145

Department of Electronics and Communication

VCET,Hyderabad.

Chapter 5

Conclusion
This project gives an understanding of the DTMF tone generation and the DTMF decoding algorithm (The GOERTZEL algorithm) using MATLAB.

The modules designed are 1. A tone generation function that produces a signal containg appropriate tones of a given digit. 2. A decoding function to implement the Geortzel Equation, that accepts a DTMF signal and produces an array of tones that corresponds to a digit.

A tone of the digit 7 was generated and detected using Goertzel algorithm. And the Goertzel algorithm was compared with the single FFT. the Goertzel algorithm looks at specific, predetermined frequency, while the general Fast Fourier transform (FFT) algorithm computes evenly across the bandwidth of the incoming signal. The Goertzel algorithm can perform tone detection using much less CPU horsepower than the Fast Fourier Transform.

This project can be extended for the generation of tones of a series of digits using the code proposed in this report, as a MATLAB function.

Digital Signal Processing Lab Manual

Page 146

Department of Electronics and Communication

VCET,Hyderabad.

Chapter 6

References
1. Digital Signal Processing Using MATLAB, (Bookware Companion Series): Vinay K. Ingle, John G. Proakis, PWS Publishing Company. Pp. 405-409. 2. Understanding Telephone Electronics, 4th edition, By Stephen J. Bigelow, Joseph J. Carr, Steve Winder,Published by Newnes, 2001, 3. Digital Signal Processing and Applications with the C6713 and C6416 DSK , By Rulph Chassaing, A John Wiley & Sons Inc., Publication, 2005, pp 347-348. 4. Mitra, Sanjit K. Digital Signal Processing: A Computer-Based Approach. New York, NY: McGraw-Hill, 1998, pp. 520-523. 5. www.crazyengineers.com/forum/electrical/dtmf_geort.html 6. www.en.wikipedia.org/dtmf.html 7. www.dsprelated.com/dtmf.html

Digital Signal Processing Lab Manual

Page 147

Você também pode gostar