0

I looked at this post but it seems to be outdated: Swift gyroscope yaw, pitch, roll

I am trying to use CoreMotion to calculate the rotation around the Y axis and return it as a double in a Swift Playground on iOS. I am currently trying to work out how to get the yaw because from the Apple documentation for Swift it seems to be returned as a double, and save the value as a variable. This is what OI have done so far:

let yaw = 0.0
    if motionManager.isGyroAvailable {
        motionManager.deviceMotionUpdateInterval = 0.2;
        motionManager.startDeviceMotionUpdates()

        motionManager.gyroUpdateInterval = 0.2
        motionManager.startGyroUpdatesToQueue(OperationQueue.currentQueue ?? ) {
            [weak self] (gyroData: CMGyroData!, error: NSError!) in

            self?.outputRotationData(gyroData.rotationRate)
            if error != nil {
                println("\(error)")
            }
        }
    } else {
        print("gyroscope not working")
    }

I am trying to use this on Swift Playgrounds on iOS 12 for the iPad with the most up to date versions of swift and XCode.

1 Answers1

1

Try this solution.

var motion = CMMotionManager()
var timer: Timer!


 override func viewDidLoad() {
 super.viewDidLoad()
   startData()
 }

func startData() {

    motion.startGyroUpdates()

    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(SensorViewController.update), userInfo: nil, repeats: true)

}

private func roundDouble(value: Double) -> Double {
    return round(1000 * value)/100
}

@objc func update() {


    if let gyroMeterData = motion.gyroData {

        print(\"self.roundDouble(value: gyroMeterData.rotationRate.x)")
        print(\"self.roundDouble(value: gyroMeterData.rotationRate.y)")
        print(\"self.roundDouble(value: gyroMeterData.rotationRate.z)")

    }

Hope this will help.

  • Thanks for the response. However, when I tried running the code I was having issues with SensorViewController. I'm not sure if this is different in a Swift playground but it doesn't seem to exist. – Rohith Vishwajith Mar 19 '19 at 17:11
  • SensorViewController is the class in which i'm using the above code replace it with your class name. – Prithvi Raj Mar 20 '19 at 04:23
  • Thank you for your reply and the code works! However, I am not trying to get the rotation rate per time interval, I am trying to get the overall rotation on the y axis from the starting point. For example, if the user rotated 60 degrees, then I would store 60 degrees as a variable. I tried simply adding the rotation rate ot another variable which started at 0 but that didn't work, it was very glitchy and kept increasing, – Rohith Vishwajith Mar 20 '19 at 05:50
  • You will need to Use CMAttitude with gyro data that will give you exactly what you are looking for. – Prithvi Raj Mar 20 '19 at 07:33
  • thanks for your answer. I was able to get it working with CMAttitude to get the yaw. – Rohith Vishwajith Mar 20 '19 at 07:34