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

Parth picture Parth · Nov 20, 2015 · Viewed 8.3k times · Source

I am using THREE.js and creating a web-app where the user can rotate the device and the scene will move accordingly. Something similar to this.

I am having a problem differentiating between devices that have a gyroscope and those that don't.

Detecting devices that don't have orientation sensors at all is easy. All the alpha, beta, gamma values of DeviceOrientationEvent are null. But, if a mobile device doesn't have a gyro, it still gives alpha, beta, gamma values in DeviceOrientationEvent. The problem is these values are very noisy, and cause a lot of shaking in the scene. So, I want to disable the device orientation for these devices. But, so far I haven't been able to find how to make out if the data is coming from a gyro or accelerometer (that's my guess on where the data is coming from).

I don't know if it helps, but a good example of how this is handled can be seen here. (Press the axis like icon at the bottom; you'll have to see it on a device that doesn't have a gyroscope and a gyroscope to see the difference). What they are doing for devices without a gyroscope is only updating the pitch and the roll. The yaw isn't updated when you rotate with the phone.

So, it is definitely possible, but I haven't yet found out how even after searching a lot. It would be great if anyone could help.

Thanks a lot.

EDIT:

On devices that just have an accelerometer, like MOTO E, all values are null - DeviceOrientationEvent and rotationRate - with the only exception of accelerationIncludingGravity. But, the device I was testing earlier, that didn't have a gyro but still gave alpha, beta, gamma values for DeviceOrientationEvent, seems to have 2 accelerometers according to the "sensors" details on GSM Arena. That is how I suspect it was able to give DeviceOrientationEvent data, albeit noisy. Looks like 2 accelerometers aren't enough to give rotation rate ;)

Answer

Dhyey Shah picture Dhyey Shah · Nov 21, 2015

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.