Plotting speed and distance calculated using accelerometer
<p>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.</p>

<p>My steps are:</p>

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

<pre><code>  X_real = X_sample - X_calibrated;

  if(X_real &lt;= X_drift )
  {
   X_real = 0;
  }
</code></pre>

<p>Where X_drift is 2 mg (From datasheet of accelerometer)</p>

<p>2) Calculate velocity:</p>

<pre><code>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 &amp;&amp; x(i)==0)
v(i)=0;
end

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

velocity = velocity + v(i);
</code></pre>

<p>3) Calculate distance:</p>

<pre><code>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);
</code></pre>

<p>After testing this by dragging accelerometer on table 20 cm i got these results:</p>

<pre><code>velocity = 0.09 m/s
distance = 0.21 m 
time = 3.2s  
</code></pre>

<p>Error of 1 cm is OK for classroom.</p>

<p>Chart tells something different:
<img src="https://i.stack.imgur.com/Hjk4I.png" alt="Acceleration, velocity and distance chart"></p>

<p>I tried to plot distance after this:
<code>s(i) = s(i)+s(i-1);</code> </p>

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

<p>*UPDATE: Position y value is in mm not cm! Sorry</p>