在ADC中断中使用位移和数组的平均值

时间:2014-05-15 20:00:38

标签: c average interrupt microcontroller mplab

我有一个ADC中断,我想对通道(ADCBUF0)进行8次采样,然后取样本的平均值。我的代码使用标志跳出if语句。代码编译,我的变量在其他地方初始化。有人可以告诉我为什么我没有收到SpeedADC的价值???

///////Global////////////
int SpeedADCcount=0;
/////////////////////////

SpeedADCflag=1;
    if(SpeedADCflag==1)     //The following is meant to take a an average of the incoming ADC voltages
    {
        SpeedADCcount++;
        for(i = SpeedADCcount; i < 16; i++)
        {
            while(!ADCON1bits.SAMP);    //Sample Done?          
            ADCON1bits.SAMP=0;          //Start Converting
            while(!ADCON1bits.DONE);    //Conversion Done? Should be on next Tcy cycle
            SpeedADCarray[i] = ADCBUF0;
            SpeedADCflag=0;
        }
    }
    if(SpeedADCcount==15)
    {

        SpeedADC=SpeedADCarray[i]>>4;
        SpeedADCcount=0;
        // Re-enable the motor if it was turned off previous
        if((SpeedADC>246) && Flags.RunMotor==0){RunMotor();}

        /*Go through another stage of "filtering" for any analog input voltage below 1.25volts

1 个答案:

答案 0 :(得分:3)

你需要获得正确的降档量(以避免分裂),这样8 - > 3,16 - &gt; 4等。对于8个样本,您只需要降档3(3位)。

您需要将所有值汇总到一个值中,而不是将它们放在单独的数组条目中。

SpeedADCarray += ADCBUF0;  /* accumulate in a single integer, not an array */