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

Scroll to Top
Read previous post:
Meet Fribo, a robot built for lonely young people
Meet Fribo, a robot built for lonely young people

The number of people living alone is on the rise in the US and other developed nations, and it’s definitely...