From: Wright, A. <Ale...@my...> - 2011-03-15 21:07:08
|
Sorry if the reply isnt going in the right place, I have mail deliverably turned off and was looking through the archives. I wrote some i2c bus code for the devantech compass on my project http://www.robot-electronics.co.uk/htm/cmps3tech.htm I think your issue might be that you need to rightshift the address one bit in order to have a 7 bit wide I2C address. eg: ioctl(file, I2C_SLAVE, addr >> 1) here is my prototyping code: (not pretty but it works) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/i2c-dev.h> int main(void) { int file; char device[] = "/dev/i2c-0"; int addr = 0xC0; char buf[4]; char result[4] = {0}; file = open(device, O_RDWR); if (file < 0) { //couldnt open perror("Failed to open i2c device"); return 0; } if (ioctl(file, I2C_SLAVE, addr >> 1) < 0) { // check errno perror("Error setting address"); return 0; } buf[0] = 0; // register 0 if (write(file, buf, 1) != 1) { printf("failed\n"); return 0; } if (read(file, buf, 1) != 1) { printf("failed\n"); return 0; } printf("Compass software revision %d\n", (int)buf[0]); buf[0] = 1; //register 1 if (write(file, buf, 1) != 1) { printf("failed\n"); return 0; } if (read(file, buf, 1) != 1) { printf("failed\n"); return 0; } printf("Compass bearing as byte [0-255] %d\n", (int)buf[0]); buf[0] = 2; // register to read from if (write(file, buf, 1) != 1) { printf("failed\n"); return 0; } if (read(file, buf, 2) != 2) { printf("failed\n"); return 0; } result[1] = buf[0]; result[0] = buf[1]; close(file); printf("compass bearing as short [0-3599] %d\n", *((int *)result)); return 0; } |