Search code examples
javascriptdevice-orientation

Acceleration regardless of device orientation


This javascript code measures the horizontal acceleration on the x axis. The intention is to measure the acceleration if the device was to move on a straight line parallel to the earth "horizontal" surface, irrespective of the device orientation.
Can that be done via gyroscope data during a given period of acceleration approx. 5 seconds? How? thx

let xAxis = '';

function handleMotionEvent(event) {
  let x = event.accelerationIncludingGravity.x;
  if (!xAxis) {
    xAxis = x;
  } else {
    if (Math.abs(x - xAxis) > 0.4) {
      console.log(x);
    }
  }
}

if (window.DeviceMotionEvent) {
  window.addEventListener("devicemotion", handleMotionEvent, true);
}

Solution

  • Based on this documentation, the accelerationIncludingGravity property is an object providing information about acceleration on three axis. Each axis is represented with its own property:

    • x: acceleration in x axis (west to east)
    • y: acceleration in y axis (south to north)
    • z: acceleration in z axis (down to up)

    So from mathematics, to get total horizontal acceleration we can combine x and y components using r^2 = x^2 + y^2 formula.

    ...
    a = Math.sqrt(x*x + y*y); //horizontal acceleration
    ...