16.5.4 Oversampling

In Oversampling Example, the conversions are started by a software trigger and continued by back-to-back triggers. The number of accumulated conversion results is set to 16. The oversampling process cannot be interrupted by other channel conversions because the ACCBRST bit is set.

Oversampling Example

#include <xc.h>

// The channel output.
long result = 0; 

int main(){ 
    
    //Set up clock for 40Msps operation
    clock_ADC_for_40Msps_from_PLL2();
    
    _TRISC8 = 0;
    _ANSELC8 = 0;
    
    // In this example channel 0 will be used.
    // Oversampling conversion mode.
    AD5CH0CON1bits.MODE = 3;
    // Set number of conversions accumulated to 16.
    AD5CH0CON1bits.ACCNUM = 1;
    // The oversampling if started cannot be interrupted
    // by a high priority channels conversion requests.
    AD5CH0CON2bits.ACCBRST = 1;
    // Software trigger will start a conversions.
    AD5CH0CON1bits.TRG1SRC = 1; 
    // Re-trigger back to back.
    AD5CH0CON1bits.TRG2SRC = 2; 
    // Select the AN0 analog positive input/pin.
    AD5CH0CON1bits.PINSEL = 0;
    // Select signal sampling time (6.5 TADs = 81nS).
    AD5CH0CON1bits.SAMC = 3;
    // Set ADC to RUN mode.
    AD5CONbits.MODE = 2;
    // Enable ADC.
    AD5CONbits.ON = 1;
    // Wait when ADC will be ready/calibrated.
    while(AD5CONbits.ADRDY == 0);
    // Trigger channel #0 in software and wait for the 16 samples
    // oversampling result.
    
    while(1){
        // Trigger channel # 0.
        AD5SWTRGbits.CH0TRG = 1;
        // Wait for a conversion ready flag.
        while(AD5STATbits.CH0RDY == 0);
        // Read oversampling result. It will clear the conversion ready flag.
        result = AD5CH0DATA;
        
        _LATC8 ^= 1;
    }
    return 1;
}