HC-SR04 ping sensor cutting out at ~3 meters
It's probably working "well enough".

At present your code should NOT hang but should loop every 1.5 seconds  - 1 second for the Arduino mediated pulsein timeout and 500 ms due to delay(500).  Nothing the SR04 module does should be able to prvent your code looping every ~= 1.5s. If you eg turn on the on board LED during the delay(500) period you should be able to see that the loop is occurring. 

Odds are that your system is not "hearing" the return on soft targets at larger ranges, as per manual, timing out at 1s, delaying for 500 mS then repeating.

The 500 mS delay is not needed (but helps if a heartbeat LED is used) as the 1 second pulsein timeout is independent of the SR04 which has long before "given up". 

IF the above is correct then a proof of sorts would be in flicking the sensor JUST AS / AFTER the added heart beat LED goes out. This should work every time if you are fast enough. Whereas flicking it eg when the heartbeat LED goes on would not help. 

And/or pointing it at a close object for at least 1.54+ seconds should restore operation. 



Bonus:

I would not think it would explain the behaviour BUT the trigger pulse is meant to be 10 uS - not 20 uS plus. The processor will add finite time to that delay - but 'with luck' the low to high and high to low delays of the digitalWrite's will cancel. BUT I'd try 10 uS delay, and also look at the pulse on a scope, if available. |