This timout thing bugged me too. I applied a bit of RTFM strategy and found a solution. Good luck, and please let me know if this helps you.
// JamesHappy
// Arduino UNO 0022
// Demonstration sketch of HC-SR04 Ultrasonic Range Finder with echo timeout
// Onboard LED should blink while searching for surface
// Onboard LED should be solid when surface is within a specified distance
// Rangefinder should only wait for echos under a calculated timeout
// Reference: http://www.elecfreaks.com/244.html
// Reference: http://www.arduino.cc/en/Reference/PulseIn
// Note: HC-SR04 tested successful in both 5v and 3.5v
int iTrigger = 2; // Digital Pin 2
int iEcho = 3; // Digital Pin 3
int iAlertLED = 13; // Digital Pin 13
int iEchoTimeout = 0; // In Microseconds
int iMaxDistance = 20; // In Centimeters
int iTriggerPullDown = 2; // In Microseconds
int iPingWidth = 10; // In Microseconds
void setup() {
pinMode(iTrigger,OUTPUT);
pinMode(iEcho,INPUT);
pinMode(iAlertLED, OUTPUT);
iEchoTimeout = iMaxDistance*2*29;
}
void loop() {
digitalWrite(iTrigger, LOW);
delayMicroseconds(iTriggerPullDown);
digitalWrite(iTrigger, HIGH);
delayMicroseconds(iPingWidth);
digitalWrite(iTrigger, LOW);
unsigned long ulPing = pulseIn(iEcho,HIGH,iEchoTimeout);
if(ulPing) {
digitalWrite(iAlertLED, HIGH);
SimulateLoad(250);
}
else {
digitalWrite(iAlertLED, HIGH);
delay(25);
digitalWrite(iAlertLED, LOW);
SimulateLoad(225);
}
}
void SimulateLoad(int iDutyCycle) {
delay(iDutyCycle);
}