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

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


// Set up the A2D module
void adc_setup(void) {
    TRISA |= 0x2F;  // set all adc pins as inputs
    ADCON0 = 0;     // select Fosc/2
    ADCON1 = 0;     // select right justify result, A/D port configuration 0
    ADON = 1;       // turn on the A2D conversion module
} // end adc_setup()

// Read a single adc channel
unsigned int adc_read(unsigned char channel) {
    channel &= 0x07;                // truncate channel to 3 bits
    ADCON0 &= 0xC5;                 // clear current channel select
    ADCON0 |= (channel << 3);       // apply the new channel select
    GO_DONE = 1;                    // start conversion
    while(GO_DONE) continue;        // wait for conversion complete
    return(ADRESH << 8 + ADRESL);   // return 10-bit result
} // end adc_read
