How can I get the magnetic field vector, independent of the device rotation?

Viewed 7466

What I want to archieve is a sort of "magnetic fingerprint" of a location. I use the MAGNETIC_FIELD sensor and in the event I get the 3 values for the (unfortunately not further explained) X, Y and Z axis.

Problem is, that the values change as I rotate the device, so I guess the 3 axis are relative to the device. What I'd need is to compensate the device rotation so that I get the same 3 values, regardless of how the device is rotated.

I tried to multiply with the rotation matrix (I know how to get that), tried to multiply with the inclination matrix and so on, but nothing works. Regardless of what I try, still the values change when I rotate the device.

So does anyone know how to do it right? Preferrably with code, because I read a lot of stuff like 'well then you'll have to compensate that using rotation matrix' but did not find a single concrete, working example.

4 Answers

to get the strength of the magnetic field, you have to get the x,y,z values of the magnetic field (from Sensor.TYPE_MAGNETIC_FIELD), and apply the following formula:

double magnetic_field_strength = Math.sqrt( (Xvalue*Xvalue) + (Yvalue*Yvalue) + (Zvalue*Zvalue) );

magnetic_field_strength is expressed in microtesla (µT)
It could be noted that the average magnetic field strength of the Earth is 50 µT, according to this website.


So a possible code would be:

private SensorEventListener sensorEventListener = new SensorEventListener() {   
    @Override
    public void onSensorChanged(SensorEvent event) {

        switch (event.sensor.getType()) {
        case Sensor.TYPE_MAGNETIC_FIELD:                        
            magnetic_field_strength = Math.sqrt((event.values[0]*event.values[0])+(event.values[1]*event.values[1])+(event.values[2]*event.values[2]));
            break;                      
        default: 
            return;
        }                
    }
}
Related