我正在尝试读取i2c值,就像使用i2cget一样,但它在其中一种情况下返回了错误的值。I2C读取返回不正确的值
i2cget -y 0 0x57 0x40
回报0x57
i2cget -y 0 0x3b 0x09
回报0x86
当我跑我的#define I2C_ADDR 0x57
和buffer[0] = 0x40
我的程序返回0x57
程序。
但是当我用#define I2C_ADDR 0x3b
和buffer[0] = 0x09
运行我的程序时,我的程序返回0x00
。
这里是我的代码:
// #define I2C_ADDR 0x57
#define I2C_ADDR 0x3b
// #define I2C_REG 0x40
#define I2C_REG 0x09
int main(int argc, char **argv) {
char buffer[1];
buffer[0] = I2C_REG;
int fd;
// Get i2c File Descriptor
if((fd = open("/dev/i2c-0", O_RDWR)) >= 0){
// Set i2c Block Address
if((ioctl(fd, I2C_SLAVE, I2C_ADDR)) >= 0) {
// Set i2c Register Address
write(fd, buffer, 1);
// Read data at Register into buffer
read(fd, buffer, 1);
// Close fd
close(fd);
// Print Result
printf("0x%02x\n", buffer[0]);
} else {
// ioctl error
printf("ioctl error: %s\n", strerror(errno));
}
} else {
// file error
printf("Error opening file: %s\n", strerror(errno));
}
return 0;
}
我在i2cget -y 0x3b 0x09
和我的程序运行的strace
。这是一段输出结果,显示了2次读取的不同之处。
i2cget:
open("/dev/i2c-0", O_RDWR|O_LARGEFILE) = 3
ioctl(3, 0x705, 0xbeae5bf8) = 0
ioctl(3, 0x703, 0x3b) = 0
ioctl(3, 0x720, 0xbeae5b4c) = 0
close(3) = 0
我的程序:
open("/dev/i2c-0", O_RDWR|O_LARGEFILE) = 3
ioctl(3, 0x703, 0x3b) = 0
write(3, "\t", 1) = 1
read(3, "\0", 1) = 1
close(3)
我不知道你的I2C器件,但我猜的结果是不是在第一个字节。尝试enlagre缓冲区并打印缓冲区。 – flotto
它给了我一系列的0x00。 – Dobz