1

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

3
  • @JohnnyMopp, Thanks for the reply. Please see the link on how code works.When distance == 20==> prevTime=time ==> prevTime=4000(After delay). Now when curTime is calculated, it's coming as 5000 (since time=9000 and prevTime=4000). But when I keep prevTime = millis(), curTime is started from 0 again. For my output , as soon as distance==20, after the delay, again the distance should get calculated from 21, but in the above code, the distance is skipped to 30.
    – Sri Harsha
    Jun 19 '17 at 12:31
  • Thanks for the reply. I tried it earlier, but it didn't work.
    – Sri Harsha
    Jun 19 '17 at 12:52
  • 2
    This program is not measuring anything. As it stands, it is completely useless, and unlikely to be what you want. Could you please explain clearly what you actually want to do? Jun 20 '17 at 12:33
0

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 && prevTime == 0) {
  delay(5000);
  prevTime = 5000;  // Adjust for the delay
}

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