Question

i have an appli which display x, y, z orientation values calculated with accelerometer and magnetometer. But when i swap from portrait to landscape, i don't get the same X value. I tryed to implement with Rotation Vector, but my device doesn't have rotation vector sensor :s

Here's my code to calculate X, Y, Z value :

@Override
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    float x, y, z;
    String s1 = "stringX", s2 = "stringY", s3 = "stringZ";
    // Mettre à jour la valeur de l'accéléromètre et du champ magnétique
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        acceleromterVector=event.values;
    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        magneticVector=event.values;
    }
    // Demander au sensorManager la matrice de Rotation (resultMatrix)
    SensorManager.getRotationMatrix(resultMatrix, null, acceleromterVector, magneticVector);
    // Demander au SensorManager le vecteur d'orientation associé (values)
    SensorManager.getOrientation(resultMatrix, values);
    // l'azimuth
    x = (float) Math.toDegrees(values[0]);
    // le pitch
    y = (float) Math.toDegrees(values[1]);
    // le roll
    z = (float) Math.toDegrees(values[2]);


    s1 = "X :" + x;
    s2 = "Y :" + y;           
    s3 = "Z :" + z;

    tvx.setText(s1);
    tvy.setText(s2);
    tvz.setText(s3);

    updateOrientation(x);
}

Thank you guys.

Was it helpful?

Solution

The sensor values are always relative to the default orientation, so you need to take account of the rotation away from the default orientation. To do this, use something like the following:

int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
float screen_adjustment = 0;
switch(rotation) {
    case Surface.ROTATION_0:   screen_adjustment =          0;         break;
    case Surface.ROTATION_90:  screen_adjustment =   (float)Math.PI/2; break;
    case Surface.ROTATION_180: screen_adjustment =   (float)Math.PI;   break;
    case Surface.ROTATION_270: screen_adjustment = 3*(float)Math.PI/2; break;
}

to adjust the azimith. For a fully working example, see the code that I posted in my answer here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top