calcIrms - initialising sampleI

Just hoping someone would have the time to explain me something concerning the calcIrms function which I am pasting below for reference.

double EnergyMonitor::calcIrms(int NUMBER_OF_SAMPLES)
{
 
int SUPPLYVOLTAGE = readVcc();

 
  for (int n = 0; n < NUMBER_OF_SAMPLES; n++)
  {
    lastSampleI = sampleI;
    sampleI = analogRead(inPinI);
    lastFilteredI = filteredI;
    filteredI = 0.996*(lastFilteredI+sampleI-lastSampleI);

    // Root-mean-square method current
    // 1) square current values
    sqI = filteredI * filteredI;
    // 2) sum
    sumI += sqI;
  }

  double I_RATIO = ICAL *((SUPPLYVOLTAGE/1000.0) / 1023.0);
  Irms = I_RATIO * sqrt(sumI / NUMBER_OF_SAMPLES);

  //Reset accumulators
  sumI = 0;
//--------------------------------------------------------------------------------------      
  return Irms;
}

 

The variable sampleI does not seem to be initialised. Therefore I believe it holds value 0 when  the function is called. If no CT is plugged in then the value read by analogRead() should be approx 512 which means that the high pass filter will see a jump of 512 steps from the first reading. Over more than a thousand sample that might be really small but still inducing a small error.

Testing with my own hardware I found that results were much better if I initialised the sampleI variable first at the start of the function with an analogRead. With no CT plugged returned value is much closer to 0.

Or maybe I must be missing something and this variable is initialised somewhere else.

Robert Wall's picture

Re: calcIrms - initialising sampleI

This is a problem that was recognised a while ago. A change to emonLib was made a few days ago, but the change produced wholly inaccurate values and on analysis it proved to be based on a totally invalid assumption. It turns out that to initialise the high pass filter is not the trivial operation that you suggest. I sent to Glyn Hudson a few days ago a new emonLib, which correctly initialises the filter and thus completely removes the error, and I imagine he will release it to GitHub when he is satisfied that it is correct.

In the meantime, you can get reasonably accurate results by running the filter for a few thousand iterations - 5 time constants, or 1250 iterations, should be enough - in setup( ) and of course discard the result, before entering loop( ).

Robert Wall's picture

Re: calcIrms - initialising sampleI

See the 'sticky' post at the top of this forum. There's a new emonLib available for testing, which I think fixes the problem that Jack Kelly's change attempted to solve.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.