case Computer :

[iPhone/iPad] Gyroscope 센서 사용

거곰 2011. 7. 20. 16:42
iOS 4.0 이상부터만 사용하능한 기능입니다. iphone 3gs 이하 버젼은 소스를 추가해도 동작하지 않습니다.

먼저 자이로 스코프 센서를 사용하기 위해  CoreMotion.framework 를 추가해야 합니다.

프레임워크 추가하는 방법은 다들 아실꺼라 생각하고 넘어가겠습니다.



먼저 header source 입니다. 
가장 중요한건 CMMotionManager 입니다.
그리고 자이로 센서의 정보를 받기위해 roll, pitch, yaw 를 변수로 따로 뺏습니다.

#import <Foundation/Foundation.h
#import <CoreMotion/CoreMotion.h

@interface MotionSensor : NSObject {
    CMMotionManager *motionManager;
    CMDeviceMotion *motion;
    CMAttitude *attitude;
    NSTimer *timer;
    
    short roll;
    short pitch;
    short yaw;
}

@property (nonatomic, retain) CMDeviceMotion *motion;
@property (nonatomic, retain) CMAttitude *attitude;
@property short roll;
@property short pitch;
@property short yaw;

-(void) updateGyro;
@end

다음은 main source 입니다.
초기화 후에 timer를 통해 일정시간마다 정보를 업데이트 하게 합니다.

#import "MotionSensor.h"

@implementation MotionSensor

@synthesize motion;
@synthesize attitude;
@synthesize roll;
@synthesize pitch;
@synthesize yaw;

-(id)init{
    motionManager = [[CMMotionManager alloc] init];
    motionManager.deviceMotionUpdateInterval = 1.0f/20.0f;
    
    if(motionManager.gyroAvailable){
        [motionManager startDeviceMotionUpdates];
        timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self 
                                               selector:@selector(updateGyro) userInfo:nil repeats:YES];
    }else{
        [motionManager release];
    }
    return self;
}

-(void) updateGyro{
    motion = motionManager.deviceMotion;
    attitude = motion.attitude;

    roll = (short) (attitude.roll*180 / M_PI);   
    pitch = (short) (attitude.pitch*180 / M_PI); 
    yaw = (short) (attitude.yaw*180 / M_PI);     
}

- (void)dealloc{
    [motionManager release];
    [super dealloc];
}
@end


roll, pitch, yaw는 기본적으로 -1~1 사이에 실수값을 보냅니다.
이를 일반적인 각도 값으로 표현하기 위해서  위와 같이 계산 후에 보내면 
roll은 -180 ~ 180
pitch는 -180~180
yaw는 0~360 값을 표현합니다.
 
이값을 출력하는건 여러분의 몫입니다. 
반응형