[Objective-C] 纯文本查看 复制代码
#import <CoreMotion/CoreMotion.h>
#define ACCELEROMETER_UPDATE_INTERVAL 1.0
#define GYRO_UPDATE_INTERVAL 1.0
@interface firstVC (){
UILabel *lbl;
CMMotionManager *motionManager;
}
@end
@implementation firstVC
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor yellowColor];
self.title = @"苏飞论坛";
motionManager = [[CMMotionManager alloc] init];
[self startAccelerometerSensor];
[self startGyroSensor];
// [self startDeviceOrientationChangeListener];
}
//加速计
-(void)startAccelerometerSensor {
//更新时间间隔
motionManager.accelerometerUpdateInterval = ACCELEROMETER_UPDATE_INTERVAL;
//开始获取数据
[motionManager startAccelerometerUpdates];
//(1)使用”定时器“(NSTimer)获取数据
[NSTimer scheduledTimerWithTimeInterval:ACCELEROMETER_UPDATE_INTERVAL target:self selector:@selector(accelerometerDidUpdate) userInfo:nil repeats:YES];
//(2)将数据传递给“操作队列”(NSOperationQueue)
NSOperationQueue *operationQueue = [NSOperationQueue currentQueue];
[motionManager startAccelerometerUpdatesToQueue:operationQueue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
CMAcceleration acceleration = accelerometerData.acceleration;
NSLog(@"加速计acceleration (%lf,%lf,%lf)", acceleration.x, acceleration.y, acceleration.z);
}];
//[motionManager stopAccelerometerUpdates];
}
- (void)accelerometerDidUpdate {
CMAcceleration acceleration = motionManager.accelerometerData.acceleration;
NSLog(@"acceleration (%lf,%lf,%lf)", acceleration.x, acceleration.y, acceleration.z);
}
//陀螺仪
-(void)startGyroSensor {
//首先需要判断陀螺仪是否可用,因为2010年以前的设备是没有“陀螺仪”的
if(motionManager.gyroAvailable) {
//更新时间间隔
motionManager.gyroUpdateInterval = GYRO_UPDATE_INTERVAL;
//开始获取数据
[motionManager startGyroUpdates];
//(1)使用”定时器“(NSTimer)获取数据
[NSTimer scheduledTimerWithTimeInterval:GYRO_UPDATE_INTERVAL target:self selector:@selector(gyroDidUpdate) userInfo:nil repeats:YES];
//(2)将数据传递给“操作队列”(NSOperationQueue)
NSOperationQueue *operationQueue = [NSOperationQueue currentQueue];
[motionManager startGyroUpdatesToQueue:operationQueue withHandler:^(CMGyroData * gyroData, NSError * error) {
CMRotationRate rotationRate = gyroData.rotationRate;
NSLog(@"陀螺仪gyro (%lf,%lf,%lf)", rotationRate.x, rotationRate.y, rotationRate.z);
}];
//[motionManager stopGyroUpdates];
} else {
NSLog(@"gyro not available");
}
}
-(void)gyroDidUpdate {
CMRotationRate rotationRate = motionManager.gyroData.rotationRate;
NSLog(@"gyro (%lf,%lf,%lf)", rotationRate.x, rotationRate.y, rotationRate.z);
}