Android中的指南针

use*_*923 14 android android-sensors

我正在尝试使用accelorometer和磁场传感器用Android编程指南针,现在我想知道如何为我的指南针获得正确的角度.

我分别用"加速度"和"磁力"读取加速度计和磁场传感器的值.为了获得角度,我执行以下操作:

float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, accele, magne);
        if(success) {
            float orientation[] = new float[3];
            SensorManager.getOrientation(R, orientation);
            azimuth = orientation[0]; // contains azimuth, pitch, roll
                            ....
Run Code Online (Sandbox Code Playgroud)

后来,我使用旋转矩阵来放我的针:

rotation.setRotate(azimuth, compass.getWidth() / 2, compass.getHeight() / 2);
canvas.drawBitmap(needle, rotation, null);
Run Code Online (Sandbox Code Playgroud)

现在,getOrientation的文档说,方向[0]应该是围绕z轴的旋转.TYPE_ORIENTATION的文档指出"方位角,磁北方向和y轴之间的角度,围绕z轴(0到359).0 =北,90 =东,180 =南,270 =西".

然而,我的方位角不在0到359之间,而是在-2到2之间.来自getOrientation的方位角到底是什么?如何将其转换为角度?

rgr*_*cha 21

使用以下方法将给定方位角(弧度)(-PI,+ PI)转换为度数(0,360)

float azimuthInRadians = orientation[0];
float azimuthInDegress = (float)Math.toDegrees(azimuthInRadians);
if (azimuthInDegress < 0.0f) {
    azimuthInDegress += 360.0f;
}
Run Code Online (Sandbox Code Playgroud)

用于方便的变量名;-)

  • 嗨!是的,这实际上应该有效.谢谢!但是-180和180被解释为与Matrix.setRotate()相同,因此不需要if子句 (2认同)

iut*_*nvg 8

可以从https://github.com/iutinvg/compass获取代码段

它不使用弃用的东西,应用低通滤波器.