#include "adc.h" 
#include "string.h"
#include "stdio.h"


uint8_t buf[10] = {0};
uint16_t adc_val = 0;


void ADC_Init()
{
	SYSCON |= 0xC0;//系统时钟不分频
	CKCON = 0x00;	
	P3CR = 0x00;
	P3PCR = 0x00;
	AENCON0 = 0x0F; //adc输入使能
	AENCON1 = 0x00;	
	ADCH		= 0x00;
	ADCON 	= 0x80;	//使能adc，选择内部参考电压
  ADT			= 0x2F; //adc时钟为系统时钟8分频，采样时间为15个adc时钟  0x2F 1Mhz   0x0F 2Mhz

}


void  get_adc_val(uint8_t channel)
{
    ADCH |= channel;	//选择通道	
    ADCON |= 0x01;
		while(ADCON & 0x01); // 等待转换完成	
		adc_val = ((uint16_t)ADDH << 2) |(ADDL & 0x03);
	  ADCH = 0x00; //清零等待下次赋值

}

void ADC_Test(void)
{
	uint8_t temp;

	delay_ms(50);
	ADC_Init();
	Uart_Init();


	while(1)
	{	
		if(SCON & 0x01)
		{
			SCON ^= 0x01;
			temp = SBUF;
			switch(temp)
			{
				case '0': 
								get_adc_val(0x00);
								sprintf(buf,"CH0:%d\r\n",adc_val);
								sendString(buf);
					break;
				case '1': 
								get_adc_val(0x01);
								sprintf(buf,"CH1:%d\r\n",adc_val);
								sendString(buf);
					break;
				case '2': 
								get_adc_val(0x02);
								sprintf(buf,"CH2:%d\r\n",adc_val);
								sendString(buf);
					break;
				case '3': 	
								get_adc_val(0x03);
								sprintf(buf,"CH3:%d\r\n",adc_val);
								sendString(buf);
				  break;
				default:
					break;				
			}			
		}
	}
}

