3

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)?

Jancoz
  • 51
  • 1
  • 5

2 Answers2

0

Have a look at https://github.com/kriswiner/MPU9250
Specifically, MPU9250BasicAHRS.ino has calculations on Arduino for roll, pitch, and yaw.

Brian Wright
  • 93
  • 1
  • 9
0

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.

JJJ
  • 1,009
  • 6
  • 19
  • 31
Jancoz
  • 51
  • 1
  • 5
  • 2
    Please try to provide as complete an answer as possible. Can you give a working example? – JJJ Apr 14 '19 at 22:16