I've been struggling with this for hours now and am officially chasing my tail.
Not seeing the expected behavior on my physical circuit, I started playing with the simulator. Every time I set the GO_DONE bit in ADCON0, I get a warning from the simulator that says "ADC-W101: Selected channel is configured as digital IO. The channel selected:X." Where X is whichever channel I've selected (I've tried AN0 and AN2 so far with identical results).
The first goal of this program is just to blink the LED on GPIO4 at a speed that is proportional to the input voltage to the ADC (0-5V).
I'm confident I must be missiong something on my setup, but I've been through the datasheets and countless examples online and have been unable to spot the problem.
Here is the code:
I appreciate any help or guidance!
Not seeing the expected behavior on my physical circuit, I started playing with the simulator. Every time I set the GO_DONE bit in ADCON0, I get a warning from the simulator that says "ADC-W101: Selected channel is configured as digital IO. The channel selected:X." Where X is whichever channel I've selected (I've tried AN0 and AN2 so far with identical results).
The first goal of this program is just to blink the LED on GPIO4 at a speed that is proportional to the input voltage to the ADC (0-5V).
I'm confident I must be missiong something on my setup, but I've been through the datasheets and countless examples online and have been unable to spot the problem.
Here is the code:
Code:
#include <htc.h>
#include <stdio.h>
#define _XTAL_FREQ 4000000
#define _ADCBITS 10;
#define _ADC_CLOCK3;
#define _ADC_SAMPLEUS 50;
__CONFIG(FCMEN_OFF & WDTE_ON & PWRTE_ON & MCLRE_OFF & IESO_OFF & CP_OFF & BOREN_OFF & FOSC_INTOSCIO);
void config_ADC(void);
int read_ADC(void);
bit on_state;
unsigned char delay;
volatile unsigned int count;
void main()
{
config_ADC();
while(1)
{
on_state = ~on_state;
GPIObits.GP4 = on_state;
count = 1000 * read_ADC();
while(count>0)
{
count--;
}
}
}
void config_ADC(void) {
/* Turn off all comparators */
CMCON0 = 7;
/* Set the ADC Control register per Data sheet */
ADCON0 = 0; //initialize to zero
ADCON0bits.VCFG = 0; // reference Vdd
ADCON0bits.CHS = 0b010; // read AN2
ADCON0bits.ADON = 1; // turn ADC on
ADCON0bits.ADFM = 1; // right-justify for 10-bit ADC
/* Set all ports except GP0 to digital (0) */
ANSEL = 0;
ANSELbits.ANS = 0b0100; // set AN2 to analog
ANSELbits.ADCS = 0b001; // set freq to fosc/8
/* Set all pins to output except GP0 (to be used as ADC input)*/
TRISIO = 0;
TRISIObits.TRISIO2 = 1; // set AN2/GPIO2 to input
TRISIObits.TRISIO3 = 1; // set MCLR/GPIO3 to input
}
int read_ADC(void)
{ // start an ADC conversion and return the result
int ret = 0;
//__delay_ms(5);
ADCON0bits.GO_DONE = 1; //start conversion
while(ADCON0bits.GO_DONE); // wait for conversion
ret = (ADRESH & 0x3) << 8; // get
ret += ADRESL; // result
return ret;
}
I appreciate any help or guidance!