Saturday, 16 October 2021

The simplest way to solve gimbal lock when using DeviceOrientation events in javascript - How to make a spirit level/bubble level app

Starting with

window.addEventListener("deviceorientation", handleDeviceTilt);
function handleDeviceTilt(e){
// Here we can use e.beta, e.gamma
// Note that we don't need e.alpha because that's just the compass
}

beta and gamma values are nice and usable as long as the phone or tablet is held parallel to the ground (like resting on a table). But when the phone or tablet is held parallel to a wall, both beta and gamma stop offering realistic values. gamma gets especially crazy when the device is held upright-vertically (i.e. portrait mode) which is the most common way of holding a mobile device.

enter image description here

We need to calculate the real angles so that we can use the tilt information accurately in the app. The question is,

What would be the simplest way using Math.cos() and Math.sin() to calculate the real angles like realBeta and realGamma and unlock the so called gimbal lock? Can this be done without matrices and quaternions? Is there a cool formula that can fit in a few lines of minimalist code?

Note 1: There is a spirit level app on PlayStore that does show the real tilt angles of the device perfectly. So there is proof that it is doable. However as of 2021 there seems to be no open source code available for such an app written in javascript.

Note 2: This issue has been mentioned here.

Note 3: Precision is necessary. We need exact angles. Random divisions that yield inaccurate results are not a solution. ALPHA MUST BE OMITTED for simplicity.

Note 4: Libraries like fulltilt.js and gyronorm.js seem to be outdated.

P.S. Do not post recommendations or vague personal experience as answers. ONLY TESTED AND PERFECTLY WORKING SOLUTIONS PLEASE.



from The simplest way to solve gimbal lock when using DeviceOrientation events in javascript - How to make a spirit level/bubble level app

No comments:

Post a Comment