gpt4 book ai didi

c - C 中有任何更快的 RMS 值计算吗?

转载 作者:太空狗 更新时间:2023-10-29 17:08:41 26 4
gpt4 key购买 nike

我正在用C语言编写一个小型8位微 Controller 的软件。部分代码是读取电流互感器(ZCT)的ADC值,然后计算RMS值。流过 ZCT 的电流呈正弦曲线,但可能会失真。我的代码如下:

float       adc_value, inst_current;
float acc_load_current; // accumulator = (I1*I1 + I2*I2 + ... + In*In)
double rms_current;

// Calculate the real instantanous value from the ADC reading
inst_current = (adc_value/1024)*2.5; // 10bit ADC, Voltage ref. 2.5V, so formula is: x=(adc/1024)*2.5V

// Update the RMS value with the new instananous value:
// Substract 1 sample from the accumulator (sample size is 512, so divide accumulator by 512 and substract it from the accumulator)
acc_load_current -= (acc_load_current / 512);
inst_current *= inst_current; // square the instantanous current
acc_load_current += inst_current; // Add it to the accumulator

rms_current = (acc_load_current / 512); // Get the mean square value. (sample size is 512)
rms_current = sqrt(rms_current); // Get RMS value

// Now the < rms_current > is the real RMS current

但是,它有很多浮点计算。这给我的小MCU增加了很大的负担。而且我发现 sqrt() 函数在我的编译器中不起作用。

有没有可以运行得更快的代码?

最佳答案

当您需要在缺少 FPU 的处理器上获得更快的速度时,最好的bet是用定点代替浮点计算。结合这与 joop 的建议(一个 Newton-Raphson sqrt)你得到像这样:

#define INITIAL 512  /* Initial value of the filter memory. */
#define SAMPLES 512

uint16_t rms_filter(uint16_t sample)
{
static uint16_t rms = INITIAL;
static uint32_t sum_squares = 1UL * SAMPLES * INITIAL * INITIAL;

sum_squares -= sum_squares / SAMPLES;
sum_squares += (uint32_t) sample * sample;
if (rms == 0) rms = 1; /* do not divide by zero */
rms = (rms + sum_squares / SAMPLES / rms) / 2;
return rms;
}

只需通过此过滤器运行您的原始 ADC 样本。你可以添加一些在这里和那里移位以获得更高的分辨率,但你必须注意不要溢出你的变量。我怀疑你真的需要额外分辨率。

过滤器的输出与其输入采用相同的单位。在这种情况下,它是你的 ADC 的单位:2.5 V/1024 ≈ 2.44 mV。如果你能保持该单元在后续计算中,您将通过避免不必要的转换。如果您真的需要以伏特为单位的值(它可能是 I/O 要求),那么你将不得不转换为 float 观点。如果你想要毫伏,你可以留在整数领域:

uint16_t rms_in_mV = rms_filter(raw_sample) * 160000UL >> 16;

关于c - C 中有任何更快的 RMS 值计算吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28807537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com