I2cread.c

From ArmadeusWiki
Revision as of 10:47, 3 April 2008 by FabienM (Talk | contribs)

Jump to: navigation, search
/* a simple program to test accelerometer *
 * Fabien Marteau <fabien.marteau@armadeus.com>
 *
 *  Inspired from another code, but I don't remember who.
 */


#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include <linux/i2c.h> 
#include <linux/i2c-dev.h>
 
#include <sys/ioctl.h>

int fd;

/* Read a byte on the I2C bus
   This is done by writing the register address 
   we want to access and then by reading this register
     @param fd: file descriptor of the device
     @param reg: register to access
     @param buf: buffer used to store the result
     @return : -1 in case of error otherwise 0
 */
int read_byte( int fd,unsigned char addr, unsigned char reg, unsigned char *buf )
{ 
    // create an I2C write message (only one byte: the address)
    struct i2c_msg msg = {addr, 0, 1, buf };
    // create a I2C IOCTL request
    struct i2c_rdwr_ioctl_data rdwr = { &msg, 1 };

    buf[0] = reg; // select reg to read

    // write the desired register address
	if ( ioctl( fd, I2C_RDWR, &rdwr ) < 0 ){
		printf("Write error\n");
		return -1;
	}
    msg.flags = I2C_M_RD; // read
    
    // read the result and write it in buf[0]
	if ( ioctl( fd, I2C_RDWR, &rdwr ) < 0 ){
		printf("Read error\n");
		return -1;
	}
    return 0;
}

/* i2cread i2c-devfile addr*/
int main(int argc, char **argv){
  unsigned char buf;
  unsigned char addr;
  unsigned char subaddr;
  unsigned char value;

  if(argc != 4){
    printf("wrong args numbers\nsyntaxe (hexa) :\ni2cread i2c-devfile addr subaddr\n");
    return -1;
  }

  fd = open(argv[1],O_RDWR);
  if(fd < 0){
    printf("can't open %s\n",argv[1]);
    return -1;
  }
  addr =    (unsigned char )strtol(argv[2], (char **)NULL, 16);
  subaddr =    (unsigned char )strtol(argv[3], (char **)NULL, 16);

  read_byte(fd,addr, subaddr, &buf); 

  printf("Read component %02x at subaddress %02x -> %02x\n",addr,subaddr,buf);

  return value;
}