HC-SR04 with Arduino: Wiring and Reliable Distance Measurement

Engineering illustration: HC-SR04 with Arduino: Wiring and Reliable Distance Measurement

One of the most widely used sensors in robotics and obstacle-avoidance systems is the HC-SR04 ultrasonic sensor - an inexpensive sensor that's accurate enough for most educational and practical applications.

Sensor specifications

The HC-SR04 operates at 5V and is commonly used over a nominal range of roughly 2 to 400 centimeters, with reliability falling near the limits, relying on 40 kHz sound waves that are inaudible to the human ear.

Wiring it up

The VCC pin connects to the Arduino's 5V pin, and GND to ground, while the Trig pin (responsible for sending the wave) connects to digital pin 9, and the Echo pin (responsible for receiving the reflected wave) connects to digital pin 10.

How the measurement works

The sensor sends a 10-microsecond pulse through the Trig pin, triggering a sound wave that hits the nearest object in front of it and bounces back to be picked up by the Echo pin. Arduino's pulseIn() function measures the time elapsed between sending the wave and receiving its echo, and the distance is then calculated using the following formula:

Distance (cm) = echoTime (µs) × 0.0343 ÷ 2

Here "x" represents the total round-trip time in microseconds. The division by 2 is needed because the measured time covers the wave's full round trip, not just a one-way distance.

Practical applications

This sensor is widely used in mobile robots to avoid colliding with obstacles, in parking assist systems, for measuring liquid levels in tanks, and even in some security and monitoring applications.

You can find the HC-SR04 sensor and the rest of the connection accessories needed for this project in the sensors section at Juthour Tech.

A timeout-safe measurement

digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

unsigned long echoTime = pulseIn(ECHO_PIN, HIGH, 30000UL);
if (echoTime == 0) {
  // No valid echo within the timeout
} else {
  float distanceCm = echoTime * 0.0343f / 2.0f;
}

Air temperature, target angle, surface softness, and geometry all affect the echo. Multiple nearby sensors may interfere with one another, so trigger them sequentially rather than simultaneously.

Leave your comment

*
*
Only registered users can leave comments.