Home / Programming / ROBOTC / ROBOTC: Using the NXT 2.0 Colour Sensor

ROBOTC: Using the NXT 2.0 Colour Sensor

NXT 2.0 Colour SensorSo you just bought yourself one of the NXT 2.0 Colour Sensors and you’re keen to get started with it. You browse through the example programs that are shipped with ROBOTC and open the “ColorSensor.c” program. “300 lines of code to read a simple colour?” you ask yourself.

Fear not, it’s a lot easier than that. In order to use the NXT 2.0 colour sensor you’ll need to make sure of one thing: you absolutely need at least ROBOTC 2.26.1 for NXT, anything less simply won’t work.  Don’t worry, though, it’s a very stable beta.  Don’t let that word scare you off, I’ve been using it for months now and it’s never failed me.

The NXT 2.0 Colour Sensor is super easy to use.  Here’s a very simple program that will display the currently detected colour on the screen.  Please note that this is basically a stripped down version of the one shipped with ROBOTC; I just removed all of the diagnostics crud that the developers added so they could debug their drivers.

#pragma config(Sensor, S1, colorPort, sensorCOLORFULL)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//

task main()
  string sColor;
  while (true) {
    switch (SensorValue[colorPort])
      case BLACKCOLOR: sColor = "Black"; break;
      case BLUECOLOR: sColor = "Blue"; break;
      case GREENCOLOR: sColor = "Green"; break;
      case YELLOWCOLOR: sColor = "Yellow"; break;
      case REDCOLOR: sColor = "Red"; break;
      case WHITECOLOR: sColor = "White"; break;
      default: sColor = "???"; break;
    nxtDisplayCenteredTextLine(2, sColor);

As you can see, not a whole lot to it.  Have fun and enjoy your new sensor!

About Xander

Xander Soldaat is a Software Engineer and former Infrastructure Architect. He loves building and programming robots. He recently had the opportunity to turn his robotics hobby into his profession and has started working for Robomatter, the makers of ROBOTC and Robot Virtual Words.