Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compass in Android

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?

like image 896
user1809923 Avatar asked Nov 08 '12 16:11

user1809923


2 Answers

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

like image 143
rgrocha Avatar answered Oct 06 '22 00:10

rgrocha


A code snippet could be got from https://github.com/iutinvg/compass

It does not use deprecated stuffs, applies low-pass filter.

like image 22
iutinvg Avatar answered Oct 06 '22 00:10

iutinvg