首页 > 解决方案 > 我如何在 Swift 4 中使用陀螺仪来获得 Yaw?

问题描述

我看了这篇文章,但它似乎已经过时了: Swift gyroscope yaw, pitch, roll

我正在尝试使用 CoreMotion 计算绕 Y 轴的旋转并将其作为双精度返回到 iOS 上的 Swift Playground 中。我目前正在尝试解决如何获得偏航,因为从 Swift 的 Apple 文档中,它似乎作为双精度返回,并将值保存为变量。这是 OI 迄今为止所做的:

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")
    }

我正在尝试在 iOS 12 上的 Swift Playgrounds 上使用它,并使用最新版本的 swift 和 XCode。

标签: swiftxcodeswift-playgroundgyroscopecore-motion

解决方案


试试这个解决方案。

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)")

    }

希望这会有所帮助。


推荐阅读