/* Define ATmega128 I2C Bit rate at using 16MHz(fix fCLK)*/
#define _80K        92
#define _100K       72
#define _400K       12

#define TSC2003_ADDR      0x90
#define TSC2003_CMD_XPOS  0xd1
#define TSC2003_CMD_YPOS  0xc1

/* Define I2C Device & Sub Address */
#define	ACK	     0
#define	NACK         1

void init_I2C(void)
{
    TWSR = 0x00;
    TWBR = _400K;  
}

void TSC2003_setup_cmd(BYTE cmd)
{
// START 1 bit 출력
   TWCR = 0xA4;
   while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x08));

// Write Address 출력
   TWDR = TSC2003_ADDR;
   TWCR = 0x84;
   while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x18));

// Command 출력
   TWDR = cmd;
   TWCR = 0x84;
   while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x28));

// STOP 1 bit 츨력
   TWCR = 0x94;

// 입력 Delay
   Delay_ms(2);
}

unsigned int TSC2003_data_read(BYTE cmd)
{
   unsigned char temp;
   unsigned int ret = 0;
   
// START 1 bit 출력
   TWCR = 0xA4;
   while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x08));

// Write Address 출력
   TWDR = TSC2003_ADDR;
   TWCR = 0x84;
   while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x18));

// Command 출력
   TWDR = cmd;
   TWCR = 0x84;
   while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x28));

// START 1 bit 출력 repeat
   TWCR = 0xA4;
   while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x10));

// Read Address 출력
   TWDR = TSC2003_ADDR + 0x01;
   TWCR = 0x84;
   while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x40));

// Data read
   TWCR = 0xc4;
   while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x50));
// Data 입력
   temp = TWDR;
   ret = (unsigned int)temp;
   ret <<= 8;

// Data read
   TWCR = 0x84;
   while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x58));
// Data 입력
   temp = TWDR;
   ret += temp;
   
// STOP 1 bit 츨력
   TWCR = 0x94;
   
   return ret;
}
