I am trying figure out the most accurate way to detect when the phone moves forward and count it. So far I have been able to count every time the accelerometer y acceleration goes above a certain double but it isnt very accurate since all I have to do make the counter go up is tilt the phone forward instead of having the phone actually move. How can I achieve what I want? Should I add more variables like the x or z axis or do I need to incorporate the gyroscope or another feature within the phone that I am not currently using? Thanks
This is my code so far:
`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)"
}
What you can do is calculate a current acceleration magnitude using the square root of the sum of the squares for x, y, and z. At rest, this value will be constant (Earth's gravitational pull) no matter how the phone is oriented. If someone hits or picks up the phone, then this magnitude will temporarily change and you can detect that delta. You may need to filter this magnitude slightly before detection depending on how small a movement you are trying to detect.