AForge.Robotics.Lego.NXTBrick.ReadHiTechnicColorSensor C# (CSharp) Method

ReadHiTechnicColorSensor() public method

Read data from HiTechnic color sensor (also color sensor v2).

The method retrieves the color valuse of a HiTechnic color sensor by communicating with I2C device (writing to and reading from low speed bus). The method first sends { 0x02, 0x42 } command to the specified device using LsWrite( Sensor, byte[], int ) method. Then it waits until there is something available to read using LsGetStatus method. Finally it reads sensor's value using LsRead device. See this page for details.

Before using this method it is required to use SetSensorMode( Sensor, SensorType, SensorMode, bool ) method to set sensor's type to SensorType.Lowspeed mode. It should be done once after NXT brick is powered on. If sensor's type is not set properly, the method will generate an exception. Also after setting sensor's type application may need to wait a bit to give device some time to initialize.

NXT Firmware version 1.24 must be loaded in the NXT for the HiTechnic color sensor to operate correctly. You can check the firmware version using the GetVersion method.

The color sensor V2 must be configured to match the mains electricity frequency for your country. Details on how to configure the Color Sensor V2 can be found at

public ReadHiTechnicColorSensor ( NXTBrick sensor, int &colorNumber, int &redValue, int &greenValue, int &blueValue ) : bool
sensor NXTBrick Sensor to read from.
colorNumber int Found color number.
redValue int Found red value.
greenValue int Found green value.
blueValue int Found blue value.
return bool
        public bool ReadHiTechnicColorSensor( NXTBrick.Sensor sensor, ref int colorNumber, ref int redValue, ref int greenValue, ref int blueValue )
        {
            byte[] command = { 0x02, 0x42 };
            byte[] readBuffer = new byte[4];

            int bytesReady;
            int bytesRead;

            LsWrite( sensor, command, readBuffer.Length );
            LsGetStatus( sensor, out bytesReady );
            LsRead( sensor, readBuffer, out bytesRead );

            if ( bytesRead == readBuffer.Length )
            {
                colorNumber = readBuffer[0];
                redValue    = readBuffer[1];
                greenValue  = readBuffer[2];
                blueValue   = readBuffer[3];
                return true;
            }

            return false;
        }