How to calibrate Mpu6050 using library? I am using i2cdev library

Code:(i did not know this code is correct or not)

#include &lt;Arduino.h&gt;
#include &lt;MPU6050.h&gt;
#include &lt;kalman.h&gt;
#include &lt;stdint.h&gt;

#define ACCELLSB  2048
#define GYROLSB   16.4

#define CONSOLE
#define CALIBRATE

#ifdef  CALIBRATE
int16_t Accel_X_offset;
int16_t Accel_Y_offset;
int16_t Accel_Z_offset;

int16_t Gyro_X_offset;
int16_t Gyro_Y_offset;
int16_t Gyro_Z_offset;
#endif

MPU6050 mpu6050;

Kalman  AngleX;
Kalman  AngleY;


void setup()
{
   mpu6050.initialize();
   mpu6050.setFullScaleAccelRange(MPU6050_ACCEL_FS_16);
   mpu6050.setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

   #ifdef CALIBRATE
   mpu6050.CalibrateAccel();
   mpu6050.CalibrateGyro();

   Accel_X_offset = mpu6050.getXAccelOffset();
   Accel_Y_offset = mpu6050.getYAccelOffset();
   Accel_Z_offset = mpu6050.getZAccelOffset();

   Gyro_X_offset  = mpu6050.getXGyroOffset();
   Gyro_Y_offset  = mpu6050.getYGyroOffset();
   Gyro_Z_offset  = mpu6050.getZGyroOffset();
   #endif

   int16_t AccelX, AccelY, AccelZ;
   int16_t GyroX, GyroY, GyroZ;

   mpu6050.getMotion6(&amp;AccelX,&amp;AccelY,&amp;AccelZ,&amp;GyroX,&amp;GyroY,&amp;GyroZ);

   // I am going to use this values in kalman filter
   #ifdef CALIBRATE
   AccelX -= Accel_X_offset;
   AccelY -= Accel_Y_offset;
   AccelZ -= Accel_Z_offset;

   GyroX  -= Gyro_X_offset;
   GyroY  -= Gyro_Y_offset;
   GyroZ  -= Gyro_Z_offset;
   #endif
}


void loop()
{

}


What is the correct way to calibrate mpu6050(Correct me what i am wrong or this is correct)?

Thanks.
I personally suggest you MPU6050_tockn library.https://github.com/tockn/MPU6050_tockn

If you use calcGyroOffsets() in setup(), it will calculate calibration of the gyroscope, and the value of the gyroscope will calibrated.

#include &lt;MPU6050_tockn&gt;
#include &lt;Wire.h&gt;

MPU6050 mpu6050(Wire);

void setup(){
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets();
}


If you use calcGyroOffsets(true) in setup(), you can see state of calculating calibration in serial monitor.

#include &lt;MPU6050_tockn&gt;
#include &lt;Wire.h&gt;

MPU6050 mpu6050(Wire);

void setup(){
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);
}


Serial monitor:

Calculate gyro offsets
DO NOT MOVE MPU6050.....
Done!
X : 1.45
Y : 1.23
Z : -1.32
Program will start after 3 seconds


If you know offsets of gyroscope, you can set them by setGyroOffsets(), and you don't have to execute calcGyroOffsets(), so you can launch program quickly.

#include &lt;MPU6050_tockn&gt;
#include &lt;Wire.h&gt;

MPU6050 mpu6050(Wire);

void setup(){
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.setGyroOffsets(1.45, 1.23, -1.32);
}


But if want to do it with Kalman filter goto https://github.com/jarzebski/Arduino-KalmanFilter/blob/master/KalmanFilter_MPU6050/KalmanFilter_MPU6050.ino It will guide you.