Search code examples
matlabaccelerometer

Plotting speed and distance calculated using accelerometer


I am working on basic distance calculation using accelerometer by dragging object on a single axis for physics class in MATLAB and have problem with plotting data.

My steps are:

1) After calibrating device to read zero g on every axis, I eliminate drift errors:

  X_real = X_sample - X_calibrated;

  if(X_real <= X_drift )
  {
   X_real = 0;
  }

Where X_drift is 2 mg (From datasheet of accelerometer)

2) Calculate velocity:

velocity = 0; % On start

% Integration
v(i) = v(i-1) - x(i-1)-(x(i)+x(i-1)+x(i-2)+x(i-3))/4;

%Check if we stopped
if(x(i-1)==0 && x(i)==0)
v(i)=0;
end

%Check if velocity is under 0 (Not allowed)
if(v(i) < 0)
v(i)=0;
end

velocity = velocity + v(i);

3) Calculate distance:

distance = 0; % On start

%Integration
s(i) = s(i-1) + v(i-1) + (v(i)-v(i-1)-v(i-2)-v(i-3))/4;
distance = distance + s(i);

After testing this by dragging accelerometer on table 20 cm i got these results:

velocity = 0.09 m/s
distance = 0.21 m 
time = 3.2s  

Error of 1 cm is OK for classroom.

Chart tells something different: Acceleration, velocity and distance chart

I tried to plot distance after this: s(i) = s(i)+s(i-1);

And got 21 cm on chart but after 6 s not after 4 s where it should be. What am I doing wrong?

*UPDATE: Position y value is in mm not cm! Sorry


Solution

  • Im sorry for asking for help, i thought my formulas were ok, but they didn't. After step by step calculations my final solution is:

    1) Velocity:

    v(i) = v(i-1) - x(i-1)-(x(i)+x(i-1))/2;
    

    2) Distance:

    s(i) = s(i-1) + v(i-1)+(v(i)+v(i-1))/2;
    

    And chart is:

    Acceleration,Velocity,Position chart

    Sorry once more time. I hope this will help someone calculating velocity and distance. It surely helped me as lesson to better study my code next time before asking for help.