首页 > 解决方案 > 使用 react-native-sensors 的磁力计的平滑定向指南针

问题描述

我正在使用react-native-sensors磁力计开发指南针应用程序。我得到了正确的值并且指南针工作正常,主要问题是指南针的快速更新,方向不断变化太频繁,变化是 +-5 度。我想做一个平滑的方向罗盘。

_angle = (magnetometer) => {
    if (magnetometer) {
      let { x, y, z } = magnetometer

      if (Math.atan2(y, x) >= 0) {
        angle = Math.atan2(y, x) * (180 / Math.PI)
      } else {
        angle = (Math.atan2(y, x) + 2 * Math.PI) * (180 / Math.PI)
      }
    }

    return Math.round(angle)
  }


//Inside ComponentDidMount
magnetometer.subscribe(({ x, y, z, timestamp }) =>
      this.setState({ sensorValue: this._angle({ x, y, z }) })

标签: androidreact-nativereact-native-sensors

解决方案


发现一个答案听起来与SamuelPS 的答案相似,我使用了 LPF: Low Pass Filter for JavaScript,它更加优化和流畅。

constructor(props) {
    super(props)
    LPF.init([])
  }

_angle = (magnetometer) => {
    if (magnetometer) {
      let { x, y, z } = magnetometer

      if (Math.atan2(y, x) >= 0) {
        angle = Math.atan2(y, x) * (180 / Math.PI)
      } else {
        angle = (Math.atan2(y, x) + 2 * Math.PI) * (180 / Math.PI)
      }
    }

    return Math.round(LPF.next(angle))
  }

推荐阅读