Measuring distance based on time I have written a arduino sketch which is used to measure the distance travelled. Since distance = speed * time , I have initiated speed = 6. I have initiated time = millis() variable and it calculates the time in millis().

So, distance is calculated as (speed*time) /1000 and we get distance for every second.

Now, as soon as the distance==20, I want to print distance and then delay for 5 seconds. So, as soon as distance==20 implies time = 4000 . If I delay for 5 seconds, time becomes 9000. But I want time to start from 4000 itself. So I have initiated another variable called curTime = time - prevTime.At the start, prevTime = 0. Code:

int prevTime = 0;
void loop(){
  unsigned long time = millis();
  unsigned long curTime = time - prevTime;
  int speed = 6;
  unsigned long distance = (speed * curTime)/1000; 
  Serial.println(distance); // displays values of distance 
  if(distance == 20){
    Serial.println(distance);
    delay(5000);
    prevTime = time; 
  }
}


So prevTime = 4000 if distance == 20.
After this, time will be equal to 9000 and curTime will be 9000-4000 which equal 5000. So the distance will be 30 skipping all the values between 20 and 30. I don't want the distance to skip the values between 20 and 30. I have tried a lot but couldn't achieve it. Please help me fix this.

Thanks.

Link for code:

https://circuits.io/circuits/5260912-the-unnamed-circuit/edit
When distance == 20 you pause for 5 secs. So all calculations after that will be off by 5 secs. So, prevTime should equal 5000.

unsigned long time = millis();
unsigned long curTime = time - prevTime;    // 0 or 5000
int speed = 6;
unsigned long distance = (speed * curTime) / 1000; // calculating distance in meters for every milli second
Serial.println(distance);
// Only pause once
if (distance == 20 &amp;&amp; prevTime == 0) {
  delay(5000);
  prevTime = 5000;  // Adjust for the delay
}