I'm developing a compass app using react-native-sensors
magnetometer. I'm getting the correct values and the compass is working perfectly, the main problem is the fast update of the compass, the direction keeps changing too frequently and the change is +-5 degrees.
I want to do a smooth orientation compass.
_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 }) })
Found an Answer sounds similar to SamuelPS's answer, I used LPF: Low Pass Filter for JavaScript it's just more optimized and smooth.
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))
}