Search code examples
androidaccelerometerazimuth

How to make azimuth and degree less shaky in Android


First I used TYPE_ORIENTATIONbut this was depreciated. Therefore I changed the code to a more recent version and used TYPE_ACCELEROMETER and TYPE_MAGNETIC_FIELD as suggested in this post.

// Initialize android device sensor capabilities
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

Then in onResume(), I used this:

// For the system's orientation sensor registered listeners
mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);

and below that I used:

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // not in use
}

float[] mGravity;
float[] mGeomagnetic;

@Override
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 azimuthInRadians = orientation[0];
            float azimuthInDegrees = (float) Math.toDegrees(azimuthInRadians);
            if (azimuthInDegrees < 0.0f) {
                azimuthInDegrees += 360f;
            }
            float degree = Math.round(azimuthInDegrees);
            directionHeading.setText("Heading: " + degree + " degrees");

            // Create rotation animation
            RotateAnimation ra = new RotateAnimation(currentDegree, -degree,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);

            // How long the animation will take place
            ra.setDuration(210);

            // Set the animation after the end of the reservation status
            ra.setFillAfter(true);

            // Start the animation
            image.startAnimation(ra);
            currentDegree = -degree;
        }
    }
}

The old way was pretty precise and did not shake at all. But now, with the non-depreciated way, it shakes heavily. Why is that and how can I fix the shakiness?


Solution

  • Solution is to apply (LPF) Low Pass Filter. It's smooth and working perfectly now. I found the solution here: Low Pass Filter