clear all;
close all;

port = "COM5";
I_offset = 0.5;
I_amp     = 0.5;
T         = 10;
dt        = 0.01;
duration  = 30;

sp = serialport(port, 4800);
BK_EnableRemote(sp,1)
BK_SetCCMode(sp)
BK_LoadOn(sp,1)

% --- GRAPH SETUP ---
figure;
h = animatedline('LineWidth', 2);
xlabel("Time (s)");
ylabel("Current (A)");
title("Real-Time Current Output");
grid on;
hold on;

% Storage for later analysis
time_log = [];
current_log = [];

t0 = tic;

while toc(t0) < duration
    t = toc(t0);
    I = I_offset + I_amp*cos(2*pi*t/T);

    % Send to device
    BK_SetCurrent(sp,I)
    writeline(sp, "CURR " + sprintf("%.3f", I));

    % --- UPDATE GRAPH ---
    addpoints(h, t, I);
    drawnow limitrate;

    % Store data
    time_log(end+1) = t;
    current_log(end+1) = I;

    fprintf("t = %.3f seconds\n", t);
    pause(dt);
end
