2

I am having troubles with my curiousity HPC board. I am new to microchip and i want to read the analogValue of the onboard potentiometer. I am using a serial converter to display the value in a terminal on my PC. It works fine, EXCEPT when i fully turn the potentiometer from beginning to end, the analogValue goes from 0 to 255, drops to 0, goes up to 255, drops to 0, goes up to 255, drops to 0 and goes up to 255. I expected it to go from 0 to 1023. All my variables are 16 bits. The uC is the PIC16F18875 and the serial converter is UM230XB.

How can this be? All the variables and constant have the right size (unless i am missing one)

This is the main.c:

void main(void){

   SYSTEM_Initialize();


   static uint16_t adcResult; // Used to store the result of the ADC

   adcResult = ADCC_GetSingleConversion(POT_CHANNEL);


       IO_RC7_SetLow();
       console_print("Value = ");
       console_print_dec_char(adcResult);
       console_print("\t\n\r");
       __delay_ms(100);

This is the ADCC_GetSingleConversion function:

adc_result_t ADCC_GetSingleConversion(adcc_channel_t channel){
// select the A/D channel
ADPCH = channel;  

// Turn on the ADC module
ADCON0bits.ADON = 1;

//Disable the continuous mode.
ADCON0bits.ADCONT = 0;    

// Start the conversion
ADCON0bits.ADGO = 1;

// Extra NOP() instruction required; See rev. A2 errata:  http://ww1.microchip.com/downloads/en/DeviceDoc/80000669C.pdf 
NOP();    

// Wait for the conversion to finish
while (ADCON0bits.ADGO)
{
}


// Conversion finished, return the result
return ((adc_result_t)((ADRESH << 8) + ADRESL));

ADC_result_t is also 16 bits.

1 Answers1

0

You should cast the 8 Bit value of ADRESH to a 16 Bit value before the left shift, otherwise the result of the shift is always 0.

 return ((adc_result_t)(((uint16_t)ADRESH << 8) + ADRESL));
Mike
  • 4,041
  • 6
  • 20
  • 37