CoreMotion
ios通過CoreMotion架構操作陀螺儀和加速度計
#import <CoreMotion/CoreMotion.h>
陀螺儀和加速度計的操作方法有push和pull兩種
push方式是陀螺儀每次更新資料通知使用者
pull方式則是使用者需要時去申請陀螺儀資料
push方式
CMMotionManager *manger = [[CMMotionManager alloc]init];
manger.accelerometerUpdateInterval = (NSTimeInterval)();
manger.gyroUpdateInterval = (NSTimeInterval)();
NSOperationQueue *queue1 = [[NSOperationQueue alloc]init];
NSOperationQueue *queue2 = [[NSOperationQueue alloc]init];
NSLog(@"available %d:%d", [manger isAccelerometerAvailable], ![manger isAccelerometerActive]);
[manger startAccelerometerUpdatesToQueue:queue1 withHandler:^(CMAccelerometerData *data, NSError *error)
{
manger.accelerometerUpdateInterval = (NSTimeInterval)();
NSLog(@"acce x:%.02f y:%.02f z:%.02f", data.acceleration.x, data.acceleration.y, data.acceleration.z);
}];
[manger startGyroUpdatesToQueue:queue2 withHandler:^(CMGyroData *data, NSError *error)
{
manger.gyroUpdateInterval = (NSTimeInterval)();
NSLog(@"rotation x:%.02f y:%.02f z:%.02f", data.rotationRate.x, data.rotationRate.y, data.rotationRate.z);
}];
注意每次執行設定的回調函數代碼時 都要重新設定陀螺儀和加速度計的采集頻率
否則回調函數隻會被執行一次
一些部落格的陀螺儀示例代碼都缺少這個動作 導緻并不能正确的使用push方式更新
pull方式
CMMotionManager *manger = [[CMMotionManager alloc]init];
manger.accelerometerUpdateInterval = (NSTimeInterval)();
manger.gyroUpdateInterval = (NSTimeInterval)();
NSLog(@"available %d:%d", [manger isAccelerometerAvailable], ![manger isAccelerometerActive]);
[manger startAccelerometerUpdates];
[manger startGyroUpdates];
for (;;) {
CMAccelerometerData *acce = manger.manger.accelerometerData;
CMGyroData *gyro = manger.gyroData;
NSLog(@"acce x:%.02f y:%.02f z:%.02f", acce.acceleration.x, acce.acceleration.y, acce.acceleration.z);
NSLog(@"rotation x:%.02f y:%.02f z:%.02f", gyro.rotationRate.x, gyro.rotationRate.y, gyro.rotationRate.z);
}