从陀螺仪传感器获取旋转角度的方法(Android平台)

5

到目前为止,我已经在互联网上搜索了很多内容。我正在尝试开发一个问题,需要从手机的起始点获取旋转角度。为了知道用户是否将手机向上或向下移动,我使用了加速度计,开始时有点不稳定,但我设法使它变得稳定。 现在我需要自身旋转的角度。就像方向传感器一样,它已被弃用。然后我尝试使用磁力计,但它非常不稳定。 然后我决定尝试使用陀螺仪,当我使用示例代码时:

 // 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 = (float) Math.sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);

     // Normalize the rotation vector if it's big enough to get the axis
     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 = (float) Math.sin(thetaOverTwo);
     float cosThetaOverTwo = (float) Math.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;

这段代码来自于他们的文档,有没有办法将其转换为360度?或者我能得到数值,即手机离起点转了多少度?

提前感谢。


请查看此线程:https://dev59.com/pnbZa4cB1Zd3GeqPFWew - M.Hefny
1个回答

2
使用 getRotationMatrix() 获取两个时间点的 3x3 旋转矩阵 R1R2。您想知道将 R1R2 对齐所需的旋转角度 angle,即旋转矩阵 R 的角度。

首先计算旋转矩阵 R

R = R1 * transpose(R2)

然后计算这个旋转的角度:
angle = acos((trace(R)-1)/2)

这就是全部内容。


非常感谢你抽出时间来尝试回答这个问题。我不是数学高手。返回的RotationMatrix不是二维的,如何转置?我制作了自己的转置方法:public float[] transposeMatrix(float[] m){ float[] res = new float[9]; res[0] = m[0]; res[1] = m[3]; res[2] = m[6]; res[3] = m[1]; res[4] = m[4]; res[5] = m[7]; res[6] = m[2]; res[7] = m[5]; res[8] = m[8]; return m; } - user1819127
但是,我在Java中无法对R1和R2进行*运算,它显示操作符未定义。您能再给我一些帮助吗?提前感谢! - user1819127
维基百科是你的朋友:转置矩阵乘法. - Ali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接