Search code examples
androidandroid-sensorsandroid-orientation

Android device angle on vertical axis while device stays still


I am developing my first app and for some calculations I need an angle of vertical axis. Basically I am trying to make simple measure tool which would do the calculations on Button click. I have height(H) in which is device and I need angle of device vertical axis. Having these values I'll be able to calculate sin and so on.

I tried to use code from this link (finding orientation using getRotationMatrix() and getOrientation()) to get values, but it crashes and also I think it's not the values I want, because device stays still.

Iliustration of what I mean (I have 'H' value and I am searching for angle 'a' or data from which I can extract it):

http://s2.postimg.org/z4mgu4l49/angle_A.jpg

Any useful links, tutorials or samples would be very helpful.


Solution

  • I assume that the Android device will be lying along the hypotenuse of the triangle that you've drawn, so that if the device was lying flat on the table then your angle 'a' would be 90 degrees, and if the device is standing upright then the angle 'a' would be zero. If so, then that angle 'a' is related to the pitch of the device, which is exactly what you should be able to get by using getRotationMatrix() and getOrientation(). However, the pitch is usually defined as being zero when the device is lying flat on the table and 90 degrees when it's upright, so your angle 'a' is equal to (90 degrees - pitch). Beware of units, sometimes angles are in radians, and sometimes in degrees.

    If you code is crashing, then you must have accidentally introduced a bug somewhere, because I've certainly got code that uses getRotationMatrix() and getOrientation() without crashing.

    You'll find that some of the orientation values produced by getOrientation() become erratic when the device approaches a vertical position. This is a problem known as Gimbal lock, because when the device is verical, azimuth and roll are the same thing. However, pitch should remain reliable.

    If you ever need reliable azimuth as well as pitch when the device is vertical, then you could have a look at my answer to the question 'Android Compass that can Compensate for Tilt and Pitch'. That answer has code that definitely works, and if you can't get getRotationMatrix() and getOrientation() working, then the pitch that comes out of that will work fine for you.