2017-08-25 66 views
2

我遇到了加速度計的問題。刪除重力對IOS加速度計的影響

如果設備平放,我會得到(0,0,-1),這顯然是不正確的。當我旋轉手機時,根據手機的位置,此-1會移至其他軸。

我至今非常簡單的代碼:

override func viewDidAppear(_ animated: Bool) { 

    motionManager.accelerometerUpdateInterval = 0.1 
    motionManager.startAccelerometerUpdates(to: OperationQueue.current!){(data,error) 
     in 
     if let myData = data { 
      print(Double(myData.acceleration.y) ) 
    } 
+2

爲什麼它不對?由於地球的重力,有一個恆定的-1g。 – Paulw11

回答

2

您正在訪問的原始加速,這將包括重力。這意味着(0,0,-1)實際上是顯然是正確的

如果您想要一些更穩定的東西(並且避免重力矢量),請使用設備運動。值得注意的是,使用傳感器融合濾波方法對來自設備運動界面的數據進行濾波和穩定處理,因此加速度數據將更加準確。

import UIKit 
import CoreMotion 

class ViewController: UIViewController { 

    let motionManager = CMMotionManager() 

    override func viewDidAppear(_ animated: Bool) { 
     super.viewDidAppear(animated) 

     motionManager.deviceMotionUpdateInterval = 0.1 
     motionManager.startDeviceMotionUpdates(to: .main) { (motion, error) in 
      if let motion = motion { 
       var x = motion.userAcceleration.x 
       var y = motion.userAcceleration.y 
       var z = motion.userAcceleration.z 

       // Truncate to 2 significant digits 
       x = round(100 * x)/100 
       y = round(100 * y)/100 
       z = round(100 * z)/100 

       // Ditch the -0s because I don't like how they look being printed 
       if x.isZero && x.sign == .minus { 
        x = 0.0 
       } 

       if y.isZero && y.sign == .minus { 
        y = 0.0 
       } 

       if z.isZero && z.sign == .minus { 
        z = 0.0 
       } 

       print(String(format: "%.2f, %.2f, %.2f", x, y, z)) 
      } 
     } 
    } 
} 

順便說一下,這一切都在the docs的第一段。

創建CMMotionManager的一個實例後,應用程序可以利用它來接收四個類型的運動:原始加速度計數據,原始陀螺儀數據,原始磁強計數據,並處理設備的運動數據(包括加速度計,rotation-速率和姿態測量)。由Core Motion的傳感器融合算法提供的處理過的設備運動數據給出設備的姿態,旋轉速率,校準磁場,重力方向以及用戶賦予設備的加速度。

+0

親愛的艾倫,我將此代碼添加到一個新的文件來設置它...它說motionManager是一個未解決的標識符? –

+0

這個錯誤意味着你還沒有創建'motionManager'。我提供的代碼旨在替換您在問題中包含的代碼。它在獨立的環境中是不完整的。 –

+0

@DamianTalaga我更新了我的示例以更明確。 –

相關問題