Search code examples
androidaccelerometerandroid-sensorssensormanager

Using Accelerometer and getting a stable azimuth


I have been hunting around on how to rotate a 3D object using the device hardware (Compass, Accelerometer)

The following guide was amazing: http://ibuzzlog.blogspot.co.uk/2012/08/how-to-use-android-sensors.html?showComment=1409868331799#c665801926070707020

However the azimuth is incredible jumpie on multiple devices. (imagine this was strapped to your face, looking left and right)

@Override
    public void onSensorChanged(SensorEvent event) {

        int type = event.sensor.getType();

        //Log.i("TAG", "Sensor " + type);

        if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        {
            MagneticFieldValues_last[0] = event.values[0];
            MagneticFieldValues_last[1] = event.values[1];
            MagneticFieldValues_last[2] = event.values[2];

            bHaveMagneticField = true;
        }
        if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        {
            AccelerometerValues_last[0] = event.values[0];
            AccelerometerValues_last[1] = event.values[1];
            AccelerometerValues_last[2] = event.values[2];

            bHaveAccelerometer = true;
        }
        if(bHaveMagneticField && bHaveAccelerometer)
        {
            if(SensorManager.getRotationMatrix(R, null, AccelerometerValues_last, MagneticFieldValues_last))
            {
                SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, remapR);
                SensorManager.getOrientation(remapR, orientationValues);

                Matrix.multiplyMV(orientationVector, 0, remapR, 0, sZVector, 0);
                pitch2 = (float) (-Math.atan2(orientationVector[1], orientationVector[2]) * RADIANS_TO_DEGREES);

                Matrix.multiplyMV(orientationVector, 0, remapR, 0, sZVector, 0);
                orientation = (float) (-Math.atan2(orientationVector[0], orientationVector[1]) * RADIANS_TO_DEGREES);

                Matrix.invertM(remapR_inv, 0, remapR, 0);
                Matrix.multiplyMV(azimuthVector, 0, remapR_inv, 0, sZVector, 0);
                azimuth = (float) (180 + Math.atan2(azimuthVector[0], azimuthVector[1]) * RADIANS_TO_DEGREES);
            }
        }
    }

UPDATE

Found this that seems to do the trick http://blog.thomnichols.org/2011/08/smoothing-sensor-data-with-a-low-pass-filter

Update 2

Sadly it does not do the trick, still need a way to smooth out values. How so others do this?


Solution

  • Incase anyone find this, just use Google Cardboard head tracking, it works perfectly and easy to use

    https://github.com/MasDennis/RajawaliVR