I'm trying to make a compass app for a project I'm working on that will work while going over rough terrain. I've used the standard TYPE_ACCELEROMETER
and TYPE_MAGNETIC_FIELD
sensors and it seems to give reasonably accurate readings. However, when I tilt the phone around its y and z axes, the the Heading reading changes even though the phone is pointing in the same direction (constant z axes).
Does anyone know how to compensate for this? Example code would be appreciated.
Here is the code I'm currently using:
private void updateDirection() {
float[] R = new float[16];
float[] orientationValues = new float[3];
if(SensorManager.getRotationMatrix (R, null, accelerometerValues, magneticValues)){
SensorManager.getOrientation (R, orientationValues);
orientationValues[0] = (float)Math.toDegrees (orientationValues[0]);
orientationValues[1] = (float)Math.toDegrees (orientationValues[1]);
orientationValues[2] = (float)Math.toDegrees (orientationValues[2]);
if(orientationValues[0] < 0){
orientationValues[0] = 360 + orientationValues[0];
}
final int trueNorthHeading = NavigationUtils.getTrueNorthBearing(currentLocation, orientationValues[0]);
if(trueNorthHeading == currentHeading) {
return;
}
int accuracy = 3;
if(NavigationUtils.isSignificantHeadingChange(currentHeading, trueNorthHeading, accuracy, SIGNIFICANT_CHANGE_LIMIT)){
int headingChangeDegrees = NavigationUtils.getStearageDegree(currentHeading, trueNorthHeading);
currentHeading = trueNorthHeading;
navigationManager.headingUpdate(trueNorthHeading, Math.round(orientationValues[0]), headingChangeDegrees);
Log.d("COMPASS", "North: values[0]: " + (int)orientationValues[0]);
}
}
}
Thanks for your help,
Adam