androidaccelerometermagnetometertilt

Android Tilt issue with Accelerometer and Magnetometer


I am trying to detect Yaw, Pitch & roll using the following code:

    @Override
    public void onSensorChanged(SensorEvent event) {

        if (event.sensor == mAccelerometer) {
            System.arraycopy(event.values.clone(), 0, mLastAccelerometer, 0, event.values.length);
            mLastAccelerometerSet = true;
        } else if (event.sensor == mMagnetometer) {
            System.arraycopy(event.values.clone(), 0, mLastMagnetometer, 0, event.values.length);
            mLastMagnetometerSet = true;
        }
        if (mLastAccelerometerSet && mLastMagnetometerSet) {
            SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer);
            SensorManager.getOrientation(mR, mOrientation);

            mOrientation[0] = (float) Math.toDegrees(mOrientation[0]);
            mOrientation[1] = (float) Math.toDegrees(mOrientation[1]);
            mOrientation[2] = (float) Math.toDegrees(mOrientation[2]);

            mLastAccelerometerSet = false;
            mLastMagnetometerSet = false;
            ManageSensorChanges();
        }
    }

This works fine apart from one issue;

When the phone is up-side-down or starts to go up-side-down (even if tilted a little forward in the portrait mode), the angles go haywire ... spitting out random angles!

Why is this happening - and - Any solution to this?


Solution

  • In case some one is stuck with this issue:

    Strange behavior with android orientation sensor

    In summary, the trouble is with the use of Eulers angle - so there is little that can be done to sort the above issue at extreme angles of the device ... apart from using Quaternions (which is suitable for OpenGL or 3D projections).

    I am using it for 2D drawing on my app (to create a parallax effect), so I just ended up using the Accelerometer values (range is obviously -9.8 to 9.8) ... It works perfectly and an annoyingly easy solution for my crude needs. This technique is not acceptable for 3d projection... if needing precise measurements, see https://bitbucket.org/apacha/sensor-fusion-demo.