user25533: I want to read sensor data using analogRead() after every 5ms. I have read other answers to similar questions but what I'm confused about is:

let's say, I made a loop to read sensor data using analogRead() at the end of which I write delay(50) 
it means it'll take some time to read data(adc) , then it'll wait for 50ms 
time to execute loop isn't same for every iteration so we get the pattern as: some time for loop execution, delay of 50ms, some time for next iteration........and so on
I want to ask if I want arduino to read sensor data exactly every 5ms, what should I do?
Thanks


user2881: You store the time (millis()) of the last measurement. Then wait till 5ms have past since the last measurement. Do your measurement, and update the time.
Something like:
unsigned long lastMeasurement = millis();

void loop()
{
  while( (millis()-lastMeasurement)<5 ){/* do nothing */}
  lastMeasurement = lastMeasurement + 5; //or use `lastMeasurement=millis();` depending on whether you want accuracy between measurement, or accuracy over time
  auto measurement = analogRead(A0);
}


25533: <p>I want to read sensor data using <em>analogRead()</em> after every 5ms. I have read other answers to similar questions but what I'm confused about is:</p>

<ul>
<li><p>let's say, I made a loop to read sensor data using <em>analogRead()</em> at the end of which I write <em>delay(50)</em> </p></li>
<li><p>it means it'll take some time to read data(adc) , then it'll wait for 50ms </p></li>
<li><p>time to execute loop isn't same for every iteration so we get the pattern as: <em>some time for loop execution</em>, <em>delay of 50ms</em>, <em>some time for next iteration</em>........and so on
<strong>I want to ask if I want arduino to read sensor data exactly every 5ms, what should I do?</strong>
Thanks</p></li>
</ul>
 2881: <p>You store the time (<code>millis()</code>) of the last measurement. Then wait till 5ms have past since the last measurement. Do your measurement, and update the time.</p>

<p>Something like:</p>

<pre><code>unsigned long lastMeasurement = millis();

void loop()
{
  while( (millis()-lastMeasurement)&lt;5 ){/* do nothing */}
  lastMeasurement = lastMeasurement + 5; //or use `lastMeasurement=millis();` depending on whether you want accuracy between measurement, or accuracy over time
  auto measurement = analogRead(A0);
}
</code></pre>
