如何在 android 中校准方向传感器

How to calibrate orientation sensors in android

我正在尝试从我的 phone 的陀螺仪中获取数据。 到目前为止,角度不断变化取决于我移动 phone.

的角度

但是,例如方位角,我希望它从我开始的位置开始计数,而不是从北方向开始 --> 我希望它从 0 开始。

我的问题是:如何保存从陀螺仪获得的第一个数据,这样当我移动 phone 时,我可以根据其余数据做 "minus"? 代码如下所示:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
    rotationvector=sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    sm.registerListener(this,rotationvector,SensorManager.SENSOR_DELAY_NORMAL);

    rotationx=(TextView)findViewById(R.id.rotationx);
    rotationy=(TextView)findViewById(R.id.rotationy);
    rotationz=(TextView)findViewById(R.id.rotationz);


}
@Override
public void onSensorChanged(SensorEvent event) {


    rotationx.setText(" " +event.values[0]);
    rotationy.setText(" " +event.values[1]);
    rotationz.setText(" " +event.values[2]);

}

我想做的事情是这样的:

    rotationx.setText(" " +event.values[0]-FirstAzimuthValue);

谢谢!

新代码:

private boolean isFirstMeasure = true;
private float FirstAzimuthValue = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
    rotationvector=sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    sm.registerListener(this,rotationvector,SensorManager.SENSOR_DELAY_NORMAL);

    rotationx=(TextView)findViewById(R.id.rotationx);
    rotationy=(TextView)findViewById(R.id.rotationy);
    rotationz=(TextView)findViewById(R.id.rotationz);

}
@Override
public void onSensorChanged(SensorEvent event) {

    if (isFirstMeasure){
        FirstAzimuthValue - event.values[0]; //error this line
        isFirstMeasure = false;
    }

    rotationx.setText(" " +(event.values[0] - FirstAzimuthValue));
    rotationy.setText(" " +event.values[1]);
    rotationz.setText(" " +event.values[2]);

}

为什么不只是

private boolean isFirstMeasure = true;
private float firstAzimuthValue = 0;

// ...

@Override
public void onSensorChanged(SensorEvent event) {
    if (isFirstMeasure) {
        firstAzimuthValue = event.values[0];
        isFirstMeasure = false;
    }

    rotationx.setText(" " + (event.values[0] - firstAzimuthValue));
    rotationy.setText(" " +event.values[1]);
    rotationz.setText(" " +event.values[2]);
}