我已经为罗盘实现了以下代码,但是当我将以下代码中的值(由 azimut 返回)与 iphone 罗盘应用程序进行比较时,似乎我在阅读时偏离了 90 度。我需要从其他任何地方获取值吗传感器..??。此外,即使在应用低通滤波器后,似乎也有相当多的抖动。对此有什么建议..??
public class CompassExample4Activity extends Activity implements SensorEventListener{
private SensorManager mSensorManager;
CompassView mCompassView;
Sensor accelerometer;
Sensor magnetometer;
float azimut;
float[] mGravity;
float[] mGeomagnetic;
static final float ALPHA = 0.2f;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCompassView = new CompassView(this);
setContentView(mCompassView);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
@Override
public void onResume() {
super.onResume();
mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);
}
@Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = lowPass(event.values, mGravity);
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = lowPass(event.values, mGeomagnetic);
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
// Correct if screen is in Landscape
SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_X,
SensorManager.AXIS_Z, R);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
float azimut = orientation[0]; // orientation contains: azimut, pitch and roll
mCompassView.updateDirection(azimut*360/(2*3.14159f));
//mCompassView.updateDirection(azimuth);
}
}
}
protected float[] lowPass( float[] input, float[] output ) {
if ( output == null ) return input;
for ( int i=0; i<input.length; i++ ) {
output[i] = output[i] + ALPHA * (input[i] - output[i]);
}
return output;
}
}