int file; int adapter_nr = 1; /* I2C适配器编号 */ char filename[20]; snprintf(filename, 19, "/dev/i2c-%d", adapter_nr); file = open(filename, O_RDWR); if (file < 0) { /* 打开失败 */ exit(1); }
int addr = 0x40; /* I2C 从机地址 */ if (ioctl(file, I2C_SLAVE, addr) < 0) { /* 打开失败 */ exit(1); }
__u8 register = 0x10; /* I2C从机 寄存器地址 */ __s32 res; char buf[10]; /* 使用SMBus函数 */ res = i2c_smbus_read_word_data(file, register); if (res < 0) { /* 错误 */ } else { /* 成功读取到一个字 */ } /* 使用I2C Write, 等价于i2c_smbus_write_word_data(file, register, 0x6543) */ buf[0] = register; buf[1] = 0x43; buf[2] = 0x65; if (write(file, buf, 3) ! =3) { /* 错误*/ } /* 使用I2C Read, 等价于 i2c_smbus_read_byte(file) */ if (read(file, buf, 1) != 1) { /* 错误 */ } else { /* buf[0]为读取到的字节 */ }
标记符
|
长度
|
说明
|
S
|
1 bit
|
I2C启动
|
P
|
1 bit
|
I2C停止
|
Rd/Wr
|
1 bit
|
控制字中的读写标志位,读操作为1,写操作为0
|
A, NA
|
1 bit
|
应答标志
|
Addr
|
7 bits
|
7位I2C地址
|
Data
|
8 bit
|
字节数据 |
Comm
|
8 bits
|
命令字节,可理解为I2C设备寄存器地址
|
[..]
|
N char
|
I2C设备返回的数据
|