2

假设我的当前方向为(azimuth, pitch, roll). 现在我想用陀螺仪更新我的方向。根据Android开发网给出的代码,我可以得到所谓deltaRotationMatrix的如下:

// Create a constant to convert nanoseconds to seconds.
private static final float NS2S = 1.0f / 1000000000.0f;
private final float[] deltaRotationVector = new float[4]();
private float timestamp;

public void onSensorChanged(SensorEvent event) {
  // This timestep's delta rotation to be multiplied by the current rotation
  // after computing it from the gyro sample data.
  if (timestamp != 0) {
    final float dT = (event.timestamp - timestamp) * NS2S;
    // Axis of the rotation sample, not normalized yet.
    float axisX = event.values[0];
    float axisY = event.values[1];
    float axisZ = event.values[2];

    // Calculate the angular speed of the sample
    float omegaMagnitude = sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);

    // Normalize the rotation vector if it's big enough to get the axis
    // (that is, EPSILON should represent your maximum allowable margin of error)
    if (omegaMagnitude > EPSILON) {
      axisX /= omegaMagnitude;
      axisY /= omegaMagnitude;
      axisZ /= omegaMagnitude;
    }

    // Integrate around this axis with the angular speed by the timestep
    // in order to get a delta rotation from this sample over the timestep
    // We will convert this axis-angle representation of the delta rotation
    // into a quaternion before turning it into the rotation matrix.
    float thetaOverTwo = omegaMagnitude * dT / 2.0f;
    float sinThetaOverTwo = sin(thetaOverTwo);
    float cosThetaOverTwo = cos(thetaOverTwo);
    deltaRotationVector[0] = sinThetaOverTwo * axisX;
    deltaRotationVector[1] = sinThetaOverTwo * axisY;
    deltaRotationVector[2] = sinThetaOverTwo * axisZ;
    deltaRotationVector[3] = cosThetaOverTwo;
  }
  timestamp = event.timestamp;
  float[] deltaRotationMatrix = new float[9];
  SensorManager.getRotationMatrixFromVector(deltaRotationMatrix, deltaRotationVector);
    // User code should concatenate the delta rotation we computed with the current rotation
    // in order to get the updated rotation.
    // rotationCurrent = rotationCurrent * deltaRotationMatrix;
   }
}

我应该如何处理这个片段以更新我的方向?

4

1 回答 1

1

您只需将 deltaRotationMatrix 乘以 rotationCurrentMatrix,然后调用 SensorManager.getOrientation()。您将需要实现一个矩阵乘法方法。您还需要一个初始 currentRotationMatrix,您可以使用带有 SensorManager.getRotationMatrix 和 SensorManager.getOrientation 的加速度传感器和磁传感器来获取初始 currentRotationMatrix。或者,您可以使用 TYPE_ROTATION_VECTOR 来获取初始 currentRotationMatrix。

    currentRotationMatrix = matrixMultiplication(
                currentRotationMatrix,
                deltaRotationMatrix);

    SensorManager.getOrientation(currentRotationMatrix,
                gyroscopeOrientation;

不幸的是,您会意识到,即使是应该针对漂移进行校准的 TYPE_GYROSCOPE 传感器也不能很好地完成工作,并且传感器很快就会随着设备的旋转而漂移。令人沮丧。

我有一个 GitHub 存储库,这里实现了所有这些,还有 一个 Play Store 上的工作项目在这里

于 2013-12-04T16:49:27.530 回答