AnsweredAssumed Answered

I2C READ and WRITE

Question asked by amonica on May 12, 2014
Latest reply on May 12, 2014 by igorpadykov

Hi

     I wanted to do a i2c read - write operation on imx6 . So i have added the following code.

 

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <sys/ioctl.h>

#include <fcntl.h>

#include <linux/fs.h>

#include <errno.h>

#include <string.h>

#include <linux/i2c-dev.h>

#include <linux/i2c.h>

 

int main(void)

{

            

  unsigned char rbuf[16];

  int i2c_addr = 0x21;

  int status;

  unsigned short int i;

  

  // OPENING I2C DEVICE

  int fd = open("/dev/i2c-2", O_RDWR);

  if (fd < 0)

  {

  printf("ERROR: open(%d) failed\n", fd);

  return -1;

  }

  printf("\nSUCCESS: open(%d) passed\n", fd);

  

 

  status = ioctl(fd, I2C_SLAVE, i2c_addr>>1);

  if (status < 0)

  {

  printf("ERROR: ioctl(fd, I2C_SLAVE, 0x%02X) failed\n", i2c_addr);

  close(fd);

  return -1;

  }

  printf("\nSUCCESS: ioctl(fd, I2C_SLAVE, 0x%02X>>1) passed\n", i2c_addr);

  

  printf ("\nPerforming MONZA Read operation\n");

 

  if (read(fd,rbuf,16) != 16)

    {

  printf("ERROR: read() failed\n");

  close(fd);

  return -1;

  }

  for(i = 0; i< 16; i++)

  printf("ReadBuffer[%d] %d \r\n", i, rbuf[i]);

  printf("\nSUCCESS: Data READ from the MONZA\n");

  

  printf("\n MONZA test successfull \n");

  close(fd);

}

 

When i run this code i get read error

SUCCESS: open(3) passed

 

 

SUCCESS: ioctl(fd, I2C_SLAVE, 0x21) passed

 

 

Performing MONZA Read operation

ERROR: read() failed

read: Input/output error

errno = 5

 

My Device is connected i2c-dev 2. I observed it using i2cdetect-2. My slave address came to be 0x21.

 

Can somebody please help me out?

Outcomes