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

GetUltrasonicSensorsValue() public method

Read value of ultrasonic distance sensor.

The method retrieves value of ultrasonic distance 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.Lowspeed9V 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.

public GetUltrasonicSensorsValue ( Sensor sensor, int &value ) : bool
sensor Sensor Sensor to read value from.
value int Distance value obtained from ultrasonic sensor, [0..255] cm.
return bool
        public bool GetUltrasonicSensorsValue( Sensor sensor, out int value )
        {
            value = -1;

            // request distance value
            if ( !LsWrite( sensor, new byte[] { 0x02, 0x42 }, 1 ) )
                return false;

            int readyBytes = -1;

            for ( int i = 0; i < 10; i++ )
            {
                if ( !LsGetStatus( sensor, out readyBytes ) )
                    return false;

                if ( readyBytes >= 1 )
                {
                    // read from I2C device
                    byte[] readValues = new byte[1];
                    int bytesRead;

                    if ( !LsRead( sensor, readValues, out bytesRead ) )
                        return false;

                    value = readValues[0];

                    return true;
                }
            }
            return false;
        }