arduinoaccelerometergyroscopemagnetometer

Getting heading/direction from MPU-9250


I'm trying to get the heading from the MPU-9250 sensor which contains a Gyroscope, Acceleratometer and Magnetometer using a Arduino.

For my product I need to get the roll and the heading from the device. I already figured out how to fetch the roll. Using the Boulderflight MPU-9250 library I was able to determine the roll using:

roll = 180 * atan(accY/sqrt(accX*accX + accZ*accZ))/M_PI;

I found this calculation somewhere and it seems to work well, I have to admit that I don't actually know how it works.

For the heading I found:

  if (magY > 0) { heading = 90 - atan(magX/magY)*(180/M_PI); }
  else if (magY < 0) { heading = 270 - atan(magX/magY)*(180/M_PI); }
  else if (magY == 0 && magX < 0) { heading = 180; }
  else if (magY == 0 && magX > 0) { heading = 0; }

This, at first, seemed to work but as soon as you would "roll" the device, keeping the heading the same, the values of the heading are all over the place.

Does anyone have a good code snippet for determining the heading using either a Gyroscope, Accelerometer or Magnetometer (In C++, using an Arduino)?


Solution

  • For who may still find it useful, the bad outputs were caused by using Sleep()s in the code. Apparently this messes up measurements. I used them for making an LED pattern. I suppose the next best thing would be to use millis() in combinations with if-statements to reproduce the Sleep()s.