Measure Distance with an HC-SR04 — The sensor sends a short ultrasonic burst and times the echo. Your job is to generate one clean trigger pulse and convert the returned pulse width.

Sensors

Measure Distance with an HC-SR04

Measure Distance with an HC-SR04 — The sensor sends a short ultrasonic burst and times the echo. Your job is to generate one clean trigger pulse and convert the returned pulse width.

The sensor sends a short ultrasonic burst and times the echo. Your job is to generate one clean trigger pulse and convert the returned pulse width into a distance.

22 November 20268 min read
An HC-SR04 ultrasonic sensor with trigger and echo wires connected to an Arduino on a breadboard
Four connections are enough: power, ground, a trigger output and an echo input.

Bu projeyi gerçekten kurmak istersen parçaları hobidevre.com'dan temin edebilirsin →

Build it for real

To build this project for real, get the parts from hobidevre.com → hobidevre.com →

More build guides: hobidevre.com/blog

How the sensor measures distance

The HC-SR04 has a transmitter that emits an ultrasonic burst and a receiver that listens for the reflection. The module measures the time between sending and receiving and reports that time as the width of a pulse on its Echo pin. The Arduino only has to measure a pulse duration; the sensor handles the analogue front end.

Because the signal travels to the object and back, the measured time covers twice the distance. That is the origin of the division by two in the conversion formula.

The echo arrives as a pulse width, so the Arduino needs no audio circuitry of its own. This simple interface is one reason the module is a common first choice for distance projects.

Wiring the four pins

Connect VCC to the 5 V header and GND to ground. Connect Trig to a digital output pin and Echo to a digital input pin. A common mistake is swapping Trig and Echo; the sketch will then wait for a pulse that never arrives and report zero.

Check the logic level of the Echo pin against your board. On a 5 V Uno it can be read directly. On a 3.3 V board, use a simple resistor divider on the Echo line so that the input is not overdriven.

The 10 microsecond trigger

To start a measurement, hold Trig LOW, bring it HIGH for a very short pulse, then bring it back LOW. A pulse around ten microseconds is what the module expects. The time-critical part is measured in microseconds, so use the microsecond timing function rather than a millisecond delay.

Allow a short pause between measurements. Firing again before the previous echo has returned can produce a reading that belongs to the earlier burst.

Reading the echo pulse

After the trigger, the Echo pin goes HIGH and stays HIGH for a duration proportional to the distance. The pulseIn function measures that width. Give it a timeout so the program does not wait forever when there is no echo; a timeout is also how you detect that nothing is in range.

A zero or a timeout is not a distance of zero. Treat it as "no usable reading" and keep the last valid value or display a clear message instead.

Time to centimetres

Sound travels through air at roughly 343 metres per second near room temperature, which is about 0.0343 centimetres per microsecond. Because the measured pulse covers the round trip, distance in centimetres is approximately the echo time in microseconds multiplied by 0.0343 and divided by two.

Temperature changes the speed of sound slightly, so this conversion is an approximation. For a hobby project at ordinary room conditions it is more than adequate; precision work would need temperature compensation.

Round the printed value to a sensible precision. Reporting several decimal places suggests an accuracy the sensor does not have, and it makes a moving object harder to follow on the serial monitor.

sure = pulseIn(ECHO, HIGH, 30000);
mesafeCm = sure * 0.0343 / 2;

A complete sketch

The sketch below sets the pin modes, sends the trigger pulse, reads the echo with a timeout and prints the calculated distance. Notice that the sensor is triggered only after the serial port is ready, and that each measurement is separated by a short delay.

Read the serial output while moving an object toward and away from the sensor. A steady change confirms that the wiring and conversion agree. Large jumps usually point to a surface the ultrasound does not reflect well.

const int TRIG = 9;
const int ECHO = 10;

void setup() {
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  unsigned long sure = pulseIn(ECHO, HIGH, 30000);
  if (sure > 0) {
    float mesafeCm = sure * 0.0343 / 2.0;
    Serial.println(mesafeCm);
  } else {
    Serial.println("yanki yok");
  }
  delay(100);
}

Limits and error sources

Soft materials such as fabric absorb ultrasound and may return a weak echo. Angled surfaces can reflect the burst away from the receiver. Very close objects can arrive before the sensor is ready to listen, and very distant ones may exceed the pulseIn timeout.

Mount the sensor firmly and keep the two transducers clear of obstructions. Averaging several readings smooths small fluctuations without hiding genuine changes.

Keep the sensor at a steady height above the floor when you compare readings. Tilting it by a few degrees changes which part of the object reflects the burst and can shift the result noticeably. Marking a fixed position on your bench makes repeated measurements far easier to compare.

Get the parts

HC-SR04 modules and jumper wires are available from hobidevre.com.

Frequently asked questions

Why divide the echo time by two?

The sound travels to the object and back, so the measured interval covers twice the one-way distance.

Which surfaces are hardest to measure?

Soft or heavily angled surfaces. They absorb or deflect the ultrasound so little energy returns to the receiver.

Do I need a level shifter for the Echo pin?

Not on a 5 V board. On a 3.3 V board, use a small resistor divider because Echo is driven at the sensor’s supply voltage.

Related reading

Practise in the browser

Open the same layout in the simulator and follow the steps. Sign in to save your work.