Damian Talaga
Damian Talaga

Reputation: 73

Removing the effects of the gravity on IOS iphone accelerometer

I am having issues with the accelometer.

If the device is lying flat, I get (0, 0, -1 ) which obviously is not right. As I rotate the phone, this -1 moves to other axes depending on the phone position.

I have very simple code so far :

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

Upvotes: 4

Views: 2518

Answers (1)

allenh
allenh

Reputation: 6622

You are accessing the raw acceleration, which will include gravity. This means that (0, 0, -1) is actually obviously correct.

If you'd like something a little more stable (and sans the gravity vector), use the device motion. It's worth noting that the data that comes from the device motion interface is filtered and stabilized using sensor fusion filtering methods, so the acceleration data will be more accurate.

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

By the way, this is all in the docs, first paragraph.

After creating an instance of CMMotionManager, an app can use it to receive four types of motion: raw accelerometer data, raw gyroscope data, raw magnetometer data, and processed device-motion data (which includes accelerometer, rotation-rate, and attitude measurements). The processed device-motion data provided by Core Motion’s sensor fusion algorithms gives the device’s attitude, rotation rate, calibrated magnetic fields, the direction of gravity, and the acceleration the user is imparting to the device.

Upvotes: 6

Related Questions