NicolasColsoul
NicolasColsoul

Reputation: 31

TCA9548a (I2C multiplexer) C++ integration

I have 4 VL680 laser distance sensors to use with à Raspberry. It is a I2C bus compatible sensor but we can't change the address. So, I use the TCA9548a Adafruit board I2C multiplexer. I can run only one VL680 directly on my I2C bus but it won't work trough the multiplexer. Datasheet is not clear and I find only code for Arduino or bad Python example.

Here I am :

char filename[20];
const int adapter_nr = 1;
snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
file = open(filename, O_RDWR);
if (file < 0) 
{
    printf("Unable to connect reach I2C bus \n");
    exit(EXIT_FAILURE);
}

// multiplex address
const int addr = 0x70;

if(ioctl(file, I2C_SLAVE, addr) < 0) 
{
    printf("Fail to reach multiplex laser \n");
    exit(EXIT_FAILURE);
}

char buf[10];
buf[0] = 0x01; // to select channel 0
write(file, buf, 1);
I2C_init();

doTheSameAsOneOnlyVL680();
...

I don't know how I must do and nothing help. Is that the way to select the channel ? How write and read then ?

void I2C_init()
{   
    const int addr = 0x29;

    if(ioctl(file, I2C_SLAVE, addr) < 0) 
    {
        printf("Fail to reach laser \n");
        exit(EXIT_FAILURE);
    }

    if(read_byte(file, 0x000) != 0xB4)
    {
        printf("Problem with VL6180X\n");
        //exit(EXIT_FAILURE);
    }

    int setup = read_byte(file, 0x016);

    if(setup == 1)
    {
        printf("Init all registers \n");
        write_byte(file, 0x0207, 0x01);
                ...

    }
    else
    {
        printf("Fail \n");
    }

    set_scaling(file, 1);
}

Upvotes: 0

Views: 1187

Answers (1)

Alex Baban
Alex Baban

Reputation: 11732

When ioctl(file, I2C_SLAVE, addr) runs you're saying "On I2C talk to the multiplexer."

Then, with

buf[0] = 0x01; // to select channel 0 write(file, buf, 10);

you make the multiplexer connect the VL680 that's connected to multiplexer first port to the I2C bus.

After you talked to the multiplexer with

write(file, buf, 10);

and before you talk to the distance sensor with

doTheSameAsOneOnlyVL680();

you need to run some code in order to say "On I2C talk to the distance sensor."

Something like:

if(ioctl(file, I2C_SLAVE, vl680Addr) < 0) 
{
    printf("Fail to reach distance sensor \n");
    exit(EXIT_FAILURE);
}

, where vl680Addr is the address (you'll need to define that) for the VL680 laser distance sensor,

Upvotes: 1

Related Questions