Home / Programming / ROBOTC / ROBOTC: Using the NXT 2.0 Colour Sensor as a Light Sensor

ROBOTC: Using the NXT 2.0 Colour Sensor as a Light Sensor

Colour Sensor as a Light SensorUsing the NXT 2.0 Colour Sensor as an old fashioned NXT 1.0 Light Sensor as very simple in NXT-G but a little more involved in ROBOTC. The old Light Sensor uses a small red LED to illuminate the target and a small sensor to see how much was reflected. The new colour sensor can be used in a very similar way.  The only thing is you will need to do some work yourself to turn it into a normalised value (0-100).

Below is the code for a simple program that allows you to read both the raw value from the Colour Sensor and a normalised one.  Make sure you change the blackValue and whiteValue variables to match your own environment.

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

/*
* Program to use the NXT 2.0 colour sensor as a standard Lego Light sensor
* Written by Xander Soldaat 18-Feb-2011
*/

// Calibration values, these may be different for you
const int blackValue = 220;
const int whiteValue = 580;

// Normalise a raw value, returns a value from 0 to 100
int normaliseReading(int rawValue) {
  // Anything less than the black value should return 0
  if (rawValue <= blackValue)
    return 0;
  
  // Anything brighter than the white value should return 100
  else if (rawValue >= whiteValue)
    return 100;
  
  // Anything else should be calculated in a scale from 0-100%
  else
    return ((long)(rawValue - blackValue) * 100) / (whiteValue - blackValue);
}

task main () {
  int rawValue = 0;
  int normalisedValue = 0;
  
  while (true) {
    // Get the raw value from the sensor.
    rawValue = SensorRaw[COLOUR];
    
    // Calculate the normalised value
    normalisedValue = normaliseReading(rawValue);
    
    nxtDisplayTextLine(4, "Raw: %3d", rawValue);
    nxtDisplayTextLine(5, "Norm: %3d", normalisedValue);
    wait1Msec(100);
  }
}

You can download the program here: [LINK].

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.