Arduino初學者,學習如何使用超聲波模組。

Arduino STEM DIY (Session 3): Build an Ultrasonic Distance Sensor with HC-SR04 (2026)

Want to measure the distance between an object and an Arduino? In this beginner-friendly project, we will use an Arduino Uno R3 and an HC-SR04 ultrasonic sensor to build a simple distance-measuring system with an LED indicator.

You will learn how ultrasonic distance measurement works, how to read echo timing, how to calculate distance in centimetres, and how to use an if statement to control an LED based on the measured distance.

What you will learn

  • Understand the basic working principle of the HC-SR04 ultrasonic sensor
  • Send a trigger signal and read the echo pulse
  • Calculate distance using sound travel time
  • Use conditional statements to control an LED
  • Understand basic measurement limitations and troubleshooting

Suitable for: Arduino beginners, parents and children, students, and makers
Estimated time: 30–45 minutes, depending on age and experience
Difficulty: Beginner
Tools required: Computer, USB cable, and basic electronic prototyping accessories

1. Components Required

Prepare the following components before starting:

  1. Arduino Uno R3 — Runs the program and controls the LED.
  2. HC-SR04 ultrasonic sensor — Sends ultrasonic waves and receives reflected echoes.
  3. LED — Indicates the result of the distance check.
  4. 220Ω resistor — Limits the current flowing through the LED.
  5. Breadboard and jumper wires — Allow solderless prototyping.
  6. USB cable and computer — Used to upload the program and view distance readings.

Product links:

Before wiring: The Arduino Uno R3 uses 5V logic on its digital pins. The wiring and code in this tutorial are intended for a typical HC-SR04 module connected to an Arduino Uno R3. Check the voltage and wiring requirements if you use a different sensor model.

2. How Does the HC-SR04 Measure Distance?

The HC-SR04 is a common ultrasonic distance sensor. Its two round transducers are used to transmit and receive ultrasonic waves.

The basic process is:

  1. The Arduino sends a short trigger pulse to the Trig pin.
  2. The sensor emits an ultrasonic wave.
  3. The wave reflects off an object.
  4. The sensor outputs an echo signal through the Echo pin.
  5. The Arduino measures the echo duration and calculates the estimated distance.

Because the sound travels to the object and back, the measured travel time must be divided by two.

Distance (cm) = Echo duration (μs) × 0.0343 ÷ 2

The value 0.0343 represents the approximate speed of sound in air at around 20°C, expressed in centimetres per microsecond. Actual readings can vary with temperature, surface material, object angle, and environmental conditions.

3. Arduino Wiring

Arduino初學者,學習如何使用超聲波模組,了解如何運作。

In this project, we will use D9 for the Trig signal, D10 for the Echo signal, and D13 to control the external LED.

HC-SR04 Wiring

HC-SR04 Pin Arduino Uno R3
VCC 5V
GND GND
Trig D9
Echo D10

LED Wiring

LED / Component Connection
Arduino D13 Connect to a 220Ω resistor
Other end of resistor LED anode (long leg)
LED cathode (short leg) GND

This is a standard active-high LED connection: the LED turns on when D13 is HIGH and turns off when D13 is LOW.

Wiring tips

  • The LED's longer leg is usually the anode, and the shorter leg is usually the cathode.
  • Connect the 220Ω resistor in series with the LED to limit current.
  • The sensor and LED circuit must share a common GND with the Arduino.
  • Disconnect USB power before wiring. Reconnect it only after checking all connections.

4. Complete Arduino Code

Copy the following code into the Arduino IDE. Select the correct board and port, then upload the program to your Arduino Uno R3.

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

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  long duration;
  float distance;

  // Send the ultrasonic trigger pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

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

  // Read the Echo pulse duration
  // Wait for up to 30,000 microseconds
  duration = pulseIn(echoPin, HIGH, 30000UL);

  if (duration == 0) {
    // No valid echo received
    Serial.println("No echo - please check sensor or target.");

    // Turn off the LED when there is no valid reading
    digitalWrite(ledPin, LOW);
  } else {
    // Calculate distance in centimetres
    distance = duration * 0.0343 / 2;

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

    // Turn off the LED when the distance is less than 10 cm
    if (distance < 10) {
      digitalWrite(ledPin, LOW);
    } else {
      // Turn on the LED at 10 cm or more
      digitalWrite(ledPin, HIGH);
    }
  }

  delay(200);
}

Code Explanation

1. Define the pins

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

D9 sends the trigger signal, D10 reads the echo signal, and D13 controls the LED.

2. Send the trigger pulse

digitalWrite(trigPin, LOW);
delayMicroseconds(2);

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

The Arduino first sets Trig to LOW, then sends a HIGH pulse lasting approximately 10 microseconds to start a measurement.

3. Read the echo duration

duration = pulseIn(echoPin, HIGH, 30000UL);

pulseIn() measures how long the Echo signal stays HIGH. The timeout is set to 30,000 microseconds. If no valid echo is received within this period, the function returns 0.

4. Calculate the distance

distance = duration * 0.0343 / 2;

The program uses the echo duration and the approximate speed of sound to calculate the distance. It divides the result by two because the sound travels to the object and then returns to the sensor.

5. Control the LED

if (distance < 10) {
  digitalWrite(ledPin, LOW);
} else {
  digitalWrite(ledPin, HIGH);
}

With the LED wiring described in this tutorial:

  • Distance below 10 cm: D13 is LOW, so the LED turns off.
  • Distance of 10 cm or more: D13 is HIGH, so the LED turns on.

The 10 cm threshold is a value chosen for this demonstration. It is not a fixed threshold built into the HC-SR04.

If no valid echo is received, the program displays a message and turns off the LED rather than treating the missing reading as a valid distance.

 

5. How to Test the Project

After completing the wiring and uploading the program:

  1. Open the Serial Monitor in the Arduino IDE.
  2. Set the baud rate to 9600 baud.
  3. Place a flat object approximately 20 cm in front of the sensor.
  4. Check the displayed distance and the LED status.
  5. Slowly move the object closer to the sensor.
  6. When the measured distance falls below 10 cm, the LED should turn off.
  7. Move the object back to 10 cm or farther away. The LED should turn on again.

Expected Results

Test Condition Serial Monitor LED Status
Object approximately 20 cm away Shows around 20 cm; readings may vary On
Object approximately 12 cm away Shows around 12 cm; readings may vary On
Object approximately 8 cm away Shows around 8 cm; readings may vary Off
No valid echo received Shows a No echo message Off

Actual readings may vary depending on the object, angle, environment, and sensor. Small differences between readings are normal.

6. Troubleshooting and FAQs

1. Nothing appears in the Serial Monitor. What should I do?

Check that:

  • The correct board and port are selected in the Arduino IDE.
  • The Serial Monitor is set to 9600 baud.
  • The program has uploaded successfully.
  • Your USB cable supports data transfer, not just charging.

2. The program keeps showing “No echo”. What should I check?

Check the VCC, GND, Trig, and Echo connections. Place a flat object in front of the sensor and avoid holding it at an extreme angle.

If the problem continues, check the jumper wires and confirm that the sensor is functioning correctly.

3. The LED behaves opposite to what I expected. Why?

Check the LED wiring first. This tutorial uses a standard active-high connection: the LED turns on when D13 is HIGH and turns off when D13 is LOW.

Different circuit arrangements may reverse the LED's behaviour, so the program may need to be adjusted accordingly.

4. Why do the distance readings fluctuate?

Ultrasonic readings can be affected by the object's surface, reflection angle, nearby objects, and air temperature. Use a flat target, avoid extreme angles, and keep the sensor steady.

For more stable readings, you can experiment with taking multiple measurements and calculating an average.

5. Can the HC-SR04 measure every type of object?

Reliable readings are not guaranteed for every object. Soft, sound-absorbing, irregular, or angled surfaces may produce weak echoes or reflect sound away from the sensor.

6. Why does the LED turn off when the distance is below 10 cm?

This is intentional. When the distance is below 10 cm, the program sets D13 to LOW. With the LED wiring in this tutorial, LOW means the LED is off.

At 10 cm or more, D13 is set to HIGH, so the LED turns on.

7. Does no echo mean the object is closer than 10 cm?

No. A missing echo may be caused by an unsuitable surface, an angled target, poor wiring, or a sensor problem.

This tutorial handles missing echoes separately and displays a message instead of treating them as valid distance readings.

8. Can I use this project as a car parking sensor?

This project is a useful learning prototype for distance-based control. However, a single HC-SR04 and a simple Arduino program are not a reliable automotive parking safety system. Real-world parking or safety-related applications require additional consideration of sensor limitations, fault handling, and overall system reliability.

7. STEM DIY Extension Challenges

After completing the basic project, try these extensions:

Challenge A: Change the distance threshold

Change 10 in the code to 15 or 20 and observe how the LED's switching distance changes.

Challenge B: Add a buzzer

Add a suitable buzzer to provide an audible alert when an object enters the selected distance range. Check the buzzer type and wiring requirements first.

Challenge C: Display the distance

Add an LCD or OLED display to show the measured distance directly on a screen.

Challenge D: Improve measurement stability

Take several measurements and calculate the average to reduce the effect of individual reading variations.

These challenges help learners explore sensors, conditional logic, data processing, and electronic outputs.

8. Conclusion

In this project, we used an Arduino Uno R3 and an HC-SR04 ultrasonic sensor to build a simple distance-measuring system. You learned how to send a trigger signal, measure echo duration, calculate distance, and control an LED based on the result.

This project demonstrates how sensor data can be converted into an actual control response, making it a useful starting point for learning automation, robotics, and STEM DIY.

Looking for Arduino boards, ultrasonic sensors, or other STEM DIY accessories? Browse our Arduino collection:

Browse Arduino Boards, Sensors and STEM DIY Accessories

Sun Cheong Computer Company Limited
G/F, 246 Apliu Street, Sham Shui Po, Kowloon, Hong Kong
Arduino, electronic components, sensors, and technical accessories.


Back to blog