I have an app that reads the values returned by the magnetometer.
The way it does it at the moment is in the phone's coordinates system.
I want to be able to always read the magnetic field vector in a global coordinates system (x,y,z - east, north, sky)
The code I tried (inspired from this question) will result in a value of 0 for the x axis component, and variable y,z depending on the way I tilt the phone. As far I understood, the rotation matrix transform should make my coordinates system global, but it doesn't seem that way.
The expected behaviour would be to have the same value on the x,y,z components as long as I hold the phone in one place, no matter its tilt.
private final float alpha = (float) 0.8;
private float gravity[] = new float[3];
private float magnetic[] = new float[3];
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// Isolate the force of gravity with the low-pass filter.
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];
} else if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnetic[0] = event.values[0];
magnetic[1] = event.values[1];
magnetic[2] = event.values[2];
float[] R = new float[9]; //rotation matrix
float[] I = new float[9]; //inclination
SensorManager.getRotationMatrix(R, I, gravity, magnetic);
float [] A_D = event.values.clone(); // device coordinates
float [] A_W = new float[3]; // global coodinates
A_W[0] = R[0] * A_D[0] + R[1] * A_D[1] + R[2] * A_D[2];
A_W[1] = R[3] * A_D[0] + R[4] * A_D[1] + R[5] * A_D[2];
A_W[2] = R[6] * A_D[0] + R[7] * A_D[1] + R[8] * A_D[2];
Log.d("Field","\nX :"+A_W[0]+"\nY :"+A_W[1]+"\nZ :"+A_W[2]);
}