c - I2C Read returns incorrect value -
i trying read in i2c value i2cget, returning wrong value in 1 of cases.
i2cget -y 0 0x57 0x40
returns 0x57
i2cget -y 0 0x3b 0x09
returns 0x86
when run program #define i2c_addr 0x57
, buffer[0] = 0x40
program returns 0x57
.
but when run program #define i2c_addr 0x3b
, buffer[0] = 0x09
program returns 0x00
.
here code:
// #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; // 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 @ register 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; }
i ran strace
on i2cget -y 0x3b 0x09
, program. here piece of output shows how 2 reads differ.
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
my program:
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)
from strace
of i2cget
researched 0x720 , found out value of i2c_smbus. found source code i2cget
in buildroot
.
there no use of in c code, there use of function i2c_smbus_read_byte_data
. added code , ran it, wouldn't run due function being undefined. copied i2c-dev.h
file buildroot folder , changed #include
include local file , ran, , output right data.
here code:
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/ioctl.h> #include <errno.h> #include "i2c-dev.h" #define i2c_addr 0x3b #define i2c_reg 0x09 // prints value of /dev/i2c-0 @ block 0x3b register 0x09 int main(int argc, char **argv) { int fd, res; if ((fd = open("/dev/i2c-0", o_rdwr)) >= 0) { ioctl(fd, i2c_slave, i2c_addr); res = i2c_smbus_read_byte_data(fd, i2c_reg); close(fd); printf("value - 0x%02x\n", res); } else { printf("error opening file: %s\n", strerror(errno)); } return 0; }
Comments
Post a Comment