【问题标题】:Obtaining user's heading using Accelerometer and Magnetometer使用加速度计和磁力计获取用户的航向
【发布时间】:2015-04-23 14:56:53
【问题描述】:

我正在尝试仅使用加速度计和磁力计传感器在 Android 手机上获取用户航向的值。我一直在寻找许多其他解决方案,但是在尝试实现自己的代码时遇到了一些问题。

代码如下:

if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
    Log.d("MAG_FIELD", "ITS A MAG FIELD");

        //aX, aY, aZ are raw accelerometer values 
        float aTheta = (float) Math.atan2(-aX, aZ);
        float aPhi = (float) Math.atan2(-aY, aZ);

        //Obtaining the current magnetometer readings
        float mDegX = event.values[0];
        float mDegY = event.values[1];
        float mDegZ = event.values[2];

        float rotationVectorX = (float) ((mDegX * Math.cos(aPhi)) + (mDegY *Math.sin(aTheta) * Math.sin(aPhi)) - (mDegZ * Math.cos(aTheta) * Math.sin(aPhi)));
        float rotationVectorY = (float) ((mDegY * Math.cos(aTheta)) + (mDegZ * Math.sin(aTheta)));

        //HEADING calculation

        float heading = (float)  Math.abs(Math.toDegrees(Math.atan(rotationVectorY /rotationVectorX)));

        if(rotationVectorX >= 0.0f && rotationVectorY >=0.0f) {}
        else if(rotationVectorX < 0.0f && rotationVectorY >= 0.0f) {heading = 180 - heading ;}
        else if(rotationVectorX < 0.0f && rotationVectorY < 0.0f) {heading = 180 + heading;}
        else if(rotationVectorX >= 0.0f && rotationVectorY < 0.0f){heading = 360 - heading;}

我的问题是:

  1. 当设备时,航向总是偏离大约 90 度 平坦
  2. 当屏幕从平面上改变时,标题会改变 - 我需要它是相同的

【问题讨论】:

    标签: android android-sensors


    【解决方案1】:

    使用磁力计和加速度计您可以实时找到设备的航向。即使您的设备不在平面上也可以使用。

     if (event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD) {
                geomag[0]=event.values[0];
                geomag[1]=event.values[1];
                geomag[2]=event.values[2];
            }
    
     if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
                float alpha = 0.8f;
    
                gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
                gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
                gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];               
            }
    
                rotationMatrix = new float[16];
                SensorManager.getRotationMatrix(rotationMatrix, null, gravity, geomag);
                SensorManager.getOrientation(rotationMatrix,vals);
    
                double Heading=vals[0] * (180/Math.PI);
    

    【讨论】:

      猜你喜欢
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 2020-11-14
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      相关资源
      最近更新 更多