/********************************************************************
* FileName:        example ADC.c
* Processor:       PIC18F4520
* Compiler:        MPLAB C18 v.3.06 
*
* This file uses the LCD to display the value of the RA0 potentiometer
* The AD conversion uses 10 bits and this program prints those bits
*   in decimal.
*
* Author               Date        Comment
* Dave Fisher         9/9/07
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


/** Header Files ***********************************************/     
#include <p18f4520.h> 
#include "LCD Module.h"	
#include <adc.h>		
#include <stdio.h>		

/** Define Constants Here ******************************************/

/** Local Function Prototypes **************************************/

/** Configuration Bits **************************************/
#pragma config OSC = EC  // External 4MHz crystal
#pragma config WDT = OFF
#pragma config LVP = OFF
#pragma config BOREN = OFF
#pragma config XINST = OFF

/** Global Variables *********************************************/
char line1[20];  //  Must be at least 17 character long, minimum = 16 characters + 1 for null terminator
char line2[20];  //  Changed to 20 to allow for accidental spaces at the end of the string
int RA0result, RB0result;

/*****************************************************************
* Function:        void main(void)
******************************************************************/
#pragma code

void main (void)
{	
  XLCDInit();
  XLCDClear();

  // configure A/D convertor
  // config 1 = Setup the timing to a conservative value (you don't need to ever change this)
  // config 2 = Use channel 0, not interrupts off, use the power and ground as referrences
  // portconfig = 0x0E setup only analog 0 as a possible analog input pin
	
  OpenADC(ADC_FOSC_8 & ADC_RIGHT_JUST & ADC_12_TAD, 
  	ADC_CH0 & ADC_INT_OFF & ADC_REF_VDD_VSS, 
  	0x0E);

  //  This library function simply set the following SFR's
  //    ADCON0 = 0x01;        //### Turn On ADC	
  //    ADCON1 = 0x0E;        //### Select Vref+ = VDD, Vref- = VSS, AN0 = Analog Input
  //    ADCON2 = 0xA9;        //### Acquisition delay 12 TAD, A/D conversion clock 8TOSC, Right Justified

  while (1) {
    SetChanADC( ADC_CH0 );		// Select the pin
    ConvertADC(); 			// Start conversion
    while( BusyADC() ); 		// Wait for completion
    RA0result = ReadADC(); 		// Read result
		
    sprintf(line1, "RA0 ADC -> %#4u", RA0result);
    XLCDL1home();
    XLCDPutRamString(line1);	
		
    sprintf(line2, "  %#12.10b  ", RA0result);
    XLCDL2home();
    XLCDPutRamString(line2);
  }   	
}