2010年12月27日月曜日

CMMotionManager

CMMotionManagerの使い方

awakeFromNib内などで、
motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 1.0/30.0;
motionManager.accelerometerUpdateInterval = 1.0/30.0;
motionManager.gyroUpdateInterval = 1.0/30.0;
[motionManager startDeviceMotionUpdates];
[motionManager startAccelerometerUpdates];
[motionManager startGyroUpdates];
[NSTimer scheduledTimerWithTimeInterval:1.0/30 target:self selector:@selector(timer:) userInfo:nil repeats:YES];

timer:(NSTimer *)timer内などで

// DeviceMotion (Rotation) data //
CMDeviceMotion *deviceMotion = motionManager.deviceMotion;
CMRotationRate motionRotationRate = deviceMotion.rotationRate;
deviceMotionLabel.text = [NSString stringWithFormat:@"DeviceMotion(Rotation) X:%f Y:%f Z:%f", motionRotationRate.x, motionRotationRate.y, motionRotationRate.z];

// Accelerometer Data //
CMAccelerometerData *accelerometerData = motionManager.accelerometerData;
CMAcceleration acceleration = accelerometerData.acceleration;
accelerometerLabel.text = [NSString stringWithFormat:@"Accelerometer X:%f Y:%f Z:%f", acceleration.x, acceleration.y, acceleration.z];

// Gyro Data //
CMGyroData *gyroData = motionManager.gyroData;
CMRotationRate gyroRotationRate = gyroData.rotationRate;
gyroLabel.text = [NSString stringWithFormat:@"DeviceMotion(Rotation) X:%f Y:%f Z:%f", gyroRotationRate.x, gyroRotationRate.y, gyroRotationRate.z];

ネットではOperationQueueとブロックを使った例が多いが、ブロックが嫌いなのでその場合はNSTimerなどでも良い。CMMotionManagerが各センサーデータを保持しているので、それを読みに行けば良い。

0 件のコメント: