title: DeviceOrientationEvent: how to deal with crazy gamma when beta approaches/hits 90deg?
body: <p>Anyone with DeviceOrientationEvent experience and a phone/tablet handy?</p>
  
  <p>Running the following code snippets on a gyroscope-having device, I notice gamma (rotating left/right along y-axis) gets large and unpredictable as beta approaches 90deg (device pointing straight up).  I assume this is <a href="https://en.wikipedia.org/wiki/Gimbal_lock" rel="noreferrer">gimbal-lock</a>.  </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var data, raf, alpha = document.getElementById("alpha"),
    beta = document.getElementById("beta"),
    gamma = document.getElementById("gamma");
  
  window.addEventListener("deviceorientation", processData);
  window.addEventListener('click', togglePause);
  updateText();
  
  function processData(e) {
    data = e;
  }
  
  function updateText() {
    if (data) {
      alpha.textContent = Math.round(data.alpha);
      beta.textContent = Math.round(data.beta);
      gamma.textContent = Math.round(data.gamma);
    }
    raf = requestAnimationFrame(updateText);
  }
  
  function togglePause(e) {
    if (raf) {
      cancelAnimationFrame(raf);
      raf = null;
      window.removeEventListener("deviceorientation", processData);
    } else {
      window.addEventListener("deviceorientation", processData);
      raf = requestAnimationFrame(updateText);
    }
  }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font: normal 30px/200% sans-serif;
    margin: 20px;
    cursor: default;
  }
  span {
    font-size: 50px;
    vertical-align: middle;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt;
    alpha: &lt;span id="alpha"&gt;null&lt;/span&gt;
    &lt;br&gt;beta: &lt;span id="beta"&gt;null&lt;/span&gt;
    &lt;br&gt;gamma: &lt;span id="gamma"&gt;null&lt;/span&gt;
    &lt;br&gt;[tap to pause/resume]
  &lt;/body&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p><a href="https://jsfiddle.net/1us8p1ad/show" rel="noreferrer">https://jsfiddle.net/1us8p1ad/show</a></p>
  
  <p>My question: How can I predictably track left/right device orientation using gamma?  Gamma is the only value I care about - no 3d space needed.  </p>
  
  <p>I looked into using rotation matrix and quaternion as discussed <a href="https://dev.opera.com/articles/w3c-device-orientation-usage/" rel="noreferrer">here</a>, but not getting valid results.  In fact, the examples on the author's github page also break when beta hits 90deg!  Same with this <a href="https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation" rel="noreferrer">MDN tutorial</a> - check it on your device: when it's straight up, the ball goes bonkers.  How have these aberrations gone unnoticed!</p>