How to use ultrasonic sensor with Arduino?
Publish Time: 2021-07-26 Origin: Site
How to Use Ultrasonic Sensor with Arduino: HC-SR04 Guide
The HC-SR04 ultrasonic sensor is one of the most popular distance measurement modules for Arduino projects. It is widely used in obstacle avoidance robots, parking sensors, level detection, smart trash bins, distance meters, and other non-contact sensing applications.
The module emits 40kHz ultrasonic waves through a transmitter. When the sound wave meets an object, it reflects back to the receiver. By measuring the echo time and using the speed of sound, Arduino can calculate the distance between the sensor and the object.
HC-SR04 Main Technical Parameters
| Parameter | Value |
| Typical working voltage | 5V DC |
| Static working current | Less than 5mA on some module versions |
| Operating frequency | 40kHz ultrasonic wave |
| Detection distance | Common range: 2cm to 400cm; some gain-adjusted versions may support longer range. |
| Detection angle | Usually within 15 degrees; some versions with higher gain may reach about 30 degrees. |
| Precision | Up to about 0.3cm under suitable test conditions |
| Blind zone | About 2cm minimum measuring distance |
HC-SR04 Pin Description
The HC-SR04 ultrasonic module has four pins: VCC, TRIG, ECHO, and GND. Arduino sends a short trigger pulse to the TRIG pin, then reads the return pulse from the ECHO pin.
| HC-SR04 Pin | Arduino Connection | Function |
| VCC | 5V | Power supply for the ultrasonic module. |
| TRIG | Digital pin 9 | Trigger input. Arduino applies a 10us pulse to start ranging. |
| ECHO | Digital pin 10 | Echo output. Arduino reads pulse width to calculate distance. |
| GND | GND | Ground connection. |
Working Principle of HC-SR04 Ultrasonic Sensor
The HC-SR04 works by time-of-flight measurement. Arduino sends a high-level trigger signal of at least 10 microseconds to the TRIG pin. The module then automatically sends eight 40kHz ultrasonic pulses and waits for the reflected echo.
When the reflected ultrasonic signal is detected, the ECHO pin outputs a high-level pulse. The duration of this pulse is the round-trip travel time of the ultrasonic wave.
Distance = Echo high-level time × Speed of sound / 2
In Arduino code, the common simplified formula is:
Distance in cm = duration × 0.0343 / 2
HC-SR04 Ultrasonic Module Timing Diagram
The timing process is simple: Arduino keeps TRIG low briefly, sends a 10us high pulse, then returns TRIG to low. The HC-SR04 sends an ultrasonic burst and sets ECHO high until the reflected signal returns or the measurement times out.
To avoid unstable readings, leave a short delay between measurements. A measurement cycle of about 60ms is commonly used so the previous ultrasonic echo has time to disappear before the next trigger.
Arduino Programming Basics: pulseIn Function
The Arduino pulseIn() function is used to measure how long a digital pin stays HIGH or LOW. For HC-SR04, Arduino uses pulseIn(echoPin, HIGH) to read the high-level pulse width from the ECHO pin.
| Syntax | Meaning |
| pulseIn(pin, value) | Reads the duration of a HIGH or LOW pulse. |
| pulseIn(pin, value, timeout) | Reads the pulse with a timeout value in microseconds. |
Using a timeout is recommended. If no echo is returned, the function can stop waiting and return 0 instead of blocking the program for too long.
How to Connect HC-SR04 Ultrasonic Sensor to Arduino
The wiring is straightforward. Connect VCC to 5V, GND to GND, TRIG to an Arduino digital output pin, and ECHO to an Arduino digital input pin. The following example uses Arduino Uno, TRIG on pin 9, and ECHO on pin 10.
HC-SR04 Ultrasonic Sensor Arduino Code
The following typical Arduino program sends a 10us trigger pulse, reads the ECHO pulse width, calculates distance in centimeters, and prints the result in the Serial Monitor.
const int trigPin = 9;
const int echoPin = 10;
long duration;
float distanceCm;
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);
duration = pulseIn(echoPin, HIGH, 30000);
if (duration == 0) {
Serial.println("Out of range");
} else {
distanceCm = duration * 0.0343 / 2;
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
}
delay(60);
}
If you see distance values in the Serial Monitor, the HC-SR04 ultrasonic sensor and Arduino wiring are working correctly. You can then use the distance data for obstacle detection, robot movement control, automatic doors, parking reminders, or liquid level projects.
How to Improve HC-SR04 Measurement Accuracy
Keep the measured object within the recommended distance range and outside the 2cm blind zone.
Use a flat and solid target surface for better ultrasonic reflection.
Avoid measuring soft, angled, porous, or sound-absorbing materials.
Use a stable 5V power supply and keep wiring short and secure.
Add a timeout to pulseIn() to prevent long blocking when no echo returns.
Average or median-filter several readings to reduce noise.
For higher accuracy, compensate for temperature because sound speed changes with air temperature.
Common Applications of Arduino Ultrasonic Sensor Projects
| Application | How HC-SR04 Is Used |
| Obstacle avoidance robot | Detects nearby objects and helps the robot change direction. |
| Parking distance sensor | Measures distance between the vehicle and an obstacle. |
| Liquid level detection | Measures the distance from the sensor to the liquid surface without contact. |
| Smart trash bin | Detects a nearby hand or object and triggers automatic lid opening. |
Summary
To use an HC-SR04 ultrasonic sensor with Arduino, connect VCC to 5V, GND to GND, TRIG to a digital output pin, and ECHO to a digital input pin. Send a 10us trigger pulse, read the echo duration with pulseIn(), and calculate distance with the time-of-flight formula.
The HC-SR04 is inexpensive, easy to use, and suitable for many Arduino distance measurement projects. For best results, pay attention to target surface, measuring angle, blind zone, stable power, timeout handling, and temperature effects.
Frequently Asked Questions About HC-SR04 Arduino Ultrasonic Sensor
How does the HC-SR04 ultrasonic sensor work with Arduino?
Arduino sends a 10us pulse to the TRIG pin. The HC-SR04 emits eight 40kHz ultrasonic pulses and sets the ECHO pin high until the reflected sound returns. Arduino measures this pulse time and calculates distance.
What is the distance formula for HC-SR04 Arduino projects?
The formula is distance = duration × speed of sound / 2. In centimeters, a common Arduino formula is distanceCm = duration × 0.0343 / 2, where duration is measured in microseconds.
Why do we divide the ultrasonic sensor result by 2?
The measured echo time is the round-trip time from the sensor to the object and back to the sensor. Dividing by 2 gives the one-way distance between the sensor and the object.
Which Arduino pins should I use for TRIG and ECHO?
You can use most Arduino digital pins. In many examples, TRIG is connected to digital pin 9 and ECHO is connected to digital pin 10. The code must match the pins used in your wiring.
Why does my HC-SR04 ultrasonic sensor return zero or random values?
Common causes include loose wiring, unstable 5V power, wrong TRIG or ECHO pin numbers, no object in range, angled target surfaces, soft materials, blocked sensor heads, or no timeout in the pulseIn() function.
What is the blind zone of the HC-SR04 ultrasonic sensor?
The blind zone is the minimum distance where the module cannot measure reliably. For HC-SR04, the blind zone is usually about 2cm. Objects closer than this may produce unstable readings.
Can HC-SR04 measure water level with Arduino?
Yes, HC-SR04 can be used for simple non-contact water level projects if the sensor is protected from moisture and mounted above the liquid surface. For humid, outdoor, or industrial tanks, a waterproof ultrasonic sensor is recommended.
How can I make Arduino ultrasonic sensor readings more stable?
Use a stable power supply, keep the sensor perpendicular to the target, avoid soft or angled surfaces, add pulseIn timeout, take multiple readings, use median filtering, and allow about 60ms between measurements.