手机的角度沿X轴旋转

时间:2017-01-01 15:39:34

标签: android accelerometer android-sensors

我正在开发一款Android应用,我希望水平滚动一张大图片。我使用加速度计(Sensor.TYPE_ACCELEROMETER)和磁场(Sensor.TYPE_MAGNETIC_FIELD)数据来获得旋转角度。这些数据频繁出现噪音,我无法实现平滑的动作效果。

@Override
public void onSensorChanged(SensorEvent event) {
    switch (event.sensor.getType()) {
        case Sensor.TYPE_MAGNETIC_FIELD:
            mags = event.values.clone();
            break;
        case Sensor.TYPE_ACCELEROMETER:
            accels = event.values.clone();
            break;
    }

    if (mags != null && accels != null) {
        gravity = new float[16];
        boolean success = SensorManager.getRotationMatrix(gravity, null, accels, mags);
        if (success) {
            float[] outGravity = new float[16];
            SensorManager.remapCoordinateSystem(gravity, SensorManager.AXIS_X, SensorManager.AXIS_Z, outGravity);
            SensorManager.getOrientation(outGravity, values);

            rollingAverage[0] = roll(rollingAverage[0], values[0]);
            rollingAverage[1] = roll(rollingAverage[1], values[1]);
            rollingAverage[2] = roll(rollingAverage[2], values[2]);

            azimuth = Math.toDegrees(values[0]);
            pitch = Math.toDegrees(values[1]);
            roll = Math.toDegrees(values[2]);
            mags = null;
            accels = null;

            double diffRoll = lastRoll - roll;
            double diffPitch = lastPitch - pitch;
            long curTime = System.currentTimeMillis();
            if (Math.abs(diffRoll) >= 2) {
                if (diffRoll > 0)
                    imageView.panLeft();
                else
                    imageView.panRight();
                lastRoll = roll;
            }
        }
    }
}

有关使用其他方法实现此目的的任何想法吗?

1 个答案:

答案 0 :(得分:0)

您必须实施基于卡尔曼滤波器或其他滤波器的传感器融合技术。如果需要,您可以使用开源库。请参阅此bitbucket repository。如果您想自己做,请阅读tutorial.