I don't have much experience with linux/i2c (plenty of i2c, just not much on linux).
Anyway, in preparation for a few I2C devices on our custom hardware I wanted to play with the generic
linux i2c driver just to get used to it. I picked the accelerometer (MMA8451Q, device addr: 0x1C, bus 0).
The device seems simple enough to use, but I keep getting a Input/Output error when I try to write
to it. Here's the entire snippet of code...
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#define SLAVE_ADDR 0x1c /* SA0 is low, so addr=1c */
int
main(int argc, char *argv[])
{
int i, j, dev;
char buf[8];
if ((dev = open("/dev/i2c-0", O_RDWR)) < 0) {
perror("open failed");
exit(1);
}
if (ioctl(dev, I2C_SLAVE, SLAVE_ADDR) < 0) {
perror("ioctl failed");
close(dev);
exit(1);
}
buf[0] = 0;
if (write(dev,buf,1) != 1) {
perror("write failed");
close(dev);
exit(1);
}
if (read(dev,buf,1) != 1) {
perror("read failed");
close(dev);
exit(1);
}
close(dev);
for(i=0;i<1;i++)
printf("buf[%d]: 0x%02x\n",i,buf[i]);
exit(0);
}
Is the the correct way to access a device on the I2C bus?
Any hints as to where the problem might be?