%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Problema Nº4, Guia Nº1: Amplificadores Operacionales
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

close all

%Constantes del problema
gm=70;
R0=4.5;
C=43e-6;

%%%%%%% PLANTA %%%%%%%
%Primer caso, Lmin, Rmin
L=0.01;
R=0.05;
num1=gm*R*[L/R 1];
den1=[L*C (C*R+L/R0) 1];
Gp1=tf(num1,den1);

%Segundo caso, Lmin, Rmax
R=0.5;
num2=gm*R*[L/R 1];
den2=[L*C (C*R+L/R0) 1];
Gp2=tf(num2,den2);

%Tercer caso, Lmax, Rmin
L=0.07;
R=0.05;
num3=gm*R*[L/R 1];
den3=[L*C (C*R+L/R0) 1];
Gp3=tf(num3,den3);

%Cuarto caso, Lmax, Rmax
R=0.5;
num4=gm*R*[L/R 1];
den4=[L*C (C*R+L/R0) 1];
Gp4=tf(num4,den4);

%Grafica de BODE
figure
bodemag(Gp1,'r',Gp2,'y--',Gp3,'gx',Gp4,'k:'),grid on
set(findobj('Type','line'),'LineWidth',3)
title('Planta') 


%%%%%%% LAZO DE CONTROL %%%%%%%
%Compensador
numGc=2*pi*212e3*[1/(2*pi*600) 1];
denGc=[1 0];
Gc=tf(numGc,denGc);
% figure
% bode(Gp1,'r',Gp2,'y--',Gp3,'gx',Gp4,'k:',Gc,'k--')

%Realimentacion
numH=[1/(2*pi*1e3) 1];
denH=177;
%%denH=177*[1/(177*2*pi*1e3) 1]; %%Caso pasivo
H=tf(numH,denH);

%Compensador + Planta(Lmin,Rmin) + Realimentacion
% figure
% bode(Gp1,'r',Gc,'y--',Gc*Gp1,'g',1/H,'k:')
figure
bodemag(Gp1,'r',Gc,'y--',Gc*Gp1,'g',1/H,'k:'),grid on
set(findobj('Type','line'),'LineWidth',3)
title('Planta - Compensador - G_c*G_p - Realimentacion') 


%%%%%%% LAZO DE CONTROL REAL %%%%%%%
% Operacionales
LM741P1=2*pi*10;
LM741P2=2*pi*1e6;
numLM741=10^(105/20);
denLM741=[1/(LM741P1*LM741P2) 1/LM741P1+1/LM741P2 1];
GLM741=tf(numLM741,denLM741);

LM318P1=2*pi*100;
LM318P2=2*pi*100e3;
numLM318=10^(110/20);
denLM318=[1/(LM318P1*LM318P2) 1/LM318P1+1/LM318P2 1];
GLM318=tf(numLM318,denLM318);

%Compensador + Operacionales
figure
bodemag(GLM741,'r',GLM318,'y--',Gc,'g'),grid on
set(findobj('Type','line'),'LineWidth',3)
title('Compensador + Amplificadores operacionales') 


GC741=GLM741/(1+GLM741*(Gc)^-1)
GC318=GLM318/(1+GLM318*(Gc)^-1)

figure
bodemag(GLM741,'r',GC741,'y--',Gc,'g'),grid on
set(findobj('Type','line'),'LineWidth',3)
title('Compensador construido con un LM741') 

figure
bodemag(GLM318,'r',GC318,'y--',Gc,'g'),grid on
set(findobj('Type','line'),'LineWidth',3)
title('Compensador construido con un LM318') 

figure
bodemag(GC741,'r',GC318,'y--',Gc,'g'),grid on
set(findobj('Type','line'),'LineWidth',3)
title('Compensador ideal + Comp. LM741 + Comp. LM318') 


%Sistema definitivo

TLC741=(GC741*Gp1)/(GC741*Gp1*H)
TLC318=(GC318*Gp1)/(GC318*Gp1*H)

figure
grid on
bodemag(GC741*Gp1,'r',GC318*Gp1,'y--',1/H,'g'),grid on
set(findobj('Type','line'),'LineWidth',3)
title('Sistema definitivo: G_C741*G_p // G_C318*G_p // Realimentacion') 

figure
grid on
bodemag(TLC741,'r',TLC318,'y--',1/H,'g'),grid on
set(findobj('Type','line'),'LineWidth',3)
title('TLC: 741 // 318 // 1/H') 

figure
grid on
margin(GC741*Gp1*H)
%title('Margen de fase y ganancia para G_C741*G_p*H') 

figure
grid on
margin(GC318*Gp1*H)
%title('Margen de fase y ganancia para G_C318*G_p*H') 