Objective-C (iOS): ジャイロスコープ

GyroScopeViewController

CoreMotion.framework を追加してください。

Objective-C: GyroScopeViewController.h

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

@interface GyroScopeViewController : UIViewController

@end

Objective-C: GyroScopeViewController.m

#import "GyroScopeViewController.h"

@interface GyroScopeViewController ()

@end

@implementation GyroScopeViewController

CMMotionManager *motionManager_;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *gyroXAxisLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,320,30)];
    UILabel *gyroYAxisLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,30,320,30)];
    UILabel *gyroZAxisLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,60,320,30)];
    [self.view addSubview:gyroXAxisLabel];
    [self.view addSubview:gyroYAxisLabel];
    [self.view addSubview:gyroZAxisLabel];
    
    motionManager_ = [[CMMotionManager alloc] init];
    
    //Gyroscope
    if([motionManager_ isGyroAvailable])
    {
        if([motionManager_ isGyroActive] == NO)
        {
            [motionManager_ setGyroUpdateInterval:1.0f / 2.0f];
            
            [motionManager_ startGyroUpdatesToQueue:[NSOperationQueue mainQueue]
                                            withHandler:^(CMGyroData *gyroData, NSError *error)
             {
                 gyroXAxisLabel.text = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.x];
                 gyroYAxisLabel.text = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.y];
                 gyroZAxisLabel.text = [[NSString alloc] initWithFormat:@"%.02f",gyroData.rotationRate.z];
             }];
        }
    }
    else
    {
        NSLog(@"Gyroscope not Available!");
    }
}

@end