
#include <math.h>

#include "type.h"
#include "rtp_drv.h"


#include "delay.h"
#include "adc_drv.h"
#include "eport_drv.h"
#include "pwm_drv.h"
#include "i2c_drv.h"
#include "tp_drv.h"


extern u16 LCD_XSIZE_TFT, LCD_YSIZE_TFT;

#if TOUCHPANEL == RESISTIVE

//X+:AIN[4]
//X-:AIN[6]
//Y+:AIN[5]
//Y-:AIN[7]
void ADC_Initial(void)
{
	ADC->CFGR2 |= ((10-1)<<8);         	 		//10MHz/10=1MHz
	ADC->CFGR2 |= 0x20;											// 启动计数位	
//	ADC->CFGR2 |= 2*72/6/12;							// 启动计数位	

	ADC->CFGR1 &=~(1<<20);								//不连续转换
	ADC->CFGR1 &=~(7<<24);								//序列长度为1单位
	ADC->CFGR1 &=~(3<<8);									//分辨率:12
	ADC->CFGR1 &=~(1<<10);								//右对齐
	ADC->SMPR = 0x20;	//采样时间
}

UINT16 Get_ADC_Val(UINT8 ADC_Channel_x)
{
	UINT32 adcisr = 0,i;
	
	UINT16 Val = 0;
	
	ADC_Initial();
	
	ADC->CHSELR1 = ADC_Channel_x;
	ADC_Cmd(ADC_EN);
	
	for (i = 0; i < 4; i++)
	{
		ADC_StartConv();
		DelayMS(1);
		while (EOSEQ !=(ADC->ISR & EOSEQ));
		ADC->ISR |= EOSEQ;
		ADC_StopConv();
		
		if(i == 0)
		{// 第一个数丢掉
			adcisr = (ADC->uFIFO_DAT.FIFO)&0xFFFF;
			adcisr = 0;
			continue;
		}
		adcisr += (ADC->uFIFO_DAT.FIFO)&0xFFFF;			
	}
	
	ADC_Cmd(ADC_DIS);

	return ((adcisr>>3)&0x0fff);
}

bool PenDown_Detect(void)
{
	UINT16 ain0_Value;

	RTP_XM_OUT; RTP_XM_UP;   RTP_XM_LEVEL(0);       //X-配置为GPIO上拉输出低电平
	RTP_XP_OUT; RTP_XP_UP;   RTP_XP_LEVEL(0);       //X+配置为GPIO上拉输出高电平
	RTP_YM_IN; RTP_YM_UP;									      //Y-配置为GPIO上拉输入
	RTP_YP_IN; RTP_YP_UP;         							//Y+配置为GPIO上拉输入

	DelayUS(5);
	
//	Get_ADC_Val(ADCCH_0);
	ain0_Value = Get_ADC_Val(ADC_CH0);	// Y+取ADC值
	
//	printf("AIN0=%d\r\n",ain0_Value);

	if(ain0_Value<1000)
	{
//		printf("down:AIN0=%d\r\n",ain0_Value);
		return 0;
	}
	else 
	{
//		printf("up:AIN0=%d\r\n",ain0_Value);
		return 1;
	}
}


#endif



