I’ve been staring at this code for to long now. I’m running this on an esp32. I’m simulating two 50hz sinewaves with the sine function. Having trouble measuring the delay between the zero crossing of the two waveforms. I imagined measuring the time between two events happening would be straigth forward but for some reason it just won’t happen on a reliable basis.

what am i doing wrong here? two to three of five times the reading is an order of magnitude off.

I have two functions to simplify finding the zero crossing. what they do is return a -1 if it crossed from positive to negative and a 1 if the wave went from negative to positive. I did not include the second one but it’s exactly the same as the first.

```
void setup(){
Serial.begin(9600);
}
int lastVoltReading;
int voltCrossing;
byte vCrossingTaken;
void getVoltCrossing(int voltReading) {
if (voltReading > vZeroPoint && lastVoltReading < vZeroPoint) {
voltCrossing = 1;
vCrossingTaken = 1;
}
if (voltReading < vZeroPoint && lastVoltReading > vZeroPoint) {
voltCrossing = -1;
vCrossingTaken = 1;
}
if(vCrossingTaken == 0){
voltCrossing = 0;
}
lastVoltReading = voltReading;
vCrossingTaken = 0;
}
1 -| ,-'''-.
| ,-' `-.
| ,' `.
| ,' `.
| / \
|/ \
----+-------------------------\--------------------------
| __ __ \ __ / __
| ||/2 || \ 3||/2 / 2||
| `. ,'
| `. ,'
| `-. ,-'
-1 -| `-,,,-'
output:01000000000000000000000000-100000000000000000000000001
unsigned long t1 = 0;
unsigned long t2 = 0;
unsigned long zCrossDelay[5];
int zCross;
float zCrossRadians = 0;
float pf;
bool counting = 0;
byte n = 0;
void getPowerFactor() {
if (voltCrossing == 1 && counting == 0 ){
t1 = micros();
counting = 1;
}
if (ampCrossing == 1 && counting == 1 && micros() - t1 > 5) {
t2 = micros();
zCrossDelay[n] = t2 - t1; // this is where the problem is. off by an
// order of magnitude some of the time
zCross = zCrossDelay[0] + zCrossDelay[1] + zCrossDelay[2] + zCrossDelay[3] + zCrossDelay[4];
zCross = zCross / 5;
zCrossRadians = (float)zCross / 20000 * 6.283185;
n++;
if (n == 5) {
n = 0;
}
pf = cos(zCrossRadians);
counting = 0;
}
}
double dY, dY2;
float seconds;
float frequency = 50;
void loop(){
seconds = (float)millis() / 1000;
dY = sin(6.2831853 * frequency * seconds);
dY = dY * 325;
dY2 = sin(6.2831853 * frequency * seconds + PI / 16);
dY2 = dY2 * 325;
//everything above generates the two sinewaves
getVoltCrossing(dY);
getAmpCrossing(dY2);
getPowerFactor();
}
```