% Create Bode plots of LP, HP, and BP filters with R, L, C values
% R. Kozick, ELEC 226

R = 10;     % Resistance of speaker, fixed for all filters

w0 = 1000;  % Center of BP filter (rad/sec)
B = 100;    % Bandwidth of BP filter (rad/sec)

% Set LP and HP cutoff freqs. equal to the BP cutoff freqs.
wcL = sqrt((B/2)^2 + w0^2) - B/2;   % Cutoff freq. of LP (rad/sec)
wcH = sqrt((B/2)^2 + w0^2) + B/2;   % Cutoff freq. of HP (rad/sec)

% NOTE: The default values given below for L and C are not a good design!!
% Put in your chosen values for L and C for each filter, and check the
% individual and total response Bode plots. If you choose the L's and C's
% properly, the Bode plots will be identical to filter_design_LHB.m

% BP filter L and C values
L_BP = 10e-3; % henry
C_BP = 100e-6; % farad

% LP filter L and C values
L_LP = 5e-3;   % henry
C_LP = 400e-6;  % farad

% HP filter L and C values
L_HP = 4e-3;   % henry
C_HP = 100e-6;  % farad

% Print the values of L and C for each filter
fprintf('\nBP: L=%f mH, C=%f uF\nLP: L=%f mH, C=%f uF\nHP: L=%f mH, C=%f uF\n', ...
    L_BP*1e3, C_BP*1e6, L_LP*1e3, C_LP*1e6, L_HP*1e3, C_HP*1e6);

% Evaluate frequency responses with R, L, C component values

wv = logspace(1, 5, 500);   % Vector of freqs. for Bode plot (rad/sec)
HB = 1 ./ (1 + j*(wv/(R/L_BP).*(1 - (1/(L_BP*C_BP))./(wv.^2))));
HL = 1 ./ (1 + j*wv*(L_LP/R).*(1 + j*wv*R*C_LP));
HH = 1 ./ (1 + 1./(j*wv*R*C_HP).*(1 + 1./(j*wv*L_HP/R)) );

MLdB = 20*log10(abs(HL));   % Magnitude in dB
MHdB = 20*log10(abs(HH));
MBdB = 20*log10(abs(HB));

pL = angle(HL)/pi*180;      % Phase in degrees
pH = angle(HH)/pi*180;
pB = angle(HB)/pi*180;

figure(1)   % Magnitude response of individual filters
semilogx(wv, MLdB, 'b-', wv, MBdB, 'k-', wv, MHdB, 'r-');
legend('LP', 'BP', 'HP');
xlabel('Frequency (rad/sec)')
ylabel('dB')
title('Magnitude Responses')
axis([1e1 1e5 -80 10]);
grid

figure(2)   % Phase response of individual filters
semilogx(wv, pL, 'b-', wv, pB, 'k-', wv, pH, 'r-');
legend('LP', 'BP', 'HP');
xlabel('Frequency (rad/sec)')
ylabel('Degrees')
title('Phase Responses')
axis([1e1 1e5 -180 180]);
grid

% Total frequency response of system is sum of LP, HP, and BP filters
% (the summation occurs by the sound waves in space)
HT = HL + HB + HH;          % Total complex freq. response
MTdB = 20*log10(abs(HT));   % Magnitude in dB
pT = angle(HT)/pi*180;      % Phase in degrees

figure(3)   % Bode plots of total response
subplot(211)
semilogx(wv, MTdB, 'b-');
xlabel('Frequency (rad/sec)')
ylabel('dB')
title('Total Magnitude Response')
axis([1e1 1e5 (min(MTdB)-3) 10]);
grid
subplot(212)
semilogx(wv, pT, 'b-');
xlabel('Frequency (rad/sec)')
ylabel('Degrees')
title('Total Phase Response')
axis([1e1 1e5 (min(pT)-5) (max(pT)+5)]);
grid
