Tutorial: Getting Distance from Ultrasonic Sensor HC-SR04

The concept of ultrasonic Sensor is echolocation, similiar to how bats navigate and detect objects in a cave. To communicate and interface with this type of sensor, A short 10uS pulse is needed to supply to the trigger input to start the ranging, and then the module will send out an 8-cycle burst of ultrasound at 40 kHz and raise its echo. The Echo is a distance object that is pulse width and the range in proportion. The range can be calculated through the time interval between sending trigger signal and receiving echo signal.

Hardware Connection 

  1. Using HC-SR04 which can be purchased from this link, https://shop.techmakers.com.my/ultrasonic-sensor-hc-sr04?search=ultrasonic , Connect the ultrasonic sensor to the Arduino by following the example of connection.


  1. Upload the following sketch into Arduino UNO
  2. Open Serial Monitor, you will see the results of distance spitting at an interval of 100ms.

//define pin and initialize variables
#define trigPin 9
#define echoPin 8
long duration, distance_cm;
void setup() {
Serial.begin(9600); //set baud rate for communicating with the computer
//define the input and output
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
void loop() {
//the sensor is triggered with a HIGH pulse for 10us
//before that, we give a short LOW pulse to ensure we’ll get a clean HIGH pulse
digitalWrite(trigPin, LOW);
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance
distance_ cm = (duration/2) / 29.1;
Serial.print("Length: ");
Serial.print(distance_ cm);
delay(100); //delay 100 ms