Distance Calculation with Ultrasonic Sensor

Ultrasonic Sonar

HC-SR04 is a commonly used module for non-contact distance measurement for distances from 2cm to 400cm. It uses sonar (like bats and dolphins) to measure distance with high accuracy and stable readings. It consists of an ultrasonic transmitter, receiver and control circuit. The transmitter transmits short bursts which gets reflected by target and are picked up by the receiver.distance calculation with ultrasonic sensor

The time difference between transmission and reception of ultrasonic signals is calculated. Using the speed of sound and ‘Speed = Distance/Time‘ equation, the distance between the source and target can be easily calculated.

HC-SR04 ultrasonic distance sensor module has four pins:

  • VCC – 5V, input power
  • TRIG – Trigger Input
  • ECHO – Echo Output
  • GND – Ground
  • VCC -> 5 volt pin on Pi
  • Trig -> Trigger activates the sensor and connect to GIO output pin
  • Echo -> Receives the signal, read by GPIO input pin

Distance Calculation

Time taken by pulse is actually for to and from travel of ultrasonic signals, while we need only half of this. Therefore time is taken as time/2.

Distance = Speed * Time/2

Speed of sound at sea level = 343 m/s or 34300 cm/s

Thus, Distance = 17150 * Time (unit cm)


For accurate distance readings, the output can be calibrated using a ruler. In the below program a calibration of 0.5 cm is added.

Schematics schematic distance calculation with ultrasonic sensor

For more detail: Distance Calculation with Ultrasonic Sensor

About The Author

Ibrar Ayyub

I am an experienced technical writer with a Master's degree in computer science from BZU Multan University. I have written for various industries, mainly home automation, and engineering. I have a clear and simple writing style and am skilled in using infographics and diagrams. I am a great researcher and is able to present information in a well-organized and logical manner.

Scroll to Top