// A/D converter routine header

#include "877reg.h"

/* adc initialization: 
	ADCON1 = 0x00; // port A all analog, result left justified
	ADCON0 = 0x81; // 0b 1000 0001 activate A/D, ch 0, Tad = Fosc/32
*/

// inits ADC to configuration x
#define adc_init(x) (ADCON1 = x)

//
// Have to initialize ADC before using this function!!!
//
char adc_read(char ch) {

	ADCON0 = (ch << 3) & 56; // shift ch to correct bit position
	ADCON0 |= 0x81; // Tad = Fosc/32, ADC on.

	delay_us(12); // wait for Tacq
    
    ADCON0 |= 4; // acquire go!
	
    while (ADCON0 & 4); // wait for AD to complete

    delay_us(4); // wait for 2Tad
    
    return ADRESH; // return captured value
}
