java – Pitched forward or backwards? TYPE_ROTATION_VECTOR-ThrowExceptions

Exception or error:

I’m trying to get the pitch from the Sensor.TYPE_ROTATION_VECTOR, but i don’t know how to interpret the results.

It seems the pitch values are the same whether the phone is tilted forward or backward (forward = top of the phone moves away from the users face and the bottom of the phone moves closer to the users face).

The lines in the image represent the phone viewed from the side and tilted to different angles. The top/middle phone is perpendicular to the ground.

I need a value represented similar to the azimuth (which goes from -180 to +180 and doesn’t repeat).

@Override
public void onSensorChanged(SensorEvent sensorEvent) {
  if (sensorEvent.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
    SensorManager.getRotationMatrixFromVector(rMat, sensorEvent.values);
    SensorManager.getOrientation(rMat, orientation);
    pitch = (int) (Math.toDegrees(orientation[1]) ) ;

enter image description here

How to solve:

I ended up adding another sensor listener of TYPE_ACCELEROMETER.
Im checking if values[2] is positive and depending on the result i calculate the pitch to a number between 0 and 360 (going clockwise from 12 o’clock).
It works ok, but it skips a few numbers between 355-5 and 175-185.
Let me know if you have a better solution.

From Android documentation:

values[2] : angular speed (w/o drift compensation) around the Z axis in rad/s

boolean isPositive = true;

@Override
public void onSensorChanged(SensorEvent sensorEvent) {
  if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
    isPositive = sensorEvent.values[2] > 0;
  }

  if (sensorEvent.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
    SensorManager.getRotationMatrixFromVector(rMat, sensorEvent.values);
    SensorManager.getOrientation(rMat, orientation);
    pitch = (int) (Math.toDegrees(orientation[1]) ) ;

    if(isPositive) //between 6 and 12 o'clock
      pitch = 270 - pitch;
    else //between 12 and 6 o'clock
      pitch = 90 + pitch;
  //...

Leave a Reply

Your email address will not be published. Required fields are marked *