c - write() returns -1 when writing to I2C_SLAVE device -


i've read through linux kernel documents on i2c , written code try replicate command i2cset -y 0 0x60 0x05 0xff

the code i've written here:

#include <stdio.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <sys/ioctl.h> #include <stdint.h> #include <string.h>  int main(){   int file;      file = open("/dev/i2c-0", o_rdwr);  if (file < 0) {   exit(1);  }   int addr = 0x60;   if(ioctl(file, i2c_slave, addr) < 0){  exit(1);  }  __u8 reg = 0x05; __u8 res; __u8 data = 0xff;  int written = write(file, &reg, 1);  printf("write returned %d\n", written);  written = write(file, &data, 1);  printf("write returned %d\n", written);  } 

when compile , run code get: write returned -1
write returned -1

i've tried follow docs tell me, understanding address set first call ioctl, need write() register , data want sent register.

i've tried use use smbus, can't code compile using this, complains @ linking stage can't find functions.

have made mistakes in code? i'm beginner i2c , don't have lot of experience c either.

edit: errno give following message: operation not supported. logged in root on machine though, don't think can permissions thing, although may wrong.

the way got around problem use smbus, in particular functions i2c_smbus_write_byte_data , i2c_smbus_read_byte_data. able use these functions read , write device.

i did have little trouble finding these functions, kept trying download libraries using apt-get install appropriate header files. in end downloaded files smbus.c , smbus.h.

then code needed was:

#include <stdio.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> #include "smbus.h" #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <sys/ioctl.h> #include <stdint.h> #include <string.h> #include <errno.h>   int main(){  int file;      file = open("/dev/i2c-0", o_rdwr); if (file < 0) {     exit(1); }  int addr = 0x60;  if(ioctl(file, i2c_slave, addr) < 0){     exit(1); }  __u8 reg = 0x05; /* device register access */ __s32 res;  res = i2c_smbus_write_byte_data(file, reg, 0xff); close(file); } 

then if compile smbus.c file: gcc -c smbus.c , myfile: gcc -c myfile.c, link them: gcc smbus.o myfile.o -o myexe working executable runs i2c command. ofcourse, have smbus.c , smbus.h in same directory myfile.c.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -