ben ben - 5 months ago 39
Java Question

How to calibrate orientation sensors in android

I'm trying to get data from my phone's gyros.
So far,the angles keep changing depends on the angle that i move my phone.

However, the azimuth angle for example, i want it to start counting from the position i started and not from the north direction --> i want it to start from 0.

my question is: how can i save the first data i get from the gyro so i could do "minus" from the rest of the data when i move the phone?
The code looks like this:

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]);

}


The thing i want to do is like:

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


Thanks!

new code:

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]);

}

Answer

Why not just

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]);
}