ios中加速器和重力感應器
#import
@interface ViewController : UIViewController{
CMMotionManager *_manager;
NSTimer *_timer;
}
//動作管理器指標
@property(nonatomic,retain)CMMotionManager *manager;
@property (retain, nonatomic) IBOutlet UILabel *accelerometerLabel;
@property (retain, nonatomic) IBOutlet UILabel *gyroscopeLabel;
@property(nonatomic,retain)NSTimer *timer;
@end
//
self.manager = [[CMMotionManager alloc] init];
//新增一個佇列執行緒
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//判斷是否可以加速
if (_manager.accelerometerAvailable == YES) {
//更新速度
_manager.accelerometerUpdateInterval = 0.1;
//block
[_manager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
NSString *acceleterString;
if (error) {
[_manager stopAccelerometerUpdates];
acceleterString = [NSString stringWithFormat:@"acceletererror:%@",error];
}else{
//重力加速度三維分量
acceleterString = [NSString stringWithFormat:@"%f\n,%f\n,%f\n",accelerometerData.acceleration.x,accelerometerData.acceleration.y,accelerometerData.acceleration.z];
//跳轉到主執行緒
[self.accelerometerLabel performSelectorOnMainThread:@selector(setText:) withObject:acceleterString waitUntilDone:NO];
}
}];
}else{
self.accelerometerLabel.text = @"裝置沒有加速器";
}
//重力感應
if (_manager.gyroAvailable == YES) {
_manager.gyroUpdateInterval = 1.0;
[_manager startGyroUpdatesToQueue:queue withHandler:^(CMGyroData *gyroData, NSError *error) {
NSString *gryString;
if (error) {