% DEMO          BEATING BETWEEN TONES DEMO
%
% Program:      beating_tones.m
% Written by:   
% For:          EE 311
%               Demo For Computer Lab 2
% Date:         6-7-2001
% Purpose:      To plot beating between two tones according
%               to the formula      x(t)=x1(t)+x2(t),
%               where               x1(t)=A1*cos(w1*t+phi1)
%               and                 x2(t)=A2*cos(w2*t+phi2)
clear all, hold off, clf reset, close all

disp('Beating between two tones demonstration')
A=input('Enter the amplitude for A1 and A2: ');
f1=input('Enter frequency f1 in Hertz:  ');
p1=input('Enter phase phi1 in degrees:  ');
f2=input('Enter frequency f2 in Hertz:  ');
p2=input('Enter phase phi2 in degrees:  ');

disp(' ')
disp('Enter the number of periods')
disp('you would like to see')
num_periods=input('of your beating tone:         ');

phi1=(2*pi/360)*p1;             % Phase phi1 in [rad]
phi2=(2*pi/360)*p2;             % Phase phi2 in [rad]
T1=1/f1;                        % Period T1
w1=2*pi*f1;                     % Frequency w1 in [rad/sec]
T2=1/f2;                        % Period T2
w2=2*pi*f2;                     % Frequency w2 in [rad/sec]
fb=(f1-f2)/2;                   % Beat frequency
wb=2*pi*fb;                     % Beat frequency wb in [rad/sec]
Tb=abs(1/fb);                   % Beat period for graphs
phib=(phi1-phi2)/2;             % Beat phase

res=4096;                       % Resolution is 1024 points per period
t=(max([T1 T2])/res)*[0:3*res];
                                % Range for t is [0:3*max(period)]
tx=(Tb/res)*[0:num_periods*res];
                                % Range for tx is [0:num_periods*max(period)]                     
one=ones(1,length(t));
x1=A*cos(w1*t+phi1*one);        % x1(t)
x2=A*cos(w2*t+phi2*one);        % x2(t)

onex=ones(1,length(tx));
x1x=A*cos(w1*tx+phi1*onex);     % x1(t)
x2x=A*cos(w2*tx+phi2*onex);     % x2(t)
x=x1x + x2x;                    % x(t)
x_beat=2*A*cos(wb*tx+phib*onex);
                                

% ************ Print Results *************************************
zm=max([abs(x1) abs(x2)]);
ti=min(t);
ta=max(t);

subplot(221)
axis([ti ta -zm zm])
title('Waveform x1(t)')
xlabel('t [sec]')
ylabel('x1(t)')
hold on
plot(t,x1,'-g')
grid

subplot(222)
axis([ti ta -zm zm])
title('Waveform x2(t)')
xlabel('t [sec]')
ylabel('x2(t)')
hold on
plot(t,x2,'-r')
grid

subplot(212)
axis([0 tx(length(tx)) -2*zm 2*zm])
title('Beating between tones: x(t)=x1(t)+x2(t)')
xlabel('Time t [sec]')
ylabel('x(t)')
hold on
plot(tx,x,'-b')
grid
% Plot the beat frequency
plot(tx,x_beat,'r')
plot(tx,-x_beat,'r')

figure(gcf)