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 ofCMMotionManagerto 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 theCMGyroHandlerformat.
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", ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access