%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Lektion 6                              %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Uppgift 6.1
clear
clc

% a)
Va = 240;
Rf = 200;
Ra = 50e-3;
n0 = 4000;
If0 = 0.4;
w0 = 2*pi/60*n0;
Kf = Va/(If0*w0)

% b)
n = [1500:4000];
w = 2*pi/60*n;
P = 20*(n/3600).^3*1e3;
T = P./w;
figure(1)
plot(n,T,'Linewidth',2)
xlabel('n [rpm]')
ylabel('T [Nm]')
grid
Tmin = T(1)
Tmax = T(end)

% c)
If = 1/Kf*(Va./(2*w)+sqrt((Va./(2*w)).^2-T*Ra./w));
figure(2)
plot(n,If,'Linewidth',2)
xlabel('n [rpm]')
ylabel('If [A]')
grid
Ifmax = If(1)
Ifmin = If(end)

% d)
R = Va./If-Rf;
figure(3)
plot(n,R,'Linewidth',2)
grid
xlabel('n [rpm]')
ylabel('R [Ohm]')
Rmin = R(1)
Rmax = R(end)


%% Uppgift 6.2
clear
clc

Va = 200;
I = 7.5;
n = 1000;
Ra = 4;
Rf = 400;

% b)

If = Va/Rf;
Ia = I-If
Ea = Va-Ia*Ra 
P = Ea*Ia
w = 2*pi*n/60;
T = P/w

% c)

Kf = T/(Ia*If)
% Alt
Kf = Ea/(If*w)

% d)
n = [100:1000];
w = 2*pi*n/60;
T = 5;

Va = sqrt(T*Rf*Ra/Kf./(1-Kf/Rf*w));
figure(1)
plot(n,Va,'Linewidth',2)
grid
xlabel('n [rpm]')
ylabel('Va [V]')

n = 500;
w = 2*pi*n/60;
Va = sqrt(T*Rf*Ra/Kf./(1-Kf/Rf*w))

%% e) 
n = [100:1000];
w = 2*pi*n/60;
T = 5;
Va = sqrt(T*Rf*Ra/Kf./(1-Kf/Rf*w));
Put = T*w;
Ia = T*Rf./(Kf*Va);
If = Va/Rf;
Pin = Va.*(Ia+If);
eta = Put./Pin;

figure(2)
plot(n,eta,'Linewidth',1)
grid
xlabel('n [rpm]')
ylabel('\eta [-]')

n = 500;
w = 2*pi*n/60;
Va = sqrt(T*Rf*Ra/Kf./(1-Kf/Rf*w));
Put = T*w;
Ia = T*Rf./(Kf*Va);
If = Va/Rf;
Pin = Va.*(Ia+If);
eta = Put./Pin

%% Uppgift 6.3
clear all
clc

n0 = 2000;
Ra = 0.54;
Rf = 10;

% a)
If0 = 3;
Va0 = 300;
 
Ea0 = 100*If0-If0^3;
Ia0 = (Va0-Ea0)/Ra
Put = Ea0*Ia0
Pin = Va0*Ia0 + Rf*If0^2
eta = Put/Pin

%% b)
n1 = 2500;
w1 = n1*2*pi/60;
T = 10;
Ea1 = Va0/2 + sqrt((Va0/2)^2 - T*w1*Ra)
Ia1 = (Va0-Ea1)/Ra

syms If real
If1s = solve(Ea1-n1/n0*(100*If-If^3));
double(If1s)
If1 = double(If1s(3))

%% Uppgift 6.4
clear all
Put = 1100;
Va0 = 150;
n0 = 3000;
w0 = n0*2*pi/60;
Km = 0.465;
Ra = 1.37;
Prot = 87;
Trot = Prot/w0
Pe = Put + Prot;
Ea0 = Km*w0;
Ia0 = Pe/Ea0
T = Pe/w0
T = Km*Ia0
Va0 = Ea0 + Ia0*Ra

%% b)
Ia1 = 6.2;
n1 = 2670;
w1 = n1*2*pi/60;

Tmech = Km*Ia1;
Tload = Tmech-Trot
Pload = Tload*w1

% c)
Kload = Tload/w1;
J = 2.28e-3;
Ia2 = 7;
t = [-1:0.01:2];
w = max(w1,(w1 - (Km*Ia2-Trot)/Kload)*exp(-Kload/J*t) + (Km*Ia2-Trot)/Kload);
plot(t,w*60/(2*pi),'Linewidth',2)
xlabel('tid [s]')
ylabel('varvtal [rpm]')
grid