iOS core motion detect forard / backward tilt

core-motion, ios

Solution

Using attitude pitch, leaning forward and backward are indistinguishable. However with quaternions you can calculate pitch, and if you convert radians to degrees,

- 0 means the device is on its back

- 90 means it's standing up

- 180 means it's on its face

The opposite hemisphere of rotation is 0 to -180. Here's the code:

func radiansToDegrees(_ radians: Double) -> Double {
    return radians * (180.0 / Double.pi)
}

let quat = motionData.attitude.quaternion
let qPitch = CGFloat(radiansToDegrees(atan2(2 * (quat.x * quat.w + quat.y * quat.z), 1 - 2 * quat.x * quat.x - 2 * quat.z * quat.z)))

Problem

I am using the iOS core motion framework to detect if the device is tilted forward or backwards. See image for details: https://i.stack.imgur.com/2Ojw5.jpg Using the pitch value a can detect this movement but I can not distinguish between forward AND backward. More details: I try to detect if there is a movement (tilting forward and backward) in either the forward area OR backward area (see updated sketch). The problem with the pitch is that it starts with a value of about 1.6 if the device is in an upright position. And the value decreases the same when I am tilting it towards a horizontal potion either forward or backward. The same behavior applies to the accelerometer y value. It looks like I miss something in the whole core motion thing. ANy Ideas thanks christian

Original source