加速度计检测 Phone 运动

Accelerometer To Detect Phone Movement

我正在尝试找出最准确的方法来检测 phone 何时向前移动并计算它。到目前为止,每当加速度计 y 加速度超过某个双倍时,我都能计数,但它不是很准确,因为我要做的就是让计数器上升,向前倾斜 phone 而不是让 phone实际移动。我怎样才能达到我想要的?我应该添加更多变量,如 x 轴或 z 轴,还是需要在我当前未使用的 phone 中加入陀螺仪或其他功能?谢谢

到目前为止,这是我的代码:

`override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        motionManager.accelerometerUpdateInterval = 0.1

        motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: { (accelerometerData: CMAccelerometerData?, error: NSError?) -> Void
            in

            self.outputAccelData(accelerometerData!.acceleration)
            if error != nil {

                print(error)

            }

        })
    func outputAccelData(acceleration: CMAcceleration) {


            if acceleration.y > 0.3 {

                countInt += 1

            }

            count.text = "\(countInt)"

        }

您可以使用 x、y 和 z 的平方和的平方根来计算当前加速度大小。在静止状态下,无论 phone 的方向如何,该值都将保持不变(地球的引力)。如果有人击中或捡起 phone,那么这个幅度会暂时改变,你可以检测到那个增量。您可能需要在检测之前稍微过滤此幅度,具体取决于您尝试检测的运动有多小。