ios - 去除重力对 IOS iphone 加速度计的影响

标签 ios swift accelerometer gravity

我的加速度计有问题。

如果设备平放,我得到 (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/

相关文章:

android - 将箭头指向用户面对的方向

android - 使用地理定位 api cordova/phonegap 查找距离、速度和加速度

ios - 在 iOS 的后台持续更新加速度计

iOS:当应用程序处于后台时防止显示特定通知

ios - 点击按钮时显示 UIPickerView

ios - 如何检测 HealthKit 数据是否是从设备设置的?

swift - App Store 审核中的推送通知

arrays - swift : protocol extension and arrays

ios - 如何将用户输入的文本保存到 UITextView 中

ios - 我应该如何将多个 BLE 外围设备连接到 iOS 设备?