/* ADC routines */
/* Designed by Paolo Subiaco http://www.creasol.it */

#include "main.h"
#include "adc.h"

void adcInit(void) {
	_adcr=ADCR_VALUE;	// only PB0..PB2 are enabled
	_acsr=ADSR_VALUE;
}

void adcStop(void) {
	// STOP ADC to avoid power consumption
	_adcr=0;	
}

uint adcRead(uchar channel, uchar n) {
	// read the ADC value for that channel
	// make n iteration to obtain high resolutions
	uint value=0;
	_adcr=ADCR_VALUE|channel;	// set internal multiplexer
	//_delay(1000);	// wait for avoid any transient on analog input
	for (;n;n--) {
		_start=1;
		_nop();
		_start=0;
		while (_eocb);	// wait until conversion end
#if ADC_RESOLUTION==9
		if (_adrl&0x80)
			value++;
		value+=((uint)_adrh)<<1;
#elif ADC_RESOLUTION==10
	value+=(_adrl>>6);
		value+=((uint)_adrh)<<2;
#endif
	}
//	_adcr=0x00;	// disable all PBx as analog inputs (needed because PB0 is used as output)
	return value;
}


