Search code examples
androidorientationaccelerometergyroscope

Correct way to use ONLY Gyroscope and Accelerometer to get the reliable current angle in any axis on ANDROID


A week ago i didn't know anything about Android Motion Sensors. After know the amazing thing called Virtual Reality I started to search about which sensors are used to get those results. Than I had a idea for a APP but I still don't know which sensors I should use for the situation below:

I have to get the phone orientation in reference to it self. I mean, I should be able to isolate each axis in degress. Something like it:

enter image description here

In this case, using gyroscope, I think that this variation is on the Z Axis. Using ONLY gyroscope I had a good result for this situation, but after some repetions, I got a famous problem for the Gyro Sensor: Drift.

After this tutorial: http://www.thousand-thoughts.com/articles/#articles

things became more clear in my head, but I still am having problems like latency between the real movement, and the output and wrong outputs when I change the device orientation (I think that the gravity is the guilty for that).

Is there some code example about how to get 0 - 360 degrees for each axis using ONLY the gyroscope and accelerometer sensors?

(I may had commited some english mistakes. Sorry for that)


Solution

  • The following code will give you correct lean angle, but only if your phone Z axis is 0. (like the way you illustrated it). When starting to change the Z axis as well, it become problematic, i'm still working on that. (* Degrees has minus "-" sign when lean left and "+" sign to the right)

    float[] mGravity;
    float[] mGeomagnetic;
    
    
        float[] temp = new float[9];
        float[] RR = new float[9];
        //Load rotation matrix into R
        SensorManager.getRotationMatrix(temp, null,
                mGravity, mGeomagnetic);
    
        //Remap to camera's point-of-view
        SensorManager.remapCoordinateSystem(temp,
                SensorManager.AXIS_X,
                SensorManager.AXIS_Z, RR);
    
        //Return the orientation values
        float[] values = new float[3];
        SensorManager.getOrientation(RR, values);
    
        Double degrees = (values[2] * 180) / Math.PI;