Search code examples
iphonecore-motionpitch

CMAttitude roll and pitch calculation


The question itself is simple. When using the CMDeviceMotion motion it contains an object named attitude of type CMAttitude which contains roll and pitch. Roll and pitch describe the rotation of the object around the Y and X axis. When the iPhone lies on a table with the display pointing up roll and pitch are both 0. When rotating the iPhone around Y or X axis these values get updated.

I want to know how these values are calculated.There is a way to calculate roll and pitch from the current gravity vector of the device. The pitch seems to be: pitch = -asin(motion.gravity.y) but I can not figure out how to calculate the roll.

Thanks for your help


Solution

  • It's likely something like:

    roll = -atan(x / z);
    

    though you need to alter the sign depending on which orientation you're in, and be careful around the asymptotes where z=0.

    I believe Core Motion in reality uses gyro measurements in addition to the accelerometer readings to calculate the attitude more accurately (and maybe also to deal with gimbal lock).