Looking for your assistance in solving a strange ADC problem. My code is currently set up to return an 8 bit result. The trouble is, with the analog pin in question tied to VDD, instead of returning 255 like one would expect, it's returning 186. I think I may have a variable casting problem or something like that but I'm not too sure. Thanks in advance!
Code:
#include <pic.h>
__CONFIG(INTCLK & WDTDIS & PWRTDIS & MCLREN & UNPROTECT & UNPROTECT & BORDIS & IESODIS & FCMDIS);
/* A2D module initalization*/
void init_a2d(void)
{
ADCON1 = 0x60; // select sample rate
ADFM = 0; // left justify result
VCFG = 0; // VDD reference voltage
ADON = 1; // turn on ADC
}
/* Return an 8 bit result */
unsigned char read_a2d(unsigned char channel)
{
volatile unsigned int value;
ADCON0 &= 0xC1; // clear current channel select
ADCON0|=(channel<<2); // apply the new channel select
GODONE=1; // initiate conversion on the selected channel
while(GODONE)continue;
return(ADRESH); // return an 8 bit result
}
void main(void)
{
unsigned int x;
GIE=0; // no interupts
TRISA = 0x4;
TRISC = 0x00;
ANSEL = 0x4;
ANSELH = 0x0;
init_a2d(); // initialize the A2D module
while(1)
{
x=read_a2d(2); // sample the analog value on AN2
if (x > 186)
{
PORTC = 0xFF;
}
else
{
PORTC = 0;
}
}
}