Wednesday, 28 October 2020

Detecting phone tilt with CoreMotion

I'm trying to use CoreMotion to detected whether phone is a little bit tilted in order to alert the user when the phone is not in an upright position.

Let's say that the device is in upright position when it's rotated left or right in less than 40 degrees and it's rotated backward or forward in less than 40 degrees.

description

Now I've used the CMMotionManager like that:

motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
motionManager.showsDeviceMovementDisplay = true
motionManager.startDeviceMotionUpdates(to: OperationQueue()) { motion, error in
    if let data = motion {
        let pitch = data.attitude.pitch.toDegrees()
        let roll = data.attitude.roll.toDegrees()
        let yaw = data.attitude.yaw.toDegrees()

        print("Pitch: \(pitch), roll: \(roll), yaw: \(yaw).")
    }
}

extension Double {

    func toDegrees() -> Double {
        self * 180.0 / .pi
    }
}

If I understand correctly, the pitch value will tell me that the phone is rotated left or right, and the yaw value will tell me that the phone is rotated forward or backward. Now I have looked at the printed values, and pitch seems to be fine, it is equal to 90 degrees when the phone is upright. But the yaw value is not changing as I would expected while rotating the phone.

The question is, am I doing something wrong? Which values I should use to check whether phone is not rotated forward / backward or left / right?



from Detecting phone tilt with CoreMotion

No comments:

Post a Comment