Ping sensor pausing on if statement

Hi, im working on making a robotic RC car. I have the steering servo, motor, and ping sensor all wired up. For some reason in my code. When it runs this
“if (inches == 10){” the ping sensor does what it’s supposed to by turning the servos… Then it unexpectedly pauses for a second then resumes. Here is my code:

#include <Servo.h>

Servo ESC;
Servo Steering;

const int pingPin = 7;


void setup()
{
  Serial.begin(115200);
  ESC.attach(10);
  Steering.attach(9);

  arm();
}


void setSpeed(int speed)
{
  int angle = map(speed, 0, 100, 0, 180);
  ESC.write(angle);
}



void arm()
{  
  Serial.println("Arming");
  setSpeed(30);
  delay(100);
  
  setSpeed(50);
  delay(200);
  
  Serial.println("Armed");
  setSpeed(30);
  delay(200);
}


long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}

void loop()
{
  int speed;
 
  long duration, inches, cm;

  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  inches = microsecondsToInches(duration);
  
  Serial.print(inches);
  Serial.print("in");
  Serial.println(); 
  
  if (inches == 10){
    ESC.write(70);
    Steering.write(150);
  }else{
    ESC.write(30);
    Steering.write(90);
  }
}

If anyone has any ideas please let me know.

Thanks, Will

There is nothing in that immediate block of code that would cause any delay, but I suspect that what’s happening is the subsequent pulseIn() is missing the pulse and timing out - the default timeout is one second. Perhaps the servo movement is interfering with the ping sensor?

Also, you almost certainly want to replace the == 10 part with either >= 10 or <= 10 so that the correct logic is applied at all ranges and not just when the range is exactly 10 inches.

What would be the simplest way to fix this? And yes, thank you. I was just using the "== 10" for testing.

wfs123:
What would be the simplest way to fix this?

The simplest way would probably be to wait for the servo movement to complete before you try the next ping. Alternatively, specify a shorter timeout when you call pulseIn() so that the problem has less effect. You'd need to ensure the timeout was longer than the longest pulse you wanted to measure. You might also need to introduce a minimum delay between ping attempts to make sure you don't pick up any echoes of the previous ping. You'll soon find out about that side of things if you test it in realistic conditions and monitor the ping results.