Expo Magnetometer returns inconsistent values

48 views Asked by At

I'm trying to calculate the rotation angle of a device but the more I turn it the more I get inconsistent values.

import { Magnetometer, MagnetometerMeasurement } from "expo-sensors";

const calculateDeviceOrientation = (magnetometerValues: MagnetometerMeasurement) => {
  let angle = 0;
  if (magnetometerValues) {
    const { x, y } = magnetometerValues;
    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);
    }
  }

  // North returns 90 so I make it 0 instead
  return Math.round(angle >= 90 ? angle - 90 : angle + 270);
}

const App = () => {
  const [deviceOrientation, setDeviceOrientation] = useState<number | null>(null);
  
  useEffect(() => {
    Magnetometer.setUpdateInterval(1000);
    const subscription = Magnetometer.addListener((values) => {
      setDeviceOrientation(calculateDeviceOrientation(values));
    });

    return () => subscription.remove();
  }, []);
}

So with this, pointing the phone towards North I get 0, towards East I get 110, and towards South 240. Basically the more I turn the less accurate it gets. Any idea?

0

There are 0 answers