我的加速度计有问题。
如果设备平放,我得到 (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) )
}
最佳答案
您正在访问原始加速度,其中将包括重力。这意味着 (0, 0, -1) 实际上显然是正确的。
如果您想要更稳定的东西(并且没有重力矢量),请使用设备运动。值得注意的是,来自设备运动接口(interface)的数据使用传感器融合过滤方法进行过滤和稳定,因此加速度数据会更准确。
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里了, 第一段。
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.
关于ios - 去除重力对 IOS iphone 加速度计的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45890060/