Arduino Uno HC-SR04: Industrial Ultrasonic Ranging

Professional HC-SR04 module integrates STK014 ultrasonic transmitter/receiver pair operating at 40kHz ±1kHz center frequency with 30° conical beamwidth measuring 2-400cm range (±3mm accuracy). 10μs trigger pulse initiates 150μs burst transmission followed by echo pulse-width measurement (58μs/cm round-trip at 343m/s).

5V operation, 15mA average current, built-in 74HC14 Schmitt trigger conditioning. Median filtering eliminates acoustic noise/spikes. Temperature compensation corrects speed-of-sound variations (0.607μs/cm/°C).

How It Works

The HC-SR04 measures distance by timing an echo. It emits a burst of eight 40 kHz pulses, then waits for the reflection to come back. Sound travels at roughly 343 m/s in air at 20 °C, so the round-trip time directly gives distance: distance = time × 343 / 2, with the division by two because the sound travels out and back.

Expressed in the units the Arduino works in, that becomes distance in centimetres equal to the echo duration in microseconds divided by 58. The sensor's useful range is about 2 cm to 400 cm with roughly 3 mm resolution, which is far better than infrared alternatives at a similar price.

Operation is a strict handshake. The host raises TRIG for at least 10 µs; the module then emits its burst and raises ECHO for exactly as long as the round trip takes. pulseIn() measures that width. If no echo returns, ECHO stays high until an internal timeout — which is why a blocking pulseIn() without a timeout can stall a sketch for tens of milliseconds.

Because it relies on reflected sound, the sensor has blind spots. Soft materials such as curtains and foam absorb the pulse, and surfaces angled more than about 15° deflect it away. It also has a beam angle of roughly 15°, so it reports the nearest object anywhere in a cone rather than straight ahead.

Components Needed

  • Hard flat: ±2mm accuracy
  • Clothing: ±15mm reduced range
  • Liquid surface: ±5mm excellent
  • People: ±10mm torso optimal
  • Glass: ±20mm transmission loss

Wiring to the Arduino Uno

Connect TRIG to D2, ECHO to D3, VCC to 5 V and GND to ground. The module genuinely needs 5 V — at 3.3 V its range collapses or it fails to trigger at all.

Both TRIG and ECHO sit within the 5 V logic domain of this board, so they connect directly with no level shifting.

Mount the sensor clear of the chassis and pointing at the target. The two cylinders must both be unobstructed, and keeping them at least a few centimetres from any surface prevents the module hearing its own reflections.

Module pinArduino Uno pinFunction
TRIGD2Pulse high for 10 µs to start a measurement
ECHOD3Goes high for the round-trip duration
VCC5VSupply — the HC-SR04 needs 5 V
GNDGNDCommon ground

Example Code

Distance measurement with a timeout and median filtering to reject dropouts. Upload it with the board set to Arduino Uno and open the Serial Monitor at 9600 baud.

Distance measurement with a timeout and median filtering to reject dropouts
const int TRIG_PIN = 2;
const int ECHO_PIN = 3;
const unsigned long ECHO_TIMEOUT_US = 25000;   // ~4 m ceiling, stops long stalls

long readOnce() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  return pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);   // 0 means no echo
}

void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
}

void loop() {
  long s[5];
  for (int i = 0; i < 5; i++) { s[i] = readOnce(); delay(30); }
  for (int i = 0; i < 4; i++)
    for (int j = i + 1; j < 5; j++)
      if (s[j] < s[i]) { long t = s[i]; s[i] = s[j]; s[j] = t; }

  long us = s[2];                       // median of five
  if (us == 0) {
    Serial.println("no echo — out of range or absorbing surface");
  } else {
    Serial.print("Distance: ");
    Serial.print(us / 58.0, 1);
    Serial.println(" cm");
  }
  delay(200);
}

Applications

A hc-sr04 ultrasonic distance sensor turns up in a wide range of projects. These are the uses where it is the right choice rather than a compromise:

  • Obstacle avoidance and navigation on mobile robots
  • Water and grain level measurement in tanks and silos
  • Parking assistance and reversing aids
  • Automatic doors, taps and bins triggered by approach
  • People counting and queue monitoring at fixed positions

Working with the Arduino Uno

The Arduino Uno is built around the ATmega328P and runs on 5 V logic with 2 KB of SRAM and 32 KB of program flash. These details change how this circuit is wired and what the sketch can do, so they are worth stating plainly before you build.

The Uno runs at 5 V, so most hobby sensor modules connect directly with no level shifting.

With only 2 KB of SRAM, avoid large buffers and prefer the F() macro for constant strings.

The single hardware UART is shared with the USB connection, so heavy Serial printing competes with uploads.

Arduino Uno characteristicValueWhy it matters here
Logic voltage5 VMatches most hobby modules directly
ADC resolution10-bit (0–1023)Sets how finely an analog reading can be resolved
Analog inputsA0–A5 (six channels)Determines how many analog sensors can share the board
PWM outputsD3, D5, D6, D9, D10 and D11Needed for brightness, speed and tone control
I²C pinsA4 (SDA) and A5 (SCL)Fixed by hardware — wiring copied from another board may not match
Interrupt pinsD2 and D3 onlyRequired for counting fast or asynchronous events
Seriala single hardware UART shared with USBMonitor runs at 9600 baud by default

Troubleshooting

Most problems with this module fall into a handful of categories. Work through these before suspecting the part itself:

  • Readings are always 0 — ECHO is not connected, or pulseIn() timed out because nothing reflected.
  • Distances are wildly inconsistent — the target is soft or angled. Hard, flat, perpendicular surfaces read best.
  • Values drift with the weather — the speed of sound varies with temperature by about 0.6 m/s per °C. Compensate for accuracy better than a centimetre or two.
  • Close objects read as very far — below roughly 2 cm the echo returns before the module starts listening.
  • Two sensors interfere — they hear each other's bursts. Trigger them alternately rather than simultaneously.
  • Code written for an ESP board gives odd analog values — the Arduino Uno uses a 10-bit ADC returning 0–1023; rescale any constant taken from a 12-bit example.
  • An I²C sensor is not found after copying wiring from another Arduino — on the Arduino Uno I²C is on A4 (SDA) and A5 (SCL).

Taking It Further on the Arduino Uno

Once the basic reading works, where you go next depends very much on which board you are using. These are the directions that suit the Arduino Uno specifically:

The Uno’s shield ecosystem is its real advantage. Once the circuit works on a breadboard, a prototyping shield turns it into something permanent that still stacks with a data-logging or Ethernet shield without rewiring.

Logging to an SD card via a shield is the natural next step, since the Uno has no onboard storage and no network. Timestamp each reading with a DS3231 real-time clock so the log survives power cuts with correct times.

Because SRAM is limited to 2 KB, keep logged strings short and write them out immediately rather than buffering. Building a long String in memory is the most common cause of an Uno sketch that runs for hours and then freezes.

Notes and Practical Limits

The timeout in pulseIn() is not optional in a responsive sketch. Without it, a missing echo blocks for up to 200 ms, and a robot that stops reacting for a fifth of a second while moving will hit things.

For temperature compensation, measure air temperature and compute the speed of sound as 331.3 + 0.606 × T m/s. Across a 0–40 °C swing that is a 7% change in reported distance.