clear all; close all;

% ----- USER SETTINGS -----
I_amp = 0.5;                 % same amplitude used in Script 1
f = 0.2;                     % because your file is 0p2 (0.2 Hz)
filename = "0p1.csv";    % your actual exported file

fprintf("\nReading %s...\n", filename);

% ----- LOAD CSV -----
data = readmatrix(filename);
t = data(:,1);               % time column
V = data(:,2);               % voltage column

% ----- REMOVE DC OFFSET -----
V_ac = V - mean(V);

% ----- FIT SINE WAVE -----
w = 2*pi*f;
sine_model = @(b,t) b(1)*sin(w*t + b(2));
beta0 = [0.01, 0];           % initial guess

beta = nlinfit(t, V_ac, sine_model, beta0);

V_amp = abs(beta(1));
phase_deg = rad2deg(beta(2));

fprintf("Phase Lag = %.2f degrees\n", phase_deg);

% ----- PLOT FIT -----
t_fit = linspace(min(t), max(t), 2000);
V_fit = beta(1)*sin(w*t_fit + beta(2));

figure;
plot(t, V_ac, 'b'); hold on;
plot(t_fit, V_fit, 'r', 'LineWidth', 2);
xlabel("Time (s)");
ylabel("Voltage (V)");
title(sprintf("Phase Lag Fit at %.2f Hz", f));
legend("Measured Voltage", "Fitted Sine");
grid on;


