實用知識:陀螺儀的方法使用
阿新 • • 發佈:2019-01-27
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
@property (strong, nonatomic) CMMotionManager *manager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_manager = [[CMMotionManager alloc] init];
if ([_manager isGyroAvailable] == NO ) {
NSLog(@"陀螺儀不能用");
return;
}
// GRYO
// 獲取陀螺儀資料的時間間隙
_manager.gyroUpdateInterval = 0.5;
// Pull 與 Push 方式
[self pushTest];
}
#pragma mark - Pull方式
- (IBAction)startBtnAction:(UIButton *)sender
{
if ([self.manager isGyroActive] == NO) {
[self.manager startGyroUpdates];
}
}
- (IBAction)pullBtnAction:(UIButton *)sender
{
CMGyroData *data = [self.manager gyroData];
CMRotationRate rate = data.rotationRate;
NSLog(@"%f, %f, %f", rate.x, rate.y, rate.z);
}
- (IBAction)stopBtnAction:(UIButton *)sender
{
if ([self.manager isGyroActive] == YES ) {
[self.manager stopGyroUpdates];
}
}
#pragma mark Push方式
- (void)pushTest
{
[_manager startGyroUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMGyroData * _Nullable gyroData, NSError * _Nullable error) {
// CMRotationRate 陀螺儀資料的結構體
CMRotationRate rate = gyroData.rotationRate;
NSLog(@"%f, %f, %f", rate.x, rate.y, rate.z);
}];
}
@end