void TaskSensores(void *pdata)
{    
#if OS_CRITICAL_METHOD == 3 
    OS_CPU_SR  cpu_sr;
#endif
    struct AdcMsg *m;
    INT16U value = 0;
    INT16U ValorTeclado = 0;
	INT8U err;
	for(;;)
	{
        
        m = (struct AdcMsg *) OSMemGet(dMemory,&err);
        if(err == OS_NO_ERR){
            OSSemPend(STeclado,0,&err);
            ValorTeclado = NumeroSensores;
            OSSemPost(STeclado);       
            m->adc0 = 0;
            m->adc1 = 0;
            m->adc2 = 0;
            switch(ValorTeclado){
                case 3:
                    Delay10TCYx(100);
                    SetChanADC(ADC_CH2);
                    ConvertADC();
                    while( BusyADC() );
                    value = ReadADC();
                    m->adc2 = Temp(value);
                case 2:
                    Delay10TCYx(100);
                    SetChanADC(ADC_CH1);
                    ConvertADC();
                    while( BusyADC() );
                    value = ReadADC();
                    m->adc1 = Temp(value);                    
                case 1:
                    Delay10TCYx(100);
                    SetChanADC(ADC_CH0);
                    ConvertADC();
                    while( BusyADC() );
                    value = ReadADC();
                    m->adc0 = Temp(value);
                default:
                    break;
            }

            err = OSQPost(QueueADC0,m);
            if(err == OS_Q_FULL){
                OSMemPut(dMemory,m);
                OSSemPost(STaskTxSerial);
            }
        }else{
            OSSemPost(STaskTxSerial);
        }
		//OSSemPost(STask2);
		OSTimeDly(1);
	}
}
Exemplo n.º 2
0
void main(void) {
    int count;
    unsigned int adcValue = 0;
    unsigned int adcValueOld = 0;
    char buffer[16];

    ConfigureOscillator();
    InitApp();

    lcd_init();
    lcd_enable();
    lcd_cursor_off();
    lcd_test();
    lcd_pos(2, 1);
    while (1) {
        ConvertADC();
        while (BusyADC());
        adcValue = ReadADC();
        if (adcValue != adcValueOld) {
            lcd_clear();
            lcd_pos(1, 1);
            memset(&buffer[0], 0, sizeof(buffer));
            sprintf(&buffer[0], "Valor: %.4u %.3u%%", adcValue, (int)(((float)adcValue / 1024) * 100));
            lcd_write_buffer(buffer, strlen(buffer));
            adcValueOld = adcValue;
        }
        __delay_ms(20);
    }
}
Exemplo n.º 3
0
void main(void)
{
    int16_t moyenne;

    BoardInit();

    /* Configuration de l'ADC
     *  horloge: oscillateur RC interne
     *  résultat justifié à droite
     *  temps d'acquisition: 2*Tad (délai minimum entre 2 conversions)
     *  canal 4
     *  interruption desactivée
     *  tensions référence par défaut (Vref+ = AVdd / Vref- = AVss)
     */
    OpenADC(ADC_FOSC_RC|ADC_RIGHT_JUST|ADC_2_TAD, ADC_CH4|ADC_INT_OFF, 0);

    moyenne = 0;
    for (uint8_t i = 0; i < 16; i++) {
        ConvertADC();               /* démarrage conversion */
        while (BusyADC());          /* attente fin conversion */
        moyenne += ReadADC();       /* lecture résultat */
    }
    moyenne /= 16;

    while (1);
}
Exemplo n.º 4
0
Arquivo: daq.c Projeto: nsaspook/mandm
/* switch to ADC chan 8 (shorted to ground) to reset ADC measurement cap to zero before next measurement */
void ADC_zero(void)
{
	ClrWdt(); // reset the WDT timer
	SetChanADC(ADC_CH8); // F3 grounded input
	Delay10TCYx(ADC_CHAN_DELAY);
	ConvertADC();
	while (BusyADC());
}
Exemplo n.º 5
0
void main (void)
{
  int count = 0;
  int analogTemp = 0;  	// A temporary place holder is needed
						// since ADC will screw with the number
						// you are assigning to, and we could
						// switch threads during that time.
  TRISB = 0;  // Output for relay
  TRISD = 0;  // Output for seven segment display
  TRISC = 0;  // More output for seven segment display
  TRISAbits.TRISA0 = 1; // Analog input
  writeNum(0);

  // Enable timer interrupt
  Flags.Byte = 0;
  INTCON = 0x20;                //disable global and enable TMR0 interrupt
  INTCON2 = 0x84;               //TMR0 high priority
  RCONbits.IPEN = 1;            //enable priority levels
  TMR0H = 0;                    //clear timer
  TMR0L = 0;                    //clear timer
  T0CON = 0x84;                 //set up timer0 - prescaler 1:8
  INTCONbits.GIEH = 1;          //enable interrupts
		
  while(1){
    OpenADC(ADC_FOSC_8 & ADC_RIGHT_JUST & ADC_0_TAD,
       ADC_CH0 & ADC_INT_OFF & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS,
	   0b1011);
    SetChanADC(ADC_CH0);
    ConvertADC(); // Start conversion
    while( BusyADC() ); // Wait for ADC conversion
    analogTemp = ReadADC(); // Read result and put in temp
    CloseADC();
    analogInput = analogTemp >> 6; // Get only the most significant bits

	// If we didn't change values since last time, we are in a holding state
	if( analogPrevious == analogInput && !hold) hold = 1;
    else if (analogPrevious != analogInput){
 	    acceptedNum = 0;
		hold = 0;
    }
	
	// Turn off potential for activating the relay if we aren't on 0
    if(analogInput) PORTB = 0;


	// If we are allowing the second relay activation and we are on 0
    if(secondRun && !analogInput) {
      PORTB = 0xFF;
      secondRun = 0;
	  passDigit = 0;
	}

    analogPrevious = analogInput;
    writeNum(analogInput);
  }
}
Exemplo n.º 6
0
unsigned int ADC_read(unsigned char ADC_channel)
 {
  unsigned int ad_res;
	   
  SetChanADC(ADC_channel);
  Delay10TCYx(5);
  ConvertADC();
  while(BusyADC());
  ad_res = ReadADC();
  return ad_res;
}
Exemplo n.º 7
0
unsigned int io_read_analog(unsigned char port)

{
    unsigned int    result;
    unsigned char   channel;
#ifndef SDCC
    static unsigned char inputs[] = {
	ADC_CH0, ADC_CH1, ADC_CH2, ADC_CH3,
	ADC_CH4, ADC_CH5, ADC_CH6, ADC_CH7,
	ADC_CH8, ADC_CH9, ADC_CH10, ADC_CH11,
	ADC_CH12, ADC_CH13, ADC_CH14, ADC_CH15 };
#endif

    /* Make sure port does not exceed current Analog_ports */
    if ( ! VALID_ANALOG_PORT(port) )
	return OV_BAD_PARAM;

#ifdef SDCC
    result = 0;

    channel = port - 1;

    /*
     *  SDCC generic adc_open() doesn't work for the 8520.  Lots of
     *  stuff missing.
     */
    adc_open8520(channel);

    /* Allow settling time before starting a conversion */
    delay10tcy(10);
    
    adc_conv();
    while ( adc_busy() )
	;
    result = adc_read();
    adc_close();

#else   /* MCC18 */

    channel = inputs[port - 1];

    OpenADC(ADC_FOSC_RC & ADC_RIGHT_JUST & Analog_ports_const,
	  channel & ADC_INT_OFF & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS);
    Delay10TCYx(10);
    ConvertADC();
    while (BusyADC())
	;
    ReadADC();
    CloseADC();
    result = (unsigned int)ADRESH << 8 | ADRESL;
#endif

    return result;
}
Exemplo n.º 8
0
/******************************************************************************************
*    GENERAL FUNCTIONS        *
******************************************************************************************/
void Read_Analog_Inputs(void)
{
    // Read Analog Channels -----------------------------
    for (unsigned char i=0;i < ADC_channels; i++)
    {
        ADCON0bits.CHS=i; // Select the channel to read
        Delay10TCYx(50);  // Small 50 time cycles delay
        ConvertADC();
        while(BusyADC());
        ADCValue[i] = ReadADC();
    }
}
Exemplo n.º 9
0
void measureCarbon()
{

	//Perform Measurement and convert to correct format
	//Choose a channel adc channel AN1
//    OpenADC(ADC_FOSC_4 & ADC_RIGHT_JUST & ADC_8ANA_0REF , ADC_CH1 & ADC_INT_OFF);
    SetChanADC(ADC_CH1);
    Delay10KTCYx(5);
    ConvertADC();
    while(BusyADC());
    carbon = ReadADC(); //take value read and divide by 204.8 to get voltage read
}
Exemplo n.º 10
0
void main(void)
{
    uint8_t max = MAX;
    dp_std_status_t current_status;
    dp_std_command_t cmd_from_master;
    int8_t adc = 1;
    
    // Debug LED
    TRISCbits.TRISC2 = 0;
    PORTCbits.RC2 = 0;

    // Initialize LEDs
    led_initialize();
    
    // Initialize ADC
    OpenADC ( 
        ADC_FOSC_16 & ADC_RIGHT_JUST & ADC_4_TAD, // ADC_4_TAD = Converting over 4*(1/(FOSC/16)) = 4*(1/250kHz) = 16us
        ADC_CH0 & ADC_INT_OFF & ADC_REF_VDD_VSS, // FOSC = 4 MHz
        0b0000000000000001 // wieso geht ADC_1ANA nicht?
    );

    // Open SPI
    OpenSPI1(SLV_SSON, MODE_00, SMPMID);

    // Initial ADC conversion and SPI reading
    ConvertADC();
    cmd_from_master.byte = spi_tranceive(0);
    
    /* MAIN LOOP:
     * At first we read the ADC value of the piezo-weight sensors if already present. 
     * Then we fill this data into a status package which is to be sent to our SPI master.
     * After that we await a command from our SPI master and send our status to it (tranceive).
     * If we got a color, we light our LEDs per PWM. If we got a command, we analyze it and take action.
     */
    while (1) {
        if (!BusyADC()) {
            adc = ReadADC() >> 2; // we just need 8bits from the returned 10bit sample
            ConvertADC(); // already start next conversion. Meanwhile we're gonna do stuff with SPI
        }
        
        current_status.data.value = adc;
        current_status.is_pressed = 0; // TODO: Analyze the adc value and set this one to 0 or 1
        cmd_from_master.byte = spi_tranceive(current_status.byte); // TODO: error handling needed: what if spi is not present? Will we operate on our own?
        if (cmd_from_master.is_rgb) {
            // we got a color
            PORTCbits.RC2 = 0; // Debug LED
            led_set_rgb(cmd_from_master.rgb.r*10, cmd_from_master.rgb.g*10, cmd_from_master.rgb.b*10); // TODO: introduce multiplicator to reach 100% PWM
        } else {
            // we got a command
            PORTCbits.RC2 = 1; // Debug LED
        }
    }
Exemplo n.º 11
0
unsigned short adc_busy_read()
{
    unsigned short result;

    // Beginn der A->D Umsetzung
    ConvertADC();
 
    // Warten bis die Umsetzung fertig ist
    while( BusyADC() );
    
    // Das Ergebnis in "result" speichern
    return ReadADC();
}
Exemplo n.º 12
0
void measureTemperature()
{
    int i;
    for(i=0;i<5;i++){
            // perform measurement on AN5 note that AN3 is the +Vref signal and is 7 volts
        //OpenADC(ADC_FOSC_4 & ADC_RIGHT_JUST & ADC_8ANA_0REF , ADC_CH5 & ADC_INT_OFF);
        SetChanADC(ADC_CH5);
        Delay10KTCYx(5);
        ConvertADC();
        while(BusyADC());
        temp[i] = ReadADC();
    }
}
Exemplo n.º 13
0
/*******************************************************************************
* FUNCTION NAME: Get_Analog_Value
* PURPOSE:       Reads the analog voltage on an A/D port and returns the
*                10-bit value read stored in an unsigned int.
* CALLED FROM:   user_routines.c, typically
* ARGUMENTS:     
*      Argument         Type        IO   Description
*     -----------   -------------   --   -----------
*     ADC_channel       alias       I    alias found in ifi_aliases.h
* RETURNS:       unsigned int
*******************************************************************************/
unsigned int Get_Analog_Value (unsigned char ADC_channel)
{
  unsigned int result;

  OpenADC( ADC_FOSC_RC & ADC_RIGHT_JUST & ifi_analog_channels,
          ADC_channel & ADC_INT_OFF & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS );
  Delay10TCYx( 10 );
  ConvertADC();
  while( BusyADC() );
  ReadADC();
  CloseADC();
  result = (int) ADRESH << 8 | ADRESL;
  return result;
}
Exemplo n.º 14
0
/*****************************************************************
* Function:			readIRSensor
* Input Variables:	none
* Output Return:	1 if there is IR
*					0 if there is no IR
* Overview:			Reads the valus for the IR and determs if there is IR
******************************************************************/
int readIRSensor()
{
    int ra0 = 0;
    SetChanADC(ADC_CH0);
    ConvertADC();
    while(BusyADC());
    ra0 = ReadADC();
    
    if(ra0 >= 500){
    	return 0;
    }else{
    	return 1;
    }	
}	
Exemplo n.º 15
0
void main(void) {
    int count;
    int size;
    unsigned int adcValue = 0;
    unsigned int adcValueOld = 0;
    char buffer[16];

    ConfigureOscillator();
    InitApp();

    lcd_init();
    lcd_enable();
    lcd_cursor_off();
    lcd_test();
    lcd_pos(2, 1);
    while (1) {
        ConvertADC();
        while (BusyADC());
        adcValue = ReadADC();
        if (adcValue != adcValueOld) {
            lcd_clear();
            //Linha 1
            lcd_pos(1, 1);
            memset(&buffer[0], 0, sizeof (buffer));
            sprintf(&buffer[0], "Step:%.4u %3.1f%%", adcValue, ((float) adcValue / 1023) * 100);
            size = (strlen(buffer) > sizeof(buffer)) ? sizeof(buffer) : strlen(buffer);
            lcd_write_buffer(buffer, size);
            for(count = 0; count < size; count++){
                while(BusyUSART());
                putcUSART((char)buffer[count]);
            }
            //Linha 2
            lcd_pos(2, 1);
            memset(&buffer[0], 0, sizeof (buffer));
            sprintf(&buffer[0], "Volts:%1.7fV", (float)adcValue * ((float)5 /1023));
            size = (strlen(buffer) > sizeof(buffer)) ? sizeof(buffer) : strlen(buffer);
            lcd_write_buffer(buffer, size);
            //Variável de controle
            adcValueOld = adcValue;
            for(count = 0; count < size; count++){
                while(BusyUSART());
                putcUSART((char)buffer[count]);
            }
        }
        for (count = 0; count < 40; count++) {
            __delay_ms(10);
        }
    }
}
Exemplo n.º 16
0
/******************************************************************************
  Function:
    void ADLsample(BYTE *data, const BYTE ADLoffset, const BYTE ch)
  Summary:
	Function to sample an analog pin and place the value in an array
  Conditions:
    * A/D Converter must be configured
    * Analog pins must be initilized
  Input:
	*data - pointer to data array
	ADLoffset - where in the data array to place the data to conform to ADL
	protcol
	ch - the analog channel (pin) to sample
  Return Values:
    none
  Side Effects:
	sampled value is added to the data array passed
  Description:

  ****************************************************************************/
void ADLsample(BYTE *data, const BYTE ADLoffset, const BYTE ch) {

    unsigned int temp;
	SelChanConvADC(ch);	// configure which pin you want to read and start A/D converter

	while(BusyADC());	// wait for complete conversion

	// put result in data array in accordance with specified byte location
    temp = (unsigned int)ReadADC();
	modifyRotary(&temp);
    data[ADLoffset] = ((BYTE *)&temp)[1];
    data[ADLoffset + 1] = ((BYTE *)&temp)[0];

	return;
}
Exemplo n.º 17
0
Arquivo: power.c Projeto: m2i/LASER
/* getArrayCurrent -- Major Function
 * Gather and convert the current provided
 * by the solar array, in mA
 */
int getArrayCurrent(void){
    int i;
    int average = 0;

    SetChanADC(PWR_I_AN_CH);

    for (i = 0; i < POWER_FILT; ++i){
        ConvertADC();
        while(BusyADC());
        average += ReadADC();
    }
    
    average /= POWER_FILT;
    average =(int)(average * POWER_BIT_MA);
    return average;
}
Exemplo n.º 18
0
Arquivo: power.c Projeto: m2i/LASER
/* getArrayVoltage -- Major Function
 * gathers and scales the voltage from
 * the output of the solar array, in mV
 */
int getArrayVoltage(void){
    int i;
    int average = 0;

    SetChanADC(PWR_V_AN_CH);

    for (i = 0; i < POWER_FILT; ++i){
        ConvertADC();
        while(BusyADC());
        average += ReadADC();
    }
    
    average /= POWER_FILT;
    average *= POWER_BIT_MV;
    return average;
}
Exemplo n.º 19
0
unsigned int GetCO()
{
    unsigned int CORaw=0;

    SetChanADC(ADC_CH0);

    ConvertADC();

    while(BusyADC());
    CORaw = ReadADC();

    //CloseADC();

    return CORaw;

}
Exemplo n.º 20
0
void measureSalinity()
{
	// send power on to measure circuit
	measureOn = 1;

	//Perform Measurement and convert to correct format  on AN0
   // OpenADC(ADC_FOSC_4 & ADC_RIGHT_JUST & ADC_8ANA_0REF , ADC_CH0 & ADC_INT_OFF);
    SetChanADC(ADC_CH0);
    Delay10KTCYx(5);
    ConvertADC();
    while(BusyADC());
    salinity = ReadADC(); //take value read and divide by 204.8 to get voltage read

	// power off measureing circuit
	measureOn = 0;
}
/*! **********************************************************************
 * Function: readDial(void)
 *
 * Include:
 *
 * Description: Read the position of the dial
 *
 * Arguments: None
 *
 * Returns: The dial position scaled by
 *************************************************************************/
unsigned int readDial(unsigned int max)
{
    unsigned int value;
    int divisor;

    //Sets the AD channel for the DIAL
    ADCON0 = ADC_DIAL_READ;

    //Begin convertion
    ConvertADC();
    while(BusyADC());
    value = ReadADC();
    if (value >= (ADC_MAX - 9)) return max;
    divisor = ADC_MAX/(max + 1);
    // Return a number from 0 - max
    return (value/divisor);
}
Exemplo n.º 22
0
/* Eval voltage on a channel
 * result on volt
 */
short V_Eval(unsigned char channel,signed float *voltage)
{
    signed float temp = 0;
    SelChanConvADC(channel);
    timeout = ADC_TIMEOUT;
    while(BusyADC() && timeout > 0); //Wait here until conversion is finished

    if (timeout == 0)
    {
        return KO;
    }

    temp = ReadADC();
    *voltage = (temp / 1024.0) * 5.0;
    
    return OK;
}
Exemplo n.º 23
0
Arquivo: hw.c Projeto: BeeeOn/sensors
uint16_t GetBatteryStatus(uint16_t *value) {
    BatteryInit();
    ADCON0 = 1; //enable a/d module
        
    ADCON0bits.GO = 1;
        
    while(ADCON0bits.DONE);
    while(BusyADC());
        
    uint16_t adc_val = ADRES*3.3/1024*100;
        
    //printf("Battery: %d \n", adc_val);
        
    ADCON0 = 0; //disable a/d module
    //printf("BAT: %d\n", adc_val);
    *value = adc_val;
    return adc_val;
}
Exemplo n.º 24
0
int GetVOC()
{
    unsigned int VOC_Raw=0;

    SetChanADC(ADC_CH1);

    ConvertADC();

    while(BusyADC());
    VOC_Raw = ReadADC();

    //CloseADC();
    

    return VOC_Raw;


}
Exemplo n.º 25
0
int readADC(BYTE address) {
  int data;

  // Choosing ADC channel (override ADC_CH0)
  switch(address) {
    case 0: SetChanADC(ADCCHAN(0)); break;
    case 1: SetChanADC(ADCCHAN(1)); break;
    case 2: SetChanADC(ADCCHAN(2)); break;
    case 3: SetChanADC(ADCCHAN(3)); break;
    case 4: SetChanADC(ADCCHAN(4)); break;
    default: return -1;  // non existing channel
  }

  delay_us(125);       // wait until channel selection is stable
  ConvertADC();        // Start conversion
  while (BusyADC());   // Wait for ADC conversion
  data = ReadADC();    // Read result

  return data;
}
Exemplo n.º 26
0
/* **********************************************************************
 * Function: readTempx2(void)
 *
 * Include: ADC.h
 *
 * Description: Reads the temperature from the Temp sensor
 *
 * Arguments: None
 *
 * Returns: temp x 2 (in deg celsius) as an unsigned char
 *************************************************************************/
unsigned char readTempx2(void)
{
    int ad_result;
    unsigned char tempx2;

    //Sets the ADC channel to read the temperature
    SetChanADC(ADC_TEMP_READ);

    //Performs the conversion
    ConvertADC();
    while(BusyADC());
    ad_result = ReadADC();

    //10mV per deg C, which 0V at 0deg, with the ADC res ~5mV
    tempx2 = ad_result;

    lastTempx2 = tempx2;
    
    return tempx2 + calibration_offset;
}
Exemplo n.º 27
0
unsigned int MPX6115_uiGetPression(void)
{
	int iResult; 
	unsigned long ulPression;
	OpenADC(ADC_FOSC_32 & ADC_RIGHT_JUST & ADC_12_TAD, ADC_CH0 & ADC_INT_OFF, 0); //open adc port for reading
	ADCON1 =0x00; //set VREF+ to VDD and VREF- to GND (VSS)
	SetChanADC(ADC_CH5); //Set ADC to Pin 5
	Delay1KTCYx(5);
	ConvertADC();
	while( BusyADC() );
	iResult = ReadADC();
	CloseADC();
	ulPression=((unsigned long)iResult*5000/1024 + 475)*10 /45;
#ifdef DEBUG
	printf("Pression %ld %x\n\r",ulPression,iResult);
#endif
	
	ADCON1=0b00001111;			// Digital Channel Allocation 
	return (unsigned int)ulPression;
}
Exemplo n.º 28
0
Arquivo: hax.c Projeto: ellbur/hax
uint16_t analog_get(AnalogInIndex ain) {
	if ( ain > kAnalogSplit ) {
		/* get oi data */
		/* we may not want to trust "ain" */
		return rxdata.oi_analog[ ain - kAnalogSplit ];
	}
	/* kNumAnalogInputs should be checked somewhere else... preferably at
	 * compile time.
	 */
	else if ( ain < kNumAnalogInputs && NUM_ANALOG_VALID(kNumAnalogInputs)  ) {
		/* read ADC */
		SetChanADC(ain);
		Delay10TCYx( 5 ); /* Wait for capacitor to charge */
		ConvertADC();
		while( BusyADC() );
		return ReadADC();
	}
	else {
		return 0xFFFF;
	}
}
Exemplo n.º 29
0
void Button_update(void)
{
	unsigned char i = 0;

	unsigned int mask = 0;
	unsigned int stateLed = 0;
    unsigned int temp_i = 0x0001;
	en_button_state_t enSampledState;
                                                                                                                       
	for (i = 0; i < 16; i++)
	{
		/* Подаем напряжение на кнопку, которую считаваем*/
		Sethc595(temp_i << i);	
		/* Измеряем напряжение на выходе*/
		ConvertADC();
    	while(BusyADC());
		ADC_value = ReadADC();
		if (ADC_value > 100)
			enSampledState = StateHigh;
		else
			enSampledState = StateLow;
		/* Сравниваем состояние кнопки с предыдущим */
		if (m_astcButtonCtrl[i].currState != enSampledState)
		{
			m_pfnCallback(i, enSampledState);
			m_astcButtonCtrl[i].currState = enSampledState;
			if  (enSampledState == StateHigh)
				m_astcButtonCtrl[i].saveState = ~m_astcButtonCtrl[i].saveState;	
		}			 
		
	}
	/* В перерывах между сканированием зажигаем светодиоды*/
	for (i = 0; i < 16; i++)
	{
		if ((m_astcButtonCtrl[i].saveState) && (m_astcButtonCtrl[i].light))
			stateLed = stateLed | (temp_i << i); 			
	}
	Sethc595(stateLed);
}
Exemplo n.º 30
0
unsigned int ADC_call(char c)
{
	int adc;
	char ADC_CHAN;
	if (c == 0)
		ADC_CHAN = ADC_CH9;
	else if (c == 1)
		ADC_CHAN = ADC_CH8;
	else if (c == 2)
		ADC_CHAN = ADC_CH10;
	else
		ADC_CHAN = ADC_CH12;

	OpenADC(ADC_FOSC_32 & ADC_LEFT_JUST & ADC_2_TAD
	, ADC_CHAN & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS
	, 0);	
	Delay10TCYx(5);  // Delay for 5us
	ConvertADC();  // Start conversion
	while(BusyADC()); // wait for completion
	adc = ReadADC();  // Read result
	CloseADC();  // Disable A/D converter
	return adc;	
}