#include <pic.h>
#include <delay.c>
#include "lcd.h"

__CONFIG(XT & WDTDIS & PWRTEN & BORDIS & LVPDIS & WRTEN & DEBUGDIS & DUNPROT & UNPROTECT);

char * utoa(char * buf, unsigned int val, int base);
unsigned int ReadADC(unsigned char ADC_Channel);
void init(void);

void 
init(void) 
{
	TRISA	= 0x3f;
	ADCON1	= 0b10000100;
	ADCON0=0; // select Fosc/2
	ADON=1; // turn on the A2D conversion module
	INTCON = 0b00000000;
	GIE = 0;
}



char *											
utoa(char * buf, unsigned int val, int base)	.
{
	unsigned	v;
	char		c;

	v = val;
	do {
		v /= base;
		buf++;
	} while(v != 0);
	*buf-- = 0;
	do {
		c = val % base;
		val /= base;
		if(c >= 10)
			c += 'A'-'0'-10;
		c += '0';
		*buf-- = c;
	} while(val != 0);
	return buf;
}



/*--------------------------------------------------------------- 
	Reads the ADC level input on a specified ADC channel.
	Takes in an 10-bit ADC channel number.
	Returns an 10 bit number that signifies this level.
	Approximate sampling time = 76.8us
	---------------------------------------------------------------*/
unsigned int ReadADC(unsigned char ADC_Channel)
{
	
	volatile unsigned int ADC_VALUE;

	/* Selecting ADC channel */
	ADCON0 = (ADC_Channel << 3) + 1;	 /* Enable ADC, Fosc/2 */			

	ADIE	  =	0;		 	 		 	 /* Masking the interrupt */
	ADIF 	  = 0;						 /* Resetting the ADC interupt bit */						
	ADRESL	=	0; 						 /* Resetting the ADRES value register */
	ADRESH	=	0; 						 

	ADGO = 1;				  			 /* Staring the ADC process */					
	while(!ADIF) continue;			     /* Wait for conversion complete */ 			

	ADC_VALUE	=	 ADRESL;			 /* Getting HSB of CCP1 */
	ADC_VALUE	+= (ADRESH << 8);		 /* Getting LSB of CCP1 */

	return (ADC_VALUE);     			 /* Return the value of the ADC process */
}

void 
main(void) 
{
	char  ertek[5];
	unsigned int a =0;
	lcd_init();
	DelayMs(100);
	lcd_goto(0);
	lcd_puts("DA erteke:");
	while(1)
	{
		a = ReadADC(0);
		utoa(ertek,a,10);
		lcd_goto(0x40);
		lcd_puts(ertek);
		DelayMs(250);
		DelayMs(250);
		
	}

}
