读取x,y数据总是255,正常应该为x=0,y=255; or x=255,y=0.查了好久没有发现问题。 程序如下: #include <REG51.h> #include "intrins.h"
typedef unsigned char UINT8; typedef unsigned int UINT16; typedef unsigned long UINT32;
/*Address Byte 1 0 0 1 0 A1 A0 R/W |_____________| |_____| fixed bits input pins read"1"/write"0" */ #define TSC2003_WRITE 0x90 //1001 0000 #define TSC2003_READ 0x91 //1001 0001
/*Command Byte C3 C2 C1 C0 PD1 PD0 M X |_____________| |______| Configuration bits power_down bits mode bit reserved */ //1011 0000 reserved #define COMMAND_X 0xc0 //1100 0000 #define COMMAND_Y 0xd0 //1101 0000 #define COMMAND_Z1 0xe0 //1110 0000 #define COMMAND_Z2 0xf0 //1111 0000
#define I2C_DELAY 2
unsigned char data touch_x,touch_y;
sbit SDIO = P1^6; sbit SCLK = P1^7;
void ShortDelay(unsigned char time) { while(--time); }
void i2c_start(void) { SDIO = 1; SCLK = 1; ShortDelay(I2C_DELAY); SDIO = 0; ShortDelay(I2C_DELAY); SCLK = 0; ShortDelay(I2C_DELAY); }
void i2c_stop(void) { SCLK = 0; ShortDelay(I2C_DELAY); SDIO = 0; ShortDelay(I2C_DELAY); SCLK = 1; ShortDelay(I2C_DELAY); SDIO = 1; }
UINT8 i2c_byte_wr(UINT8 dat) /* return 0 --> ack */ { UINT8 i; UINT8 temp_value = 0;
for(i=8; i!=0; i--) { SCLK = 0; ShortDelay(I2C_DELAY); SDIO = (bit)(dat & 0x80); ShortDelay(I2C_DELAY); dat <<= 1; SCLK = 1; ShortDelay(I2C_DELAY); }
SCLK = 0; ShortDelay(I2C_DELAY); SDIO = 1; ShortDelay(I2C_DELAY); SCLK = 1; ShortDelay(I2C_DELAY); temp_value = SDIO;
return temp_value; }
UINT8 i2c_byte_rd(UINT8 ack) { UINT8 i, temp_value; SDIO = 1; temp_value = 0; ShortDelay(I2C_DELAY);
for(i=8; i!=0; i--) { SCLK = 0; ShortDelay(I2C_DELAY); SCLK = 1; ShortDelay(I2C_DELAY); temp_value <<= 1; if(SDIO) temp_value++; ShortDelay(I2C_DELAY); }
SCLK = 0; ShortDelay(I2C_DELAY); SDIO = ack; ShortDelay(I2C_DELAY); SCLK = 1; ShortDelay(I2C_DELAY); SCLK = 0;
return temp_value; }
void write_tsc2003(unsigned char address,unsigned char command) { i2c_start(); i2c_byte_wr(address); i2c_byte_wr(command); i2c_stop(); }
unsigned int read_tsc2003(unsigned char address) { unsigned int retValue; i2c_start(); i2c_byte_wr(address); retValue = i2c_byte_rd(0)*0x100+i2c_byte_rd(1); i2c_stop(); retValue>>=4; return (retValue); }
void delay_30ms(void) { unsigned int i; #ifdef CLOCK6 for(i = 0; i < 20000; i ++); #else for(i = 0; i < 10000; i ++); #endif }
void main(void) { IE = 0; IP = 0; // init all I/Os P0 = 0xff; P1 = 0xff; P2 = 0xff; P3 = 0xff; delay_30ms(); delay_30ms();
for(;;) { write_tsc2003(TSC2003_WRITE,COMMAND_X); //用差分方式读X坐标 touch_x = read_tsc2003(TSC2003_READ)>>4; //读X轴坐标地址命令,只取8位数据
write_tsc2003(TSC2003_WRITE,COMMAND_Y); //用差分方式读Y坐标 touch_y = read_tsc2003(TSC2003_READ)>>4; //读Y轴坐标地址命令,只取8位数据 P0 = touch_x; //接8个LED P2 = touch_y; //接8个LED delay_30ms(); } } |