Search code examples
androidsensorsandroid-sensors

How to use SensorEventListener to determine direction phone is facing relative to magnetic north


I'm trying to write a class that implements SensorEventListener to determine the direction the phone's camera is facing (Galaxy S3), in degrees east from magnetic north. Here are the sensors I'm using:

  public void start()
  {
    mManager.registerListener(this, mManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_GAME);
    mManager.registerListener(this, mManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),  SensorManager.SENSOR_DELAY_GAME);
  }

I believe I'm looking for the azimuth, which is stored in mOrientation[0] after calling SensorManager.getOrientation(mRotationMatrix, mOrientation);.

However, when I do that, the result seems to be rotation around gravity and not rotation from magnetic north. Am I doing something wrong?


Solution

  • You need to call remapCoordinateSystem(inR, AXIS_X, AXIS_Z, outR); before calling getOrientation to get the direction of back camera. The azimuth is then the direction with respect to magnetic north. This amount to projecting the minus Z-axis of the device coordinate system to the world East-North plane and then calculate the angle between the projected vector and the North axis.