android - 过滤方向传感器

时间:2014-09-15 13:44:41

标签: android android-sensors

我正在使用方向传感器来测量相对于代码中定义的校准点的斜率等级。当平板电脑处于稳定的待测点时,输出相当跳跃(+/-〜。35)。我想对传感器的输出进行某种过滤,但我不确定如何真正做到这一点。

到目前为止,这是我的代码:

在onCreateView()

sensorCalibrate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    calibratedPitch = pitch;
                    adjustedRoll = roll;
                    // adjPitchDisplay.setText(Float.toString(Math.abs(calibratedPitch)) + "   ");

                    Toast.makeText(getActivity(), "Sensor Calibrated!", Toast.LENGTH_SHORT).show();

                }
            });

然后再做一些方法

public void onSensorChanged(SensorEvent event) {
    if (event.sensor == mRotationSensor) {
        if (event.values.length > 4) {
            float[] truncatedRotationVector = new float[4];
            System.arraycopy(event.values, 0, truncatedRotationVector, 0, 4);
            update(truncatedRotationVector);
        } else {
            update(event.values);
        }
    }
}

private void update(float[] vectors) {
    final NumberFormat formatter = NumberFormat.getNumberInstance();
    formatter.setMinimumFractionDigits(5);
    formatter.setMaximumFractionDigits(5);

    float rads_to_Degrees = 57.29578F;

    float[] rotationMatrix = new float[9];
    SensorManager.getRotationMatrixFromVector(rotationMatrix, vectors);
    int worldAxisX = SensorManager.AXIS_X;
    int worldAxisZ = SensorManager.AXIS_Z;
    float[] adjustedRotationMatrix = new float[9];
    SensorManager.remapCoordinateSystem(rotationMatrix, worldAxisX, worldAxisZ, adjustedRotationMatrix);
    float[] orientation = new float[3];
    SensorManager.getOrientation(adjustedRotationMatrix, orientation);

    pitch = orientation[1]*rads_to_Degrees;
    roll = orientation[2]*rads_to_Degrees; // roll will be implemented later on
    pitch = Math.abs(pitch);
    roll = Math.abs(roll);

    outputPitch = (calibratedPitch - pitch);
    final double tanPitch = Math.tan(Math.toRadians(outputPitch));
    outputGrade = tanPitch * 100D;

    outputGradeDisplay.setText("Current grade " + String.format("%.2f",outputGrade) + "%");
}

1 个答案:

答案 0 :(得分:0)

你可以试试一个快速而又脏的低通滤波器:

private static final double K = 0.9;

private void update (..) {
  ...
  pitch     = K*lastPitch + (1.0 - K)*(Math.abs(orientation[1] * rads_to_Degrees); 
  lastPitch = pitch;
  ...
}

其中0.0 <= K <= 1.0。

K接近1.0的值将为您提供更稳定但输出响应更慢的输出,K接近0.0的值将使输出响应更快但更“紧张”。