Using the Rotation Vector Sensor

Dmitry picture Dmitry · May 26, 2013 · Viewed 8.6k times · Source

I would like to know how to properly use the output from the "Rotation Vector Sensor". Currently I came up with the following and wanted to calculate yaw and pitch from the result[], in order to know where the device is pointing (lying in landscape mode). But I have trouble with the results. The yaw calculation is pretty precise but pitch is behaving strange. Maybe anybody can point me in the right direction on how to use the data. Another thing i also would like to know is whether the device orientation (landscape or portrait) has any influence at the output of this sensor. Thanks in advance.

private double max = Math.PI / 2 - 0.01;
private double min = -max;

private float[] rotationVectorAction(float[] values) {
    float[] result = new float[3];
    float vec[] = values;
    float quat[] = new float[4];
    float[] orientation = new float[3];
    SensorManager.getQuaternionFromVector(quat, vec);
    float[] rotMat = new float[9];
    SensorManager.getRotationMatrixFromVector(rotMat, quat);
    SensorManager.getOrientation(rotMat, orientation);
    result[0] = (float) orientation[0];
    result[1] = (float) orientation[1];
    result[2] = (float) orientation[2];     
    return result;
}

private void main () {
    float[] result = rotationVectorAction(sensorInput);
    yaw = result[0];
    pitch = result[1];
    pitch = (float) Math.max(min, pitch);
    pitch = (float) Math.min(max, pitch);
    float dx = (float) (Math.sin(yaw) * (-Math.cos(pitch)));
    float dy = (float) Math.sin(pitch);
    float dz = (float) (Math.cos(yaw) * Math.cos(pitch));
}

And in OpenGL ES 2.0 I set this to move my camera around:

Matrix.setLookAtM(mVMatrix, 0, 0, 0, 0, dx, dy, dz, 0, 1, 0);

Answer

Dmitry picture Dmitry · May 28, 2013

Finally I solved it myself. The reason for pitch to not work properly was the difference betweeen the INPUT and the OUTPUT from SensorManager.getQuaternionFromVector(quat, vec);. The method is expecting a vector vec to be (x|y|z|w) and the output quat to look like this (w|x|y|z). In my case I just had to move the first value of quat array to the end and it worked like a charm.