Contents
In embedded development, enabling a device to perceive the distance to its surrounding environment is a very fundamental yet extremely critical capability. Ultrasonic ranging plays a vital role across a wide range of fields, including robot obstacle avoidance, autonomous driving, liquid level detection, and smart home applications. An ultrasonic module calculates the distance to an object by transmitting sound waves and receiving the reflected echoes, leveraging the time difference in the propagation of the sound waves.
This chapter will guide you to learn how to use the ultrasonic ranging module (HC-SR04) for distance measurement. We will delve into the working principle of the module, hardware connection, as well as how to perform simple programming control via ESP32 to read and calculate the measured distance. Through the study of this chapter, you will master how to utilize ultrasonic technology in practical projects to achieve accurate object detection and distance measurement.
1. Ultrasonic Ranging
An ultrasonic module is an electronic component commonly used in applications such as distance measurement, positioning, and obstacle avoidance. By transmitting and receiving ultrasonic waves, and utilizing the time difference and the propagation speed of sound, the distance from the module to the obstacle ahead can be calculated.

2. Module Workflow
SR04 ultrasonic module is a sensor that uses the characteristics of ultrasonic waves to detect distance. It is equipped with two ultrasonic probes, which are used to transmit and receive ultrasonic waves respectively, and its measurement range is 2 to 400 meters.

The ultrasonic transmitter first emits ultrasonic waves in a specific direction and starts timing simultaneously with the transmission.
Ultrasonic waves propagate in air at a speed of 340 m/s and will return immediately upon encountering an obstacle along the path.
The ultrasonic receiver stops timing upon receiving the reflected wave;
Based on the time recorded by the timer, we can calculate the distance between the launch point and the obstacle: s = 340 (m/s) ×(t/2).

The working principle of the ultrasonic module is a closed-loop process of "transmission-reception-timing-calculation". By measuring the flight time of the ultrasonic wave from transmission to reception and combining it with the speed of sound in the environment, it finally calculates the distance to the target object. As a non-contact, low-cost and reliable distance measurement solution, it is widely used in fields such as robot obstacle avoidance, liquid level detection, drone altitude stabilization, and smart home systems.
3. Module Pins

The HC-SR04 module has 4 pins:
- VCC: Connect to the 3.3V (or 5V, depending on the voltage supported by the module, typically 5V) pin of the ESP32
- GND: Connect to the GND pin of the ESP32.
- Trig: Trigger pin, connected to a digital output pin of the ESP32.
- Echo: Echo pin, connected to a digital input pin of the ESP32.
4. Module Usage Instructions

- Trigger Signal: The ESP32 sends a high level of at least 10µs to the Trig pin of the ultrasonic module to trigger the distance measurement function of the SR04.
- Ultrasonic wave transmission: After the ranging function of the SR04 is triggered, the module automatically transmits 8 40kHz ultrasonic pulses in the air and automatically detects whether there is a returned signal. This step is completed automatically inside the module.
- Receive reflected waves: When ultrasonic waves encounter an obstacle and reflect back, if they are received by the SR04 module, the Echo pin will output a high level, and the duration of this high level is exactly the time elapsed from the transmission of the ultrasonic wave to its return.
- Calculate the distance: Calculate the distance by detecting the time difference between transmission and reception and using the speed of sound formula.
Distance = High level time * Speed of sound (340m/s) / 2
ESP32 → Trig (instructs the module to start distance measurement)
Module → Air (Ultrasonic Emission)
Obstacle → Module (Reflected wave returns)
Module → ESP32 (Echo high level duration)
5. Software Design Example
5.1 Initialize the serial port
At the beginning of the code, we first need to initialize the serial communication in the setup () function, so that we can output the measured distance data to the serial monitor.
Serial.begin(115200);5.2 Configure Pins
Then, we need to configure the Trig and Echo pins as output and input respectively.
// Define pins
#define TRIG_PIN 23 // Trig pin is connected to GPIO 23
#define ECHO_PIN 22 // Echo pin is connected to GPIO 22
// Configure Trig and Echo pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);5.3 Triggered Measurement
Output a 10µs low-level pulse on the Trig pin to trigger ultrasonic transmission.
// Send trigger signal
digitalWrite(TRIG_PIN, LOW); // First set the Trig pin low
delayMicroseconds(2); // Wait 2 microseconds to ensure the level is stable
digitalWrite(TRIG_PIN, HIGH); // Set the Trig pin high
delayMicroseconds(10); // Hold for 10 microseconds to trigger ultrasonic emission
digitalWrite(TRIG_PIN, LOW); // Set the Trig pin low again5.4 Calculate Distance
The Echo pin will remain at a high level after the ultrasonic signal is fully received, and its duration is proportional to the round-trip time of the ultrasonic wave. We can measure the duration for which the Echo pin is at a high level to calculate the distance between the object and the sensor.
Syntax:
pulseIn(pin, value);
pulseIn(pin, value, timeout);
Parameters:
pin: the pin to read the pulse signal from
value: the type of pulse to read: the duration of a HIGH or LOW level. Common choices are:
timeout: optional parameter, timeout in us.
If no pulse is detected within the specified time, the output is 0 // Measure the high-level time of the Echo pin (i.e., the ultrasonic round-trip time)
long duration = pulseIn(ECHO_PIN, HIGH); // Returns the duration of the high-level pulse, in microseconds
// Calculate distance (formula: distance = (time * speed of sound) / 2)
// Speed of sound: 340 m/s = 0.034 cm/μs
float distance = duration * 0.034 / 2;5.5 Overall Code Development
Ultrasonic Module - Wokwi ESP32, STM32, Arduino Simulator
// Define pins
#define TRIG_PIN 23 // Trig pin is connected to GPIO 23
#define ECHO_PIN 22 // Echo pin is connected to GPIO 22
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Configure Trig and Echo pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Send trigger signal
digitalWrite(TRIG_PIN, LOW); // First set the Trig pin low
delayMicroseconds(2); // Wait 2 microseconds to ensure the level is stable
digitalWrite(TRIG_PIN, HIGH); // Set the Trig pin high
delayMicroseconds(10); // Hold for 10 microseconds to trigger ultrasonic emission
digitalWrite(TRIG_PIN, LOW); // Set the Trig pin low again
// Measure the high-level time of the Echo pin (i.e., the ultrasonic round-trip time)
long duration = pulseIn(ECHO_PIN, HIGH); // Returns the duration of the high-level pulse, in microseconds
// Calculate distance (formula: distance = (time * speed of sound) / 2)
// Speed of sound: 340 m/s = 0.034 cm/μs
float distance = duration * 0.034 / 2;
// Print the measured distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait 1 second before the next measurement
delay(1000);
}6. Summary of This Chapter
In this chapter, we learned the basic principle and implementation method of ultrasonic ranging. The ultrasonic module calculates the distance by transmitting sound waves and receiving the reflected waves after they encounter obstacles, based on the relationship between the speed of sound and the propagation time. The HC-SR04 module has two key pins: Trig and Echo. The ESP32 can trigger the measurement by sending a short high-level signal to the Trig pin, while the Echo pin indicates the time taken for the ultrasonic wave to travel back and forth through the duration of the high level. Combined with the corresponding formula, the distance between the obstacle and the sensor can be calculated.
In terms of software design, we use the pulseIn () function to measure the high-level duration of Echo, and then output the converted distance result to the serial monitor.
Through the study of this chapter, we have not only understood the principle of ultrasonic ranging, but also mastered how to drive the sensor and perform data processing on the ESP32.