I am currently working on the motion sensor about measure the orientation angle of my Android device. When it comes to implementation , the device turns to zero no matter how we turn or not. Are there any conditions to initialize the float array such the angle can be calculated ?
The below is my code
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
TextView xCoor; // declare X axis object
TextView yCoor; // declare Y axis object
TextView zCoor; // declare Z axis object
float[] mRotationMatrixFromVector = new float[3];
float[] mRotationMatrix = new float[9];
float[] orientationVals = new float[3];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xCoor=(TextView)findViewById(R.id.xcoor); // create X axis object
yCoor=(TextView)findViewById(R.id.ycoor); // create Y axis object
zCoor=(TextView)findViewById(R.id.zcoor); // create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
// add listener. The listener will be HelloAndroid (this) class
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
// check sensor type
if(event.sensor.getType()==Sensor.TYPE_ROTATION_VECTOR){
SensorManager.getRotationMatrixFromVector(mRotationMatrixFromVector, event.values);
SensorManager.remapCoordinateSystem(mRotationMatrixFromVector,
SensorManager.AXIS_X, SensorManager.AXIS_Z,
mRotationMatrix);
SensorManager.getOrientation(mRotationMatrix, orientationVals);
// Optionally convert the result from radians to degrees
orientationVals[0] = (float) Math.toDegrees(orientationVals[0]);
orientationVals[1] = (float) Math.toDegrees(orientationVals[1]);
orientationVals[2] = (float) Math.toDegrees(orientationVals[2]);
xCoor.setText("X: "+ String.valueOf(orientationVals[0]));
yCoor.setText("Y: "+ String.valueOf(orientationVals[1]));
zCoor.setText("Z: "+ String.valueOf(orientationVals[2]));
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
From docs: mRotationMatrixFromVector
must have length 9 or 16.