Search code examples
androidandroid-sensorsquaternions

Android get quaternion data


Fast and simple. How to get the quaternion data from the sensors? basically I need:

float quaternion_x = ?
float quaternion_y = ?
float quaternion_z = ?
float quaternion_w = ?

I have something like this:

if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
{
    float[] values = event.values;

    float quaternion_x = values[0];
    float quaternion_y = values[1];
    float quaternion_z = values[2];
    float quaternion_w = values[3];  <----- ERROR HERE 
}

I get an index out of bound exception because values has only 3 values inside. According to this page: http://developer.android.com/guide/topics/sensors/sensors_motion.html There should be 4 values or am I understanding something wrong?


Solution

  • The SensorManager class offers a helper function to convert for you:

    SensorManager.getQuaternionFromVector(Q, values);
    float[] quaternion_w = Q[0];
    float[] quaternion_x = Q[1];
    float[] quaternion_y = Q[2];
    float[] quaternion_z = Q[3];