Click here to Skip to main content
13,146,402 members (44,785 online)
Rate this:
Please Sign up or sign in to 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:

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;

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;

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.

Posted 13-Jun-12 8:09am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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

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

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;
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.170915.1 | Last Updated 13 Jun 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100