15.5.6 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() { 
    // In this example channel 1 will be used.
    // Select single conversion mode.
    AD1CH1CONbits.MODE = 0;
    // Software trigger will start a conversion.
    AD1CH1CONbits.TRG1SRC = 1; 
    // Select the AN9 analog positive input/pin for the signal.
    AD1CH1CONbits.PINSEL = 9;
    // Select signal sampling time (6.5 TADs = 81nS).
    AD1CH1CONbits.SAMC = 3;
    // Enable the comparator for this channel.
    // Select out of bounds mode.
    AD1CH1CONbits.CMPMOD = 1;
    // Select low limit. To generate comparator event when AD1DATA1 < 1024.
    AD1CH1CMPLO = 1024; 
    // Select high limit. To generate comparator event when AD1DATA1 > 3072.
    AD1CH1CMPHI = 3072; 
    // Enable timer interrupt. 
    _AD1CMP1IE = 1;
    // Set ADC to RUN mode.
    AD1CONbits.MODE = 2;
    // Enable ADC.
    AD1CONbits.ON = 1;
    // Wait when ADC will be ready/calibrated.
    while(AD1CONbits.ADRDY == 0);
    // Trigger channel #1 in software and wait for the result.
    while(1){
        // Trigger channel # 1.
        AD1SWTRGbits.CH1TRG = 1;
        // Wait for a conversion ready flag.
        while(AD1STATbits.CH1RDY == 0);
        // Read result. It will clear the conversion ready flag.
        result = AD1CH1DATA;
    }
    return 1;
}

void __attribute__((interrupt)) _AD1CMP1Interrupt(){
    // Process the comparator event here.
    // Clear the comparator event flag.
    AD1CMPSTATbits.CH1CMP = 0; 
    // Clear the comparator flag.
    _AD1CMP1IF = 0;
}