AForge.Robotics.Lego.NXTBrick.ReadHiTechnicCompassSensor C# (CSharp) Метод

ReadHiTechnicCompassSensor() публичный Метод

Read data from HiTechnic compass sensor.

The method retrieves the angle of a HiTechnic compass 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.

The HiTechnic compass sensor will only operate correctly in a horizontal plane so you must keep the compass level for it to read correctly. This is very important so remember this when you build it into your robot. It is highly desirable to mount the compass at least 6 inches (15cm) away from the motors and 4 inches (10cm) away from the NXT brick itself. Try to make sure it is firmly mounted, if it bounces around, the readings may bounce around too.

NXT Firmware version 1.03 must be loaded in the NXT for the compass to operate correctly. You can check the firmware version using the GetVersion method.

public ReadHiTechnicCompassSensor ( NXTBrick sensor, int &angle ) : bool
sensor NXTBrick Sensor to read from.
angle int The magnetic heading, [0, 359] degrees.
Результат bool
        public bool ReadHiTechnicCompassSensor( NXTBrick.Sensor sensor, ref int angle )
        {
            byte[] command = { 0x02, 0x42 };
            byte[] readBuffer = new byte[2];

            int bytesReady;
            int bytesRead;

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

            if ( bytesRead == readBuffer.Length )
            {
                angle = ( readBuffer[0] * 2 ) + readBuffer[1];
                return true;
            }

            return false;
        }