HC-SR04 connected to Arduino Uno for distance measurement, HC-SR04 interface, Arduino Uno, distance measurement

Interfacing of Ultrasonic Sensor With Arduino

1.5M Views
40
700
60
25
60
PCBWay

Hello friends! Today we will connect a real HC-SR04 ultrasonic sensor to an Arduino Uno and display distance on the Serial Monitor. Our earlier Proteus library tutorial introduced the simulated sensor, and the simulation examples explored different input conditions. This article moves to the four-pin physical module and the practical details of a measurement.

Libraries

HC-SR04 Simulation Libraries

Latest library: Ultrasonic Sensor Library for Proteus V2.0 (October 2026): HC-SR04 with real TRIG and ECHO timing, Simple and Advance devices, test tools and an Arduino demo

Helping Tools

The wiring is short, but there is more to a useful distance reading than dividing a number. We need the correct signal directions, a clean trigger, an echo timeout and a target that reflects sound back toward the receiver. We also need to distinguish a valid distance from the absence of a usable echo.

We will preserve the original D8 trigger and D7 echo connections, improve the sketch and work through the timing calculation. Then we will examine measurement limits, compare readings with a ruler and discuss simple filtering. The code is a learning example; the retained circuit images are not a report of newly performed hardware tests.

HC-SR04 connected to Arduino Uno for distance measurement, HC-SR04 interface, Arduino Uno, distance measurement
Figure: HC-SR04 connected to Arduino Uno for distance measurement.

What Does the HC-SR04 Measure?

The HC-SR04 estimates the distance to a reflecting target by transmitting an ultrasonic burst and measuring its return. Ultrasound is a mechanical sound wave above normal human hearing, not electromagnetic radiation. One transducer transmits and the other receives; both need an acoustic path to the target.

The module exposes four connections: VCC, GND, Trig and Echo. The Arduino drives Trig to request a measurement, while Echo is driven by the sensor. Therefore Trig is an input from the sensor's perspective and an output from the Arduino's perspective. Echo has the opposite direction.

HC-SR04 connections for this Uno example
Sensor pinArduino connectionFunction
VCCSuitable 5 V supplyPowers the conventional module
GNDCommon groundEstablishes the signal reference
TrigD8Receives Arduino's trigger pulse
EchoD7Sends the pulse measured by Arduino

The conventional module reference describes an approximate 2 cm to 4 m working range, with a trigger pulse of at least 10 µs and an ultrasonic burst at 40 kHz. Those figures do not guarantee successful detection of every object throughout that range. Consult the HC-SR04 reference sheet and the documentation supplied with your actual module.

How Trigger and Echo Produce a Distance

Arduino holds Trig low, briefly raises it high and then returns it low. The module performs its measurement and presents an Echo pulse whose duration represents round-trip travel time. The important quantity for the sketch is how long Echo remains high, not simply the moment at which a pin changes state.

The original explanation described Echo as becoming high when the reflected signal arrives. That is not a useful description of the pulse-width interface. For distance calculations, follow the module's timing behavior and measure the complete output pulse.

Derive the equation with units

Let d be the one-way distance, c the sound speed and t the outward-and-return time. The sound travels approximately 2d, so 2d = ct and d = ct/2. If c is 343 m/s, it is also 0.0343 cm/µs.

For t = 2,000 µs, d = 0.0343 × 2,000 / 2 = 34.3 cm. For t = 5,000 µs, the result is 85.75 cm. If you omit the division by two, both distances become twice their intended values.

The older expression divided time by 29.1 and then by two. The value 29.1 is approximately a travel time in microseconds per centimeter under a chosen sound-speed assumption; it is not a speed in meters per second. Writing units beside constants makes this distinction visible.

Why different examples use 58 or 58.2

Combining the two divisions gives an approximate round-trip divisor. With 343 m/s, the divisor is about 58.31 µs/cm. A simplified 58 divisor is common in introductory examples. Small numerical differences between these formulas arise from their assumed sound speeds and rounding.

The sketch below uses 0.0343 cm/µs explicitly so the assumption is visible. Printing two decimal places does not establish that the sensor is accurate to one-hundredth of a centimeter. Display precision and physical measurement accuracy are separate concepts.

Wire the Sensor to Arduino

Disconnect power while making the connections. Identify pin labels on the actual board rather than relying on which side of a photograph faces you. Connect VCC and GND, then route Trig to D8 and Echo to D7. Keep jumper connections secure and use a common ground if the sensor has a separate regulated supply.

Arduino Uno D8 trigger and D7 echo wiring, HC-SR04 interface, Arduino Uno, distance measurement
Figure: Arduino Uno D8 trigger and D7 echo wiring.

The retained wiring image illustrates the original arrangement. A classic 5 V Uno is the target of this example. A 3.3 V board needs a separate compatibility check, particularly for the conventional module's Echo output. Do not treat the Uno wiring as a universal connection diagram for every Arduino-branded or compatible board.

Example of reducing a 5 V Echo signal

For a controller that requires a lower input voltage, an appropriately designed divider or level translator can be used. As a numerical example only, a 10 kΩ upper resistor and 15 kΩ lower resistor divide an ideal 5 V signal to 5 × 15/(10 + 15) = 3.0 V.

Before using that divider, verify the controller's guaranteed input-high threshold, maximum input voltage, component tolerances and edge timing. The calculation shows the nominal ratio; it is not a substitute for the actual electrical limits. The sensor supply and trigger-input requirements also remain relevant.

Arduino Sketch with Validity Checking

This version keeps the original pin assignment and serial output while adding a timeout. It returns a success flag separately from the measured value, so a missing pulse cannot accidentally become a valid zero-distance reading. No external ultrasonic Arduino library is required.

const byte triggerPin = 8;
const byte echoPin = 7;
const unsigned long timeoutUs = 30000UL;
const float soundCmPerUs = 0.0343f;

bool readDistanceCm(float &distanceCm, unsigned long &durationUs) {
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(2);
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW);

  durationUs = pulseIn(echoPin, HIGH, timeoutUs);
  if (durationUs == 0) return false;

  distanceCm = durationUs * soundCmPerUs / 2.0f;
  return distanceCm >= 2.0f && distanceCm <= 400.0f;
}

void setup() {
  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);
  digitalWrite(triggerPin, LOW);
  Serial.begin(9600);
}

void loop() {
  float cm = 0.0f;
  unsigned long echoUs = 0;
  if (readDistanceCm(cm, echoUs)) {
    Serial.print("Echo: ");
    Serial.print(echoUs);
    Serial.print(" us | Distance: ");
    Serial.print(cm, 1);
    Serial.println(" cm");
  } else {
    Serial.println("No usable distance reading");
  }
  delay(100);
}

The 2–400 cm comparison is an application acceptance filter based on the conventional nominal range. It does not prove that a result inside those limits is correct. A reflection from the wrong object can still produce a plausible number, which is why target placement and practical checking matter.

Understand pulseIn and its timeout

Arduino's pulseIn documentation describes the pulse duration in microseconds and the zero result when no complete pulse is received within the timeout. Our 30,000 µs limit prevents the sketch from waiting indefinitely for a measurement.

At the assumed sound speed, a 4 m outward distance corresponds to roughly 23.3 ms round trip. A 30 ms timeout leaves additional time in this learning example, but it does not make a target beyond the sensor's usable range detectable. Electrical timing limits and acoustic performance are different constraints.

The function is blocking while it measures the pulse. The final 100 ms pause also blocks ordinary loop work. For a simple serial demonstration that is acceptable; for a responsive robot, you should account for that time or use a nonblocking measurement design.

Upload and Observe the First Readings

  1. Select the correct Uno board and serial port in the Arduino IDE.
  2. Compile and upload the sketch with the sensor wiring checked.
  3. Open the Serial Monitor at 9600 baud.
  4. Place a large, flat target approximately perpendicular to the sensor.
  5. Begin at a moderate distance, such as around 30–50 cm, rather than at a range limit.
  6. Move the target between clearly separated positions and observe the timing and distance.
  7. Remove the target and observe how the sketch reports unusable measurements.

The Arduino Serial Monitor tutorial explains the terminal setup. Keep units in the printed output. A bare number such as 120 is ambiguous unless the reader knows whether it means centimeters, millimeters or microseconds.

If the monitor shows nothing, first confirm that the sketch is running and the selected port is correct. If it reports only invalid readings, inspect Trig/Echo assignment and ground continuity. Reversing the two signal pins does not merely invert a value; it breaks the request-and-response interface.

Compare the Sensor with a Reference Distance

Use a ruler or tape measure and keep the target orientation consistent. Define where the reference distance begins on the sensor assembly. A few millimeters of ambiguity in the reference point can look like a constant offset when testing at short distances.

For each target position, record several valid measurements together with the number of invalid attempts. Do not quietly delete every inconvenient result and report only the most favorable value. Repeatability and success rate are both relevant to deciding whether the setup is useful.

Example measurement record structure
Reference distanceValid readingsInvalid attemptsQuantity to calculate
Measured with a rulerSeveral values in centimetersCount of unusable acquisitionsMean and spread
A second target positionThe same number of attemptsRecorded separatelySigned error
A third target positionRepeat under similar conditionsRecorded separatelyChange in error with distance

If a 50.0 cm reference gives an average of 51.2 cm, signed error is +1.2 cm and relative error is 1.2/50.0 × 100 = 2.4%. A different result at 100 cm can help distinguish a roughly constant offset from an error that grows with distance.

Do not fit a correction from one target position and assume it applies everywhere. A changed target material or angle can alter the reflection rather than simply adding the same offset. Calibration should describe its conditions and intended range.

Why Real Readings Can Change

A flat target facing the sensor returns sound differently from a sloped surface that reflects energy away. Soft or irregular materials can weaken or scatter the return. A narrow object may not reflect enough sound, while a wider nearby object may dominate the measurement.

The sensor observes an acoustic region rather than a mathematical pencil-thin ray. Mounting it near a tabletop, chassis edge or enclosure can introduce another reflecting surface. Move the assembly or target deliberately to see whether the reading follows the object you intended to measure.

Temperature and the sound-speed assumption

Sound speed in air changes with conditions. If the actual speed differs from the constant used in software, calculated distance changes proportionally. For an illustrative comparison, using 343 m/s when the actual speed is 331 m/s overestimates the distance by a factor of 343/331, approximately 1.036.

That is about 3.6% under the stated assumptions. It explains why a fixed conversion is convenient for a room-temperature demonstration but cannot establish identical accuracy under every environment. A temperature-compensated design should use a documented model and a representative air-temperature measurement.

Filtering without Hiding Failures

A moving average can reduce small random variation, while a median can reject an isolated outlier. Neither can make a wrong reflection become the correct target. Apply filtering only after separating valid data from missing or out-of-range readings.

For example, measurements of 49, 50, 51, 50 and 180 cm have a median of 50 cm but a mean of 76 cm. The example illustrates outlier sensitivity; it does not prove that 180 cm was erroneous. Inspect the scene and acquisition conditions before deciding which result should be rejected.

A five-reading filter with approximately 100 ms between acquisitions spans several hundred milliseconds. That can make a display pleasant while delaying recognition of a moving object. Choose the filter window from the required response time, and keep a timestamp or age for the resulting value.

Use hysteresis for threshold outputs

If you later add an indicator, use separate activation and release thresholds when appropriate. For example, activate at 30 cm or below and clear at 35 cm or above. Inside that band, retain the previous state. This prevents small changes near one threshold from toggling the output repeatedly.

Invalid readings still require a separate decision. Holding the last value indefinitely can leave an obsolete clear-path indication on screen. Reporting unknown explicitly is more informative than pretending that missing information is a large distance.

Separate timing resolution from sensor accuracy

At the assumed 0.0343 cm/µs sound speed, a one-microsecond change in round-trip timing corresponds to 0.01715 cm, or about 0.17 mm. That arithmetic describes sensitivity to the time variable only. It does not establish that this Arduino function resolves every microsecond perfectly or that the acoustic module can measure a target to that accuracy.

A practical error budget also includes the transducer response, detection threshold, target shape, reference-point uncertainty and environmental assumptions. If a display changes in small increments but its average is several centimeters away from a ruler measurement, small numerical increments have not solved the larger error.

Keep repeated measurements comparable

Hold the sensor and target still while collecting a set of readings, and note the supply arrangement and approximate environment. Change one condition at a time: first distance, then angle, then material. If all three change together, you cannot tell which caused a missed return.

For a useful bench notebook, include the sketch version and conversion constant with the observations. Replacing 0.0343 with another value changes the reported distance even if every raw echo duration is identical. Keeping raw timing lets you compare calculations later without claiming that a software change altered the underlying physical sensor.

Troubleshooting the Hardware

Common symptoms and likely checks
SymptomCheck
Only invalid readingsSignal directions, supply, common ground and target placement
Distance is approximately doubledRound-trip division by two
Values jump when the board movesLoose wiring and reflections from nearby surfaces
Works in simulation but not on the benchPhysical voltage levels and acoustic conditions
Other code becomes sluggishBlocking echo measurement and delay
Reading stays old after a failureValidity handling and measurement age

When debugging, print raw echo duration alongside the interpreted distance. If the duration looks reasonable but the units are wrong, inspect the conversion. If the duration is absent or implausible, focus on the measurement path before adjusting arithmetic constants.

Review and Next Steps

The complete measurement chain is a requested pulse, an acoustic response, an Echo duration and a distance calculation with stated assumptions. A useful implementation also reports when that chain did not produce valid information. That is the main improvement over a sketch that prints every timing result as a distance.

Once a single sensor behaves consistently, continue with multiple ultrasonic sensors. The next challenge is scheduling measurements so one sensor does not mistake another sensor's transmitted sound for its own return.

Frequently Asked Questions

Why divide the measured time by two?

The sound travels to the target and back. The measured round trip covers twice the desired one-way distance.

Can I use the extra analog pin from the Proteus model on hardware?

No. That pin belongs to the simulation model. The conventional physical HC-SR04 uses VCC, GND, Trig and Echo.

Does no echo mean there is no obstacle?

No. A target may be poorly oriented or weakly reflecting, or the interface may have failed. Treat no echo as unavailable measurement information.

Why do I get different results from two identical-looking modules?

Module implementations, tolerances and operating conditions can differ. Compare them under the same wiring, target and reference-distance procedure before drawing conclusions.

Can I measure faster by removing every delay?

Not reliably by that change alone. Allow sufficient time between transmissions, account for remaining acoustic echoes and check the sensor's timing guidance.


Comments

4

Join the conversation

Reply1

Thanks for the tutorial. I plan to add ultrasonics to my bot and this is a great assist.

I have a question on your math. At the end of your ranging, you divide by 29.1 (cm/millisecond) as the speed of sound. I would put the value closer to 33 cm/millisecond. Are you assuming a different atmospheric pressure, different speed for ultrasound vs. normal sound or something else? Thanks.

Steve

Reply2

Can you please help me with the code if i integrate gsm module sim900a sending message of the distance to the mobile phone?

1 reply
1 reply