Introduction: How to Measure Distance Using Ultrasonic Sensor (Full Tutorial)

In this post, we are going to use the Ultrasonic Sensor to build a distance sensor. The HC-SR04 ultrasonic sensor can be programmed to send out a ping using an ultrasonic transmitter, and then measure the time it takes to hear the echo of the ping come back to the receiver, after bouncing off a object body. Since we know the speed of sound we can calculate the distance to the sensor.


  1. Ultrasonic sensor
  2. Arduino Uno
  3. Breadboard
  4. jumpers
  5. Ruler
  6. Obstacle

Step 1: Ultrasonic Sensor Working(timing Diagram)

In order to produce ultrasonic sound, we need to set the Trigger Pin on HIGH for 10 µs. That will send out a sonic burst which will travel at the speed of sound and it will be received in the Echo Pin. The Echo Pin will send the output the time in microseconds the sound wave traveled.

Step 2: Calculating Distance

For example, if the object is 10 cm away from the sensor, and the speed of the sound is 340 m/s or 0.034 cm/µs the sound wave have to travel for about 294 microseconds. But the output will get from the Echo pin will be double that number because the sound wave needs to travel and bounce backward. So in order to get the distance of the object in cm we need to multiply the received travel time value from the echo pin by speed of sound that is 0.034 and divide it by 2.

Step 3: Code: