0
0
AutocadHow-ToBeginner · 4 min read

How to Use Ultrasonic Sensor HC-SR04 with Arduino

To use the HC-SR04 ultrasonic sensor with Arduino, connect the Trig and Echo pins to Arduino digital pins, then send a pulse from Trig and measure the time it takes for the echo to return on Echo. Calculate distance by converting the time to centimeters using the speed of sound.
📐

Syntax

The basic steps to use the HC-SR04 sensor with Arduino are:

  • Set Trig pin as output: to send the ultrasonic pulse.
  • Set Echo pin as input: to receive the reflected pulse.
  • Send a 10 microsecond HIGH pulse on Trig: to start measurement.
  • Measure the duration of the HIGH pulse on Echo: this is the time taken for the sound to travel to the object and back.
  • Calculate distance: distance = (duration / 2) * speed of sound (0.034 cm/µs).
arduino
const int trigPin = 9;
const int echoPin = 10;

void setup() {
  pinMode(trigPin, OUTPUT); // Set trigPin as output
  pinMode(echoPin, INPUT);  // Set echoPin as input
  Serial.begin(9600);       // Start serial communication
}

void loop() {
  // Clear the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Send a 10 microsecond pulse to trigPin
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin, returns the sound wave travel time in microseconds
  long duration = pulseIn(echoPin, HIGH);

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

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

  delay(500); // Wait before next measurement
}
💻

Example

This example code measures distance using the HC-SR04 sensor and prints it to the Serial Monitor every half second. It demonstrates how to trigger the sensor, read the echo time, and convert it to centimeters.

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

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

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

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

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

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

  delay(500);
}
Output
Distance: 15.23 cm Distance: 15.10 cm Distance: 15.30 cm Distance: 15.25 cm Distance: 15.20 cm
⚠️

Common Pitfalls

  • Incorrect wiring: Mixing up Trig and Echo pins will cause no readings or wrong values.
  • Not setting pin modes: Forgetting pinMode for Trig and Echo pins can cause the sensor to not work.
  • Not clearing Trig pin before pulse: Always set Trig LOW before sending the HIGH pulse to avoid false triggers.
  • Ignoring maximum range: The sensor has a max range (~400 cm); readings beyond this may be unreliable.
  • Using pulseIn without timeout: It can block if no echo is received; consider adding a timeout to avoid freezing.
arduino
/* Wrong way: Missing pinMode and no clearing trigPin */
const int trigPin = 9;
const int echoPin = 10;

void setup() {
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, HIGH); // Wrong: no pinMode and no LOW before HIGH
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

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

  Serial.println(distance);
  delay(500);
}

/* Right way: */

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

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

  long duration = pulseIn(echoPin, HIGH, 30000); // 30ms timeout
  if (duration == 0) {
    Serial.println("Out of range");
  } else {
    float distance = duration * 0.034 / 2;
    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}
📊

Quick Reference

ParameterDescription
Trig PinOutput pin to send ultrasonic pulse
Echo PinInput pin to receive reflected pulse
Pulse DurationTime in microseconds for echo to return
Distance Calculationdistance = (duration / 2) * 0.034 cm
Max RangeAbout 400 cm (4 meters)
TimeoutUse pulseIn timeout to avoid blocking

Key Takeaways

Connect HC-SR04 Trig to Arduino output and Echo to input pins correctly.
Send a 10µs pulse on Trig and measure echo pulse duration with pulseIn.
Calculate distance using duration and speed of sound formula.
Always clear Trig pin before sending pulse to avoid false readings.
Use pulseIn timeout to prevent your program from freezing if no echo returns.