Setting i2c slave address for Devantech digital compass

1.1k Views Asked by At

I am trying to interface with a Devantech digital compass found here -

http://www.acroname.com/robotics/parts/R117-COMPASS.html

I am using a i2c-usb converter to plug it into my laptop -

http://www.robot-electronics.co.uk/htm/usb_i2c_tech.htm

First of all, I do not know much about electrical engineering. I have a good idea of the bare basics, but after that I get lost.

I am trying to follow this tutorial -

https://xgoat.com/wp/2007/11/11/using-i2c-from-userspace-in-linux/

However I get stuck at the very beginning when I try to set the device address.

if( ioctl( fd, I2C_SLAVE, ADDRESS ) < 0 )
    {
            fprintf( stderr, "Failed to set slave address: %m\n" );
            return 2;
    }

returns "Failed to set slave address: Invalid argument"

I originally thought the address should be 0xC0 because a sentence in the manual for the compass reads "First send a start bit, the module address (0xC0)..." but that did not work.

Now I have a loop that just goes from 1 to 100 and tries each one for the address, but they all fail. The loop is -

for(int i=0x0;i<0x100;i++) {
    if( ioctl( fd, I2C_SLAVE, i ) < 0 )
        fprintf( stderr, "Failed to set slave address for address %i: %m\n", i );
}

I'm not sure what else to try. Right now, I just want to set the address so I can start attempting to read and write. Since the converter is what is actually connected to the pc, should I be using the address for that? And if so, where can I find it on that link with the information for it? If someone has an idea of what I could try or what is wrong that would be great.

EDIT:

Okay I have the code like this now -

#define ADDRESS 0x55
int fd = open("/dev/i2c-0", O_RDWR);

if (fd < 0) {
    printf("\n<0, %m", errno);
    return -1;
}

if( ioctl( fd, I2C_SLAVE, ADDRESS ) < 0 ) {
    fprintf( stderr, "Failed to set slave address: %m\n" );
    return 2;
}

if( i2c_smbus_write_byte( fd, 0xAA ) < 0 )
    fprintf( stderr, "Failed to write 0xAA to I2C device: %m\n" );

It will set the address, but it won't write anything. Whenever I try to write to it, I get -

Failed to write 0xAA to I2C device: No such device or address 
1

There are 1 best solutions below

0
On

Why are your trying to send 0xAA to the device ? To my understanding this is not a register for it (for the CMPS03, the only command is register 15 and its usage is not common: change the I2C address, factory reset, ...). And 0x55 seems definitively not the address of the device ... 0xC0 should be the write one.

Could be that /dev/i2c-0 has not been created properly / is not correct? How did you get /dev/ic2-0 created ?