Stumpyhuck29
Stumpyhuck29

Reputation: 63

average using bit shift and array in ADC interrupt

I have an ADC interrupt that I'd like to sample the channel (ADCBUF0) 8 times, then take the average of the samples. My code utilizes flags to jump out of the if statement. The code compiles and my variables are initialized elsewhere. Could someone please tell me why I am not receiving a value for 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

Upvotes: 0

Views: 1687

Answers (1)

Jiminion
Jiminion

Reputation: 5164

You need to get the right downshift amount (to avoid dividing), such that 8 -> 3, 16 -> 4, etc. For 8 samples, you only need to downshift 3 (3 bits).

And you need to sum all of the values in a single value, not put them in separate array entries.

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

Upvotes: 3

Related Questions