Click here to Skip to main content
15,887,927 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I have written code to both setup and read the voltage going to the PICs onboard ADC, and displaying the digital value on an LCD. I ran the code with analog channel 9, and it worked perfectly, displaying the correct value on the LCD. However, when I changed to channel 7, I ran the same code and it didn't work (it displayed an incorrect value). I'm just about positive that my setup of the ADC and Analog channels are correct. Also pretty sure that it is the ADC that is the problem.

Here is some code:

C#
void setupADC(unsigned char channel)
{
    ADCON1 = 0b00010000;
    // Sets ad to Fosc/8
    ADCON0 = (channel << 2) + 0b10000001;
    // Right Justified, Vdd ref, channel adc, enable
    ADIE = 0;
    ADIF = 0; // Turns off AD interrupt and resets AD interrupt flag

}

unsigned int readADC()
{
    unsigned int ADCv;
    unsigned char ADCvh,ADCvl;
    GO = 1;
    while(!ADIF) continue;
    ADCvl = ADRESL;
    ADCvh = ADRESH;
    ADCvh = ADRESH & 0x03;
    ADCvh = ADCvh>>8;
    ADCv = ADCvl + ADCvh;
    return ADCv;
}


C#
ANSEL = 0b10000000; // AN7 is analog input, all others are digital
ANSELH = 0b0111; // AN10,9,and 8 are all analog inputs

TRISB = 0b10110000;
TRISA = 0b00101000;
TRISC = 0b11001010;

	setupADC(7);
;



Then in a while loop, I just use readADC() then display on LCD. When I input a dc voltage of 2.5 V, the ADC returns 255, but if my ADC is 10 bit, I should be getting 512.

Thanks,
GabeA
Posted

1 solution

You declared ADCvh as an unsigned char (8 bit value).

The last 3 lines of readADC() you shift that 8 bit value by 8:

C++
ADCvh = ADCvh>>8;
ADCv = ADCvl + ADCvh;
return ADCv;


Shifting an 8 bit value right by 8 is an undefined operation.

A C compiler is allowed to do anything it wants with that.

The most likely implementations are that it either results in 0 or in no shift being performed at all.

Perhaps what you meant was:
ADCv = (((unsigned int)(ADCvh & 0x03)) << 8) + ADCvl;
return ADCv;
 
Share this answer
 
Comments
GabeA 14-Jun-12 8:50am    
Yup, worked like a charm. I owe you one. Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900