Search code examples
javascriptreact-nativereact-native-sensors

How can I detect that the device was rotated 360deg given (x,y,z) gyroscope?


I am using react-native-sensor to grab the raw data from the sensor.

setUpdateIntervalForType(SensorTypes.gyroscope, 100)

gyroscope.subscribe(({ x, y, z, timestamp }) => {
  let pitch = Math.atan2(-x, -z) * 180 / Math.PI;// In degrees
  let roll = Math.atan2(-y, -x) * 180 / Math.PI;// In degrees
  let yaw = Math.atan2(y, -z) * 180 / Math.PI;// In degrees
  
  this.setState({pitch: pitch, roll: roll, yaw: yaw})
})

How do i know that the device was spined 360


Solution

  • A bit of theory

    Generally speaking, gyroscopes measure rotational motion. Most of the sensors that are included in our phones will specifically measure angular velocity. It means that the output in most cases will describe how much the phone has rotated over time and is usually expressed in degrees per second (°/s).

    There are 3 axes that you can rotate around: x, y and z. There's a nice picture of it in MATLAB documentation:

    Phone axes representation

    There are also 3 important concepts (that you used in your snippet): pitch, roll and yaw (or azimuth). Again, MATLAB documentation comes in handy. They described it very well in the "More about" section, but I recommend reading the whole article.

    Get your hands dirty

    As far as I'm aware, the react-native-sensors library will return exactly degrees per second. This means, that using the provided timestamp you could try to count how much the phone rotated around any axis within any time delta. You would simply need to save values and timestamps, do a few transformations and you would get the result. This, however, would require additional time and memory.

    There's an easier way, which you probably already realize after reading the attached article. Depending on the axis you want to rotate around, use pitch, roll or yaw.

    Also, if you use the library just to get the gyroscope data, you might want to consider Detecting device orientation Web API. It is still an experimental feature but will work in most of the modern browsers.