16.5.5 Channel Comparator

In Comparator Example, the comparator interrupt is generated each time when the conversion result is outside of a 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;
    _ANSELC8 = 0;
    
    // In this example channel 0 will be used.
    // Select single conversion mode.
    AD5CH0CON1bits.MODE = 0;
    // Software trigger will start a conversion.
    AD5CH0CON1bits.TRG1SRC = 1; 
    // Select the AN0 analog positive input/pin for the signal.
    AD5CH0CON1bits.PINSEL = 0;
    // Select signal sampling time (6.5 TADs = 81nS).
    AD5CH0CON1bits.SAMC = 3;
    // Enable the comparator for this channel.
    // Use channel data value in ADnDATAx register for comparison
    AD5CH0CON2bits.CMPVAL = 1;
    // Select out of bounds mode.
    AD5CH0CON2bits.CMPMOD = 1;
    // 1 comparison matching the criteria will trigger comparator event
    AD5CH0CON2bits.ADCMPCNT = 1;
    // Select low limit. To generate comparator event when AD5CH0DATA < 1024.
    AD5CH0CMPLO = 1024; 
    // Select high limit. To generate comparator event when AD5CH0DATA > 3072.
    AD5CH0CMPHI = 3072; 
    // Enable comparator interrupt. 
    _AD5CMP0IE = 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);
    // Trigger channel #0 in software and wait for the result.
    while(1) {
        _LATC8 = 0;
        // Trigger channel # 0.
        AD5SWTRGbits.CH0TRG = 1;
        // Wait for a conversion ready flag.
        while(AD5STATbits.CH0RDY == 0);
        // Read result. It will clear the conversion ready flag.
        result = AD5CH0DATA;
    }
    return 1;
}

void __attribute__((interrupt)) _AD5CMP0Interrupt(){
    // Process the comparator event here.
    // Clear the comparator event flag.
    AD5CMPSTATbits.CH0FLG = 0; 
    // Clear the comparator flag.
    _AD5CMP0IF = 0;
    
    _LATC8 ^= 1;
}