Hello,

I'm in a project, wherein the goal is to get the RMS value of the AC voltage from the power outlet (60Hz).

The code I have so far can be seen below.

```
int pinV=0;
int pinVref=4;
int i=0;
float sumV_rms;
int Ts=1;
float V[2];
float base;
int counter;
float valueV_rms;
float readVolt(int pinV){ //Transforms the value read by analogRead into volts.
return (5*analogRead(pinV))/1023.0;
}
void setup() {
Serial.begin(115200);
}
void loop() {
if(i==0){ //Getting the first values of V.
V[i]=readVolt(pinV);
i=1;
}
else{ //Run continuosly after the first run.
V[1]=V[0]; // V[1] receives the old value.
V[0]=readVolt(pinV); //V[0] receives a new value
base=readVolt(pinVref)/2; // the offset is given by this relationship
if(V[1]< base && V[0]>base){ // When it crosses the base value:
V[1]=V[0]; // V[1] receives the old value.
V[0]=readVolt(pinV); // V[0] received a new value
counter=1; // This is going to count the number of samples in the period
sumV_rms=0;
while(!((V[1]< base)&&(V[0]>base))){ //Until the next time the voltage crosses the 'base value' from down up
sumV_rms=sumV_rms+pow(V[0],2); //it sums the squared values
delayMicroseconds(125);
V[1]=V[0]; // V[1] receives the old value
V[0]=readVolt(pinV); //V[0] receives a new value.
counter++; //incrementing the counter
}
valueV_rms=sqrt(sumV_rms/(float)counter); //RMS calculation
Serial.println("Number of samples: " + String(counter)+", RMS value: " + String(valueV_rms));
// Prints out the results
}
}
}
```

The code is working fine, but I wanted to have some kind of control over my sampling rate.

I have this 'delayMicroseconds(125)' at the end of the while loop to make sure it is at 8kHz, but from the number of samples, I can tell it's not at 8kHz.

If I take 8,000 samples/second and my wave has a period of 1/60 seconds, then I should have 8,000/60=133,33 samples in one period, and I'm getting 55~57 samples / period using this code.

Is there a way to make sure my sampling frequency is at 8kHz?

Thank you in advance!