その後のその後

iOSエンジニア 堤 修一のブログ github.com/shu223

CoreMotionで3軸ジャイロの数値をとってみる

昨日AppleのiOSドキュメントをあさっていて、
「CoreMotion」なるフレームワークがあることを初めて知りました。


加速度センサとジャイロスコープからモーションデータを取得するためのフレームワークのようです。


そういえばジャイロって未だに何ができるのかよくわかってなかったので、
試しに使ってみました。


(ソースコード一式)
https://github.com/shu223/CMTest



手順はたったの3ステップ。

  1. alloc/initでCMMotionManagerのインスタンスを生成
  2. gyroUpdateIntervalプロパティに値の取得間隔を設定
  3. startGyroUpdatesToQueue:withHandler:メソッドで取得開始&取得時の処理を指定。
#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>

@interface CMTestViewController : UIViewController {

	CMMotionManager		*motionManager;

	IBOutlet UILabel	*xLabel;
	IBOutlet UILabel	*yLabel;
	IBOutlet UILabel	*zLabel;
}
@property (nonatomic, retain) CMMotionManager *motionManager;

@end
#import "CMTestViewController.h"

@implementation CMTestViewController

@synthesize motionManager;


- (void)viewDidLoad {
    [super viewDidLoad];

    // CMMotionManager生成
    CMMotionManager *manager = [[CMMotionManager alloc] init];
    self.motionManager = manager;
    [manager release];

    // ジャイロデータ取得間隔 [sec]
    self.motionManager.gyroUpdateInterval = 0.1;
    
    // ジャイロデータ取得開始
    NSOperationQueue *opQueue = [[[NSOperationQueue alloc] init] autorelease];
    [self.motionManager startGyroUpdatesToQueue:opQueue
                    withHandler:^(CMGyroData *data, NSError *error) {
                        // ジャイロデータ取得時に実行する処理
                        dispatch_async(dispatch_get_main_queue(), ^{
                            xLabel.text = [NSString stringWithFormat:@"%f", data.rotationRate.x];
                            yLabel.text = [NSString stringWithFormat:@"%f", data.rotationRate.y];
                            zLabel.text = [NSString stringWithFormat:@"%f", data.rotationRate.z];
                        });
                    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
    [super viewDidUnload];
}

- (void)dealloc {
    [self.motionManager stopGyroUpdates];
    self.motionManager = nil;
    [xLabel release];
    [yLabel release];
    [zLabel release];
    [super dealloc];
}

@end


ジャイロデータとして受け取る CMGyroData は、
rotationRate というプロパティをひとつ持つだけの、至ってシンプルなクラス。
rotationRateの型はCMRotationRateという構造体で、
x,y,z軸における回転の速さ(ラジアン/second)を保持しています。



というわけで上記サンプルを実機にインストールすると
iPhoneを動かす度に回転速度がとれるようになります。