% Design LP, BP, and HP filters  for audio speaker crossover network.
% R. Kozick, ELEC 226

w0 = 1000;      % Frequency where BP filter has gain = 1 (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)

wv = logspace(1, 5, 500);   % Vector of freqs. for Bode plot (rad/sec)

% Complex frequency response of LP, HP, and BP filters
HL = 1 ./ ( (1 - (wv/wcL).^2) + j*(wv/wcL*sqrt(2)) );       % LP
HH = 1 ./ ( (1 - (wcH./wv).^2) - j*(wcH./wv*sqrt(2)));    % HP
HB = 1 ./ ( 1 + j*(wv/B) .* (1 - (w0./wv).^2) );            % BP

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 -90 90]);
grid
