#include <xc.h>

#define _XTAL_FREQ 20000000UL

#define THRESHOLD 512           // about 2.5 V (512/1023 x 5 V)

unsigned int ADC_Read(void)
{
    __delay_us(20);                     // acquisition time
    ADCON0bits.GO_nDONE = 1;            // start conversion
    while(ADCON0bits.GO_nDONE == 1);    // wait until done
    return ((ADRESH << 8) | ADRESL);    // 10-bit result
}

void main(void)
{
    unsigned int value;

    TRISB = 0x00;               // PORTB = output (LED on RB0)
    LATB  = 0x00;

    TRISEbits.TRISE2 = 1;       // RE2/AN7 = input

    ADCON1 = 0x07;              // AN0-AN7 analog, Vref = VDD/VSS
    ADCON0 = 0x1D;              // channel AN7, ADC ON
    ADCON2 = 0x96;              // right justified, 4 TAD, Fosc/64

    while(1)
    {
        value = ADC_Read();

        if(value > THRESHOLD)
            LATBbits.LATB0 = 1; // LED ON
        else
            LATBbits.LATB0 = 0; // LED OFF
    }
}
