# DTMF Decoding

## Simple Bandpass Filter Design

function hh = dtmfdesign(fb, L, fs)
%DTMFDESIGN
%   hh = dtmfdesign(fb, L, fs)
%       returns a matrix (L by length(fb)) where each column contains
%       the impulse response of a BPF, one for each frequency in fb
%   fb = vector of center frequencies
%   L  = length of FIR bandpass filters
%   fs = sampling freq
%
%   Each BPF must be scaled so that its frequency response has a
%   maximum magnitude equal to one.
hh = zeros(L, length(fb)); % Create a matrix of length L times length(fb)
BB = zeros(1, length(fb)); % Create a vector that'll be used for scaling
ww = 0:pi/10000:pi;

% This loop will calculate the normalized freq response for all fb
for ii = 1:length(fb)
bb = cos(2 * pi * fb(ii) * (0:L-1) / fs); % Coefficients
HH = freqz(bb, 1, ww); % Calculate the impulse response
max_value = max(abs(HH)); % Get the max value of response
BB(ii) = 1 / max_value; % Insert into BB for scaling

HH2 = bb * BB(ii); % Scale the impulse response to one
hh(:, ii) = HH2; % Store normalized impulse response into hh matrix
end
ww_d = 0:pi/10000:pi;
L_min = 0; % Default

% This loop determines the smallest L that can be used
for L = 40:100
hh = dtmfdesign([697], L, 8000); % Returns a single vector (impulse response)
HH = freqz(hh, 1, ww_d); % Generates the frequency response
stopband = find(abs(HH) >= 0.25); % Determines the indexes in the stopband
stopband_right = ww_d(stopband(length(stopband))); % Determines the right index

if (2 * pi * 770 / 8000 >= stopband_right) % Checks if 770 Hz is in the stopband
L_min = L; % Successfully determined L_min -> Leave loop
break
end
end
all_frequencies = [697 770 852 941 1209 1336 1477 1633];
ww = 0:pi/10000:pi;
fs = 8000; % Sampling rate is still set at 8000
L = 40; % Should result in a passing bandwidth that is too wide
A = dtmfdesign(all_frequencies, L, fs); % Generate a matrix of impulse responses
HH = zeros(length(ww), 8); % Instantiating a matrix of frequency responses

for ii = 1:8
HH(:, ii) = freqz(A(:, ii), 1, ww); % Store frequency responses into HH
end

% Plot
figure(1);
title('Eight Bandpass Filters at Different Frequencies with L=40');
ylabel('Amplitude');
xlabel('Normalized Frequency');

plot(ww, abs(HH));