% Figure 1.2 from CMOS Mixed-Signal Circuit Design
clear; clc; close all;
duration = 10;         
t = (0:duration/500:duration);  %replace 500 with a larger number to slow the plot
y = sin(2*pi*0.3*t);    
x = cos(2*pi*0.3*t); 

% To set the Range of Phase plane, time vs. depl plots
fh = figure ;
set(fh,'name','Swinging Pendulum','numbertitle','off','color', 'w', ...
    'menubar','none','Position', [200,200,800,600]) ;
stop = uicontrol('style','toggle','string','stop','background','w');

% Plot for Pendulum
subplot(2,2,3);
h1 = plot(0,0,'MarkerSize',30,'Marker','.','LineWidth',3,'Color','b');
title('Swinging Pendulum','Color','b','FontSize',12);
axis([-0.8725 0.8725 -1.5 0.25], 'square');
set(gca,'XTickLabelMode', 'manual', 'XTickLabel', [],'YTickLabelMode', ...
    'manual', 'YTickLabel', [],'nextplot','replacechildren');
grid on ;

% Plot using the xy plane
subplot(2,2,4) ;
h2 = plot(0,0,'MarkerSize',30,'Marker','.','LineWidth',3,'Color','b');
axis([-1.1 , 1.1 , -1.1 , 1.1], 'square'); 
xlabel('x','FontSize',12);
ylabel('y','FontSize',12) ;
set(get(gca,'YLabel'),'Rotation',0.0);
set(gca,'XTickLabelMode', 'manual', 'XTickLabel', [],'YTickLabelMode', ...
    'manual', 'YTickLabel', [],'nextplot','replacechildren');
grid on;
title('Plotting on the xy plane','Color','b','FontSize',12)

% Plot for Time vs. Position Plot
subplot(2,2,1:2) ;
h3 = plot(0, 0,'LineWidth',3,'Color','b') ;
axis([0 duration -1.1 1.1]) ;
xlabel('t, time','FontSize',12);
ylabel('Position (along the arc)','FontSize',12) ;
grid on ;
title('Time vs. Position Plot','Color','b','FontSize',12);

% Code for animation
for i=1:length(y)
 % Pendulum plot
    if (ishandle(h1)==1)
        Xcoord=[0,sin(y(i))];
        Ycoord=[0,-cos(y(i))];
        set(h1,'XData',Xcoord,'YData',Ycoord);
        if get(stop,'value')==0
            drawnow;
        elseif get(stop,'value')==1
            break;
        end
 % xy plot
    if (ishandle(h2)==1)
        Xcoord1=[0,x(i)];
        Ycoord1=[0,y(i)];
        set(h2,'XData',Xcoord1,'YData',Ycoord1); 
        drawnow  
    end
    if (ishandle(h3)==1)
        DEPL(i,:) = [t(i) y(i)] ;
        set(h3,'Xdata',DEPL(:,1),'YData',DEPL(:,2)) ;
        drawnow ;    
    end     
    end
    F(i) = getframe(fh) ;          
end

