/*

TouchPad routines
AD7142ACPZ SPI

CCS compiler

TechDesign Electronics (c) April 2009. 


www.techdesign.be
info@techdesign.be

#bit touch_sclk	=pb.3		// o -->	(to touchpad) SCLK
#bit touch_cs	=pb.4		// o -->	(to touchpad) !CS
#bit touch_int	=pb.5		// i <--	(from touchpad) !INT
#bit touch_sdi	=pb.6		// o -->	(to touchpad) SDI
#bit touch_sdo	=pb.7		// i <--	(from touchpad) SDO



*/



unsigned int16 touch(short m_rw,unsigned int16 m_addr, unsigned int16 m_data);		// r/!w

void touch_calib(void);

////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int16 touch(short m_rw,unsigned int16 m_addr, unsigned int16 m_data)
{
int8 s;
unsigned int16 mm_addr=0,mm_data=0;


touch_sclk=1;
delay_cycles(5);
touch_cs=0;
delay_cycles(5);

if(m_rw==0){mm_addr=(m_addr|0xe000);}	// write to touchpad
else if(m_rw==1){mm_addr=(m_addr|0xe400);}	// read from touchpad

for (s=15;s!=255;s--){			// address

					touch_sclk=0;delay_cycles(5);
					touch_sdi=bit_test(mm_addr,s);		//printf("%u",touch_sdi);
					
					touch_sclk=1;
					delay_cycles(5);
					}

//delay_us(200);

if(m_rw==0){

			//printf(" rw=0 ");
			}
//else if(m_rw==1){printf(" rw=1 ");}



for (s=15;s!=255;s--){			// data

					touch_sclk=0;delay_cycles(5);
					if(m_rw==1){		// read
								if(touch_sdo==1){bit_set(mm_data,s);}	//printf("1");}
								//else if(touch_sdio==0){printf("0");}
								
								}
					else if(m_rw==0){touch_sdi=bit_test(m_data,s);}	// write
					touch_sclk=1;
					delay_cycles(5);
					}

//touch_sck=0;nop;nop;

touch_cs=1;

//printf(" mm_data=%x ",mm_data);
return mm_data;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void touch_calib(void)
{

unsigned int16 CDC_cd_0;
unsigned int16 AFE_off_0;

while(1){

	if(INPUT(touch_int)==0){
						//printf(" *** !INT ***");

						CDC_cd_0 = touch(1,0x000b, 0x0000);		//
						printf(" CDC_cd_0=%Lx",CDC_cd_0);

						AFE_off_0 = touch(1,0x0082, 0x0000);		
						printf(" AFE_off_0=%Lx",AFE_off_0);

						if((CDC_cd_0>0x8000)&&(AFE_off_0<0xfe00)){

											AFE_off_0 += 0x0100;
											touch(0,0x0082, AFE_off_0);

											}						


							}

		}			
	


}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
