iOS平台使用陀螺仪传感器

时间:2022-06-28 10:23:20

在移动端开发过程中,有时候会用到陀螺仪传感器获取当前手机的姿态,下面给出iOS端如何获取陀螺仪姿态数据的代码:

 //根据陀螺仪的四元数转换为矩阵
+ (GLKMatrix4)calculateMatrixFromQuaternion:(CMQuaternion*)quaternion orientation:(AVCaptureVideoOrientation) orientation{
float xx = quaternion->x * quaternion->x;
float yy = quaternion->y * quaternion->y;
float zz = quaternion->z * quaternion->z;
float xy = quaternion->x * quaternion->y;
float wz = quaternion->w * quaternion->z;
float wy = quaternion->w * quaternion->y;
float xz = quaternion->x * quaternion->z;
float yz = quaternion->y * quaternion->z;
float wx = quaternion->w * quaternion->x; float r00 = - * (yy + zz);
float r01 = * (xy - wz);
float r02 = * (wy + xz);
float r03 = ; float r10 = * (xy + wz);
float r11 = - * (xx + zz);
float r12 = * (yz - wx);
float r13 = ; float r20 = * (xz - wy);//xy - wy
float r21 = * (yz + wx);
float r22 = - * (xx + yy);
float r23 = ; float r30 = ;
float r31 = ;
float r32 = ;
float r33 = ; return GLKMatrix4Make(r00,r01,r02,r03,
r10,r11,r12,r13,
r20,r21,r22,r23,
r30,r31,r32,r33);
} //当前屏幕的方向
@property (nonatomic, readwrite, assign) AVCaptureVideoOrientation orientation;
//开启陀螺仪
- (void)updateAngleFromAttitudeSensor{
if(self.cmmotionManager){ }else{
self.cmmotionManager = [[CMMotionManager alloc] init];
self.cmmotionManager.deviceMotionUpdateInterval = 1.0/25.0;
self.cmmotionManager.gyroUpdateInterval = 1.0/25.0;
self.cmmotionManager.showsDeviceMovementDisplay = YES; NSOperationQueue *mQueue = [[NSOperationQueue alloc]init];
__weak typeof(self) wSelf = self;
[wSelf.cmmotionManager startDeviceMotionUpdatesToQueue:mQueue withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error){
CMAttitude *attitude = motion.attitude;
if (attitude == nil) {
return;
} //UID
CMQuaternion quaternion = attitude.quaternion;
wSelf.sensorMatrix = GLKMatrix4Identity;
wSelf.sensorMatrix = [GyroscopeUtil calculateMatrixFromQuaternion:&quaternion orientation:orientation]; wSelf.sensorMatrix = GLKMatrix4RotateX(wSelf.sensorMatrix,M_PI_2);
wSelf.sensorInverseMatrix = GLKMatrix4Identity; bool isInvertible = true;
wSelf.sensorInverseMatrix = GLKMatrix4Invert(wSelf.sensorMatrix, &isInvertible);
}];
}
}