2014年3月3日月曜日

方角センサ

systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    
    // 周波数(Hz)
    int frequency = 10;
    // インスタンスの生成
    manager = [[CMMotionManager alloc] init];

    // CMDeviceMotionの開始

    [self startCMDeviceMotion:frequency];


- (void)startCMDeviceMotion:(int)frequency
{
    // センサーの有無を確認
    if (manager.deviceMotionAvailable) {
        // 更新間隔の指定
        manager.deviceMotionUpdateInterval = 1 / frequency;  //
        // ハンドラ
        CMDeviceMotionHandler handler = ^(CMDeviceMotion *motion, NSError *error) {
            
            /* magnetometer */
            if (5.0 < systemVersion && manager.magnetometerAvailable) {
                // "磁北""真北"からの角度。Y軸方向を起点にするため、(x, y)を渡す
                double radian = atan2(motion.magneticField.field.x, motion.magneticField.field.y);
            }
            
            /* CMAttitude */
            roll = motion.attitude.roll;
            pitch = motion.attitude.pitch;
            yaw = motion.attitude.yaw;
            rotationMatrix = motion.attitude.rotationMatrix;
            
            double tmp[3];
            double PI = 3.14159283;
            tmp[0] =0.0;
            tmp[1] = 0.0;
            tmp[2] = -1.0;
            center[0] = rotationMatrix.m11 * tmp[0] + rotationMatrix.m21 * tmp[1] +rotationMatrix.m31 * tmp[2];
            center[1] = rotationMatrix.m12 * tmp[0] + rotationMatrix.m22 * tmp[1] +rotationMatrix.m32 * tmp[2];
            center[2] = rotationMatrix.m13 * tmp[0] + rotationMatrix.m23 * tmp[1] +rotationMatrix.m33 * tmp[2];
            for (int i=0;i<3;i++){
                center[i] = round(center[i]*100)/100.0;
            }
            NSLog(@"center=%lf,%lf,%lf",center[0],center[1],center[2]);
            
            tmp[0] = 0.0;
            tmp[1] = 1.0;
            tmp[2] = 0.0;
            up[0] = rotationMatrix.m11 * tmp[0] + rotationMatrix.m21 * tmp[1] +rotationMatrix.m31 * tmp[2];
            up[1] = rotationMatrix.m12 * tmp[0] + rotationMatrix.m22 * tmp[1] +rotationMatrix.m32 * tmp[2];
            up[2] = rotationMatrix.m13 * tmp[0] + rotationMatrix.m23 * tmp[1] +rotationMatrix.m33 * tmp[2];
            for (int i=0;i<3;i++){
                up[i] = round(up[i]*100)/100.0;
            }
            NSLog(@"up=%lf,%lf,%lf",up[0],up[1],up[2]);
        };
        
        // DeviceMotionの開始
        if (5.0 < systemVersion) {
            [manager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXTrueNorthZVertical toQueue:[NSOperationQueue currentQueue] withHandler:handler];
        } else {
            [manager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:handler];
        }
    }
}

0 件のコメント:

コメントを投稿