Inaccurate readings from integration with a L3GD20 gyro

Hello, I am making my first arduino steps this week, although I have a sufficient knowledge in C++ programing.
I've got the rev3 Uno, with an Pololu AltIMU-10 chip, currenty using the gyro L3GD20 only for testing purposes.
I use the default library, supplied by Pololu.
My aim is to take the gyro, rotate it around its three axis, and when I lay it down on the table 10 seconds later, each axis to be within 2 degrees error.
Sounds perfect in theory, almost perfect in practise, in terms of gyro drift.
The gyro is set to 190 Hz, 500dps, 70 Hz cutoff. (The last one is described on page 32 of the gyro pdf, not quite sure how it works...)
I've done the dps calculations, the trapezoid integration with the delta time, microseconds.

When I rotate it around a single axis (flat on the table, Z axis), it works like a charm, not more than a 0.5deg error for the said axis.
But if I try multi-axis movements, it gets out of hand. Easily a 20-40deg offset for a 3sec movement, at least on one of the axes.
If I get it in the air and try to rotate it mainly on one axis, this axis gets perfect readings, while the others, although barely changing, show large errors as described prior.
It is like somehow the signals influence each other, although only when all 3 are getting readings...

I've experimented with loop times, currently 10ms delay + 2ms calculations.
I have a setup() zero-value measurement, plus a static drift remover. (Both not the key to the problem.)

My code is bellow, changed a couple of times, and yet getting the error...please take a look and advise me what to do, this will be a crucial part of my quadcopter project...
(I know I need the accelerometer too, this topic is about getting a short-term drift-free gyro readings.)

#include <Wire.h>
#include <L3G.h>
L3G gyro;
int xZ=0,yZ=0,zZ=0;

void setup() {
  Serial.begin(19200);
  Wire.begin();
  if (!gyro.init())
  {
    Serial.println("Failed to autodetect gyro type!");
    while (1);
  }
  //gyro.enableDefault();
  gyro.writeReg(L3G_CTRL_REG1, 0b01111111); //2 output 2 bandwidth 4 on-off controls
  gyro.writeReg(L3G_CTRL_REG4, 0b00010000); //2 reserved 2 dps scale 4 reserved
  for(int i=0;i<50;i++){ //get 50 samples
  gyro.read();
  xZ+=gyro.g.x;
  yZ+=gyro.g.y;
  zZ+=gyro.g.z;
  delayMicroseconds(10000);
  }
  xZ/=50; //get the digital zero values
  yZ/=50;
  zZ/=50;
}

float x=0,y=0,z=0,x1=0,y1=0,z1=0,x2=0,y2=0,z2=0; //I need those global, not single loop only
long int t1=micros(); //initial gyro delta time

void loop() {
  delayMicroseconds(10000);
  long int t2=micros(); //time for loop
  gyro.read();
  
  if(gyro.g.x*17.5/1000>400)while(1); //if the reading gets out of hand
  if(gyro.g.y*17.5/1000>400)while(1); //crash it, to indicate
  if(gyro.g.z*17.5/1000>400)while(1); //400 dps is way too much, dont worry
  
  x2=(float)(gyro.g.x-xZ)*17.5/1000/(1000000.0/(micros()-(t1+128))); //calculate the angle
  y2=(float)(gyro.g.y-yZ)*17.5/1000/(1000000.0/(micros()-(t1+256))); //128 us for each calc.
  z2=(float)(gyro.g.z-zZ)*17.5/1000/(1000000.0/(micros()-(t1+384)));

  t1=micros(); //delta time for gyro
  if(abs(gyro.g.x-xZ)>20){ //if not stationaly, 20 in binary, not dps
    x+=(x2+x1)/2; //trapezoid integration
  }
    x1=x2;
  if(abs(gyro.g.y-yZ)>20){
    y+=(y2+y1)/2;
  }
    y1=y2;
  if(abs(gyro.g.z-zZ)>20){
    z+=(z2+z1)/2;
  }
    z1=z2;
  //}
  
  if(t1%20==0){ //once every 20 times to print some info
  Serial.print(" G ");
  Serial.print("X: ");
  Serial.print(x);
  Serial.print(" Y: ");
  Serial.print(y);
  Serial.print(" Z: ");
  Serial.print(z);
  Serial.print("  ");
  Serial.println(micros()-t2);
  }
}

I'm also having problems with my gyro L3G4200D needs constant reset [UPDATE - uncommunicative supplier] - Sensors - Arduino Forum whilst not the same model...

Perhaps there is something we don't understand about them but its beating me :astonished:

I'm not happy with the pololu code.

For example this:

while (Wire.available() < 6);

is wrong.
The Wire.available() return the number of bytes in the buffer. At that moment the I2C session has already ended and the bytes has already been received. So waiting for something is wrong.

Could you check your code for long/float/integer/signed/unsigned/overflow ?

For example the offset in setup().
The gyro.g.x is a float. You add 50 of those in an integer.
Could you make xZ, yZ and zZ a float ?

You use micros() and delayMicroseconds, but I think millis() and delay() will be better.
The micros() rollover every 70 minutes (or less with wrong type variables).
You also use 'long integer' for micros().
Both micros() and millis() return an unsigned long. Could you use an unsigned long with those ?

I don't know what the compiler will do with these lines:

if(gyro.g.x*17.5/1000>400)while(1);
...
x2=(float)(gyro.g.x-xZ)*17.5/1000/(1000000.0/(micros()-(t1+128)));
...

Could you make it all with float ?

if (gyro.g.x * 17.5 / 1000.0 > 400.0)
  while(1);
...
x2 = (gyro.g.x - (float) xZ) * 17.5 / 1000.0 / (1000000.0 / (float) (micros() - (t1+128)));
...

I don't know why you have those 'if' statements and forever while(1).
Perhaps you should use a minimal simple sketch, to rule out any code error.

You could try to use the Adafruit code.

Normally I would write: "I have never seen bad code by Adafruit", but they have the same wrong code, waiting until Wire.available() has 6 byte.
I can recognize a lot in Adafruit versus Pololu code, so obvious one was copied from the other.
The example with that Adafruit code is very simple.

This is interesting...

At that moment the I2C session has already ended and the bytes has already been received. So waiting for something is wrong.

Is this true? Has the 'session' ended?

stgram:
Hello, I am making my first arduino steps this week, although I have a sufficient knowledge in C++ programing.
I've got the rev3 Uno, with an Pololu AltIMU-10 chip, currenty using the gyro L3GD20 only for testing purposes.
I use the default library, supplied by Pololu.
My aim is to take the gyro, rotate it around its three axis, and when I lay it down on the table 10 seconds later, each axis to be within 2 degrees error.

Very unlikely to achieve that accuracy - you might just about get that for rotation about one axis (as you find), but its
rather borderline. The sensitivities about the separate axes are not perfectly matched for instance, so tuning
is harder in the general case.

However before you start worrying about accuracy you need to ensure you are using the right algorithm
for 3-D orientation - you cannot treat the axes independently, you need to use one of two basic techniques,
either DCM or quarternion based algorithm - you are not doing this, you'll get nonsense results.

Well, the offset is set to int, because the numbers vary by whole numbers, not fractions, every start, so I dont consider it a problem.

I know about the 70 minutes, but my code runs no longer than 60s. I'll have it in mind.

The ifs kill the program if an out of range dps measurement is detected. The threshold is 400 dps.

When I get back home I'll check the adafruit library, as well as all the variable types.

As for the i2c communication, I have no experience there... :confused:

I am currently trying out basic steps, and since it works flawlessly for single axis rotation, I was hoping to achieve something like that for multi axis rotation before I advance...

Tomorrow I will perform some tests and describe the results carefully, so you can get a better understanding of the problem.
Thanks for everything so far. :slight_smile:

stgram:
Well, the offset is set to int, because the numbers vary by whole numbers, not fractions, every start, so I dont consider it a problem.

Problem or not, later in your sketch you do calculations with float, since the library uses float number for x, y and z. So to be consistant and for better to read code, I suggest to use float.
With integers you have to calculate if 50 numbers will fit in an integer.

acboother:
Is this true? Has the 'session' ended?

Yes, Wire.requestFrom() actually is a "blocking" wait for the Slave until the bytes have been received or a stop condition is recognized. The reception of bytes is in interrupts, but the function waits while the session is still busy.
The number of bytes returned by Wire.requestFrom() is the same as the number of bytes returned by Wire.available().

stgram:
I am currently trying out basic steps, and since it works flawlessly for single axis rotation, I was hoping to achieve something like that for multi axis rotation before I advance...

I repeat: you cannot treat the axes independently for 3-D rotation, it doesn't work at all, not even slightly,
you will need DCM or quarternion code.