Android accelerometer angle calculation

Can anyone give any idea to calculate the angle at which the compass needle should rotate to point in the direction of gravity from the accelerometer x, y, z values?


source to share

1 answer

I think X should be 0 and y should be positive and z close to 0 for a compass pointing down to the ground. (This means the phone is held vertically).

In general, from angle 0, the compass angle should be something like

float accelerometerMaxRange = 10; // This is NOT right, but it a good value to work with
float newAngle = 0;
if (z > 9) {
    // Phone is horizontally flat, can't point towards gravity, really. Do whatever you think is right
} else {
    newAngle  = (float)(x * 90 / accelerometerMaxRange);
    if (y < 0) {
        newAngle = 180 - newAngle;




All Articles