I am trying to program a compass with Android using the accelorometer and the magnetic field sensor, now I am wondering how to get the correct angle for my compass.
I read in the values of the accelerometer and of the magnetic field sensor in "accele", and "magne" respectively. To get the angle, I perform the following:
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, accele, magne);
if(success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
azimuth = orientation[0]; // contains azimuth, pitch, roll
....
Later on, I use a rotation matrix to put my needle:
rotation.setRotate(azimuth, compass.getWidth() / 2, compass.getHeight() / 2);
canvas.drawBitmap(needle, rotation, null);
Now, the documentation of getOrientation says, that orientation[0] should be the rotation around the z-axis. The documentation for TYPE_ORIENTATION states that "Azimuth, angle between the magnetic north direction and the y-axis, around the z-axis (0 to 359). 0=North, 90=East, 180=South, 270=West".
My azimuth however is not between 0 and 359, but rather around -2 to 2. What exactly is the azimuth from getOrientation and how can I convert it to an angle?
Use the following to convert from the given azimuth in radians (-PI, +PI) to degrees (0, 360)
float azimuthInRadians = orientation[0];
float azimuthInDegress = (float)Math.toDegrees(azimuthInRadians);
if (azimuthInDegress < 0.0f) {
azimuthInDegress += 360.0f;
}
variable names used for convenience ;-)
A code snippet could be got from https://github.com/iutinvg/compass
It does not use deprecated stuffs, applies low-pass filter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With