Read sensor data repeatedly after specified time? 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
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)&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);
}