iPhone的Gyro + Accelerometer可以获得什么?

时间:2016-09-21 04:00:57

标签: ios iphone

我想使用Gyro + Accelerometer获得iPhone的速度和角度。这里不需要GPS。如果走路的人携带iPhone,我能获得人们的运动信息吗?

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h> 




@interface ViewController : UIViewController{
        CMMotionManager *motionManager;
        NSOperationQueue *operationQueue;
        NSTimer *timer;
    }

@property (weak, nonatomic) IBOutlet UILabel *accelerationX;
@property (weak, nonatomic) IBOutlet UILabel *accelerationY;
@property (weak, nonatomic) IBOutlet UILabel *accelerationZ;
@property (weak, nonatomic) IBOutlet UILabel *pitchLabel;
@property (weak, nonatomic) IBOutlet UILabel *yawLabel;
@property (weak, nonatomic) IBOutlet UILabel *rollLabel;
@end

//。米     #import“ViewController.h”

@interface ViewController ()

@end

@implementation ViewController
@synthesize accelerationX;
@synthesize accelerationY;
@synthesize accelerationZ;
@synthesize rollLabel;
@synthesize pitchLabel;
@synthesize yawLabel;

#define degrees(x) (180 * x / M_PI)

- (void)viewDidLoad {
    [super viewDidLoad];

    motionManager = [[CMMotionManager alloc]init];
    motionManager.deviceMotionUpdateInterval = 1;
    [motionManager startDeviceMotionUpdates];
    timer = [NSTimer scheduledTimerWithTimeInterval:(1) target:self selector:@selector(read) userInfo:nil repeats:YES];

    if([motionManager isGyroAvailable]){
        if(![motionManager isGyroActive]){
            [motionManager setGyroUpdateInterval:1.0];
            [motionManager startGyroUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMGyroData *gyroData,  NSError *error){
                accelerationX.text = [[NSString alloc]initWithFormat:@"%0.2f", gyroData.rotationRate.x ];
                accelerationY.text = [[NSString alloc]initWithFormat:@"%0.2f", gyroData.rotationRate.y ];
                accelerationZ.text = [[NSString alloc]initWithFormat:@"%0.2f", gyroData.rotationRate.z ];
            }];
        }
    }
    else{
        NSLog(@"No Gyro");
    }
}


- (void)read{
    CMAttitude *attitude;
    CMDeviceMotion *motion = motionManager.deviceMotion;
    attitude = motion.attitude;

    yawLabel.text = [NSString stringWithFormat:@"%f", degrees(attitude.yaw)];
    pitchLabel.text = [NSString stringWithFormat:@"%f", degrees(attitude.pitch)];
    rollLabel.text = [NSString stringWithFormat:@"%f", degrees(attitude.roll)];


}