I just registered to show some love for this code sample, it helped me greatly because I needed to the phone's angle to filter out gravity from the accelerometer and this code helped me do just that.

Specifically using it as a base it can be reconfigured into:

Using java Syntax Highlighting

//put these in variables so they can be adjusted for device calibration

private double gravityConstantX = SensorManager.GRAVITY_EARTH;

private double gravityConstantY = SensorManager.GRAVITY_EARTH;

private double gravityConstantZ = SensorManager.GRAVITY_EARTH;

double accX = -x/gravityConstantX;

double accY = -y/gravityConstantY;

double accZ = -z/gravityConstantZ;

double totAcc = Math.sqrt((accX*accX)+(accY*accY)+(accZ*accZ));

double tiltXInGs = Math.asin(accX/totAcc);

double tiltYInGs = Math.asin(accY/totAcc);

double tiltZInGs = Math.asin(accZ/totAcc);

//convert to rads, or something close, end up with the opposite angle

double tiltX = Math.sin(tiltXInGs);

double tiltY = Math.sin(tiltYInGs);

double tiltZ = Math.sin(tiltZInGs);

//use these angles to calculate gravity * -1

Double gx = (gravityConstantX * Math.sin(tiltX));

Double gy = (gravityConstantY * Math.sin(tiltY));

Double gz = (gravityConstantZ * Math.sin(tiltZ));

//add the resulting negative gravity and convert the result (acceleration of the phone relative to the ground)

// to centimeters a second

Integer resultx = metersToCentimeters(x + gx);

Integer resulty = metersToCentimeters(y + gy);

Integer resultz = metersToCentimeters(z + gz);

//assuming the phone is held on it's back it seems to need this correction

resultz -= 100;

Parsed in 0.022 seconds, using

GeSHi 1.0.8.4

- private Integer metersToRoundedOffCentimeters(Double meters) {
- Integer centimeters = (int) Math.round(100 * meters);
- return centimeters;
- }

The math is more advanced then I currently know, so I don't exactly understand how it works. I discovered the "double tiltX = Math.sin(tiltXInGs);" line accidentally while trying to work out how to convert it into angles.