androidmagnetometersensormanager

Android Compass Bearing


I am trying to get the compass bearing in degrees (i.e. 0-360) using the following method:

float[] mGravity;
float[] mGeomagnetic;
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        mGravity = event.values;
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        mGeomagnetic = event.values;
    if (mGravity != null && mGeomagnetic != null) {
        float R[] = new float[9];
        float I[] = new float[9];
        boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
                mGeomagnetic);
        if (success) {
            float orientation[] = new float[3];
            SensorManager.getOrientation(R, orientation);
            float azimut = orientation[0];
            bearing.setText("Bearing: "+ azimut);
        }
    }
}

The azimuth value (i.e. orientation[0]) should be 0<=azimuth<360 but I am getting only values from -3 to 3 as I rotate my device. Can someone please tell me what the problem might be please?


Solution

  • The values are in radian, you have to convert to degree of arc

    int azimut = (int) Math.round(Math.toDegrees(orientation[0]));