使用重力感應器
重力感應器提供了三個維度向量,用來指示重力的方向和重量。下列代碼顯示了如何擷取一個預設的重力感應器的執行個體:
private SensorManager mSensorManager;
private Sensor mSensor;
...
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
單位與加速度感應器所使用的單位(m/s2)相同,並且座標系統也與加速度感應器所使用的座標系相同。
注意:當裝置處於靜止狀態時,重力感應器的輸出應該與加速度感應器的輸出相同。
使用陀螺儀
陀螺儀以rad/s(弧度/每秒)為單位圍繞裝置的X、Y、Z軸來測量速率或旋轉角度。下列代碼顯示了如何擷取一個預設的陀螺儀的執行個體:
private SensorManager mSensorManager;
private Sensor mSensor;
...
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
該感應器的座標系統與加速度感應器所使用的座標系統是相同的。逆時針方向旋轉是正值,也就是說,如果裝置是逆時針旋轉,那麼觀察者就會看到一些有關以裝置原點為中心的正向的X、Y、Z軸的位置。這是標準的正向旋轉的數學定義,並且與方向感應器所使用的用於滾動的定義不同。
通常,陀螺儀的輸出會被整合到時間上,以便計算在一定時間不長之上旋轉角度的變化。例如:
// Create a constant to convert nanoseconds to seconds.privatestaticfinalfloat NS2S =1.0f/1000000000.0f;privatefinalfloat[] deltaRotationVector =newfloat[4]();privatefloat timestamp; publicvoid onSensorChanged(SensorEventevent){ // This timestep's delta rotation to be multiplied by the current rotation // after computing it from the gyro sample data. if(timestamp !=0){ finalfloat dT =(event.timestamp - timestamp)* NS2S; // Axis of the rotation sample, not normalized yet. float axisX =event.values[0]; float axisY =event.values[1]; float axisZ =event.values[2]; // Calculate the angular speed of the sample float omegaMagnitude = sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ); // Normalize the rotation vector if it's big enough to get the axis // (that is, EPSILON should represent your maximum allowable margin of error) if(omegaMagnitude > EPSILON){ axisX /= omegaMagnitude; axisY /= omegaMagnitude; axisZ /= omegaMagnitude; } // Integrate around this axis with the angular speed by the timestep // in order to get a delta rotation from this sample over the timestep // We will convert this axis-angle representation of the delta rotation // into a quaternion before turning it into the rotation matrix. float thetaOverTwo = omegaMagnitude * dT /2.0f; float sinThetaOverTwo = sin(thetaOverTwo); float cosThetaOverTwo = cos(thetaOverTwo); deltaRotationVector[0]= sinThetaOverTwo * axisX; deltaRotationVector[1]= sinThetaOverTwo * axisY; deltaRotationVector[2]= sinThetaOverTwo * axisZ; deltaRotationVector[3]= cosThetaOverTwo; } timestamp =event.timestamp; float[] deltaRotationMatrix =newfloat[9]; SensorManager.getRotationMatrixFromVector(deltaRotationMatrix, deltaRotationVector); // User code should concatenate the delta rotation we computed with the current rotation // in order to get the updated rotation. // rotationCurrent = rotationCurrent * deltaRotationMatrix; }}標準的陀螺儀提供了原始的旋轉資料,並不帶有任何過濾或噪音和漂移(偏心)的校正。在實踐中,陀螺儀的噪音和漂移會引入錯誤,因此需要對此進行抵消處理。通常通過監視其他感應器,如重力感應器或加速度感應器來判斷漂移(偏心)和噪音。