/*
 Analog to digital converter routines.
 P. McGill 8Jun11
 Based on code in the Hitech samples folder
*/

#include	<xc.h>
#include	"adc.h"

#ifndef _XTAL_FREQ
 // This definition is required to calibrate __delay_us() and __delay_ms()
 #define _XTAL_FREQ 4000000
#endif

// Set up the ADC module
void adc_setup(void) {
    //TRISA |= 0x2F;  // set RA0 pin as input
    //ANSEL = 0x01;   // set RA0 to analog mode
    ADCON0 =    0b01000000;
    //            \/\__/||_ A/D converter module not powered up yet
    //             |  | |__ don't start conversion yet
    //             |  |____ select channel 0 for now
    //             |_______ select clock speed of Fosc/8
    ADCON1 =    0b10000000;
    //            ||\/\__/
    //            || |  |__ not used
    //            || |_____ use Vss and Vdd as voltage reference
    //            ||_______ not used
    //            |________ right justify result

    //ADON = 1;       // power up the A/D converter module

} // end adc_setup()

// Read a single adc channel
// input - channel number
// output - 10-bit result
unsigned int adc_read(unsigned char channel) {

    unsigned int reading;

    channel &= 0x0F;                // mask channel to 4 bits
    ADCON0 &= 0b11000011;           // clear current channel select
    ADCON0 |= (channel << 2);       // apply the new channel select
    ADON = 1;                       // turn on the A/D converter module
    __delay_ms(1);                  // delay for 1 ms
    GO_DONE = 1;                    // start conversion
    while(GO_DONE);                 // wait for conversion complete
    reading = (ADRESH << 8) + ADRESL; // get 10-bit result
    ADON = 0;                       // turn off the A/D converter module
    return reading;
} // end adc_read()
