Measuring RMS Current with a Microcontroller

This engineering brief shows how to use a microcontroller to perform an RMS calculation and what can go wrong.

Engineering takeaways

  • Latency is unavoidable, as the calculated RMS value includes the previous N samples.
  • For clarity, the demonstration code uses a batch process, with calculations performed after N samples have been accumulated.
  • As a theoretical minimum, we must sample at least a half cycle of the waveform (asynchronous sampler assumed). In practice, several half cycles should be included to guard against noise and harmonics.
  • The RMS equation averages noise by acting as a low pass filter.
  • Smooth data is old data. Be careful with control loop and power protection circuits as the RMS data is at least a half cycle old (best case). Recommend a parallel (instantaneous) system be used when speed is important.

How is RMS current calculated in a sampled system?

The Root Mean Square calculations is a sequential operation performed on sampled data:

  • sumOfSquares: We start by squaring each sample and adding all values to an accumulator.

  • meanSquare: The squares are added together and then divided by the total number of samples.

  • RMS: The final operation is to take the square root of meanSquare.

The process is described in this equation:

I_{\text{RMS}} = \sqrt{\frac{1}{N} \sum_{i=1}^{N} I_i^2}

Figure 1: The microcontroller stores 1000 samples in an array called samples.

Tech Tip: The RMS calculation is inherently related to noise. The term “mean” implies that we are calculating the average of many independent samples. This averaging operation operates as a low-pass filter with a tendency to average out the noise. However, a “long” averaging filter lives in the past. A sudden change in current will not be detected until it propagates through the filter chain. In other words, there is a balance between noise and responsiveness.

This code snippet performs the RMS calculation on an array of samples stored in an array called samples. As described in the prerequisite article, the samples are stored in their raw integer values taken directly from the ADC. This use of integers instead of floats saves memory and results in a faster sampling process.

  sumOfSquares = 0.0;

  for (i = 0; i < NUM_SAMPLES; ++i) {
    uint16_t sample = samples[i]; // samples[] is an array of type uint16_t
    ADCVoltage = fMap((float)sample, 0.0, 4095.0, 0.0, 5.0); // Convert raw ADC values to a voltage
    ADCCurrent = fMap(ADCVoltage, 0.5, 4.5, -100.0, 100.0); //Convert voltage to corresponding current
    sumOfSquares += ADCCurrent * ADCCurrent;
  }
   meanSquare = sumOfSquares / NUM_SAMPLES;
   RMSCurrent = sqrt(meanSquare);

The crude but functional demonstration code is located here: RMS.ino (2.3 KB)

Tech Tip: The code efficiency could be improved by implementing a lookup table. In fact, a single table could be used to convert a given raw ADC integer into the square of the current. This would eliminate the two fMAP statements along with the Multiple-Accumulate (MAC) squaring operation. Be sure to evaluate your project to balance the speed vs memory consumption tradeoffs.

When RMS calculations break down

If the RMS values are inconsistent, start by checking the window length (number of samples across the monitored waveform):

In the ideal case the sampler would start synchronously at the positive-zero-crossing of the monitored waveform. It would then take N samples across the waveform. For the sake of argument, let’s assume 10 samples (600 samples per second for a 60 Hz system) are used in the RMS calculation. Let’s also assume an ideal sinusoid and ignore noise and harmonics.

In the real world, most samplers are asynchronous with the monitored waveform. This makes zero difference as the 10 samples faithfully represent the sinusoid. Stated another way, we can slide this 10-sample window across any point of the monitored waveform with minimal loss of clarity.

Suppose we want to sample faster.

What is the minimal number of samples?

Let’s keep the 10 samples but increase the sample rate to 1200 samples per second. As we slide this sample window across the waveform, we maintain the structure of a half sinusoid. Since RMS includes a squaring operation, we see that the complete half cycle is always present.

As a final step, let’s keep the 10 samples but increase the sampler to 2400 samples per second. We are now sampling 1/4 of a sinusoid. This could work if the sampler was synchronous and always started at a zero crossing. However, if the sampler is asynchronous, we are in serious trouble. At one moment in time the sample window would be centered on the top of a half wave providing a high RMS value. At another time, it may be centered on the waveform’s zero crossing providing a low RMS value.

Also be on the lookout for Nyquist errors where we need to sample at least twice the highest observed frequency. For example, in a three-phase 60 Hz system, the triplen harmonics are 180 Hz. This pushes the minimal (theoretical) sampling frequency to 360 Hz. However, the real frequency should be considerably higher unless long sampling times are allowed.

Core RMS sampling and integration lesson

We cannot sample our way out of the RMS calculation. The calculation must include a suitably large integration window. This becomes increasingly important when harmonics and noise are present.

RMS refresher

RMS is best viewed in terms of heat. We begin with two circuits; one is a DC system, and the other is AC. Each system drives an equivalent load resistance. The term RMS equates the voltages and currents in each system. For instance, 10 A DC current is equivalent to a 10 A AC_{RMS} current, as each provides the same amount of heating.

With integral calculus operating on a pure sinusoid, we can show that the RMS values are calculated as:
V_{RMS} = \dfrac{V_{peak}}{\sqrt(2)}
I_{RMS} = \dfrac{I_{peak}}{\sqrt(2)}
Always remember that this calculation holds true for a pure sinusoid. As a counterexample, a square wave symmetrical about the X-axis has an RMS value equal to the peak value.

Tech Tip: While this article is focused on calculating current, we recognize that the same technique is used for RMS voltage calculations.

Review previous work

This engineering brief introduces the concept Root Mean Square (RMS) calculations. It is applicable to a sampled system such as the one described in this article. This prerequisite article describes how a MIKROE Hall Current 7 Click current sensor may be used to measure a 60 Hz current. This sampled data is placed into an array providing a convenient starting point for our RMS introduction. Representative data are shown in Figure 1 with a 60 Hz waveform sampled at a rate of 2000 samples per second. Figure 2 presents the Arduino and MIKROE equipment featured in the prerequisite article.

Figure 2: Image of the Arduino and MIKROE equipment used to measure current.

Next steps

A batch process is used for the code described in this article where 1000 samples are collected and then processed. As written, there is a 500 ms delay between each calculation. This provides a good result as 1000 samples are used in the calculation making the system relatively immune to noise. This may be ideal for a data collection system but is unlikely to meet the requirements of a control system that acts on the RMS value.

The system’s performance may be improved if several different calculation techniques are included each with a different time frame:

  • Instantaneous: A reflexive system could be constructed that faults on a single datapoint. For example, a short circuit could be detected by a rapid change in current. This could be a simple sample-to-sample jump detector or a complex control algorithm that predicts the next sample current with a windowed trigger to identify when the current sample varies significantly from the prediction.

  • Intermediate: The RMS calculation must include enough samples to truly represent the waveform. For a symmetric sinusoid waveform, at least 50 % of the waveform must be sampled. For a 60 Hz system, this implies that an RMS calculation include multiple samples over an 8.3 ms period. For noise immunity, it is better to include at least a full cycle with a 167 ms period.

  • Long-term: The long-term RMS calculation is featured in this article where each calculation included 500 ms of sampled data. This provides the smoothest yet old data.

Additional steps could be taken to perform a “running average” RMS calculation to provide best available RMS data. The programming technique would use a circular buffer like the classic boxcar running average filter. This subtract-the-old and add-the-new to the sumOfSquares accumulator has a relatively low overhead making it perfect for use in an ISR.

Parting thoughts

The RMS calculations for a sampled system are relatively simple. A few lines of code with a loop to accumulate the sumOfSquares is found at the core of the calculation. At the same time, there is wonderful complexity as we attempt to build a control system on top of the RMS calculations. We must contend with the time it takes to sufficiently sample the signal and mitigate against noise. A variety of trade offs may be required depending on the needs of the project.

You are encouraged to review the prerequisite article. You will find a collection of promising projects including construction of a complex power meter to calculate complex AC power.

Please let us know what information you found helpful. Also, let us know what topics should be refined or expanded.

Best wishes,

APDahlen

Related articles by this author

If you enjoyed this article, you may also find these related articles helpful:

About this author

Aaron Dahlen, LCDR USCG (Ret.), serves as an application engineer at DigiKey. He has a unique electronics and automation foundation built over a 27-year military career as a technician and engineer which was further enhanced by 12 years of teaching (interwoven). With an MSEE degree from Minnesota State University, Mankato, Dahlen has taught in an ABET-accredited EE program, served as the program coordinator for an EET program, and taught component-level repair to military electronics technicians. Dahlen has returned to his Northern Minnesota home and thoroughly enjoys researching and writing articles such as this.

Is the Arduino program programmable? Please explain the program that it is programmable with.

???

sikwal
Thank you for contacting DigiKey , I am not familiar with this setup hoping APDahlen or one of the other engineers can chime in and help you with this .

Thanks Craig

Thank you very much

I want a detailed explanation of the parts I bought from Digikey.

Hi, I did not find a full explanation for some of the parts that I buy from Digikey. Please help.

Hi, if you asked about a part available in Digikey, please explain it in detail because I will buy it from Digikey, for example, an electrical circuit in which the part is supported by a picture. My warmest regards to you.

I am studying to mention that. Best regards.

I study as a hobby. I do not have the same experience as you. I hope the forum manager will clarify the matter to the group and the supervisors. I study electronics. My warmest regards to you.

Hi Remember I study at home in the little lab

Hello @sikwal,

Yes, the program is linked in the original article.

The primary article focus is on this MIKROE component:

The supporting equipment is described here:

Out of currosity, are you familiar with Arduino programming. If not, we may have some ideas to get you started.

Sincerely,

Aaron

3 Likes

Hi, this is useful information. A complete explanation. My regards to you. I will buy products from Digikey. My warmest regards to you.

I used Arduino to program nono.

1 Like

Thanks for the information my dear friend from now on we are friends

One day I will go to America to complete my studies in electronics.

I will buy from digikey after I study the three products you are buying. My warm regards to you. Sorry for the inconvenience.