# 3D maths to sutract gravity from accelerometer data

**URL:** <https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105>\
**Category:** Programming\
**Created:** [September 17, 2014, 12:01am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105 "2014-09-17T00:01:15Z")\
**Posts on this page:** 20\
**Page:** 2

<div class="post-metadata">

**Author:** ![anon94801460](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@anon94801460](https://forum.arduino.cc/u/anon94801460)\
**Post date:** [September 17, 2014, 6:22pm UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/21 "2014-09-17T18:22:22Z")

</div>

Hi, Roger:

Your data look pretty good. I plotted them on the surface of a unit sphere using Matlab, see attached.

The CHRobotics application note conveniently provides the definition for converting a quaternion to a rotation matrix. I had some free time this morning, so I cobbled together a few definitions from Richard's RTMath.cpp and the one in CHRobotics, to create a rotation matrix that should correspond to the Euler angles output by RTIMULib.

The matrix generated is quite dissimilar to the rotation matrix produced by your original code, and I assume that this is due to the differing order of application or sign convention for the rotations.

I have not yet figured out how to check whether the rotation matrix agrees with the actual orientation, as there is still some ambiguity on whether the rotation defined by the quaternion or its inverse is to be applied. Nevertheless, the code below may provide a starting point and I hope it is helpful.

I will keep thinking about it! And, after all this is working, one could add the appropriate relativistic corrections 😉

```arduino
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

// globals, current pose

float qt[]={0.,0.,0.,0.}; //current body orientation quaternion
float euler[]={0.,0.,0.}; //current body orientation Euler angles
float R[3][3];

// normalize the quaternion to a unit four-vector

void normalize()
{
    float length = sqrt(qt[0] * qt[0] + qt[1] * qt[1] +
            qt[2] * qt[2] + qt[3] * qt[3]);

    if ((length == 0) || (length == 1))
        return;

    qt[0] /= length;
    qt[1] /= length;
    qt[2] /= length;
    qt[3] /= length;
}

// generate Euler angles from the current quaternion

void toEuler(void)
{
    euler[0] = (atan2(2.0 * (qt[2] * qt[3] + qt[0] * qt[1]),
            1 - 2.0 * (qt[1] * qt[1] + qt[2] * qt[2])));

    euler[1] = (asin(2.0 * (qt[0] * qt[2] - qt[1] * qt[3])));

    euler[2]= (atan2(2.0 * (qt[1] * qt[2] + qt[0] * qt[3]),
            1 - 2.0 * (qt[2] * qt[2] + qt[3] * qt[3])));
}

// generate a quaternion from the current Euler angles

void fromEuler(void)
{
    float cosX2 = cos(euler[0] / 2.0f);
    float sinX2 = sin(euler[0] / 2.0f);
    float cosY2 = cos(euler[1] / 2.0f);
    float sinY2 = sin(euler[1] / 2.0f);
    float cosZ2 = cos(euler[2] / 2.0f);
    float sinZ2 = sin(euler[2] / 2.0f);

    qt[0] = cosX2 * cosY2 * cosZ2 + sinX2 * sinY2 * sinZ2;
    qt[1] = sinX2 * cosY2 * cosZ2 - cosX2 * sinY2 * sinZ2;
    qt[2] = cosX2 * sinY2 * cosZ2 + sinX2 * cosY2 * sinZ2;
    qt[3] = cosX2 * cosY2 * sinZ2 - sinX2 * sinY2 * cosZ2;
    normalize();
}

// generate the rotation matrix corresponding to the current quaternion
// for definition of matrix see https://www.chrobotics.com/docs/AN-1006-UnderstandingQuaternions.pdf

void quaternion_to_R(void)
{
    R[0][0] = qt[0]*qt[0] + qt[1]*qt[1] - qt[2]*qt[2] - qt[3]*qt[3];
    R[0][1] = 2.0*(qt[1]*qt[2] - qt[0]*qt[3]);
    R[0][2] = 2.0*(qt[1]*qt[3] + qt[0]*qt[2]);
    R[1][0] = 2.0*(qt[1]*qt[2] + qt[0]*qt[3]);
    R[1][1] = qt[0]*qt[0] - qt[1]*qt[1] + qt[2]*qt[2] - qt[3]*qt[3];
    R[1][2] = 2.0*(qt[2]*qt[3] - qt[0]*qt[1]);
    R[2][0] = 2.0*(qt[1]*qt[3] - qt[0]*qt[2]);
    R[2][1] = 2.0*(qt[2]*qt[3] + qt[0]*qt[1]);
    R[2][2] = qt[0]*qt[0] - qt[1]*qt[1] - qt[2]*qt[2] + qt[3]*qt[3];
}

int main()
{
float accel[3]={0.1,0,1.0};// data will come from the accelerometers
float gravity[3]={0,0,1.0};// always vertically downwards at g = 1.0
float rG[3],rA[3];
float mA[3];

// Angle of rotation will come from RTImuLib
float alpha= 0.1;// some aribitar values for testing
float beta=  0.2;// some aribitar values for testing
float theta = 0.3;// some aribitar values for testing
euler[0]=alpha;
euler[1]=beta;
euler[2]=theta;

printf("Euler angles: %5.1f %5.1f %5.1f\r\n",euler[0],euler[1],euler[2]);

fromEuler();
quaternion_to_R();

// print out the corresponding rotation matrix

printf ("QR\r\n %8.5f %8.5f %8.5f\r\n %8.5f %8.5f %8.5f\r\n %8.5f %8.5f %8.5f\r\n",
        R[0][0],R[0][1],R[0][2],R[1][0],R[1][1],R[1][2],R[2][0],R[2][1],R[2][2]);

float det =  R[0][0]*(R[1][1]*R[2][2]-R[1][2]*R[2][1])\
             -R[0][1]*(R[1][0]*R[2][2]-R[1][2]*R[2][0])\
             +R[0][2]*(R[1][0]*R[2][1]-R[1][1]*R[2][0]);

printf(" det(R) = %f\r\n",det);  //for check, should be +1 exactly

rG[0]= gravity[0]*R[0][0] + gravity[1]*R[0][1] + gravity[2]*R[0][2] ;
rG[1]= gravity[0]*R[1][0] + gravity[1]*R[1][1] + gravity[2]*R[1][2] ;
rG[2]= gravity[0]*R[2][0] + gravity[1]*R[2][1] + gravity[2]*R[2][2] ;

rA[0]= accel[0]*R[0][0] + accel[1]*R[0][1] + accel[2]*R[0][2] ;
rA[1]= accel[0]*R[1][0] + accel[1]*R[1][1] + accel[2]*R[1][2] ;
rA[2]= accel[0]*R[2][0] + accel[1]*R[2][1] + accel[2]*R[2][2] ;

mA[0]=rA[0]-rG[0];
mA[1]=rA[1]-rG[1];
mA[2]=rA[2]-rG[2];

printf("\r\nA %8.5f %8.5f %8.5f\r\n",accel[0],accel[1],accel[2]);
printf("G %8.5f %8.5f %8.5f\r\n",gravity[0],gravity[1],gravity[2]);
printf("\r\nrA %8.5f %8.5f %8.5f\r\n",rA[0],rA[1],rA[2]);
printf("rG %8.5f %8.5f %8.5f\r\n",rG[0],rG[1],rG[2]);
printf("\r\nrA-rG in body frame %8.5f %8.5f %8.5f\r\n",mA[0],mA[1],mA[2]);

//rotate modified acceleration back into the Earth frame (use transpose of R)

rA[0]= mA[0]*R[0][0] + mA[1]*R[1][0] + mA[2]*R[2][0] ;
rA[1]= mA[0]*R[0][1] + mA[1]*R[1][1] + mA[2]*R[2][1] ;
rA[2]= mA[0]*R[0][2] + mA[1]*R[1][2] + mA[2]*R[2][2] ;

printf("A-G in Earth frame  %8.5f %8.5f %8.5f\r\n",rA[0],rA[1],rA[2]);

    return 0;
}

```

Program output

> Euler angles: 0.1 0.2 0.3  
> QR  
> 0.93629 -0.27510 0.21835  
> 0.28963 0.95643 -0.03696  
> -0.19867 0.09784 0.97517  
> det(R) = 1.000000
> 
> A 0.10000 0.00000 1.00000  
> G 0.00000 0.00000 1.00000
> 
> rA 0.31198 -0.00799 0.95530  
> rG 0.21835 -0.03696 0.97517
> 
> rA-rG in body frame 0.09363 0.02896 -0.01987  
> A-G in Earth frame 0.10000 0.00000 -0.00000
> 
> Process returned 0 (0x0) execution time : -0.000 s

![data2.png](https://europe1.discourse-cdn.com/arduino/original/4X/6/8/1/68111acdc8c191229f6e523ff26777951db2351d.png)

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 17, 2014, 9:04pm UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/22 "2014-09-17T21:04:48Z")

</div>

@jremminton

Thanks, I will give your code a try this morning (its comming up to 7am here in Melbourne)

I can see that the rotation matrices could look a lot different to the one I used, mainly because of the order in which the axis need to be rotated.

My next step was actually going to be, to do one axis at a time, by having 3 separate rotation matrices, in the hope I could isolate which axis is which, and from what you've said, perhaps direction of rotation may be an issues.  
And one other thing that has crossed my mind is that perhaps the X Y and Z data from RTImuLib could already be rotated so that its most useful to aircraft. Ie x y are 0,0 when the module is level.  
However I guess this wouldn't really matter as whatever the rotation, of these planes, the gravity rotation should be able to get it into alignment.

I will have a go at moving the sensor left right back and forward to see if the x and y accelerometer values change as I'd expect, I.e side the breadboard around on a flat surface.  
Vertical acceleration, on its own, is going to be a bit more tricky, as I'm likely to move it in all three axis when it pick it up.

I installed codeblocks on another machine last night, so my plan is to read the cvs data into the test program, and see if I can get the adjusted accelerometer to be virtually zero for all axis, for all of my input data.

It should be fairly obvious if its working, e.g all three corrected accelerometer values should be somewhere around zero, as I was trying to just rotate the module to create the data and not move it much in x y and z.

Anyway, thanks again, I will let you know I get on

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 17, 2014, 11:36pm UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/23 "2014-09-17T23:36:00Z")

</div>

@jremminton

I've tried to combine the data I collected with your functions to create the rotation matrix

(See attached code for codeblocks i.,e **Not** Arduino code)

I'm just printing out the resultant accelerations, but as you can see they are not all low values.

There are still problems with some of the quadrants ☹

Looking at your code, I'm not sure why you divided the Euler angle data by 2.0f, but I must admit I don't know anything about Quarternions, so I guess this is correct ?

I've no idea about your Quarternions to rotation stuff. Is this dependent on the order in which you rotate the axis' as well ?  
Or is it supposed to be a general purpose rotation matrix ?

I guess the incomming Euler axis could be wrong, or possibly the Quarternion to rotation matrix.

Sorry this is beyond what I currently understand.

I need to get on with my day job now (programming), but I will probably take a look at isolating one axis at a time

Or perhaps looking at the output would shed some light on things for you

Anyway, thanks for your help with this

Cheers

Roger

[main.cpp](https://forum.arduino.cc/uploads/short-url/sWZxl9aYeSlOuuo99F1LDW1fYl1.cpp) (22.7 KB)

---

<div class="post-metadata">

**Author:** ![anon94801460](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@anon94801460](https://forum.arduino.cc/u/anon94801460)\
**Post date:** [September 18, 2014, 2:08am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/24 "2014-09-18T02:08:17Z")

</div>

Hi, Roger:

It was a good idea just to plug the data in and see what happens if gravity is subtracted. There were still some typos in your code, namely,

```arduino
    accel[0]=data[i][3];
    accel[0]=data[i][3];
    accel[0]=data[i][3];
(should be)
    accel[0]=data[i][3];
    accel[1]=data[i][4];
    accel[2]=data[i][5];

```

But no matter, after the fix it still doesn't work. Just looking at the data, I suspect that the problem may be in how the breakout board you are using is oriented, and how that orientation relates to how RTIMULib assumes the board is oriented in the model. For example, the very first entry in data is:

> {-0.0092498,0.1012821,1.7882684,-0.1015625,-0.0104980,0.9943848},

Correct me if my interpretation is wrong, but if this corresponds to roll ~ 0, pitch ~ 6 and yaw ~ 100 degrees, does that agree with the Z acceleration of ~1 g (I think yes) and the X acceleration of about -0.1 g? Looking at more extreme examples will probably help.

As for your other questions, the formation of the quaternion from the Euler angles is simply the definition and that was taken straight out of Richard's code in RTIMULib. I have not gone through the math to see if the rotation matrix definition from CHRobotics is actually correct, but since that is what Caleb Chamberlain does that for a living, I suspect it is.

This will eventually work! I'm happy to help.

Cheers, Jim

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 18, 2014, 2:29am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/25 "2014-09-18T02:29:23Z")

</div>

Hi jremington

Sorry about the code errors / typos. I was trying to get something done before I had to go to work... Well that's my excuse 😉

Ok about it still not working even if you correct my errors.

Re: Orientation

The IC (MPU9150) is horizontal on the breakout board, and is plugged into a small breadboard and connected to a Uno.  
(see photo)

This seems to yield X and Y values of zero (0)

If I rotate the board around (flat on the desk) the Z value changes, but not the X and Y (appreciably)

So pitch and roll should be zero, in this configuration (if its an aircraft), and the yaw is whatever the compass orientation is of the MPU9150

I've posted to the author of the RTImuLib, to see if he can shed any light on the axis orientation or order of rotation that would need to be processed in order that the gravity component can be removed, so hopefully he will be able to give some ideas of what to do next

I won't have time to take another look until the end of my working day ie in about 5 hours ☹

Cheers

Roger

![mpu9150.JPG](https://europe1.discourse-cdn.com/arduino/original/4X/0/4/e/04e5eac160ddfdfb31da0aa46abbc9199735929a.jpeg)

---

<div class="post-metadata">

**Author:** ![anon94801460](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@anon94801460](https://forum.arduino.cc/u/anon94801460)\
**Post date:** [September 18, 2014, 2:55am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/26 "2014-09-18T02:55:57Z")

</div>

Re typos: I figured you were up too late!

> If I rotate the board around (flat on the desk) the Z value changes, but not the X and Y (appreciably)

By values, do you mean acceleration or Euler angles? If Euler, what sensor axis is pointing to magnetic north when Z=0?  
If acceleration, nothing should change appreciably as you rotate the sensor, flat on the desk.

I looked through a lot of RTIMULib stuff, including the code that reads the sensors, and cannot find any comments relating to how the sensor axes are assumed to be aligned with the model axes. And it is probably different for different sensors. For example, here is a snippet from the MPU9150 driver that, without explanation, swaps the X and Y axes with a sign change:

```arduino
    //  sort out compass axes

    float temp;

    temp = m_imuData.compass.x();
    m_imuData.compass.setX(m_imuData.compass.y());
    m_imuData.compass.setY(-temp);

```

In README.md, the following important nugget was found:

> The displayed pose shows the roll, pitch and yaw seen by the IMU. Using an aircraft analogy, the roll axis points from the pilot towards the nose, the pitch axis points from the pilot along the right wing and the yaw axis points from the pilot down towards the ground. Right wing down is a positive roll, nose up is a positive pitch and clockwise rotation is a positive yaw.

These are pretty standard, yet how is the sensor oriented? In many instances body X is assumed to point North, body Y to the East and Z down, but without knowing that orientation for certain, it is not easy to figure out what the Euler angles actually mean. Let us know how you get on. Again, this WILL work.

Jim

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 18, 2014, 3:15am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/27 "2014-09-18T03:15:33Z")

</div>

Hi Jim

I got a reply from Richard of RTImuLib on his blig

see [http://richardstechnotes.wordpress.com/2014/04/22/rtimulib-arduino-9-dof-imu-library-for-the-arduino/?replytocom=230#respond](http://richardstechnotes.wordpress.com/2014/04/22/rtimulib-arduino-9-dof-imu-library-for-the-arduino/?replytocom=230#respond)

I'm just taking a quick look at his code before I get on with the day job 😉

But Richards code is just pseudo code not code that will compile

I've tried to work out what the real code should be from his pseudo code, but at the moment its not compiling

```plaintext
RTQuaternion g;
  RTVector3 newG;

  g.setScalar(0);
  g.setX(0);
  g.setY(0);
  g.setZ(1); // this indicates 1 g straight down
  RTQuaternion fusedQPose = fusion.getFusionQPose();
  newG = fusedQPose.conjugate() * g * fusedQPose;

```

I'm getting an error about operator = not being defined, which I think is the conversion of the Quarternion space back to the vector space

I'll keep you posted

Cheers

Roger

---

<div class="post-metadata">

**Author:** ![anon94801460](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@anon94801460](https://forum.arduino.cc/u/anon94801460)\
**Post date:** [September 18, 2014, 3:51am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/28 "2014-09-18T03:51:12Z")

</div>

Roger:

Richard's comment was all I needed to see. Plus, I made a mistake by rotating the measured acceleration into the body frame -- it already is, by definition, in the body frame! The original test case worked because the acceleration was _defined_ to be in the Earth frame.

Richard suggested to use the inverse quaternion to rotate the gravity vector. The equivalent in matrix notation is to use the inverse of the rotation matrix, which is just its transpose. That is now in the code and it seems to work! Attached.

I've added two lines that report the magnitudes of the original acceleration vector and the result of the subtraction A-rG. Sometimes the magnitude of the A-rG is as large as about 0.1 g, but as expected that happens when the magnitude of the acceleration vector is not 1.0 g, which means the sensor is either actually accelerating, or there is noise in the measurement.

Jim

[mainRC.cpp](https://forum.arduino.cc/uploads/short-url/gPHX2Lk143WorFHivKLbe2AcFH4.cpp) (22.6 KB)

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 18, 2014, 3:55am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/29 "2014-09-18T03:55:29Z")

</div>

Hi Jim,

Thanks. I'll give you code a try.

I did try to interpret what Richard posted

But my code didnt work, and seemed inject a factor of PI

i.e my code was

```cpp
RTQuaternion g;
RTQuaternion newGQ;
RTVector3 newG;

g.setScalar(0);
g.setX(0);
g.setY(0);
g.setZ(1); // this indicates 1 g straight down
RTQuaternion fusedQPose = fusion.getFusionQPose();
newGQ = fusedQPose.conjugate() * g * fusedQPose;
newGQ.toEuler(newG);

// Code to print out the newG to Serial (to lots of dp’s)
char printBuf[32];
dtostrf(newG.x(),12, 7, printBuf); Serial.print(printBuf); Serial.print(“,”);
dtostrf(newG.y(),12, 7, printBuf); Serial.print(printBuf); Serial.print(“,”);
dtostrf(newG.z(),12, 7, printBuf); Serial.println(printBuf);

```

but some results data was

-0.0061196, 0.0412451, 3.1414640

or if I rotated the module, the data changed to

-3.1360431, -0.0000829, -3.1111083

anyway, I'll boot my other machine and try you code now.

Cheers

Roger

Edit.

Just tried you code with the test data on my PC and it definately seems to be zeroing (well as much as expected) the acceleration vector(s) throughout the various orientations that I put the module (sensor) through.

I'm not going to have time to take your code and put it back into the Arduino code until this evening my time (about 3 or 4 hours from now), but I'll post again the results.

Its looking very promising, I just need to capture some steady state data and see how far off zero the average values for the acceleration actually are.  
I suspect I'll need to apply some form of additional filtering, i.e that presumes that the module is mostly not moving, so that I only register the large movements e.g. when the module is actually picked up and even thrown (as I'm going to put it inside a foam cube).

I've already got a piece of foam rubber that is 6 inches square (it may be 15cm but near enough!), which was an offcut so only cost me literally 40 cents.  
I also have a Lipo battery from a mobile phone to power things, and also a Arduino Pro Mini 8Mhz (3.3V compatible).

I'm not sure how to send data back from the module when its inside the foam cube (as yet).

I have some NRF24L01 modules and also some HC05 Bluetooth modules, and also some Wifi -\> Serial modules. (however the Wifi serial modules are quite power hungry i,e \> 100mA so would flatten the battery quite quickly)

I suspect Bluetooth serial modules may be my best bet

But I think I'm getting ahead of myself and I better get it working on the bench first  
(Oh and I have to strip out a lot of the code I'm not using from the RTImuLibrary as my simple program is almost 30kb with virtually no functionality ( because the RTImuLib is quite large and supports more than one sensor device)

BTW. I also have some Barometric pressure sensors that I was thinking may be able to improve the accuracy (In Z). But having done some tests the spec if a bit optimistic on the ones I have (BMP180) as they are specced at 7cm accuracy but are nearer 20cm accuracy

Re: Day job.

No. Its my choice.

I'll need to work more this evening to make up some time. Or just not bill the client for every hour today (as I'm a freelancer / contract programmer)

Cheers

Roger

---

<div class="post-metadata">

**Author:** ![anon94801460](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@anon94801460](https://forum.arduino.cc/u/anon94801460)\
**Post date:** [September 18, 2014, 4:07am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/30 "2014-09-18T04:07:19Z")

</div>

I'm not keeping you from the day job, am I?

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 18, 2014, 4:14am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/31 "2014-09-18T04:14:32Z")

</div>

Hi Jim,

I was editing while you posted,. See my last posting's Edit.

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 18, 2014, 11:55am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/32 "2014-09-18T11:55:23Z")

</div>

OK.

I've taken Jim's code (thanks Jim and Richard) and put the relevant parts into my Arduino code (see ArduinoIMU attached)

The code is very messy, but its OK as a test bed 😉

I've also attached some data recorded by the code.

The names of the data explains what it contains, (a) module is level in X and Y and not being moved at all

I then inclined it in X by around 45 degrees to see if this has a marked difference to the numbers (and it doesn't)

Finally, I used bluetac to attach the module board to the top of the Uno, and got a long usb cable and move it about 3 feet left and right, then turned it through 90 deg in Z, and did the same thing, so the motion would be in the other horizontal dimension  
Then I turned the module on its side, so that what was the top became the side, and I moved it again from side to side (which would simulate the module going up and down)

First the good news.

Jim's code worked fine and the Axis's are distinct and the gravity component has been removed.

Now the bit I need to do more work on.

(a), The corrected accelerations have a small bias, which would cause drift as it will be integrated  
(b) Rapid movements, are not handled well in my data, but this is because its only getting the data every 300ms and then sending it via serial.  
To get much better position data when the sensor is moved at normal everyday speeds, eg people walking or running or throwing the sensor, the sample rate will need to be much higher

I'll need to do some more research about Richards library (RTImuLib), as I see that there are settings for the maximum sample rate which is set at 50Hz, but I've noticed postings by Richard on his blog where he mentions the RaspberryPi doing much faster sampling.

So I'm not sure if the 50Hz is a limit of the 16Mhz processor on the ATMega328 etc, or something else

If processor speed proves to be the problem I have a Due I could try it on (though I'm not sure of the code compatibility of the I2Cdev library that it uses (but I presume that the Wire library works OK on the Due)

Anyway. My next step is just to remove the bias. To start with I will just use a running average calculation, to slowly equalize out the bias, e.g. after 1 to 2 seconds (I'll see whats needed)

I'll also try a Kalman filter as this may be better than the simple running average. Probably this one

> **[GitHub - TKJElectronics/KalmanFilter: This is a Kalman filter used to...](https://github.com/TKJElectronics/KalmanFilter)**
>
> This is a Kalman filter used to calculate the angle, rate and bias from from the input of an accelerometer/magnetometer and a gyroscope. - GitHub - TKJElectronics/KalmanFilter: This is a Kalman fil...

**If anyone has any other suggestions, I'd be interested**

Finally

I need to sample faster and also integrate over time (twice) once to get velocity and again to get position.  
But I can't do this until the initial filtering is working, otherwise it will drift like crazy

Well, I may have to do something after the first integration (that produces velocity) and assume that for my purposes that the object (namely a foam cube), generally wants to come to rest (as do most things to which friction is applied)

However. This is all I can do for today.

[ArduinoIMU.ino](https://forum.arduino.cc/uploads/short-url/cP8bBfBV4NPpwO71oo8HdWkkKRS.ino) (5.57 KB)

[imu\_data\_level\_in\_x\_and\_y.csv](https://forum.arduino.cc/uploads/short-url/a0gKPjEaD796feH12eNvI6Nd0X6.csv) (43 KB)

[imu\_data\_inclined\_in\_x.csv](https://forum.arduino.cc/uploads/short-url/xNnsbS7Oba8hx1BmrR53vw5OA87.csv) (73.9 KB)

[shaking\_in\_X\_then\_Y\_then\_Z.csv](https://forum.arduino.cc/uploads/short-url/hlQtyasFWRud1NfdSORyxXG9k0P.csv) (31.2 KB)

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 18, 2014, 11:56am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/33 "2014-09-18T11:56:32Z")

</div>

Couldn't post this nice pdf with a graph in it, to my last posting 😉

And, yes, I know the matrix etc can be simplified as gravity is 0,0,1 hence only 1/3 of the rotation matrix is needed

But I left all the code in for completeness.

Btw Jim, I didn't need to convert from Euler to Quaternion for the Pose data as there was a function to get the Pose as a Quaternion

[shaking\_in\_X\_then\_Y\_then\_Z.pdf](https://forum.arduino.cc/uploads/short-url/5G22gdZ13YDA2XOQjVPI6DzZGdq.pdf) (41.6 KB)

---

<div class="post-metadata">

**Author:** ![anon94801460](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@anon94801460](https://forum.arduino.cc/u/anon94801460)\
**Post date:** [September 18, 2014, 3:30pm UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/34 "2014-09-18T15:30:26Z")

</div>

Roger:

I'm glad it is working!

Have you calibrated the accelerometer and magnetometer as accurately as possible? My favorite technique is described here: [Sailboat Instruments: Improved magnetometer calibration (Part 1)](http://sailboatinstruments.blogspot.com/2011/08/improved-magnetometer-calibration.html)

As per the CHRobotics note, subtracting gravity requires very accurate knowledge of the orientation. An error of just one degree on either the X or Y Euler axis (with Z down) adds a spurious lateral acceleration of 9.8\*sin(1 degree) m/s/s, which is about 0.2 m/s/s. If offset and gain errors are not corrected, the angular errors can be many degrees. Even after correction, without averaging you can't do any better than about 1 degree on any axis with these sensors.

IF the angular errors are distributed randomly about the mean orientation, you would expect the "error" trajectory to be a random walk in 3D and drift slowly. That is something I had in mind to investigate in detail, and this project gave me the incentive to get on with it.

Thanks for posting!

Jim

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 18, 2014, 9:06pm UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/35 "2014-09-18T21:06:14Z")

</div>

Hi Jim

Thanks very much for your help with this.  
I still don't fully understand how you created the rotation matrix from the Quaternion data, but when I get time, I will try to take a look at you code and work out what you did.

Re calibration

I only ran the RTImu Compass calibration, which stores some values in the EEPROM, but all I think its doing is calculating the maximum and minimum values, I will need to look at Richards code to see exactly what it does.

The RTImu library does gyro correction when it starts, for a second or two, in which time, I have to keep the sensor still, but again I'm not sure precisely what its doing, I presumed it was compensating for drift in the rotation gyros rather than the accelerometers.

Looking at the link you sent, to calibration of the sensors is very interesting. I guess that ideally, the raw data would need to be calibrated and an additional step added to the RTImuLib to that it would receive corrected data rather than raw data.

I will ask Richard about the feasibility of this, or whether he feels it would conflict with processing his library already does.

Btw. I have an DIYDrones APM2.5 (clone) flight controller board, and I recall having to calibrate the compass in it, by tilting it to all possible angles / quadrants. However I don't think that this calibration can be doing anything other than the compass magnetometer, because you don't need to hold it still while doing the calibration.  
Actually I also have a DJI Naza flight controller as well, and it has a similar process.

Anyway, I will download the calibration program from your link and see if I can make use of it

I will keep you posted

Thanks again

Roger

---

<div class="post-metadata">

**Author:** ![anon94801460](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@anon94801460](https://forum.arduino.cc/u/anon94801460)\
**Post date:** [September 18, 2014, 9:24pm UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/36 "2014-09-18T21:24:16Z")

</div>

Hi, Roger:

The rotation matrix was derived from the quaternion using the definition in this document: [http://www.chrobotics.com/library/understanding-quaternions](http://www.chrobotics.com/library/understanding-quaternions) The attached should look familiar.

This also shows how to define a quaternion using Euler angles, and explains the factor of 2.0 that you asked about earlier. I strongly recommend that you go through that material. It does require you to be familiar with the rules for performing matrix multiplication, but that is really not very difficult!

I did have to use the transpose of the derived rotation matrix (which is the inverse rotation), as per the comment posted by Richard on his web site. All you do in that case is swap the array indices in the multiplication step. That is, everywhere you see a term indexed as R[i][j], substitute R[j][i].

Cheers, Jim

 ![matrix.png](https://europe1.discourse-cdn.com/arduino/original/4X/b/c/9/bc9c33683f2345643bc21ec43d1ec5edece6d39d.png)

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 18, 2014, 9:38pm UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/37 "2014-09-18T21:38:06Z")

</div>

Thanks Jim I will read that link

I will simply my code today and remove the terms in the matrices where gravity is zero I.e in x and y, also as gravity is 1 I don't even really need the rotated gravity vector, I can just use 3 terms from the rotation matrix, which will speed up the code a little, as is suspect speed may be of the essence in this case.

Re calibration.

I have left a message for Richard about doing accelerometer correction.

I took a more detailed look at the link you sent, and it looks like exactly the same calibration is applied to the accelerometers, as to the magnetometer, so I strongly suspect that I may just be able to re use Richards mag cal stuff and just store another set of calibrations for the accelerometers, and add code in his input processing to use the calibration matrices etc to correct form accelerometer errors, so watch this space 😉

I think its going to be better to try to get the incoming data as accurate as possible rather than trying to remove inaccuracies in the output data

Edit.  
I got a response from Richard and he agrees that calibration is essential. Apparently an early version of his library had accelerometer calibration, but I'm not sure if that was the Arduino version of the RPI version.

Anyway, I think my best approach is to re-use the same system that Richard already uses to calibrate and correct for compass errors, but do the same thing for the accelerometers.

However Richard said that the sensor needs to be kept very still while calibrating, and would need a special rig.

Fortunately I think I have a solution for this. I have a 3D printer (Reprap Meldelmax 1.5), so I will try to print off some sort of 3D polygon e.g. a Dodecahedron, or possibly something with even more faces, and try to put the sensor inside the middle of it.

I was thinking I may be able to put an Arduino Mini a battery, the sensor and a NRF24l01 or some other RF device inside.

However on consideration, my printer can only print things around 6 inches tall, so perhaps the best option would somehow to just put the sensor inside a smaller Dodecahedron and just run some light ribbon cable to it for the 4 wires that are needed.

I could print a base for it to stand on, to get the orientation where the wires need to come out the bottom.

anyway... Food for thought !

---

<div class="post-metadata">

**Author:** ![anon94801460](https://avatars.discourse-cdn.com/v4/letter/a/278dde/32.png) [@anon94801460](https://forum.arduino.cc/u/anon94801460)\
**Post date:** [September 19, 2014, 12:41am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/38 "2014-09-19T00:41:57Z")

</div>

Adafruit has a nice tutorial on calibrating an accelerometer -- they simply use a rectangular wood block to orient the sensor.

> **[ADXL345 Digital Accelerometer](https://learn.adafruit.com/adxl345-digital-accelerometer/programming)**
>
> Learn how to connect and program the ADXL345 triple-axis digital accelerometer.

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 19, 2014, 12:57am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/39 "2014-09-19T00:57:46Z")

</div>

Thanks Jim,

I was already 3D printing a more complex shape... perhaps too complex 😉  
Actually, I've had to stop the print, because I turned the fill percentage so low (to make the print time less), that its got no internal structure, and the slot for the module would not have been able to be printed (by my printer)

Re: Adafruit

That's interesting.

I'm not sure if I will be able to use Adafruit's code. Richard has sent me a link to his accelerometer calibration stuff

[https://github.com/richards-tech/MPU9150Lib/tree/master/AccelCal9150](https://github.com/richards-tech/MPU9150Lib/tree/master/AccelCal9150)

and its in his original (main MPU9150 file)

[https://github.com/richards-tech/MPU9150Lib/blob/master/libraries/MPU9150Lib/MPU9150Lib.cpp](https://github.com/richards-tech/MPU9150Lib/blob/master/libraries/MPU9150Lib/MPU9150Lib.cpp)

But its not in his current Arduino file. So I'll need to diff them and see if I can just copy it in

 ![imu_test.png](https://europe1.discourse-cdn.com/arduino/original/4X/9/6/4/964032c345d7575008efb6009157660289628160.png)

---

<div class="post-metadata">

**Author:** ![rogerClark](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rogerClark](https://forum.arduino.cc/u/rogerClark)\
**Post date:** [September 19, 2014, 10:24am UTC](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105/40 "2014-09-19T10:24:06Z")

</div>

Jim

I'm a bit confused about the calibration stuff you liked to at [Sailboat Instruments: Improved magnetometer calibration (Part 1)](http://sailboatinstruments.blogspot.com/2011/08/improved-magnetometer-calibration.html)

I downloaded the exe and it doesn't run for me. Well it starts but if I open their example mag.txt file and then press calibrate it crashes

It appears that there is possibly the source code for a command line version of it at [https://sites.google.com/site/sailboatinstruments1/c-language-implementation](https://sites.google.com/site/sailboatinstruments1/c-language-implementation)

However there is no point in me attempting to build the c-language-implementation unless I can find some reference material about how to use the matrix data that it produces.

And ... Looking at the source code, it uses a load of external files, and it doesn't seem to be possible to download the external programs in one go, they are all separate C files from [Matrices and Linear Algebra](http://www.mymathlib.com/matrices/) and there are hundreds of files.

I also looked in the links to [http://plan.geomatics.ucalgary.ca](http://plan.geomatics.ucalgary.ca) for the original work, to see if I could find anything about how to use the calibration matrix, but also drew a blank, i.e including in  
[http://plan.geomatics.ucalgary.ca/papers/journal\_of\_sensors\_renaudin%20et%20al\_2010c.pdf](http://plan.geomatics.ucalgary.ca/papers/journal_of_sensors_renaudin%20et%20al_2010c.pdf)

BTW. I had a look at the calibration that Richard did for the accelerometers, but it looks no were near as detail and accurate as the stuff you linked to. Because as far as I can see, Richard is not doing spherical mapping of the compass data either and he appears to have just been determining max and min value

e.g.

The compass calibration struct looks like this

typedef struct  
{  
unsigned char validL; // should contain the valid pattern if a good config  
unsigned char validH; // should contain the valid pattern if a good config  
unsigned char magValid; // true if data valid  
unsigned char pad;  
float magMin[3]; // min values  
float magMax[3]; // max values  
} CALLIB\_DATA;

I'm pretty sure magMin and magMax arrays are just min and max values for each of the three axis.

So there also looks to be scope for better calibration of the compass.

However it would make sense for me just to attempt to do the accelerometer calibration first, if I could find out how to use the data that sailboatinstruments ' s code creates

PS. I did manage to print my 24 sided polyhedron as a test jig, My printer had a bit of a headache doing some of the lower faces which have a overhang, which it isn't really capable of doing (but just does slightly messily), But on the whole its OK

But before I can use it, I need to solder a ribbon cable onto one of my MPU9150 breakout boards (I have 2 of them , one on to which I soldered pins and stuck in the breadboard, which I'm using now, and another that's still in its antistatic bag)  
So I can put it inside the polyhedron.

Cheers

Roger

[Previous page](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105.md?page=1)

[Next page](https://forum.arduino.cc/t/3d-maths-to-sutract-gravity-from-accelerometer-data/258105.md?page=3)
