I made a little function for this
double ping(int outPin, int inPin) //Get CM to obstacle in front of the sensor
{
long duration;
pinMode(outPin, OUTPUT);
pinMode(inPin, INPUT);
digitalWrite(outPin, LOW);
delayMicroseconds(2);
digitalWrite(outPin, HIGH);
delayMicroseconds(15);
digitalWrite(outPin, LOW);
delayMicroseconds(20);
duration = pulseIn(inPin, HIGH, 2500);
return duration / 29.0 / 2.0;
}
This returns the distance in CM to the thing it detected. At the same time I added a timeout on 2500 micro seconds, so if no ping back is received, it will return 0 and continue the loop, instead of hang.