ArduinoBeginner

Distance Measurement with HC-SR04 Ultrasonic Sensor

Learn to measure distance using the HC-SR04 ultrasonic sensor with Arduino and display it on the Serial Monitor.

18 December 202510 min read

Introduction

The HC-SR04 ultrasonic sensor can measure distances from 2cm to 400cm with reasonable accuracy. It works by sending out an ultrasonic pulse and measuring how long it takes for the echo to return.

Components Required

  • Arduino Uno
  • HC-SR04 Ultrasonic Sensor
  • Breadboard and jumper wires

Wiring

HC-SR04 PinArduino Pin
VCC5V
TrigPin 9
EchoPin 10
GNDGND

The Code

const int trigPin = 9;
const int echoPin = 10;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // Send a 10μs pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echo duration
  long duration = pulseIn(echoPin, HIGH);

  // Calculate distance in cm
  float distance = duration * 0.034 / 2;

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(500);
}

How It Works

  1. The Trig pin sends a short ultrasonic burst
  2. The sensor waits for the echo to bounce back
  3. The Echo pin goes HIGH for the duration of the round trip
  4. We calculate distance using: Distance = (Time × Speed of Sound) / 2
  5. Speed of sound ≈ 0.034 cm/μs

Testing

Upload the code, open Serial Monitor at 9600 baud, and point the sensor at objects at various distances. You should see accurate distance readings.

Applications

  • Obstacle avoidance robots
  • Parking sensors
  • Liquid level measurement
  • Proximity alarms
Tags:ArduinoSensorHC-SR04