clear all; close all;

filename = "0p3.csv";   % your exported file
f = 1;                    % test frequency (Hz)
Fs = 960;                   % from WinDaq Acquisition Details

data = readmatrix(filename);

V = data(:,2);              % voltage column
N = length(V);

t = (0:N-1)'/Fs;            % reconstruct time vector

% 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 = [range(V_ac)/2, 0];

beta = nlinfit(t, V_ac, sine_model, beta0);

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 (AC)");
title("Phase Lag = %.2f degrees\n", phase_deg);
legend("Measured", "Fit");
grid on;

