在項目中常常會使用到重力加速度,陀螺儀,最近在一個項目中使用到了CoreMotion 框架,需求是:上下搖擺手機控制智能椅子的角度調節,該項目是使用藍牙4.0進行通信的,在iOS 內已經封裝好了CoreBluetooth 框架,不過須要iPHone4s 以上的手機,和iPad min 以上的平板電腦纔有藍牙4.0. 框架
今天在這裏先記錄一下CoreMotion 框架的使用. this
主要的類:CMMotionManager , NSOperationQueue. atom
下面是一個被我封裝過的一個類。 code
項目須要導入CoreMotion.Framework it
在.h 文件須要#import <CoreMotion/CoreMotion.h> io
.h文件代碼: class
#import <Foundation/Foundation.h> #import <CoreMotion/CoreMotion.h> typedef enum _MotionDirection {UNKNOWDIRECTION=0,UP,DOWN}MotionDirection; @interface iCtrlCMManager : NSObject @property (nonatomic,retain) CMMotionManager * ictrlCMManager; @property (nonatomic,assign) MotionDirection motionDirection; +(id)sharedInstance; -(void)startMotion; -(void)stopMotion; @end.m文件代碼:
#import "iCtrlCMManager.h" @implementation iCtrlCMManager #pragma mark - #pragma mark life cycle +(id)sharedInstance { static iCtrlCMManager *this = nil; if(!this) { this = [[iCtrlCMManager alloc] init]; } return this; } -(id)init { self = [super init]; if(self) { _ictrlCMManager = [[CMMotionManager alloc] init]; } return self; } -(void)dealloc { [_ictrlCMManager release]; [super dealloc]; } #pragma mark #pragma mark instance methods -(void)startMotion { _motionDirection = UNKNOWDIRECTION; if(_ictrlCMManager.accelerometerAvailable) { NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease]; _ictrlCMManager.accelerometerUpdateInterval = 1.0/60.0; __block float y = 0.0; __block int i = 0; [_ictrlCMManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) { if (error) { NSLog(@"CoreMotion Error : %@",error); [_ictrlCMManager stopAccelerometerUpdates]; } if(i == 0) { y = accelerometerData.acceleration.y; } i++; if(fabs(y - accelerometerData.acceleration.y) > 0.4) { if(y > accelerometerData.acceleration.y) { NSLog(@"UP"); _motionDirection = UP; } else { NSLog(@"Down"); _motionDirection = DOWN; } y = accelerometerData.acceleration.y; } }]; } else { NSLog(@"The accelerometer is unavailable"); } } -(void)stopMotion { _motionDirection = UNKNOWDIRECTION; [_ictrlCMManager stopAccelerometerUpdates]; } @end