Reputation: 33491
I am trying to create a simple compass app (for learning purposes) and I am using the rotation matrix using the magnetic sensor and accelerometer. This is my code:
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
geomagnetic[0] = event.values[0];
geomagnetic[1] = event.values[1];
geomagnetic[2] = event.values[2];
havemag = true;
}
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
gravity[0] = event.values[0];
gravity[1] = event.values[1];
gravity[2] = event.values[2];
haveacc = true;
}
if (haveacc && havemag) {
if (SensorManager.getRotationMatrix(Rm, I, gravity, geomagnetic)) {
float[] result = new float[3];
SensorManager.getOrientation(Rm, result);
azimuth = result[0];
pitch = result[1];
roll = result[2];
}
}
}
When I look at these values while moving my phone though (outputing using Log.d
), I get incorrect values. I use this code to make degrees out of them:
int deg = (int)(azimuth * (float)57.295);
But this value never reaches zero (which is supposed to be on the exact opposite side of 180/-180). Instead, the opposite of where 180/-180 is, I get -85 (approx).
Upvotes: 2
Views: 5302
Reputation: 1137
You should use the proper JavaMath function to convert your radian angle to degree. Furthermore converting the angle (in degree) to a [0 - 360] degree interval is very useful.
// angle in degree [-180 - 0 - 180] degree
azimuth = Math.toDegrees( result[0] )
// angle in degree [0 - 360] degree
azimuth = ( Math.toDegrees( result[0] ) + 360 ) % 360;
Upvotes: 7