MeColorSensor and I2C Multiplexer issue


Short description:
If using 2 or more MeColorSensors with an I2C multiplexer the Returnresult() method has problems due to static variables in the method used for averaging the color values.

The MeColorSensor I2C address cannot be changed (ADDR pin is grounded and cannot be set). To use more than one sensor I need to use an I2C mux.

The MeColorSensor::Returnresult() method will take the RGB raw data and return a single color value based on some logic. To “reduce noise” it averages the last 3 readings and returns that result. The averages are held in a static variable array called temp.

For example:

uint8_t MeColorSensor::Returnresult(void)
  static uint8_t cnt_;
  static uint16_t temp[3];
  uint8_t result,r,g,b;
  ...  //does work
  temp[cnt_++] = result;
    cnt_ = 0;
  return (temp[0] + temp[1] + temp[2])/3;

The problem is since temp and cnt_ are static and I have two instances of the MeColorSensor class, they share the temp and cnt_ variables. That means the code is averaging the color between the two sensors. My sensors are normally NOT looking at the same color so both will average OFF the actual value.

So if one sensor is looking at WHITE(value=0) and the other sensor is looking at BLACK(value = 9) both sensors will report the average and one will say it sees Orange(value=3 because 3=(0+9+0)/3) and the other sensor will say it sees Cyan(value=6 because 6=(9+0+9)/3).

This can be fixed very easily by making the temp array and cnt_ variables non static private members of the MeColorSensor class and removing their declaration from the Returnresult() method.

I’ve tested that and it works great.


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