0

I'm making a compass app for Android and I've managed to capture the azimuth by using the gyroscope, accelerometer, and magnetometer (see here for the tutorial I used). Unfortunately, the compass reading only functions when the device is placed parallel to the ground (ie, flat on a table/the palm of my hand, etc.). Whenever I tilt the device up to a fully upright position (with the screen facing me), the compass simply gives out a wrong reading. I'm assuming that this is because the axes change when the device's orientation itself changes. How do I prevent this from happening? I would like the compass to work in BOTH these two positions: parallel to the ground AND the fully upright position. How do I go about doing this? If someone could give me a push in the right direction, that would be super helpful.

Thanks for all your help! :D

NewGradDev
  • 1,004
  • 6
  • 16
  • 35
  • Have your read this SO question? http://stackoverflow.com/questions/10192057/android-getorientation-method-returns-bad-results – Morrison Chang Dec 26 '12 at 23:48

1 Answers1

0

add mDisplay variable in your SensorFusionActivity, like this:

private Display mDisplay = null;

then, add following code in onCreate method:

mDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

finally, modify the calculateAccMagOrientation this way:

// calculates orientation angles from accelerometer and magnetometer output
public void calculateAccMagOrientation() {
    if(SensorManager.getRotationMatrix(rotationMatrix, null, accel, magnet)) {

        int rotation = mDisplay.getRotation();

        if(rotation == Surface.ROTATION_0)
            SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_MINUS_Y, SensorManager.AXIS_X, rotationMatrix);
        else if(rotation == Surface.ROTATION_180)
            SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, rotationMatrix);
        else if(rotation == Surface.ROTATION_270)
            SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_MINUS_Y, rotationMatrix);

        SensorManager.getOrientation(rotationMatrix, accMagOrientation);
    }
}