Multiple REV Color Sensors using an I2C Multiplexer (Java)

Hi everybody,
I have seen a lot of posts asking about how to use multiple REV color sensors (v3), but many of them were left unanswered, and so I have made my own solution (in Java).
In order to use multiple sensors on a multiplexer (I am using an Adafruit TCA9548A), all you have to do is create an I2C object with an address of the multiplexer (for Adafruit, it’s 0x70), and write 1 << x, where x is the port on the multiplexer (usually from 0-7).
In code, a simple solution:

//Put this in initialization, like robotInit()
int leftPort = 3;
int rightPort = 7;
I2C multiplexer = new I2C(I2C.Port.kOnboard, 0x70);
multiplexer.write(0x70, 1 << leftPort);
ColorSensorV3 leftSensor = new ColorSensor(I2C.Port.kOnboard);
multiplexer.write(0x70, 1 << rightPort);
ColorSensorV3 rightSensor = new ColorSensor(I2C.Port.kOnboard);

//Run this periodically, like in robotPeriodic()
multiplexer.write(0x70, 1 << leftPort);
int distance = leftSensor.getProximity();
multiplexer.write(0x70, 1 << rightSensor);
Color color = rightSensor.getColor();

Or you could use this handy little class MultiplexedColorSensor (found here), which acts like a wrapper around the color sensor which automatically writes to a common multiplexer before accessing the sensor. You can add the class to your project, and use it like a normal color sensor:

//Put this in initialization, like robotInit()
MultiplexedColorSensor leftSensor = new MultiplexedColorSensor(I2C.Port.kOnboard, 3);
MultiplexedColorSensor leftSensor = new MultiplexedColorSensor(I2C.Port.kOnboard, 7);

//Run this periodically, like in robotPeriodic()
int distance = leftSensor.getProximity();
Color color = rightSensor.getColor();

I hope this helps!

3 Likes

I used this code for distance sensors but after printing the distance, both sensors gave he same exact reading despite being pointed at very different distances

Which multiplexer are you using? It might use a different system for changing ports. If it’s also an Adafruit, try changing ports? Are you using the MultiplexedColorSensor class?

It seems to be an Adafruit clone, I linked it in the original post. It’s a distance sensor so I can’t use that class. I’m running into an issue where it can’t seem to keep up with the commands fast enough to change the port so it gives the wrong values

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.