linux kernel 工程师
全部博文(99)
分类: LINUX
2014-03-19 13:46:46
本测试程序通过 ioctl(fd, I2C_RDWR, &ioctl_data)访问I2C
#include
#include
#include
#include
#include
#include
#include
#define I2C_DEV "/dev/i2c-0"
#define I2C_PCA9554_ADDR 0x54
#define WRITE_VALUE 0x49
int
main()
{
#if 1
struct i2c_rdwr_ioctl_data ioctl_data = {0};
struct i2c_msg msg[4] = {{0}};
unsigned char data[4] = {0};
unsigned char out[2] = {0};
int fd;
int rc;
fd = open(I2C_DEV, O_RDWR);
if (fd < 0) {
printf("failed to open %s\n", I2C_DEV);
return (-1);
}
/* test reading and writing registers in PCA9554 */
/* read from Configuration Register (0x03) */
data[0] = 0x03;
msg[0].addr = I2C_PCA9554_ADDR;
msg[0].flags = 0; /* write */
msg[0].len = 1;
msg[0].buf = &data[0];
msg[1].addr = I2C_PCA9554_ADDR;
msg[1].flags = I2C_M_RD;
msg[1].len = 1;
msg[1].buf = &out[0];
ioctl_data.nmsgs = 2;
ioctl_data.msgs = &msg[0];
rc = ioctl(fd, I2C_RDWR, &ioctl_data);
if (rc < 0) {
printf("read, I2C_RDWR failed: %d.\n", errno);
close(fd);
return (-1);
}
printf("Config reg: 0x%02x\n", out[0] );
/* write 0x5a into Configuration Register (0x03) */
printf("write 0x%02x at 0x03\n", WRITE_VALUE);
data[0] = 0x03; /* address */
data[1] = WRITE_VALUE; /* data */
msg[0].addr = I2C_PCA9554_ADDR;
msg[0].flags = 0; /* write */
msg[0].len = 2;
msg[0].buf = &data[0];
ioctl_data.nmsgs = 1;
ioctl_data.msgs = &msg[0];
rc = ioctl(fd, I2C_RDWR, &ioctl_data);
if (rc < 0) {
printf("write, I2C_RDWR failed: %d.\n", errno);
close(fd);
return (-1);
}
sleep(1);
/* read out again to check */
printf("read out at 0x03\n");
data[0] = 0x03;
msg[0].addr = I2C_PCA9554_ADDR;
msg[0].flags = 0; /* write */
msg[0].len = 1;
msg[0].buf = &data[0];
msg[1].addr = I2C_PCA9554_ADDR;
msg[1].flags = I2C_M_RD;
msg[1].len = 1;
msg[1].buf = &out[0];
ioctl_data.nmsgs = 2;
ioctl_data.msgs = &msg[0];
rc = ioctl(fd, I2C_RDWR, &ioctl_data);
if (rc < 0) {
printf("read, I2C_RDWR failed: %d.\n", errno);
close(fd);
return (-1);
}
if (out[0] != WRITE_VALUE)
printf("write failed. ");
else
printf("write success. ");
printf("Config_reg: 0x%02x\n", out[0] );
sleep(1);
close(fd);
#endif
return (0);
}