High cycle time when using pulseIn for ultrasonic sensor

Hello forum!

Although this is a sensor-related question I figured it'd better fit in the programming sub-forum.

I recently started working with the basic Arduino ultrasonic sensor (HC-SR04).

It works very well for me but I have an issue which I'm not able to fix:

When the nearest object to the sensor is far away (~ 3m+), it takes the programm loop so long to cycle that you can clearly see the single readings tick along in the serial monitor. If that's the case the sensor struggles to detect passing objects as it is stuck waiting for the pulseIn-command to continue.

Is there a way to limit the cycle time of the distance-reading loop, e.g. by getting rid of the pulseIn-command and using something similar?

Thanks for your help!

The pulseIn() function will wait up to a preset timeout for the pulse. The default timeout is 1 second, I think.

To change the timeout, set the third (optional) argument.

pulseIn(pin, value, timeout);

30 milliseconds is about 15 feet (3 meters).

pulseIn(pin, value,30000);

An alternative to using pulseIn() is the NewPing library. I believe that that library has non-blocking methods for range finding.

groundFungus:
The pulseIn() function will wait up to a preset timeout for the pulse. The default timeout is 1 second, I think.

To change the timeout, set the third (optional) argument.

pulseIn(pin, value, timeout);

30 milliseconds is about 15 feet (3 meters).

pulseIn(pin, value,30000);

An alternative to using pulseIn() is the NewPing library. I believe that that library has non-blocking methods for range finding.

Oh, I didn't now there was a third argument for the pulseIn-command.

Thank you very much, that helps a lot!

Oh, I didn't now there was a third argument for the pulseIn-command.

The Language reference has references for all Arduino functions.