# How to measure a signal in a sampling frequency

Hello to everyone!

I have installed a voltage sensor that is measuring the voltage value at home, and my idea is to measure the 50Hz signal at a sampling frequency of 1kHz (20 measurements in 20ms) and store these values in a vector to make calculations later. Could someone tell me how can I do this?

Thank you very much in advance!

Are you working with line current? 110 to 240 volts? That tends to be dangerous. What is the output of your installed "voltage sensor"?

To do things at 1 millisecond intervals you can use a timer interrupt. You can use Timer0 or Timer1 to trigger the ADC (See: ADC Auto Trigger Source Selections in the datasheet). Since Timer0 is used for millis() and micros() you should use Timer1 if you want to set the frequency to 1 kHz. Then you can enable the "Conversion Complete" interrupt of the ADC and use that interrupt to store the result in the next element of the array (unless the array is full).

Thanks a lot John!. I'm just simulating, and thinking on installing. Studied electrical engineering but never programming.

The output is between 2,5 and 5V.

I read some things about the mills() function. but I don't know how to apply. Could you help me with the code of the ADC trigger?

You can use micros() for timing. It's more accurate than millis(). Just take 20 consecutive samples, using micros() by capturing its value, then continually subtracting it from the current micros() value, until it exceeds 1000 (representing 1ms), take a sample and repeat 20 times. The method suggested in post #1 has more predictable timing, if accuracy is super important. How much skew is allowed in the samples?

Although the example sketch, "blinkwithoutdelay" is not for the same purpose, you can look at it for an example of the millis() timing logic. You will just use micros() instead, and capture an analog value instead of toggling an LED.

You may have to find a way to hardware scale the input voltage, because 5V is too close to the end of the ADC input range.

Thank you for helping me!!
Would this code work?

``````long T0, T;
T0 = micros();
for (int i = 0; i <1000; i++){
}
T = micros()-T0;
``````

Lots of great ideas, code and safe circuitry for Arduino AC line monitoring at https://learn.openenergymonitor.org/electricity-monitoring/

davidllorca:
Thank you for helping me!!
Would this code work?

``````long T0, T;
``````

T0 = micros();
for (int i = 0; i <1000; i++){
}
T = micros()-T0;

More like:

``````const byte SampleCount = 20;
const unsigned long SampleIntervalMicroseconds = 1000;
const byte InputPin = A0;

int Samples[SampleCount];

void GetSamples()
{
unsigned long startTime = micros();

for (byte s = 0; s < SampleCount; s++)
{
while (micros() - startTime < SampleIntervalMicroseconds)
{
/* DOING NOTHING */
}
startTime += SampleIntervalMicroseconds;