我发现了很多关于如何处理设备的旋转、运动和位置传感器方向的线程。我想创建一个我将在我的汽车中使用的应用程序,首先我想测量汽车的旋转度数。所以我把手机放在手机壳上,例如当我开车左转时,我想在手机上看到汽车的转向度。
可以通过磁力计和加速度计吗?
我首先发布了一个我认为还可以的代码。(假设我拿着我的手机“肖像”模式,所以首先不是横向)
private static SensorManager sensorService;
//magnetic
private Sensor mSensor;
//accelerometer
private Sensor gSensor;
private float[] mValuesMagnet = new float[3];
private float[] mValuesAccel = new float[3];
private float[] mValuesOrientation = new float[3];
private float[] mRotationMatrix = new float[9];
@Override
public void onCreate(Bundle savedInstanceState) {
nf.setMaximumFractionDigits(2);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorService = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
this.mSensor = sensorService.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
this.gSensor = sensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorService.registerListener(this, gSensor, SensorManager.SENSOR_DELAY_NORMAL);
sensorService.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
System.arraycopy(event.values, 0, mValuesAccel, 0, 3);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
System.arraycopy(event.values, 0, mValuesMagnet, 0, 3);
break;
}
SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet);
SensorManager.getOrientation(mRotationMatrix, mValuesOrientation);
// double azimuth = Math.toDegrees(mValuesOrientation[0]); //azimuth, rotation around the Z axis.
// double pitch = Math.toDegrees(mValuesOrientation[1]); // pitch, rotation around the X axis.
double roll = Math.toDegrees(mValuesOrientation[2]); //roll, rotation around the Y axis.
//normalize
// azimuth = azimuth>0?azimuth:azimuth+360;
roll = roll>0?roll:roll+360;
String txt = "roll= "+Math.round(roll);
((EditText)findViewById(R.id.szog)).setText(txt);
}
问题: - 这个应用程序在汽车中的准确度如何?(我该怎么做才能更准确?) - 当我将手机置于“横向”模式时应该怎么做?定向滚动是否还可以?
请注意,这是第一次尝试,所以有很多事情要做!但首先我想看看我怎样才能做到这一点
谢谢!