How to Access Accelerometer/Gyroscope Data from JavaScript

How to access accelerometer/gyroscope data from Javascript?

The way to do this in 2019+ is to use DeviceOrientation API. This works in most modern browsers on desktop and mobile.

window.addEventListener("deviceorientation", handleOrientation, true);

After registering your event listener (in this case, a JavaScript
function called handleOrientation()), your listener function
periodically gets called with updated orientation data.

The orientation event contains four values:

  • DeviceOrientationEvent.absolute
  • DeviceOrientationEvent.alpha
  • DeviceOrientationEvent.beta
  • DeviceOrientationEvent.gamma

The event handler function can look something like this:

function handleOrientation(event) {
var absolute = event.absolute;
var alpha = event.alpha;
var beta = event.beta;
var gamma = event.gamma;
// Do stuff with the new orientation data
}

Access accelerometer via Javascript in Android?

As of ICS, Android 4.0, you can use the 'devicemotion' event via a JavaScript event listener to access the accelerometer data. See the W3C documentation on how to access it - http://dev.w3.org/geo/api/spec-source-orientation.html.

Note - The W3C documentation title is named with 'device orientation', but the spec does indeed include 'devicemotion' event documentation.

How do I detect if a device has a gyroscope in a web browser?

If you want to check if gyroscope is present or not, check the parameters that only gyroscope can measure. For example rotation rate is something only gyroscope measures.

Have a look at an example code which says whether gyroscope is present or not:

var gyroPresent = false;
window.addEventListener("devicemotion", function(event){
if(event.rotationRate.alpha || event.rotationRate.beta || event.rotationRate.gamma)
gyroPresent = true;
});

Hope this helps!

EDIT:

Just a small note: Here, the DeviceMotionEvent is used because the rotationRate (and acceleration etc.) can be accessed from this event only. The OP had tried only the DeviceOrientationEvent, so this is worth a mention.



Related Topics



Leave a reply



Submit