Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Embedded C ANSI PIC
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;
 
	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 13-Jun-12 9:09am
GabeA190

1 solution

Rate this: bad
good
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;
  Permalink  
Comments
GabeA at 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
0 OriginalGriff 195
1 ProgramFOX 130
2 Maciej Los 105
3 Sergey Alexandrovich Kryukov 85
4 Afzaal Ahmad Zeeshan 82
0 OriginalGriff 6,564
1 Sergey Alexandrovich Kryukov 6,048
2 DamithSL 5,228
3 Manas Bhardwaj 4,717
4 Maciej Los 4,150


Advertise | Privacy | Mobile
Web01 | 2.8.1411022.1 | Last Updated 13 Jun 2012
Copyright © CodeProject, 1999-2014
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