您的位置:首页 > 移动开发 > IOS开发

iOS之 CoreMotion 框架

2015-10-30 10:50 337 查看
在项目中经常会使用到重力加速度,陀螺仪,最近在一个项目中使用到了CoreMotion 框架,需求是:上下摇摆手机控制智能椅子的角度调节,该项目是使用蓝牙4.0进行通讯的,在iOS 内已经封装好了CoreBluetooth 框架,不过需要iPHone4s 以上的手机,和iPad min 以上的平板电脑才有蓝牙4.0.

今天在这里先记录一下CoreMotion 框架的使用.

主要的类:CMMotionManager , NSOperationQueue.

下面是一个被我封装过的一个类。

项目需要导入CoreMotion.Framework

在.h 文件需要#import <CoreMotion/CoreMotion.h>

.h文件代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
#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文件代码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: