%% CONTROLLO IN CASCATA MEDIANTE SINTESI DIRETTA 
close all
clear all
clc
P2=tf(3,[1 2]) 
P1=tf(10,poly([-1 -1 -1]))

disp('Scelta FdT desiderata per l''anello secondario')

taudes_s=0.5;
Wdes_s=tf(1,[taudes_s 1])
figure
bode(Wdes_s),grid
title('Fdt desiderata a ciclo chiuso per l''anello secondario')
B3s_des=bandwidth(Wdes_s)

%% CONTROLLO IN CASCATA - anello secondario
close all
disp('Sintesi anello secondario')

%R2_dir=Wdes_s/(1-Wdes_s)*(1/P2);
R2_dir=feedback(Wdes_s,-1)/P2;
R2_dir=minreal(R2_dir)
[nR2 dR2]=tfdata(R2_dir,'v');

WsCL=feedback(R2_dir*P2,1);
WsCL=minreal(WsCL)
figure
bode(WsCL),grid
title('Fdt a ciclo chiuso dell''anello secondario')
B3s=bandwidth(WsCL)

 %% CONTROLLO IN CASCATA - anello primario
close all
disp('Sintesi anello primario')
taudes_p=2.5;
Wdes_p=tf(1,[taudes_p^3 3*taudes_p^2 3*taudes_p 1])
Bw_ext=bandwidth(Wdes_p)

%R1_dir=Wdes_p/(1-Wdes_p)*(1/P2);
R1_dir=feedback(Wdes_p,-1)/(P1);
R1_dir=minreal(R1_dir)
[nR1 dR1]=tfdata(R1_dir,'v');

WpCL=feedback(R1_dir*P1,1);
WpCL=minreal(WpCL);
B3p=bandwidth(WpCL)

%% SINTESI A LOOP SINGOLO

close all
disp('Sintesi a loop singolo')
taudes=2.1;
Wdes=tf((-1/taudes)^4,poly([-1/taudes -1/taudes -1/taudes -1/taudes]))
Bw=bandwidth(Wdes)
R_dir=feedback(Wdes,-1)/(P1*P2);
R_dir=minreal(R_dir)
[nR dR]=tfdata(R_dir,'v');

%% SIMULAZIONE

sim('CascControlExSlides_SintesiDiretta2020')
plot(ysl.Time,ysl.Data,ycasc.Time,ycasc.Data,'Linewidth',2),grid
legend('Single-loop','Cascade')
title('Sintesi diretta')



 