77974588-DSP-Lab-Manual-for-ECE-3-2-R09

Share Embed Donate


Short Description

Download 77974588-DSP-Lab-Manual-for-ECE-3-2-R09...

Description

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

Page No. 4

1) Generation of Basic Signals

10

2) Sum of sinusoidal signals

18

3) Impulse response of the difference equation

20

4) Frequency response of a system given in Difference equation form

22

5) Determination of Power Spectrum

24

6) FIR Low pass Filter design

26

7) FIR High pass Filter design

30

8) IIR Low pass Filter design

34

9) IIR High pass Filter design

37

10) Fast Fourier Transform

40

11) DFT / IDFT of given DT signal

43

12) Implementation of Decimation Process

46

13) Implementation of Interpolation Process

49

14) Implementation of I/D sampling rate converters

52

List of experiments using CC Studio Introduction to DSP processors, TMS 320C6713 DSK

55

Introduction to CC STUDIO

63

1) Generation of Sine wave and Square wave

68

2) Linear Convolution

72

3) Impulse response of first order and second order systems

75

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

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]

b = [4 5 6]

a.*b = [4 10 18] 8

if C= [2 2 2] b.*C results in [8 10 12]

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

4.

VCET,Hyderabad.

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(n–1) = x(n) + 4 x(n–1) 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');

% Find the order n and cutt off frequency

disp('Frequency response of IIR HPF is:'); [b,a]=butter(n,wn,'low','s');

% Find the filter co-efficients of LPF

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 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');

% Find the order n and cutt off frequency

disp('Frequency response of IIR HPF is:'); [b,a]=butter(n,wn,'high','s');

% 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 (L, the resulting operation is a decimation process by a non- integer, and when M= 0; i--)

//desired+noise

//output of adaptive filter //"error" signal=(d+n)- yn

//to update weights and delays

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

//update delay samples

}

//output=((short)E);

//error signal as overall output

output=((short)dplusn);

//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 4×4 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ω ,

+ 2πiω

and requires only one multiplication (assuming 2cos(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 − 2πiω(N − 1) = (s(N − 1) − e − 2πiωs(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 + 2πiω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

Digital Signal Processing Lab Manual

VCET,Hyderabad.

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 filter‟s 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 we‟re 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 filter‟s 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 filter‟s 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 signal‟s 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

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF