0

I trying to loop over a function in arduino to get values for 2000 times, and then divide it by 2000 to get an average offset:

int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;

And inside setup():

for(int i=0; i<2000;i++)
 {
 GetXYZ(x_offset, y_offset, z_offset);
 x_offset += x_offset;
 y_offset += y_offset;
 z_offset += z_offset; 
 Serial.println(x_offset);
 delay(3);
 }
 x_offset /= 2000;
 y_offset /= 2000;
 z_offset /= 2000;
 Serial.println(x_offset);Serial.println("...");Serial.println(y_offset);Serial.println("...");
Serial.println(z_offset);Serial.println("...");

Here is the GetXYZ() function:

void GetXYZ( int16_t &x, int16_t &y, int16_t &z) {
 // Get the gyro values
 Wire.beginTransmission(MPU);
 Wire.write(0x43); // first register of gyro values
 Wire.endTransmission(false);
 Wire.requestFrom(MPU,6);
 x = Wire.read() << 8 | Wire.read();
 y = Wire.read() << 8 | Wire.read();
 z = Wire.read() << 8 | Wire.read();
}

The values printed in the serial of x_offset, y_offset and z_offset are always 0.

asked Sep 11, 2018 at 16:00

1 Answer 1

2

There's a couple of things wrong here:

  1. You are just getting the last read value doubled:

    x_offset += x_offset;

However x_offset is always replaced with the lates reading. You're not summing anything.

  1. To get anything other than 0 out of dividing an integer by 2000 the value stored in the integer would have to be> 2000. But since you can only store a maximum of 32767 in your int16_t variables, even if you didn't have the problem in point 1, the variables would overflow and the results would be meaningless.

You need to:

  • Use a second variable per axis to store your total
  • Ensure that it is big enough to store the maximum reading ×ばつ 2000. I'd suggest a long or int32_t.

For instance:

int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;
int32_t x_total = 0;
int32_t y_total = 0;
int32_t z_total = 0;

And inside setup():

for(int i=0; i<2000;i++)
 {
 GetXYZ(x_offset, y_offset, z_offset);
 x_total += x_offset;
 y_total += y_offset;
 z_total += z_offset; 
 Serial.println(x_offset);
 delay(3);
 }
 x_total /= 2000;
 y_total /= 2000;
 z_total /= 2000;
 Serial.println(x_total);Serial.println("...");Serial.println(y_total);Serial.println("...");
Serial.println(z_total);Serial.println("...");
answered Sep 11, 2018 at 16:06
1
  • Oh, I didn't noticed that. Thanks it works now. Commented Sep 11, 2018 at 16:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.