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

前端 未结 4 1978
心在旅途
心在旅途 2020-12-11 16:16

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 f

4条回答
  •  孤街浪徒
    2020-12-11 16:50

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

提交回复
热议问题