%% =========================================================================
%% SIMULASI KOMPREHENSIF MESIN ARUS SEARAH (DC MACHINES) - VERSI DISEMPURNAKAN
%% Mata Kuliah   : Teknik Tenaga Listrik (Program Studi S1 Teknik Mesin)
%% Dosen Pengampu: Novalio Daratha, S.T., M.Sc., Ph.D.
%% Institusi     : Fakultas Teknik, Universitas Bengkulu
%% =========================================================================
%% Fitur Pemodelan:
%% 1. Karakteristik Torsi-Kecepatan Motor Shunt (PWM, Field Weakening)
%%    beserta Pencocokan Titik Kerja Beban Mekanik (Konveyor & Pompa Sentrifugal)
%% 2. Karakteristik Motor Seri: Komparasi Model Ideal vs Kejenuhan Inti Magnetik
%%    (Magnetic Saturation) dan Batas Bahaya Runaway
%% 3. Respons Transien Dinamis Elektromekanis (Kopel L_a di_a/dt & J d\omega/dt)
%% 4. Karakteristik Pengereman Elektrik (Regenerative, Dynamic, & Plugging)
%% =========================================================================

clear; clc; close all;
graphics_toolkit('qt');
set(0, 'defaultaxesfontname', 'Helvetica');
set(0, 'defaultaxesfontsize', 10);

fprintf('=== Memulai Simulasi Komprehensif Motor DC (Versi Disempurnakan) ===\n');

%% =========================================================================
%% BAGIAN 1: KARAKTERISTIK STEADY-STATE, LOAD MATCHING, & SATURASI MAGNETIK
%% =========================================================================
Vt_nom = 220;         % Tegangan terminal nominal (V)
Ra = 0.40;            % Resistansi jangkar (Ohm)
KaPhi_nom = 1.35;     % Konstanta fluks nominal (V.s/rad)
T_vec = linspace(0, 120, 200); % Rentang Torsi (Nm)

% --- 1A. Motor DC Shunt ---
% (1) Kondisi Nominal (Vt = 220 V, Phi = 100%)
n_shunt_nom = ((Vt_nom ./ KaPhi_nom) - (Ra ./ (KaPhi_nom^2)) .* T_vec) .* (60 / (2*pi));

% (2) Kendali PWM Chopper (Duty Cycle D = 0.75 -> V_avg = 165 V)
D_pwm = 0.75;
Vt_pwm = D_pwm * Vt_nom;
n_shunt_pwm = ((Vt_pwm ./ KaPhi_nom) - (Ra ./ (KaPhi_nom^2)) .* T_vec) .* (60 / (2*pi));

% (3) Pelemahan Medan / Field Weakening (Phi = 80% KaPhi_nom)
KaPhi_fw = 0.80 * KaPhi_nom;
n_shunt_fw = ((Vt_nom ./ KaPhi_fw) - (Ra ./ (KaPhi_fw^2)) .* T_vec) .* (60 / (2*pi));

% --- Kurva Karakteristik Beban Mekanik (Load Torque Matching) ---
n_load_axis = linspace(0, 2000, 200);
% Beban 1: Torsi Konstan (Hoist / Konveyor) -> T_L = 55 Nm
T_load_const = 55 * ones(size(n_load_axis));
% Beban 2: Torsi Kuadratik Fluida (Pompa Sentrifugal / Blower) -> T_L = k * n^2
T_load_pump = 85 .* (n_load_axis ./ 1500).^2;

% --- 1B. Motor DC Seri (Model Linier Ideal vs Saturasi Inti Besi) ---
R_tot_seri = 0.55;    % Ra + Rse (Ohm)
ks_lin = 0.045;       % Koefisien fluks linier [V.s/(rad.A)]
Ia_seri = linspace(3.5, 65, 200);

% Model Ideal (Tanpa Saturasi: Ka*Phi = ks_lin * Ia)
KaPhi_ideal = ks_lin .* Ia_seri;
T_seri_ideal = KaPhi_ideal .* Ia_seri;
w_seri_ideal = (Vt_nom - Ia_seri .* R_tot_seri) ./ KaPhi_ideal;
n_seri_ideal = w_seri_ideal .* (60 / (2*pi));

% Model Realistis dengan Saturasi Magnetik: Ka*Phi(Ia) = KaPhi_max * tanh(Ia / Isat)
KaPhi_max = 1.65;     % Batas fluks jenuh inti baja silikon (V.s/rad)
I_sat = 32;           % Arus lutut kurva magnetisasi (A)
KaPhi_sat = KaPhi_max .* tanh(Ia_seri ./ I_sat);
T_seri_sat = KaPhi_sat .* Ia_seri;
w_seri_sat = (Vt_nom - Ia_seri .* R_tot_seri) ./ KaPhi_sat;
n_seri_sat = w_seri_sat .* (60 / (2*pi));

% --- Plot Figur 1: Karakteristik Steady-State & Saturasi ---
hFig1 = figure('visible', 'off', 'position', [50, 50, 1150, 480]);

% Subplot 1: Motor Shunt + Load Matching
subplot(1, 2, 1);
plot(T_vec, n_shunt_nom, 'b-', 'linewidth', 2.2); hold on;
plot(T_vec, n_shunt_fw, 'm--', 'linewidth', 1.8);
plot(T_vec, n_shunt_pwm, 'c-.', 'linewidth', 1.8);
plot(T_load_const, n_load_axis, 'k:', 'linewidth', 1.6);
plot(T_load_pump, n_load_axis, 'r-', 'linewidth', 1.6);

% Titik Kerja (Operating Points)
% Titik potong Nominal & Konveyor (T = 55 Nm)
n_op1 = ((Vt_nom / KaPhi_nom) - (Ra / (KaPhi_nom^2)) * 55) * (60 / (2*pi));
plot(55, n_op1, 'ko', 'markersize', 7, 'markerfacecolor', 'y');
text(57, n_op1 - 70, sprintf('Titik Kerja A\n(55 Nm, %.0f rpm)', n_op1), 'fontsize', 8, 'fontweight', 'bold');

hold off; grid on;
title('(a) Motor DC Shunt & Pencocokan Beban Mekanik (Load Matching)', 'fontsize', 11, 'fontweight', 'bold');
xlabel('Torsi Mekanik, T (Nm)', 'fontsize', 10);
ylabel('Kecepatan Putar, n (rpm)', 'fontsize', 10);
legend({'Shunt Nominal (V_t=220V, \Phi=100%)', ...
        'Field Weakening (\Phi=80%, n > n_{base})', ...
        'PWM Chopper (D=0.75, V_{avg}=165V)', ...
        'Beban Konveyor (T_L = Konstan)', ...
        'Beban Pompa Sentrifugal (T_L \propto n^2)', ...
        'Titik Operasi Stabil'}, 'location', 'southwest', 'fontsize', 8);
xlim([0 115]); ylim([0 2100]);

% Subplot 2: Motor Seri (Ideal vs Saturasi Magnetik)
subplot(1, 2, 2);
plot(T_seri_ideal, n_seri_ideal, 'b--', 'linewidth', 1.8); hold on;
plot(T_seri_sat, n_seri_sat, 'r-', 'linewidth', 2.3);
plot([0 120], [2500 2500], 'k:', 'linewidth', 1.5);
fill([0 22 22 0], [2500 2500 3300 3300], [1 0.85 0.85], 'facealpha', 0.4, 'linestyle', 'none');
text(5, 2850, 'ZONA BAHAYA RUNAWAY\n(Gaya Sentrifugal Berlebih)', 'color', [0.75 0 0], 'fontweight', 'bold', 'fontsize', 8.5);
text(58, 1250, 'Efek Saturasi Inti Besi:\nFluks jenuh (\Phi \rightarrow konstan)\npada arus beban tinggi', 'fontsize', 8.5, 'color', [0.6 0 0]);
hold off; grid on;
title('(b) Motor DC Seri: Model Linier Ideal vs Saturasi Inti Besi', 'fontsize', 11, 'fontweight', 'bold');
xlabel('Torsi Mekanik, T (Nm)', 'fontsize', 10);
ylabel('Kecepatan Putar, n (rpm)', 'fontsize', 10);
legend({'Model Ideal (\Phi = c \cdot I_a, Tanpa Saturasi)', ...
        'Model Realistis (Dengan Saturasi Magnetik)', ...
        'Batas Kecepatan Mekanis Maksimum'}, 'location', 'northeast', 'fontsize', 8.5);
xlim([0 115]); ylim([0 3300]);

print(hFig1, 'karakteristik_motor_dc.png', '-dpng', '-r300');
fprintf('1. Grafik karakteristik_motor_dc.png berhasil diperbarui.\n');
close(hFig1);

%% =========================================================================
%% BAGIAN 2: DINAMIKA TRANSIEN (J dw/dt) & PENGEREMAN ELEKTRIK 4-KUADRAN
%% =========================================================================
% Parameter Dinamis Elektromekanis Motor DC Shunt
La = 0.015;           % Induktansi jangkar (H)
J_eq = 0.08;          % Momen inersia ekivalen poros + beban (kg.m^2)
B_eq = 0.005;         % Koefisien gesek viskos bantalan (N.m.s/rad)

dt = 0.0005;          % Langkah waktu integrasi Euler (s)
t_sim = 0:dt:2.5;
N_steps = length(t_sim);

ia_sim = zeros(1, N_steps);
wm_sim = zeros(1, N_steps);
Te_sim = zeros(1, N_steps);

% Simulasi:
% t = 0.0 - 1.2 s : Starting dengan soft-starter / ramp tegangan (tanpa beban)
% t = 1.2 - 2.5 s : Beban mekanik konveyor T_L = 50 Nm masuk mendadak (step load)
for k = 1:(N_steps - 1)
    t_now = t_sim(k);
    % Soft-start PWM ramp selama 0.3 detik untuk membatasi lonjakan arus
    if t_now < 0.3
        Vt_in = Vt_nom * (0.35 + 0.65 * (t_now / 0.3));
    else
        Vt_in = Vt_nom;
    end
    
    % Beban mekanik masuk pada t = 1.2 s
    if t_now >= 1.2
        TL_now = 50.0;
    else
        TL_now = 0.0;
    end
    
    % Persamaan Diferensial Kopel Elektromekanis:
    % La * (dia/dt) = Vt - Ra*ia - KaPhi*wm
    % J  * (dwm/dt) = KaPhi*ia - B*wm - TL
    dia_dt = (Vt_in - Ra * ia_sim(k) - KaPhi_nom * wm_sim(k)) / La;
    dwm_dt = (KaPhi_nom * ia_sim(k) - B_eq * wm_sim(k) - TL_now) / J_eq;
    
    ia_sim(k+1) = ia_sim(k) + dia_dt * dt;
    wm_sim(k+1) = wm_sim(k) + dwm_dt * dt;
    Te_sim(k+1) = KaPhi_nom * ia_sim(k+1);
end
n_sim = wm_sim .* (60 / (2*pi));

% --- Karakteristik Pengereman Elektrik (Kuadran I & Kuadran II) ---
T_brake_axis = linspace(-90, 90, 200);
% 1. Motoring & Regenerative Braking (Vt = 220 V):
% Saat T < 0 (beban derek turun mendorong poros), n > n0 dan Eb > Vt -> Arus balik ke sumber!
n_regen = ((Vt_nom ./ KaPhi_nom) - (Ra ./ (KaPhi_nom^2)) .* T_brake_axis) .* (60 / (2*pi));

% 2. Dynamic / Rheostatic Braking (Vt = 0, dihubungkan ke R_brake = 2.0 Ohm)
R_dyn = Ra + 2.0;
n_dynamic = (0 - (R_dyn ./ (KaPhi_nom^2)) .* T_brake_axis) .* (60 / (2*pi));

% 3. Plugging / Reverse Current Braking (Vt = -220 V dengan R_plug = 3.5 Ohm)
R_plug = Ra + 3.5;
n_plugging = ((-Vt_nom ./ KaPhi_nom) - (R_plug ./ (KaPhi_nom^2)) .* T_brake_axis) .* (60 / (2*pi));

hFig2 = figure('visible', 'off', 'position', [50, 50, 1150, 480]);

% Subplot 1: Respons Transien Dinamis
subplot(1, 2, 1);
[ax, h1, h2] = plotyy(t_sim, n_sim, t_sim, ia_sim);
set(h1, 'linewidth', 2.2, 'color', [0 0.2 0.7]);
set(h2, 'linewidth', 1.8, 'color', [0.8 0.1 0.1], 'linestyle', '--');
grid on;
title('(a) Respons Transien Dinamis: Starting PWM & Beban Tiba-Tiba', 'fontsize', 11, 'fontweight', 'bold');
xlabel('Waktu, t (detik)', 'fontsize', 10);
ylabel(ax(1), 'Kecepatan Putar, n (rpm)', 'fontsize', 10, 'color', [0 0.2 0.7]);
ylabel(ax(2), 'Arus Jangkar, i_a (A)', 'fontsize', 10, 'color', [0.8 0.1 0.1]);
set(ax(1), 'ylim', [0 1800], 'ycolor', [0 0.2 0.7]);
set(ax(2), 'ylim', [0 120], 'ycolor', [0.8 0.1 0.1]);
text(1.25, 1300, '\leftarrow Beban Masuk (T_L = 50 Nm)\npada t = 1.2 s', 'fontsize', 8.5, 'fontweight', 'bold');
legend([h1; h2], {'Kecepatan Poros n(t) [rpm]', 'Arus Jangkar i_a(t) [A]'}, 'location', 'southeast', 'fontsize', 8.5);

% Subplot 2: Pengereman Elektrik & Kuadran I-II
subplot(1, 2, 2);
plot(T_brake_axis, n_regen, 'b-', 'linewidth', 2.2); hold on;
plot(T_brake_axis, n_dynamic, 'g-.', 'linewidth', 2.0);
plot(T_brake_axis, n_plugging, 'r--', 'linewidth', 2.0);
plot([0 0], [-500 2000], 'k-', 'linewidth', 1.2);
plot([-90 90], [0 0], 'k-', 'linewidth', 1.2);
text(20, 1750, 'KUADRAN I\n(Motoring Maju)\nT > 0, n > 0', 'fontsize', 8.5, 'fontweight', 'bold', 'color', [0 0.2 0.6]);
text(-82, 1750, 'KUADRAN II\n(Pengereman Elektrik)\nT < 0, n > 0', 'fontsize', 8.5, 'fontweight', 'bold', 'color', [0.7 0 0]);
text(-82, 1450, 'Regeneratif (n > n_0)', 'fontsize', 8, 'color', 'b');
hold off; grid on;
title('(b) Operasi Kuadran I-II & Metode Pengereman Elektrik', 'fontsize', 11, 'fontweight', 'bold');
xlabel('Torsi Elektromagnetik, T_{dev} (Nm)', 'fontsize', 10);
ylabel('Kecepatan Putar, n (rpm)', 'fontsize', 10);
legend({'Normal Motoring & Pengereman Regeneratif', ...
        'Pengereman Dinamis / Reostatik (V_t = 0)', ...
        'Pengereman Balik Arah / Plugging (V_t = -220V)'}, 'location', 'southwest', 'fontsize', 8);
xlim([-90 90]); ylim([-400 2000]);

print(hFig2, 'dinamika_dan_pengereman_dc.png', '-dpng', '-r300');
fprintf('2. Grafik dinamika_dan_pengereman_dc.png berhasil dibuat.\n');
close(hFig2);
fprintf('=== Simulasi Selesai ===\n');
