Hi all,
I'm working on a project to monitor the frequency of AC Supply in the UK (50Hz). I'm using the Uno's in-built ADC and getting an adequate sample rate of 8333 Hz using the code below.
To calculate the frequency I'm using the zero cross over method. The code below detects the point at which the voltage crosses the "zero" at 512 then storing the times in the t() and x() arrays. To improve the accuracy of the calculation I'm planning on using the first and third crossovers (as opposed to consecutive ones) at the 512, 400 and 600 positions and taking an average.
The problem is I'm struggling to extract the first and third crossovers from my t() array without severely reducing the sampling rate (I've tried introducing nested for and while loops to "fill up" the x() array one value at a time). Can anyone suggest a different way to either store the cross overs times or extract them from the t() array?
TL;DR... How can I extract three non-zero values from an array without affecting sampling rate?
int i; // Counter
int T; // Time Period
float f; // Frequency
int z[250]; // Array for storing voltage values (0-1023)
unsigned long t[250]; // Array for storing time (microseconds)
unsigned long x[2]; // Smaller array for storing zero cross-over time (microseconds)
void setup() {
Serial.begin(9600);
for (i = 0; i < 250; i++) {
z[i] = analogRead(A5);
if (z[i - 1] > 512 && z[i] < 512) // "Zero" cross-over point (with falling voltage)
x[0] = micros(), // Store cross-over time in the x-array
t[i] = micros(); // Also store time in the t-array for Serial.print later
else if (z[i - 1] < 512 && z[i] > 512) // "Zero" cross-over point (rising voltage)
x[1] = micros(),
t[i] = micros();
delayMicroseconds(8); // This makes total sampling period 0.03 seconds long,
} // equivalent to 1.5 wavelengths at 50Hz
T = abs(x[0] - x[1]); // Calculate time period between consecutive cross-overs
cross-overs
f = 1000000 / (2 * T); // Calculate frequency
for (i = 0; i < 250; i++) {
Serial.print(z[i]);
Serial.print("\t");
Serial.println(t[i]);
}
delay(1000);
Serial.println();
Serial.print(x[0]);
Serial.print("\t");
Serial.print(x[1]);
Serial.print("\t");
Serial.print(T);
Serial.print("\t");
Serial.println(f);
}
void loop() {
}