Android傳感器—Motion Sensor(三)

使用重力傳感器

重力傳感器提供瞭三個維度的矢量,用來指示重力的方向和重量。下列代碼顯示瞭如何獲取一個默認的重力傳感器的實例:

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;   }}標準的陀螺儀提供瞭原始的旋轉數據,並不帶有任何過濾或噪音和漂移(偏心)的校正。在實踐中,陀螺儀的噪音和漂移會引入錯誤,因此需要對此進行抵消處理。通常通過監視其他傳感器,如重力傳感器或加速度傳感器來判斷漂移(偏心)和噪音。

 

You May Also Like