% Obtem a resposta temporal de um sistema de segunda ordem para diferentes
% paâmetros

clear all;
close all;
clc;

    xi=0.45; % 
    wn=[0.5 0.8 5 8]; %amplitude do degrau u=1;
    
    tspan=linspace(0,15,1001); % tempo de simulação [t_inicio t_fim]
    y0=0;  %condições iniciais nulas
    dydt0=0;
    cor=['r', 'b', 'g','k'];

    for i=1:length(wn)

        upar='impulso';
        [t,y]=ode45(@(t,y) ddt(t,y,xi,wn(i),upar),tspan,[y0;wn(i)^2]);%impulso unitário
        ys = wn(i)/(2*sqrt(xi^2-1))*exp(-xi*wn(i)*t+sqrt(xi^2-1)*wn(i)*t)-wn(i)/(2*sqrt(xi^2-1))*exp(-xi*wn(i)*t-sqrt(xi^2-1)*wn(i)*t);
        figure(1);

        subplot(3,1,1);
        plot(t,y(:,1),'LineWidth',2.0,'Color',cor(i),'LineStyle','-');
        title( 'Resposta ao Impulso - EDO 2a Ordem');
        ylabel('y(t) [V]');
        xlabel('t [s]');
        hold on;
        ax = gca;
        lgd=legend('$\omega_n=0.5$','$\omega_n=0.8$','$\omega_n=5$','$\omega_n=8$');
        lgd.Interpreter='latex';
%         ax.XTick = [0 RC 2*RC 4*RC 5*RC ];
%         ax.YTick = [0 0.63*A 0.86*A 0.98*A 0.99*A];
%         ax.XTickLabel = {'0','RC','2RC','4RC','5RC'};
%         ax.YTickLabel = {'0','0.63A','0.86A','0.98A',''};
        grid on;

    end
    hold off;

    for i=1:length(wn)

        upar='degrau';
        [t,y]=ode45(@(t,y) ddt(t,y,xi,wn(i),upar),tspan,[y0;dydt0]);
    
        subplot(3,1,2);
        plot(t,y(:,1),'LineWidth',2.0,'Color',cor(i),'LineStyle','-');
        hold on;
        title( 'Resposta ao Degrau- EDO 2a Ordem');
        ylabel('y(t) [V]');
        xlabel('t [s]');
        ax = gca;
        lgd=legend('$\omega_n=0.5$','$\omega_n=0.8$','$\omega_n=5$','$\omega_n=8$');
        lgd.Interpreter='latex';
    %     ax.XTick = [0 RC 2*RC 4*RC 5*RC ];
    %     ax.YTick = [0 0.63*A 0.86*A 0.98*A 0.99*A];
    %     ax.XTickLabel = {'0','RC','2RC','4RC','5RC'};
    %     ax.YTickLabel = {'0','0.63A','0.86A','0.98A',''};
        grid on;

    end
    hold off;

    for i=1:length(wn)
    
        upar='rampa';
        [t,y]=ode45(@(t,y) ddt(t,y,xi,wn(i),upar),tspan,[y0;dydt0]);
        
        subplot(3,1,3);
        plot(t,y(:,1),'LineWidth',2.0,'Color',cor(i),'LineStyle','-');
        hold on;
        title( 'Resposta a Rampa - EDO 2a Ordem');
        ylabel('y(t) [V]');
        xlabel('t [s]');
        ax = gca;
        lgd=legend('$\omega_n=0.5$','$\omega_n=0.8$','$\omega_n=5$','$\omega_n=8$');
        lgd.Interpreter='latex';
    %     ax.XTick = [0 RC 2*RC 4*RC 5*RC ];
    %     ax.YTick = [0 0.63*A 0.86*A 0.98*A 0.99*A];
    %     ax.XTickLabel = {'0','RC','2RC','4RC','5RC'};
    %     ax.YTickLabel = {'0','0.63A','0.86A','0.98A',''};
        grid on;
    end
    hold off;


function dydt = ddt(t,y,xi,wni,upar)
    switch upar
        case 'impulso'
            u=0; %entrada impulso
        case 'degrau'
            u=1;
        case 'rampa'
            u=t;
    end
    dydt = [0 1;-wni^2 -2*xi*wni]*[y(1);y(2)] +[0;wni^2]*u; % EDO
end
    
    