#include <htc.h>
/* Basic A2D sample code for an PIC16F87x device.
* This code willl set up the A2D module to return an
* 8-Bit result. If greater precision is needed, a 10-Bit
* result can be returned if read_a2d() is modified to
* return the short ((ADRESH<<8)+(ADRESL)). Note also that
* ADCON1 should be set to 0x80 in the init_a2d() routine
* instead of zero.
*
* This code will sample an A2D value on analog port RA0, and it's value
* will be used to move a LED's position across PORTB.
*
* This project can be demonstrated on the Microchip PICDEM2 board.
*/
__CONFIG(DEBUGEN & WDTDIS & LVPDIS); // Setup the configuration word for ise with ICD2
/* Sample code to set up the A2D module */
void init_a2d(void){
ADCON0=0; // select Fosc/2
ADCON1=0; // select left justify result. A/D port configuration 0
GODONE=1; // turn on the A2D conversion module
}
/* Return an 8 bit result */
unsigned char read_a2d(unsigned char channel){
channel&=0x07; // truncate channel to 3 bits
ADCON0&=0xC5; // clear current channel select
ADCON0|=(channel<<3); // apply the new channel select
GODONE=1; // initiate conversion on the selected channel
while(GODONE)continue;
return(ADRESH); // return 8 MSB of the result
}
void main(void){
unsigned char x;
init_a2d(); // initialise the A2D module
GIE=0; // we don't want interrupts
TRISB=0xF0; // the lower four bits of POTRB will be used in output mode
for(;;){
x=read_a2d(1); // sample the analog value on RA0
PORTB = (8>>(x>>6)); // Use the 2 MS Bits of the result to select the bit position of the LED on PORTB
}
}