You are on page 1of 37

DTMF (Touch Tone) SIGNALING

Tone Generation and Detection Using MATLAB

A MINI PROJECT REPORT

Submitted in partial fulfillment of the requirements


for award of the degree of
Bachelor of Technology
In
Electronics and Communication Engineering
by

NSSV PRASAD
05001A0436

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


Jawaharlal Nehru Technological University
College of Engineering (AUTONOMOUS)
ANANTAPUR-515 002
ANDHRA PRADESH
2008

1
ACKNOWLEDGEMENT

This is acknowledgement of the intensive drive and technical competence of


many individuals who have contributed to the success of this project.

I convey my sincere thanks to Sri. K. RAMANAIDU, Associate professor and


Head of the Department for Electronics and Communications Engineering, JNTU
College of Engineering, Anantapur for the encouragement and guidance provided during
the course of my project work.

My sincere thanks to sir SRI E.VENKATANARAYANA whose constant


monitoring and valuable advice ensured the completion of this project.

My sincere thanks to Dr. K.SOUNDARARAJAN, Principal, JNTU College of


Engineering, Anantapur for providing this opportunity and encouragement to carry out
the present thesis work.

2
DECLARATION

The project entitled “ DTMF (TouchTone) signaling – Tone Generation


and Detection using MATLAB ” is a record of the bona fide work undertaken by me
towards partial fulfillment of the requirements for the award of Degree Bachelor of
Technology. The results in this project work have not been submitted to any university or
Institute for the award of any Degree or Diploma.

3
DTMF (Touch Tone) SIGNALLING
Tone Generation and Detection Using MATLAB

4
CONTENTS

Abstract

Chapter 1: Dual Tone Multi Frequency (DTMF) 7

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 13

2.1. Introduction
2.2. Explanation of algorithm
2.3. Computational complexity
2.4. Practical considerations

Chapter 3: MATLAB Simulation Codes 21

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 26

Chapter 5: Conclusion 31

Chapter 6: References 32

Chapter 7: Appendix 33

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

6
Chapter 1

Dual Tone Multi-Frequency (DTMF)

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 Recommendation 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 low-


frequency 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

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

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

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

9
DTMF keypad frequencies (with sound clips)

1209 Hz 1336 Hz 1477 Hz 1633 Hz

697 Hz 1 2 3 A

770 Hz 4 5 6 B

852 Hz 7 8 9 C

941 Hz * 0 # D

Figure 1.1. DTMF keypad frequencies

Figure 1.2. TouchTone Keypad

10
1.5. DTMF event frequencies

Event Low frequency High frequency

Busy signal 480 Hz 620 Hz

Dial tone 350 Hz 440 Hz

Ringback tone (US) 440 Hz 480 Hz

Figure 1.3. 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 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 frequencies 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.

11
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

12
Chapter 2

Goertzel algorithm

2.1. Introduction
The Goertzel 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"

13
because if you are 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).

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

Figure 2.1. Realization of two pole resonator for computing the DFT

15
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 + 2πiω and e − 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.

The Z transform of this process is

Applying an additional, FIR, transform of the form

will give an overall transform of

The time-domain equivalent of this overall transform is

which becomes, assuming x(k) = 0 for all k < 0

or, the equation for the (n + 1)-sample DFT of x, evaluated for ω and multiplied by the
scale factor e + 2πiωn.

16
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)

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;

17
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 2log2N
multiplies and 3log2N 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

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
FFT algorithm 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).

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

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.

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

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

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

22
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);
[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’);

23
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)^2-
2*cos(2*pi*31/205)*y1209(206)*y1209(205));

m(6)=sqrt(y1336(206)^2+y1336(205)^2-
2*cos(2*pi*34/205)*y1336(206)*y1336(205));

m(7)=sqrt(y1477(206)^2+y1477(205)^2-
2*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’);

24
Figure 3.2. BPF frequency response of DTMF frequencies and the detected tones

25
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)

26
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’)

% 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

27
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(‘ ‘)
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.)

28
Figure 4.1. Frequency response of the given signal

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
Fourier Transform (fft).

29
Figure 4.2. Filter output magnitude

Figure 4.3. Real and Imaginary parts of the filtered output

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

31
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

32
Chapter 7

Appendix

C-code for Goertzel Algorithm (from wikipedia)

#define SAMPLING_RATE 8000


#define MAX_BINS 8
#define GOERTZEL_N 92

int sample_count;
double q1[ MAX_BINS ];
double q2[ MAX_BINS ];
double r[ MAX_BINS ];

/*
* coef = 2.0 * cos( (2.0 * PI * k) / (float)GOERTZEL_N)) ;
* Where k = (int) (0.5 + ((float)GOERTZEL_N * target_freq) / SAMPLING_RATE));
*
* More simply: coef = 2.0 * cos( (2.0 * PI * target_freq) / SAMPLING_RATE );
*/
double freqs[ MAX_BINS] =
{
697,
770,
852,
941,
1209,
1336,
1477,
1633
};

double coefs[ MAX_BINS ] ;

/*----------------------------------------------------------------------------
* calc_coeffs
*----------------------------------------------------------------------------
* This is where we calculate the correct co-efficients.
*/
void calc_coeffs()
{
int n;

33
for(n = 0; n < MAX_BINS; n++)
{
coefs[n] = 2.0 * cos(2.0 * 3.141592654 * freqs[n] / SAMPLING_RATE);
}
}

/*----------------------------------------------------------------------------
* post_testing
*----------------------------------------------------------------------------
* This is where we look at the bins and decide if we have a valid signal.
*/
void post_testing()
{
int row, col, see_digit;
int peak_count, max_index;
double maxval, t;
int i;
char * row_col_ascii_codes[4][4] = {
{"1", "2", "3", "A"},
{"4", "5", "6", "B"},
{"7", "8", "9", "C"},
{"*", "0", "#", "D"}};

/* Find the largest in the row group. */


row = 0;
maxval = 0.0;
for ( i=0; i<4; i++ )
{
if ( r[i] > maxval )
{
maxval = r[i];
row = i;
}
}

/* Find the largest in the column group. */


col = 4;
maxval = 0.0;
for ( i=4; i<8; i++ )
{
if ( r[i] > maxval )
{
maxval = r[i];
col = i;

34
}
}

/* Check for minimum energy */

if ( r[row] < 4.0e5 ) /* 2.0e5 ... 1.0e8 no change */


{
/* energy not high enough */
}
else if ( r[col] < 4.0e5 )
{
/* energy not high enough */
}
else
{
see_digit = TRUE;

/* Twist check
* CEPT => twist < 6dB
* AT&T => forward twist < 4dB and reverse twist < 8dB
* -ndB < 10 log10( v1 / v2 ), where v1 < v2
* -4dB < 10 log10( v1 / v2 )
* -0.4 < log10( v1 / v2 )
* 0.398 < v1 / v2
* 0.398 * v2 < v1
*/
if ( r[col] > r[row] )
{
/* Normal twist */
max_index = col;
if ( r[row] < (r[col] * 0.398) ) /* twist > 4dB, error */
see_digit = FALSE;
}
else /* if ( r[row] > r[col] ) */
{
/* Reverse twist */
max_index = row;
if ( r[col] < (r[row] * 0.158) ) /* twist > 8db, error */
see_digit = FALSE;
}

/* Signal to noise test


* AT&T states that the noise must be 16dB down from the signal.
* Here we count the number of signals above the threshold and
* there ought to be only two.

35
*/
if ( r[max_index] > 1.0e9 )
t = r[max_index] * 0.158;
else
t = r[max_index] * 0.010;

peak_count = 0;
for ( i=0; i<8; i++ )
{
if ( r[i] > t )
peak_count++;
}
if ( peak_count > 2 )
see_digit = FALSE;

if ( see_digit )
{
printf( "%s", row_col_ascii_codes[row][col-4] );
fflush(stdout);
}
}
}

/*----------------------------------------------------------------------------
* goertzel
*----------------------------------------------------------------------------
*/
void goertzel( int sample )
{
double q0;
ui32 i;

sample_count++;
/*q1[0] = q2[0] = 0;*/
for ( i=0; i<MAX_BINS; i++ )
{
q0 = coefs[i] * q1[i] - q2[i] + sample;
q2[i] = q1[i];
q1[i] = q0;
}

if (sample_count == GOERTZEL_N)
{
for ( i=0; i<MAX_BINS; i++ )
{

36
r[i] = (q1[i] * q1[i]) + (q2[i] * q2[i]) - (coefs[i] * q1[i] * q2[i]);
q1[i] = 0.0;
q2[i] = 0.0;
}
post_testing();
sample_count = 0;
}
}

37

You might also like