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
.
1 Answer 1
There's a couple of things wrong here:
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.
- 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
orint32_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("...");
-
Oh, I didn't noticed that. Thanks it works now.alim1990– alim19902018年09月11日 16:09:37 +00:00Commented Sep 11, 2018 at 16:09
Explore related questions
See similar questions with these tags.