以下代码测试读取GT911的ID和VERSION
#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#define I2C_ADDR 0x14
#define GOODIX_REG_ID 0x8140
int main(int argc, char *argv[])
{
int fd, ret;
struct i2c_rdwr_ioctl_data ctrl;
struct i2c_msg msg[2];
uint8_t wbuf[2] = { 0 }, rbuf[6] = { 0 };
fd = open("/dev/i2c-0", O_RDWR);
if(fd < 0) {
perror("open error");
return -1;
}
ioctl(fd, I2C_TIMEOUT, 1); // 超时时间
ioctl(fd, I2C_RETRIES, 2); // 重复次数
ctrl.nmsgs = 2;
ctrl.msgs = msg;
ctrl.msgs[0].len = 2; // 数据长度
ctrl.msgs[0].addr = I2C_ADDR; // 设备地址
ctrl.msgs[0].flags = 0; // 写
ctrl.msgs[0].buf = wbuf;
ctrl.msgs[0].buf[0] = (GOODIX_REG_ID>>8)&0xff;
ctrl.msgs[0].buf[1] = GOODIX_REG_ID&0xff;
ctrl.msgs[1].len = 6; // 数据长度
ctrl.msgs[1].addr = I2C_ADDR; // 设备地址
ctrl.msgs[1].flags = I2C_M_RD; // 读
ctrl.msgs[1].buf = rbuf; // 存放返回的数据
ret = ioctl(fd, I2C_RDWR, (unsigned long)&ctrl);
if(ret < 0) {
close(fd);
perror("ioctl error");
return -1;
}
printf("id: %c%c%c%c version: 0x%02x%02x\n", rbuf[0], rbuf[1], rbuf[2], rbuf[3], rbuf[5], rbuf[4]);
close(fd);
return 0;
}