Book a Consultation
10 Aug 2026 • 46 views

Arduino Tutorial: HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 measures distance by timing how long a sound pulse takes to bounce off an object and return — the same principle as sonar. It's the go-to sensor for obstacle-avoiding robots and parking-sensor style projects.


Intermediate

⌛ 30 min

🔧 What You'll Need

  • Arduino Uno
  • 1x HC-SR04 ultrasonic sensor
  • Breadboard
  • 4x jumper wires

Wiring the Circuit

Connect VCC to 5V and GND to GND. Connect TRIG to digital pin 9 and ECHO to digital pin 10. Unlike most sensors, the HC-SR04 needs two separate digital pins since it sends a pulse out on one and listens for the echo on the other.

The Code

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

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

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH);
  float distanceCm = duration * 0.034 / 2;

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

  delay(500);
}

A short 10-microsecond HIGH pulse on trigPin fires the ultrasonic burst. pulseIn(echoPin, HIGH) then measures how long echoPin stays HIGH, which is the round-trip travel time in microseconds. Multiplying by the speed of sound (0.034 cm/microsecond) and dividing by 2 (round trip, not one-way) gives the distance in centimeters.

💡 Tip: The HC-SR04 has a practical range of roughly 2cm to 400cm and a fairly narrow ~15° detection cone — if an object is off to the side rather than directly ahead, it may not be detected at all.

Troubleshooting

  • Distance always reads 0: Check ECHO and TRIG aren't swapped — this is the single most common wiring mistake with this sensor.
  • Readings are wildly inconsistent: Soft or angled surfaces (fabric, foam, an angled wall) absorb or deflect the sound pulse instead of reflecting it cleanly.
  • Sensor works but readings drift over time: Temperature affects the actual speed of sound slightly — not usually significant enough to matter for hobby projects.

Between the DHT11 and the HC-SR04 you now have both an environmental sensor and a spatial one — the two most common sensor categories in beginner IoT projects. Next: driving more interesting output than a single LED.

Share:
Get new projects in your inbox
One email a month. No spam — just new project drops and workshop dates.