1

In my current project, I want the sensor to be continuously scanning for a value of less than 30cm. I was wondering how long of a delay I need (if any) between each call of the ping function. It currently works at 150ms between each ping call with no problem. The less the delay, the better for my project. This is the ping function:

void ping() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
}

For example, would having a delay of only 5ms be sufficient?

3
  • 2
    These are so minimally documented and widely sourced that you may do no better than experimenting with the ones you intend to use. Certainly there is no point in triggering a new reading before the echo at your greatest intended range has had a chance. After that it is more a question if the implementation forces a minimum, or if in highly reflective environments you could misread a delayed reflection of an old pulse as a new one. 5ms would be the roundtrip to a surface less than a meter away, so trying to re-read that quickly does seem like it could lead to such mixups. Commented Aug 21, 2016 at 2:32
  • 1
    Note that the microsecond delays in your current code are to form the trigger pulse, if you are using it as posted the inter-reading delay would be coming from the time waiting for the first echo (or the timeout waiting for it). Commented Aug 21, 2016 at 2:36
  • @ChrisStratton I am not worried about the microsecond delays. And I am aware that pulsein takes time. I was just wondering if I could decrease from 150ms.
    – shurup
    Commented Aug 21, 2016 at 3:20

2 Answers 2

1

How often can I ping an HC-SR04 ultrasonic sensor?

This ping() function is vulnerable to interrupts during the pulseIn(). This implies that a delay needs to wait for queued interrupts as from, for instance, Serial output. Input interrupts may still affect the results. This function only works in very simple sketches.

Possible solutions are to 1) disable during the pulse measurement (not the wait for pulse start), 2) use a more advanced method to allow concurrent events (such as timer capture).

Cheers!

0

Documentation from elecfreaks.com recommends 60 milliseconds between measurements. That'll cut down your time by ~60% (from your 150ms delay). It works for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.