0

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

  • 2
    do not use delay() ..... see BlinkWithoutDelay example sketch – jsotola Sep 26 '18 at 20:51
1

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);
}
  • It waited for 5ms, then last measurement=0+5=5 ms. Then it’ll do analogRead(). Let’s say analogRead() took 10ms, then mills()- last measurement() = 15-5 ms=10 ms so the loop will do another analogRead() although it’s not reading measurement exactly after 5 ms. So this will only work if loop execution time is <5ms – Talha Yousuf Sep 26 '18 at 19:15
  • Indeed. It can't magically go back in time. Was there any question there? – Gerben Sep 27 '18 at 9:29
0

You do something like this

unsigned long timerMesurement = 0;

void loop()
{
  if (millis() - timerMesurement > 5UL) { 
    timerMesurement = millis(); 
    int measurement = analogRead(A0); 
  }
}
  • Sigma, it should be >= for the right interval. It should also be timermeasurement += 5UL; for a interval that is fixed in time without increasing delays, the return value of millis() could have increased since the previous line. – Jot Sep 27 '18 at 4:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.