16.5.2 Windowed Multiple Conversions
In Windowed Conversions Example, the conversion results are accumulated until the RA4 pin is at the high level. The conversions are triggered from the internal ADC timer.
Windowed Conversions Example
#include <xc.h>
// The channel output from primary accumulator.
volatile long result = 0;
// The number of accumulated samples.
volatile long number_of_accumulated_samples;
int main(){
_TRISC8 = 0;
_ANSELC8 = 0;
//Set up clock for 40Msps operation
clock_ADC_for_40Msps_from_PLL2();
// RF1/RP82 pin is a trigger input.
// Switch to a digital input.
ANSELFbits.ANSELF1 = 0;
// Make an input.
TRISFbits.TRISF1 = 1;
// Map external pin trigger to RF1/RP82.
_ADTRG31R = 82;
// In this example channel 0 will be used.
// Set limit for the accumulated samples number.
AD5CH0CNTbits.CNT = 0xffff;
// Window conversion mode.
AD5CH0CON1bits.MODE = 1;
// Accumulation will be started/stopped from an external pin.
AD5CH0CON1bits.TRG1SRC = 31;
// Logic LOW on RF1/RP82 will trigger conversion
AD5CH0CON1bits.TRG1POL = 1;
// Trigger all conversions from the ADC repeat timer.
AD5CH0CON1bits.TRG2SRC = 3;
// Select the AN0 analog positive input/pin.
AD5CH0CON1bits.PINSEL = 0;
// Select signal sampling time (6.5 TADs = 81nS).
AD5CH0CON1bits.SAMC = 3;
// Set period of the triggers timer (63 is maximum).
AD5CONbits.RPTCNT = 60;
// Interrupt when AD5CH0DATA is updated
AD5CH0CON1bits.IRQSEL = 1;
// Set ADC to RUN mode.
AD5CONbits.MODE = 2;
// Enable ADC.
AD5CONbits.ON = 1;
// Wait when ADC will be ready/calibrated.
while(AD5CONbits.ADRDY == 0);
// Enable interrupt;
_AD5CH0IF = 0;
_AD5CH0IE = 1;
// Channel 0 is converted and results are accumulated until the RF1 pin is high.
// On transition from high to low an interrupt is generated.
while(1);
return 1;
}
void __attribute__((interrupt)) _AD5CH0Interrupt(){
_LATC8 ^= 1;
// Read result in accumulator and clear CH3RDY flag.
result = AD5CH0DATA;
number_of_accumulated_samples = AD5CH0CNTbits.CNTSTAT;
result /= number_of_accumulated_samples;
// Clear interrupt flag.
_AD5CH0IF = 0;
}