16.5. Retrieving Gyroscope Data
Problem
You want to be able to retrieve information about the device’s motion from the gyroscope hardware on an iOS device.
Solution
Follow these steps:
Find out whether the gyroscope hardware is available on the iOS device. Please refer to Recipe 16.2 for directions on how to do this.
If the gyroscope hardware is available, make sure it is not already sending you updates. Please refer to Recipe 16.2 for directions.
Use the
setGyroUpdateInterval:
instance method ofCMMotionManager
to set the number of updates you want to receive per second. For instance, for 20 updates per second (one second), set this value to 1.0/20.0.Invoke the
startGyroUpdatesToQueue:withHandler:
instance method ofCMMotionManager
. The queue object could simply be the main operation queue (as we will see later) and the handler block must follow theCMGyroHandler
format.
The following code implements these steps:
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ CMMotionManager *manager = [[CMMotionManager alloc] init]; if ([manager isGyroAvailable]){ if ([manager isGyroActive] == NO){ [manager setGyroUpdateInterval:1.0f / 40.0f]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [manager startGyroUpdatesToQueue:queue withHandler:^(CMGyroData *gyroData, NSError *error) { NSLog(@"Gyro Rotation x = %.04f", gyroData.rotationRate.x); NSLog(@"Gyro Rotation y = %.04f", gyroData.rotationRate.y); NSLog(@"Gyro Rotation z = %.04f", ...
Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.