Determine the orientation of the device and its resulting angle in one dimension?

I have the following setup:

enter image description here

iPhone lies with a display on the ceiling on the table (alpha = 0 degrees). When the iPhone moves up, as shown in the image above the alpha angle, it increases.

How to calculate the alpha angle value without worrying about any other axes that might change. I'm only interested in one axis.

How to get the right alpha angle that iPhone can rise from the table? How to get notified when alpha value changes?

+7
ios objective-c iphone swift gyroscope
source share
1 answer

You can use the CMMotionManager class to track device movement changes.

Goal c

 // Ensure to keep a strong reference to the motion manager otherwise you won't get updates self.motionManager = [[CMMotionManager alloc] init]; if (self.motionManager.deviceMotionAvailable) { self.motionManager.deviceMotionUpdateInterval = 0.1; // For use in the montionManager handler to prevent strong reference cycle __weak typeof(self) weakSelf = self; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [self.motionManager startDeviceMotionUpdatesToQueue:queue withHandler:^(CMDeviceMotion *motion, NSError *error) { // Get the attitude of the device CMAttitude *attitude = motion.attitude; // Get the pitch (in radians) and convert to degrees. NSLog(@"%f", attitude.pitch * 180.0/M_PI); dispatch_async(dispatch_get_main_queue(), ^{ // Update some UI }); }]; NSLog(@"Device motion started"); } else { NSLog(@"Device motion unavailable"); } 

Swift

 // Ensure to keep a strong reference to the motion manager otherwise you won't get updates motionManager = CMMotionManager() if motionManager?.deviceMotionAvailable == true { motionManager?.deviceMotionUpdateInterval = 0.1; let queue = NSOperationQueue() motionManager?.startDeviceMotionUpdatesToQueue(queue, withHandler: { [weak self] (motion, error) -> Void in // Get the attitude of the device if let attitude = motion?.attitude { // Get the pitch (in radians) and convert to degrees. // Import Darwin to get M_PI in Swift print(attitude.pitch * 180.0/M_PI) dispatch_async(dispatch_get_main_queue()) { // Update some UI } } }) print("Device motion started") } else { print("Device motion unavailable"); } 

NSHipster (as always) is a great source of information, and an article on CMDeviceMotion is no exception.

+10
source share

All Articles