我想做移动平均线或类似的移动平均线,因为我从ADC那里得到了嘈杂的值,这是我的第一次尝试,只是计算移动平均线,但是每次值变为0时,您能帮我吗?

这是代码的一部分,这使它变得神奇:

unsigned char buffer[5];
    int samples = 0;
    USART_Init0(MYUBRR);
    uint16_t adc_result0, adc_result1;
    float ADCaverage = 0;

    while(1)
    {

        adc_result0 = adc_read(0);      // read adc value at PA0
        samples++;
        //adc_result1 = adc_read(1);      // read adc value at PA1

        ADCaverage = (ADCaverage + adc_result0)/samples;

        sprintf(buffer, "%d\n", (int)ADCaverage);
        char * p = buffer;
        while (*p) { USART_Transmit0(*p++); }
        _delay_ms(1000);
    }
    return(0);
}


我通过usart发送此结果以显示价值。

最佳答案

您的方程式不正确。

然后让s_n = (sum_{i=0}^{n} x[i])/n

s_(n-1) = sum_{i=0}^{n-1} x[i])/(n-1)

sum_{i=0}^{n-1} x[i] = (n-1)*s_(n-1)
sum_{i=0}^{n} x[i] = n*s_n


sum_{i=0}^{n} x[i] = sum_{i=0}^{n-1} x[i] + x[n]

n*s_n = (n-1)*s_(n-1) + x[n] =  n*s_(n-1) + (x[n]-s_(n-1))
s_n = s_(n-1) + (x[n]-s_(n-1))/n


您必须使用

ADCaverage += (adc_result0-ADCaverage)/samples;

07-24 09:19