美文网首页
iOS-CoreMotion框架(加速仪与陀螺仪)

iOS-CoreMotion框架(加速仪与陀螺仪)

作者: 学_iOS | 来源:发表于2018-01-19 14:54 被阅读92次

    一:前言

    CoreMotion框架

    二:代码

    1.导入框架

    #import <CoreMotion/CoreMotion.h>
    #define kUpdateInterval (1.f / 100.f) // 更新频率高一点
    

    2.建立管理中心

        self.motionManager = [[CMMotionManager alloc]init];
        self.quene = [[NSOperationQueue alloc] init];
        self.motionManager.deviceMotionUpdateInterval = kUpdateInterval;
        [self.motionManager startDeviceMotionUpdatesToQueue:_quene withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
            /*
             //1. Accelerometer 获取手机加速度数据
             motion.userAcceleration.x
             motion.userAcceleration.y
             motion.userAcceleration.z
             CMAccelerometerData *newestAccel = self.motionManager.accelerometerData;
             double accelerationX = newestAccel.acceleration.x;
             double accelerationY = newestAccel.acceleration.y;
             double accelerationZ = newestAccel.acceleration.z;
             //2.Gravity 获取手机的重力值在各个方向上的分量 根据这个就可以获得手机的空间位置倾斜角度等
             double gravityX = motion.gravity.x;
             double gravityY = motion.gravity.y;
             double gravityZ = motion.gravity.z;
             double zTheta = atan2(gravityZ,sqrtf(gravityX * gravityX + gravityY * gravityY)) / M_PI * 180.0;
             double xyTheta = atan2(gravityX, gravityY) / M_PI * 180.0;
             NSLog(@"手机与水平面的夹角 --- %.0f, 手机绕自身旋转的角度为 --- %.0f", zTheta, xyTheta);
             //3. DeviceMotion 获取陀螺仪的数据 包括角速度,空间位置等
             //旋转角速度
             double rotationX = motion.rotationRate.x;
             double rotationY = motion.rotationRate.y;
             double rotationZ = motion.rotationRate.z;
             //空间位置的欧拉角(通过欧拉角可以算得手机两个时刻之间的夹角,比用角速度计算精确地多)
             double roll = motion.attitude.roll;
             double pitch= motion.attitude.pitch;
             double yaw  = motion.attitude.yaw;
             //空间位置的四元数(与欧拉角类似,但解决了万向结死锁问题)
             double w =  motion.attitude.quaternion.w;
             double wx = motion.attitude.quaternion.x;
             double wy = motion.attitude.quaternion.y;
             double wz = motion.attitude.quaternion.z;
             */
            double gravityX = motion.gravity.x;
            double gravityY = motion.gravity.y;
            double gravityZ = motion.gravity.z;
            double zTheta = atan2(gravityZ,sqrtf(gravityX * gravityX + gravityY * gravityY)) / M_PI * 180.0;
            double xyTheta = atan2(gravityX, gravityY) / M_PI * 180.0;
            double rotation =  atan2(motion.gravity.x, motion.gravity.y) - M_PI;
        }];
    

    3.图片(算手机与各种位置的夹角)

    算手机与各种位置的夹角.PNG

    相关文章

      网友评论

          本文标题:iOS-CoreMotion框架(加速仪与陀螺仪)

          本文链接:https://www.haomeiwen.com/subject/mtwooxtx.html