使用工程i2c-utils下载地址
https://gitcafe.com/21cnbao/i2c-utils
该工程支持的reg_address是8位的,由于需要支持16位的,对i2c-util.c做了些修改。
static int i2c_read_reg(char *dev, unsigned char *buf, unsigned slave_address, unsigned reg_address, int len)
{
struct i2c_rdwr_ioctl_data work_queue;
// unsigned char w_val = reg_address;
unsigned char w_val[2];
int ret;
...
if (reg_address >> 8)
{
(work_queue.msgs[0]).len = 2;
w_val[0] = reg_address >> 8;
w_val[1] = reg_address & 0xff;
(work_queue.msgs[0]).buf = &w_val[0];
}
else
{
(work_queue.msgs[0]).len = 1;
w_val[0] = reg_address & 0xff;
(work_queue.msgs[0]).buf = &w_val[0];
}
(work_queue.msgs[0]).addr = slave_address;
// (work_queue.msgs[0]).buf = &w_val;
// if (reg_address >> 8)
// (work_queue.msgs[1]).len = len + 1;
// else
(work_queue.msgs[1]).len = len;
(work_queue.msgs[1]).flags = I2C_M_RD;
(work_queue.msgs[1]).addr = slave_address;
(work_queue.msgs[1]).buf = buf;
...
}
static int i2c_write_reg(char *dev, unsigned char *buf, unsigned slave_address, unsigned reg_address, int len)
{
struct i2c_rdwr_ioctl_data work_queue;
unsigned char w_val = reg_address;
unsigned char w_buf[len+2];
int ret;
if (reg_address >> 8)
{
w_buf[0] = reg_address >> 8;
w_buf[1] = reg_address & 0xff;
}
else
w_buf[0] = reg_address;
...
// (work_queue.msgs[0]).len = 1 + len;
(work_queue.msgs[0]).addr = slave_address;
(work_queue.msgs[0]).buf = w_buf;
if (reg_address >> 8)
{
(work_queue.msgs[0]).len = 2 + len;
memcpy(w_buf + 2, buf, len);
}
else
{
(work_queue.msgs[0]).len = 1 + len;
memcpy(w_buf + 1, buf, len);
}
...
}
int main(int argc, char **argv)
{
unsigned int fd;
unsigned int slave_address, reg_address;
unsigned r_w;
unsigned w_val;
unsigned char rw_val;
if (argc < 5) {
printf("Usage:\n%s /dev/i2c-x dev_i2c_addr reg_addr rw[0|1] [write_val]\n", argv[0]);
return 0;
}
fd = open(argv[1], O_RDWR);
if (!fd) {
printf("Error on opening the device file %s\n", argv[1]);
return 0;
}
sscanf(argv[2], "%x", &slave_address);
sscanf(argv[3], "%x", ®_address);
sscanf(argv[4], "%d", &r_w);
if (r_w == 0) {
if (i2c_read_reg(argv[1], &rw_val, slave_address, reg_address, 1))
printf("Read %s-%02x reg %04x, read value:%02x\n", argv[1],
slave_address, reg_address, rw_val);
} else {
if (argc < 6) {
printf("Usage:\n%s /dev/i2c-x dev_i2c_addr reg_addr r|w[0|1] [write_val]\n", argv[0]);
return 0;
}
sscanf(argv[5], "%x", &w_val);
if ((w_val & ~0xff) != 0)
printf("Error on written value %s, only accept 0~FF\n", argv[5]);
rw_val = (unsigned char)w_val;
i2c_write_reg(argv[1], &rw_val, slave_address, reg_address, 1);
}
return 0;
}