Search code examples
androidalgorithmsensorsandroid-sensors

How to calculate "Pitch" and "Roll" using SensorManager.getOrientation()


I'm currently trying to replace my 'Sensor.TYPE_ORIENTATION' because it was deprecated. So Android Documentation lacks most of the Information, on how to do it. While debugging and diggin here on SO I figured out how to calculate the azimuth which was once provided by the OrientationSensor. I do it in this way:

float accelerometerVals[] = new float[3];
float magneticVals[] = new float[3];

float orientationSensorVals[] = new float[3]; 

float rotationMatrix[] = new float[16];
float orientation[] = new float[3];

    @Override
    public void onSensorChanged(SensorEvent event) {
        switch (event.sensor.getType()) {
        case Sensor.TYPE_ACCELEROMETER:
             System.arraycopy(event.values, 0, accelerometerVals, 0, 3);
             break;
        case Sensor.TYPE_MAGNETIC_FIELD:
              System.arraycopy(event.values, 0, magneticVals, 0, 3);
              break;
        case Sensor.TYPE_ORIENTATION:
              System.arraycopy(event.values, 0, orientationSensorVals, 0, 3);
              break;
        default:
              break;
        }

        if (null != magneticVals && null != accelerometerVals){
            SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerVals, magneticVals)
            SensorManager.getOrientation(rotationMatrix, orientation);
            float azimuth = Math.toDegrees(orientation[0])
            //this calculation gives me the Azimuth in the same format that OrientationSensor
            azimuth += (azimuth >= 0) ? 0 : 360
            float FALSE_PITCH = Math.toDegrees(orientation[1])
            float FALSE_ROLL = Math.toDegrees(orientation[2])
        }    

Note the variables FALSE_PITCH && FALSE_ROLL. I don't have no idea how to "normalize" (values differ from +10 to -10) this values, to get the same output than I had before inside my OrientationSensor


Solution

  • I've been through the same problem but I'm surprised your roll is not right, as it is for me. Here's what I used :

    //Let values[] be your orientation[] variable once in degrees.
    
    // Azimuth scaling
    if (values[0]<0) values[0] += 360;
    
    // Pitch scaling
    if (values[1]<-90) values[1] += (-2*(90+values[1]));
    else if (values[1]>90) values[1] += (2*(90-values[1]));
    
    // Roll scaling
    // NOT NEEDED
    

    Would you be able to post some outputs of both Orientation sensor and your degrees orientation[] variable ?