Suppose you are holding an iphone/ipad vertically in front of you with the screen facing you, in portrait orientation. You tilt the device to one side, keeping the screen facing you. How do you measure that static tilt angle using CMMotionManager? It seems a simple question which should have a simple answer, yet I cannot find any method that does not disappear into quaternions and rotation matrices.
Can anyone point me to a worked example?
It is kind of a late answer but you can found a working example on github and the blog article that comes with it.
To summarize the article mentioned above, you can use quaternions to avoid the gimbal lock problem that you are probably facing when holding the iPhone vertically.
Here is the coding part that compute the tilt (or yaw) :
You can even add a simple Kalman filter to ease the yaw :
Here is an example that rotates a UIView
self.horizon
to keep it level with the horizon as you tilt the device.This is a little oversimplified - you should be sure to have only one instance of CMMotionManager in your app so you want to pre-initialise this and access it via a property.
Look at
gravity
:With this reference frame (
CMAttitudeReferenceFrameXArbitraryZVertical
), ifz
is near zero, you're holding it on a plane perpendicular with the ground (e.g. as if you were holding it against a wall) and as you rotate it on that plane,x
andy
values change. Vertical is wherex
is near zero andy
is near -1.Looking at this post, I notice that if you want to convert this vector into angles, you can use the following algorithms.
If you want to calculate how many degrees from vertical the device is rotated (where positive is clockwise, negative is counter-clockwise), you can calculate this as:
You can use this to figure out how much to rotate the view via the Quartz 2D
transform
property:(Personally, I update the rotation angle in the
startDeviceMotionUpdates
method, and update thistransform
in aCADisplayLink
, which decouples the screen updates from the angle updates.)You can see how far you've tilted it backward/forward via:
Since iOS8 CoreMotion also returns you a
CMAttitude
object, which containspitch
,roll
andyaw
properties, as well as the quaternion. Using this will mean you don't have to do the manual maths to convert acceleration to orientation.