Ping Sensor Egg robot

I've written a code based off a test for the ping sensor using a led, I replaced the led with a dc motor command, but I'm having trouble with getting the ping to go enough times per second to get the data to tell it to stop. Basically I've built a little car with an Arduino UNO board, Arduino motor shield and a parallax ping sensor, the entire system works to move an egg from a point straight toward a wall stopping at 3 cm away from the wall. My problem is that the car will run and if the sensor happens to sense at the correct time it will stop but if its at an interval between sensing the car will run into the wall. Any ideas on how to decrease the interval, heres my frankenstein code.

 #define fP 7 //Pin the ping sensor is connected to

void setup()
{
  pinMode(12, OUTPUT);
   
}

void loop()
{
  if (ping() > 50)
  {
    digitalWrite(12, HIGH);   // set the LED on
    analogWrite(3, 145);
  }
  
  else
  {
    
    analogWrite(3, 0);    // set the LED off
  }
}


int ping() //Get CM to obstacle in front of the sensor
{
  long duration;
  pinMode(fP, OUTPUT);
  digitalWrite(fP, LOW);
  delayMicroseconds(2);
  digitalWrite(fP, HIGH);
  delayMicroseconds(15);
  digitalWrite(fP, LOW);
  delayMicroseconds(20);
  pinMode(fP, INPUT);
  duration = pulseIn(fP, HIGH);
  return duration / 29.0 / 2.0;
}

but I'm having trouble with getting the ping to go enough times per second to get the data to tell it to stop.

Perhaps you should put a timeout in the call to pulseIn(). You should also Serial.print() the time before and after the call to ping(), to see how long it is taking. (Obviously, the robot can't be running around loose while tethered to the PC.)

Failing to increase the frequency of the sensor, you could always slow down.