rbx color sensor


Example

var cs = new ColorSensor(PORT_2A, PORT_4A);
// Calibration
for (var i=0; i<3; i++) {
  print("Place object " + (i+1) + " and press any key to calibrate...");
  while(getkey() == null) delay(500);
  cs.setColor(i);
}
print("Calibration done.");
// Recognition
while(true) {
  print("Place any object and press any key to identify...");
  while(getkey() == null) delay(500);
  print("This is object " + (cs.getColor() + 1));
}

API

ColorSensor(port2, port4); 
setColor(index); // remember the color for current object in given slot (0 ~ 15)
getColor(); // get the index (0 ~ 15) for the color that is closest to current object
loadFromKeystore(prefix = ""); // load color table from keystore with optional reference prefix
saveToKeystore(prefix = ""); // save color table to keystore with optional reference prefix

Notes

It is important to understand that using this sensor is not as straightforward as reading the output frequencies and immediately being able to calculate an accurate RGB value for the color of the target object. The surface of the object, ambient lighting, how far the object is from the photodiodes etc. are all factors that will affect the output, sometimes in drastic and unexpected ways.

The best way to use the sensor is to perform a prior calibration with all the different coloured objects that the sensor will be dealng with. The objects are placed one by one at a fixed point from the sensor, and the frequency readings are entered into an internal table using setColor(index). where index is simply a number between 0 - 15 that identifies the target object. This color table can then be saved to the keystore, and persisted to flash memory for future use.

During recogition, the getColor() function will read the RGB requencies and locate the entry in the color table that is closest to the input frequencies (by treating them as points in 3D space and computing the distance between them). 

As long as prior calibration is done, and external conditions remain more or less constant, the recogition rate for the sensor will be very high.