As I mentioned in my "p.s.", you are not setting the ADCx bits, so they are defaulting to 0b000, which means the ADC is running at Fosc/2 which is way too fast at 20MHz.
From Table 11-1 in the datasheet, a 20MHz oscillator means you can only use Fosc/32 or Fosc/64,
so try setting <ADCS1:ADCS0> in ADCON0 to 0b10
You still did not mention HOW you are testing this. There is nothing in your code to output the value read, so I assume you must be running this in the debugger and inspecting the ADCresult variable directly.
Note that depending upon the compiler optimisation level, it could decide to not bother updating that variable at all, as you never use its value anywhere, and you have not declared it as "volatile".
A few other points.
[1] Some of the old PIC16F chips had a small problem in that if you checked the ADC's GO/DONE bit in the very next instruction cycle after setting it, it may not have got set yet.
It is possible that the compiler may generate assembly code doing just that from your source, so it would be a good idea to insert a NOP or something else between the instruction setting ADCON0bits.GO =1, and the test for conversion complete.
[2]
- Code: Select all
#define _XTAL_FREQ 8000000
If your clock is 20MHz, then this should be:
- Code: Select all
#define _XTAL_FREQ 20000000
however it doesn't matter in this program, as you don't use any of the built in delay macros, so the _XTAL_FREQ value is never used.
[3]
- Code: Select all
#include <pic16f876.h>
#include <stdlib.h>
#include <stdio.h>
You don't need any of these.
The PIC specific header has already been included for you by xc.h, so you are just doing it a second time.
There is nothing in your code requiring stdlib or stdio. There rarely is in an embedded program.