I am trying to use a MPU6050 accelerometer/gyrosensor.
I already managed to read the sensor values, but now I am struggling to calculate an offset to keep the values near zero when the sensor isn't moving.
It works with this code:
#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>
#include <Mouse.h>
MPU6050 mpu;
int16_t x, y, z = 0;
int16_t offX, offY, offZ = 0;
void calibrate(){
int32_t allX, allY, allZ = 0;
int i;
for(i = 1; i<=500; i++){
mpu.getRotation(&x, &y, &z);
allX+=x;
allY+=y;
allZ+=z;
}
Serial.print("Average values:");Serial.print("\t");Serial.print(allX/i);Serial.print("\t");Serial.print(allY/i);Serial.print("\t");Serial.println(allZ/i);
Serial.println("Setting offsets...");
offX = allX/i;
offY = allY/i;
offZ = allZ/i;
}
void setup() {
Wire.begin();
Serial.begin(9600);
Serial.println("Initializing MPU6050...");
mpu.initialize();
Serial.println(mpu.testConnection()? "Initialization successful":"Initialization failed");
mpu.setXGyroFIFOEnabled(false);
mpu.setYGyroFIFOEnabled(false);
mpu.setZGyroFIFOEnabled(false);
calibrate();
}
void loop() {
mpu.getRotation(&x, &y, &z);
Serial.print((x-offX));Serial.print("\t");Serial.print((y-offY));Serial.print("\t");Serial.println((z-offZ));
delay(250);
}
But not with this one:
#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>
#include <Mouse.h>
MPU6050 mpu;
int sensitivity = 1;
int16_t x, y, z = 0;
int16_t offX, offY, offZ = 0;
void calibrate(){
int32_t allX, allY, allZ = 0;
int i;
for(i = 1; i<=500; i++){
mpu.getRotation(&x, &y, &z);
allX+=x;
allY+=y;
allZ+=z;
}
offX = allX/i;
offY = allY/i;
offZ = allZ/i;
}
void setup() {
Wire.begin();
Serial.begin(9600);
mpu.initialize();
if(!mpu.testConnection()){
while(1);
}
mpu.setXGyroFIFOEnabled(false);
mpu.setYGyroFIFOEnabled(false);
mpu.setZGyroFIFOEnabled(false);
calibrate();
}
void loop() {
mpu.getRotation(&x, &y, &z);
Serial.print(-(z-offZ)/sensitivity);Serial.print("|");Serial.println(-(x-offX)/sensitivity);
delay(250);
}
I don't see any difference except a few Serial.print() calls, but the first sketch prints values near zero and the other one prints values up to 20k.
Does anyone know why this is happening?