3

I'm a beginner in Arduino and recently i got myself an Ultrasonic sensor (HC-SR04).

I looked up tutorials on how to measure distance with the sensor and the code I'm using is:

const int trigPin = 8;
const int echoPin = 7;

long duration;
int distance;

void setup() {
  // put your setup code here, to run once:
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2); //why do we delay 2 microseconds

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); //why do we delay 10 microseconds
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration*0.034/2;
  Serial.print("Distance: ");
  Serial.println(distance);
}

I would like to know why do we add delays in the loop function? Appreciate if anyone could explain it.

1

1 Answer 1

10

We need to provide the HC-SR04 with a fitting trigger signal. When you read the datasheet of the HC-SR04 you will see that it needs a 10us trigger pulse.

The first delay of 2us is to make sure we are at an established LOW level on the trigger pin, since the pin might have been HIGH before that. We are delaying here to make sure, that the HC-SR04 actually registered the level as LOW, even if it was HIGH before. If we would change from HIGH to LOW and back to HIGH as fast as we can, then the HC-SR04 might not have enough time to actually see the pin going low. Its mostly a measure to ensure the code working correctly here.

The second delay is for the actual trigger pulse. The datasheet specifies it as 10us length, so that is what we delay here. After that we go back to LOW to end the trigger pulse and wait for the echo pulse to come.

You might have read that it is bad to use delays in your code, since they are blocking. That is correct in principle, but normally really short delays in the microsecond range don't really matter for the program flow. Just be away to keep the total delay time in your code low enough to not miss any important events (like button presses).

2
  • The microsecond delays make sense but my library also has a 25 ms delay before returning. All the computation is done by this point, so it seems to be just a delay and 25 ms is a long time for a robot.
    – user88094
    Jan 7, 2023 at 14:54
  • @user88094 You didn't specify what library you mean. Yes, without seeing the code and context I would also say, that a 25ms delay is not needed.
    – chrisl
    Jan 7, 2023 at 16:31

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.