2

I'm trying to use Magnetic Field and Accelerometer to calculate Orientation. However, the calculated Az, Pitch and Roll are 0. Here's the code:

public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    Log.e(TAG, "Sensor Changed");

    float[] r = new float[9];
    float[] i = new float[9];

    float[] accValues = new float[3];
    float[] geoVallues = new float[3];


    }
    if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        Log.e(TAG, "Accelerometer Changed");
        accValues = event.values.clone();
    }

    if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        Log.e(TAG, "Magnetif Field Changed");
        geoVallues = event.values.clone();
    }

    if (accValues != null && geoVallues != null) {
        SensorManager.getRotationMatrix(r, i, accValues, geoVallues);
        float[] v = new float[3];
        SensorManager.getOrientation(r, v);
        oriView.setText("Orientation:\nAz=" + Math.toDegrees((v[0])) + "\nPitch=" + Math.toDegrees((v[1])) + "\nRoll=" + Math.toDegrees((v[2])));
    }
}

Any idea what's wrong?

dfeuer
  • 48,079
  • 5
  • 63
  • 167
Tring
  • 359
  • 2
  • 5
  • 16
  • Have you registered the listener for the sensor correctly [as demonstrated in the documentation](http://developer.android.com/reference/android/hardware/SensorManager.html)? Also, check to see if `getRotationMatrix()` is not [returning `false`](http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix%28float[],%20float[],%20float[],%20float[]%29). – Paul Lammertsma Dec 07 '11 at 11:44

1 Answers1

2

try this

boolean success = SensorManager.getRotationMatrix(
   matrixR,
   matrixI,
   valuesAccelerometer,
   valuesMagneticField);

if(success){
SensorManager.getOrientation(matrixR, matrixValues);

double azimuth = Math.toDegrees(matrixValues[0]);
double pitch = Math.toDegrees(matrixValues[1]);
double roll = Math.toDegrees(matrixValues[2]);

readingAzimuth.setText("Azimuth: " + String.valueOf(azimuth));
readingPitch.setText("Pitch: " + String.valueOf(pitch));
readingRoll.setText("Roll: "+String.valueOf(roll));
MBMJ
  • 5,323
  • 8
  • 32
  • 51
  • Thanks... I have actually solved it in a very different way (changed the whole problem altogether) but this might help others in the future. – Tring May 22 '12 at 20:07
  • This change now means I don't get any readings at all... how does this solve the problem? – David Callanan Dec 21 '19 at 13:19