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; }}标准的陀螺仪提供了原始的旋转数据,并不带有任何过滤或噪音和漂移(偏心)的校正。在实践中,陀螺仪的噪音和漂移会引入错误,因此需要对此进行抵消处理。通常通过监视其他传感器,如重力传感器或加速度传感器来判断漂移(偏心)和噪音。
补充:移动开发 , Android ,