16.6.6 Channel Comparator

In Comparator Example, the comparator interrupt is generated each time the conversion result is outside the window.

Comparator 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;
    
    // In this example channel 0 will be used.
    // Select single conversion mode.
    AD3CH0CON1bits.MODE = 0;
    // Software trigger will start a conversion.
    AD3CH0CON1bits.TRG1SRC = 1; 
    // Select the AN0 analog positive input/pin for the signal.
    AD3CH0CON1bits.PINSEL = 0;
    // Select signal sampling time (6.5 TADs = 81nS).
    AD3CH0CON1bits.SAMC = 3;
    // Enable the comparator for this channel.
    // Use channel data value in ADnDATAx register for comparison
    AD3CH0CON2bits.CMPVAL = 1;
    // Select out of bounds mode.
    AD3CH0CON2bits.CMPMOD = 1;
    // 1 comparison matching the criteria will trigger comparator event
    AD3CH0CON2bits.ADCMPCNT = 1;
    // Select low limit. To generate comparator event when AD3CH0DATA < 1024.
    AD3CH0CMPLO = 1024; 
    // Select high limit. To generate comparator event when AD3CH0DATA > 3072.
    AD3CH0CMPHI = 3072; 
    // Enable comparator interrupt. 
    _AD3CMP0IE = 1;

    // Set ADC to RUN mode.
    AD3CONbits.MODE = 2;
    // Enable ADC.
    AD3CONbits.ON = 1;
    // Wait when ADC will be ready/calibrated.
    while(AD3CONbits.ADRDY == 0);
    // Trigger channel #0 in software and wait for the result.
    while(1) {
        _LATC8 = 0;
        // Trigger channel # 0.
        AD3SWTRGbits.CH0TRG = 1;
        // Wait for a conversion ready flag.
        while(AD3STATbits.CH0RDY == 0);
        // Read result. It will clear the conversion ready flag.
        result = AD3CH0DATA;
    }
    return 1;
}

void __attribute__((interrupt)) _AD3CMP0Interrupt(){
    // Process the comparator event here.
    // Clear the comparator event flag.
    AD3CMPSTATbits.CH0FLG = 0; 
    // Clear the comparator flag.
    _AD3CMP0IF = 0;
    
    _LATC8 ^= 1;
}