I have tried something similar to your code earlier and I have noticed the velocity drift. In my latest code, I have the actual acceleration which is the acceleration minus gravity component rounded to 1 decimal place using nfc() multiplied by 9.81 to get real acceleration as follows;
String AccelX2i = nfc(AccelX2, 1); //This rounds up the acceleration to 1 decimal place and therefore I will always get the same absolute value during acceleration and decelleration, thus perfect cancellation
gravity2i[0] = nfc(gravity2[0], 1); //similar to previous line
ActualAccelX2=(float(AccelX2i)-float(gravity2i[0]))*9.81; //this gives me the real acceleration
By these three lines of code, I know I am reducing the accuracy of acceleration, but I am also eliminating the drift.
Then I am sampling the ActualAccelX2 data and store it in an array whose size increases with time. Also I am creating another array for the velocity;
float [] AccX = new float[time]; //array for the current acceleration after sampling
float [] vXn2 = new float[time]; //array for the current velocity
if(millis() % 1 == 0) //sampling at 1KHz
{
for(int n = 1; n<time; n++)
{
AccX2[n] = ActualAccelX2; //filling the array with the current accel
vXn2[n] = vXn2[n-1] + (AccX2[n])*0.001; //vX2[n] is the current velocity, vX2[n-1] is the previous velocity and AccX2[n] is the current accel
}
}
This returns exactly what I need, but I am not sure if it is giving the correct values or not. If it is correct, then the drift is eliminated since the velocity always converges to zero when the sensor is stationary and increases as I start moving the sensor. Thanks, Hatt.