AD2/WaveForms does not have built-in phase angle calculation function. Instead following script is offered for
Custom Global measurement:
var sum1 = 0
var sum2 = 0
var sum12 = 0
var d1 = Scope.Channel1.visibledata
var d2 = Scope.Channel2.visibledata
for(var i = 0; i < d1.length; i++){
sum1 += d1[i]*d1[i]
sum2 += d2[i]*d2[i]
sum12 += d1[i]*d2[i]
}
sum1 /= d1.length
sum2 /= d1.length
sum12 /= d1.length
acos(sum12/sqrt(sum1*sum2))*180/PI
As can see it is based on integration,
principle closely related to average power calculation. Drawbacks: only for sinusoidal signals, unsigned.
So I did write new one based on zero-crossing detection. Signal shape is irrelevant now, some additional code for advance/lag detection eg result is signed and range is +-180°.
// Phase angle measurement for AD2/WaveForms v0.6
// Zero crossing detection based, any wfm shape ok, +-180°
// By lab!fyi <info@lab.fyi>
// http://lab.fyi/oscilloscope_scripts/phase_shift_measurement/index.html
var channel_1 = Scope.Channel1;
var channel_2 = Scope.Channel2;
var detect_sign = true; // false for harsh conditions, very small angles
var visible_data_only = false; // false to use full record
var sign_detection_window = 4; // +-samples around trigger
var a1 = (visible_data_only) ? channel_1.visibledata : channel_1.alldata;
var a2 = (visible_data_only) ? channel_2.visibledata : channel_2.alldata;
var zti = round
(
(visible_data_only)
? channel_1.VisibleIndexOfTime(0)
: channel_1.IndexOfTime(0)
);
var i;
var s = 1;
var p = 0;
if (detect_sign)
{
for (i = zti - sign_detection_window; i < zti + sign_detection_window + 1; i++)
{
if (sign(a1[i]) > sign(a2[i])) s += 1;
if (sign(a1[i]) < sign(a2[i])) s -= 1;
}
s = sign(s / (sign_detection_window * 2 + 1));
}
for (i = 0; i < a1.length; i++)
{
p += sign(a1[i]) * -sign(a2[i]);
}
p = s * (p + a1.length) * 90 / a1.length;
p;
As can see below "Phase" (old one) is indeed ok with sines but falls apart with sine vs square. "newPhase" stays in the game in both cases and value is signed.
Edit: Updated script to v0.6. Reversed sign because function is rather phase(C1,C2) not phase (C2,C1), also modified sign detection.