Inquire: Call 0086-755-23203480, or reach out via the form below/your sales contact to discuss our design, manufacturing, and assembly capabilities.
Quote: Email your PCB files to Sales@pcbsync.com (Preferred for large files) or submit online. We will contact you promptly. Please ensure your email is correct.
Notes: For PCB fabrication, we require PCB design file in Gerber RS-274X format (most preferred), *.PCB/DDB (Protel, inform your program version) format or *.BRD (Eagle) format. For PCB assembly, we require PCB design file in above mentioned format, drilling file and BOM. Click to download BOM template To avoid file missing, please include all files into one folder and compress it into .zip or .rar format.
HC-SR04 Ultrasonic Sensor Arduino: Complete Tutorial for Distance Measurement
After incorporating ultrasonic sensors into countless robotics and automation projects, I can confidently say the HC-SR04 ultrasonic sensor Arduino combination remains the gold standard for affordable, reliable distance measurement. This sensor has earned its reputation through years of proven performance in everything from simple proximity detectors to sophisticated obstacle-avoidance robots.
Whether you’re building your first distance-measuring project or looking to optimize an existing design, this comprehensive tutorial covers the HC-SR04 from fundamental principles through advanced implementation techniques. I’ll share practical insights from real-world applications that you won’t find in basic tutorials, including noise reduction strategies and accuracy improvements that make the difference between a working prototype and a reliable finished product.
What is the HC-SR04 Ultrasonic Sensor
The HC-SR04 is a non-contact distance measurement module that uses ultrasonic sound waves to determine the distance to objects. At its core, the sensor contains two piezoelectric transducers: one transmitter that converts electrical signals into 40 kHz ultrasonic pulses, and one receiver that detects the returning echoes.
The operating principle mirrors sonar systems used in submarines and the echolocation abilities of bats. When triggered, the sensor emits a burst of ultrasonic waves that travel through air, bounce off objects, and return to the receiver. By measuring the time between transmission and reception, your Arduino calculates the precise distance to the target.
What makes the HC-SR04 particularly appealing for hobbyist and professional projects alike is its exceptional price-to-performance ratio. For just a few dollars, you get a sensor capable of measuring distances from 2cm to 400cm with approximately 3mm accuracy. This performance level would have cost significantly more just a decade ago.
How Ultrasonic Distance Measurement Works
The physics behind ultrasonic ranging is elegantly simple. Sound travels through air at approximately 343 meters per second at room temperature (20°C). When the HC-SR04 emits an ultrasonic pulse and that pulse reflects off an object, the total travel time represents twice the distance to the target (out and back).
The distance formula becomes:
Distance = (Time × Speed of Sound) ÷ 2
For practical Arduino calculations, since we measure time in microseconds and want distance in centimeters:
Distance (cm) = Time (µs) × 0.0343 ÷ 2
Or simplified:
Distance (cm) = Time (µs) × 0.01715
Understanding this relationship helps when troubleshooting accuracy issues or compensating for temperature variations, which we’ll cover later.
HC-SR04 Ultrasonic Sensor Arduino Specifications
Knowing the technical specifications helps you design appropriate circuits and set realistic expectations for your projects. Here are the key parameters from the datasheet:
Parameter
Specification
Operating Voltage
5V DC
Operating Current
15 mA
Operating Frequency
40 kHz
Measuring Range
2 cm to 400 cm
Ranging Accuracy
±3 mm
Measuring Angle
< 15°
Trigger Input Signal
10 µs TTL pulse
Echo Output Signal
TTL pulse proportional to distance
Dimensions
45 mm × 20 mm × 15 mm
HC-SR04 Pinout Configuration
The HC-SR04 features a straightforward 4-pin interface that makes integration with any microcontroller simple:
Pin
Name
Function
1
VCC
5V Power Supply
2
Trig
Trigger Input (initiate measurement)
3
Echo
Echo Output (pulse width = travel time)
4
GND
Ground
The pin header uses standard 2.54mm spacing, making it breadboard-compatible for prototyping. When designing a PCB, maintain adequate clearance around the transducers to prevent acoustic interference from nearby components.
Understanding the HC-SR04 Timing Sequence
The measurement cycle follows a precise timing sequence that your Arduino code must respect for reliable readings.
Step-by-Step Measurement Process
Step 1: Trigger Pulse Send a HIGH signal to the Trig pin for at least 10 microseconds, then return it to LOW. This tells the sensor to begin a measurement.
Step 2: Ultrasonic Burst The sensor automatically transmits eight 40 kHz ultrasonic pulses. You don’t control this directly; it happens internally after the trigger.
Step 3: Echo Detection The Echo pin goes HIGH immediately after transmission begins. It remains HIGH until the sensor detects the returning echo or times out.
Step 4: Calculate Distance Measure how long the Echo pin stays HIGH (in microseconds). Apply the distance formula to convert this time to distance.
Timing Parameter
Duration
Minimum Trigger Pulse
10 µs
Ultrasonic Burst
8 cycles at 40 kHz (200 µs)
Maximum Echo Time
~38 ms (corresponds to ~6.5m)
Recommended Measurement Interval
≥60 ms
The 60ms minimum interval between measurements prevents interference from lingering echoes. In my experience, using 100ms intervals provides more consistent readings, especially in enclosed spaces where sound can bounce around.
Wiring the HC-SR04 to Arduino
The hardware setup is refreshingly simple. Here’s how to connect the HC-SR04 ultrasonic sensor Arduino circuit:
HC-SR04 Pin
Arduino Uno
Arduino Mega
Arduino Nano
VCC
5V
5V
5V
Trig
Pin 9
Pin 9
Pin 9
Echo
Pin 10
Pin 10
Pin 10
GND
GND
GND
GND
You can use any digital pins for Trig and Echo; pins 9 and 10 are simply convenient choices. Some advanced implementations use a single pin for both trigger and echo by connecting a 2.2kΩ resistor between them, but the standard 4-wire configuration is more reliable for beginners.
Wiring Best Practices
From my PCB design experience, a few wiring practices significantly improve reliability:
Keep the power supply clean. The HC-SR04 draws current spikes during transmission that can cause voltage dips. Adding a 100µF electrolytic capacitor across VCC and GND near the sensor smooths these transients.
Use short, direct wires. Long cables act as antennas, picking up electrical noise that corrupts the Echo signal. For runs longer than 30cm, consider using shielded cable or twisted pairs.
Position the sensor carefully. Mount it perpendicular to the surface you’re measuring and away from corners or reflective surfaces that could cause false echoes.
Basic HC-SR04 Arduino Code Without Library
Understanding the raw implementation helps you appreciate what libraries do and allows customization when needed. Here’s a complete sketch that measures distance without external libraries:
// HC-SR04 Ultrasonic Sensor Arduino
// Basic example without library
const int trigPin = 9;
const int echoPin = 10;
long duration;
float distance;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send 10 microsecond trigger pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin, returns pulse duration in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate distance in centimeters
distance = duration * 0.0343 / 2;
// Print results
Serial.print(“Distance: “);
Serial.print(distance);
Serial.println(” cm”);
delay(100);
}
The pulseIn() function does the heavy lifting, measuring how long the Echo pin stays HIGH. The default timeout is 1 second, which can cause noticeable delays if no echo returns. For faster response in robotics applications, specify a shorter timeout:
While manual coding works fine, the NewPing library by Tim Eckel offers significant advantages that make it my go-to choice for most HC-SR04 ultrasonic sensor Arduino projects.
Why Use NewPing?
No lag on failed readings: Unlike pulseIn(), NewPing doesn’t wait a full second when no echo returns. This keeps your robot responsive even when pointing at the sky.
Built-in median filtering: The ping_median() function takes multiple readings and returns the middle value, eliminating outliers and improving accuracy.
Efficient code: The library uses direct port manipulation for faster, more precise timing than standard Arduino functions.
Multi-sensor support: Manage multiple ultrasonic sensors easily without code duplication.
Installing NewPing Library
Open Arduino IDE
Go to Sketch → Include Library → Manage Libraries
Search for “NewPing”
Click Install on the library by Tim Eckel
HC-SR04 Arduino Code with NewPing
// HC-SR04 Ultrasonic Sensor Arduino with NewPing Library
#include <NewPing.h>
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 400 // Maximum distance in cm
unsigned int distance = sonar.ping_median(5) / US_ROUNDTRIP_CM;
This takes 5 measurements, discards outliers, and returns the median value, dramatically improving reliability in noisy environments.
Improving HC-SR04 Measurement Accuracy
The datasheet claims ±3mm accuracy, but achieving this in practice requires attention to several factors that can degrade performance.
Temperature Compensation
Sound speed varies with temperature, approximately 0.6 m/s per degree Celsius. At 20°C, sound travels at 343 m/s, but at 0°C it’s only 331 m/s. This 4% difference translates to 4cm error at 1 meter distance.
For precision applications, add a temperature sensor like the DHT22 or DS18B20 and compensate:
// Calculate speed of sound based on temperature
float speedOfSound = 331.4 + (0.6 * temperature); // m/s
Even in ideal conditions, individual readings fluctuate. Implementing a simple moving average filter smooths the output:
#define SAMPLES 5
float readings[SAMPLES];
int readIndex = 0;
float total = 0;
float getFilteredDistance() {
total -= readings[readIndex];
readings[readIndex] = sonar.ping_cm();
total += readings[readIndex];
readIndex = (readIndex + 1) % SAMPLES;
return total / SAMPLES;
}
Optimal Mounting Position
Sensor orientation dramatically affects accuracy. Mount the HC-SR04 so the transducers face directly toward the target. The 15° beam angle means objects at steep angles may not reflect sound back to the receiver.
Avoid mounting near walls or inside enclosures where secondary reflections create false readings. If you must use an enclosure, ensure the opening around the transducers is acoustically transparent.
HC-SR04 Limitations and Workarounds
Understanding the sensor’s limitations helps you design around them rather than fighting unexpected behavior.
Detection Challenges
Scenario
Problem
Solution
Soft/fabric objects
Sound absorption, weak echo
Use shorter range, higher sensitivity
Angled surfaces
Sound reflects away
Multiple sensors at different angles
Very close objects
Minimum 2cm range
Use capacitive sensors for <2cm
Small objects
Insufficient reflection
Increase object size or use IR sensor
Multiple objects
Nearest object detected only
Accept limitation or use multiple sensors
Environmental Factors
The HC-SR04 performs poorly in certain conditions:
High humidity: Water droplets can scatter ultrasonic waves, reducing range and accuracy.
Wind: Air movement deflects sound waves, causing erratic readings outdoors.
Extreme temperatures: Performance degrades below -10°C and above 60°C.
Acoustic noise: Loud environments at 40 kHz (rare) can interfere with detection.
For outdoor or harsh environments, consider the waterproof JSN-SR04T variant, which offers similar functionality in a sealed housing.
Practical HC-SR04 Arduino Projects
The HC-SR04 ultrasonic sensor Arduino combination enables countless practical applications:
Obstacle-Avoiding Robot: Mount sensors on the front and sides to detect walls and navigate autonomously. The fast response time allows real-time path adjustment.
Parking Sensor: Replicate commercial parking assist systems with visual LED indicators and audible warnings that increase in frequency as distance decreases.
Liquid Level Monitor: Measure tank fill levels from above without contact. The sensor works well with water surfaces when mounted vertically.
Security System: Detect intruders by monitoring zones for distance changes. Combine with alarm outputs for a complete security solution.
Height Measurement: Create a digital measuring station by mounting the sensor above a platform and calculating height from the difference.
Automatic Door Opener: Trigger door mechanisms when someone approaches within a set distance.
Using Multiple HC-SR04 Sensors
Complex projects often require multiple sensors for comprehensive coverage. The main challenge is preventing crosstalk, where one sensor’s transmission triggers another sensor’s receiver.
Sequential Triggering Method
The simplest approach triggers sensors one at a time with adequate delay between readings:
The 50ms delay between sensors allows echoes to dissipate before the next measurement. In acoustically reflective environments, increase this to 100ms.
Troubleshooting Common HC-SR04 Problems
Over years of working with these sensors, I’ve encountered most failure modes. Here are solutions to the most common issues:
Sensor Returns Zero or Maximum Distance
Possible causes:
Incorrect wiring (Trig and Echo swapped)
Inadequate trigger pulse duration
Target outside measurement range
Defective sensor
Solutions:
Verify wiring matches your code
Ensure trigger pulse is at least 10µs
Test with a solid object at 30cm distance
Try a different sensor to rule out hardware failure
Readings Fluctuate Wildly
Possible causes:
Electrical noise on power supply
Interference from other electronics
Unstable target or sensor mounting
Multiple reflections in enclosed space
Solutions:
Add 100µF capacitor across VCC and GND
Keep sensor wires away from motors and switching power supplies
Secure sensor mounting firmly
Implement software filtering (median or moving average)
Readings Consistently High or Low
Possible causes:
Speed of sound assumption incorrect for temperature
Code calculation error
Sensor calibration drift
Solutions:
Implement temperature compensation
Verify formula: distance = duration × 0.0343 / 2
Measure known distance and apply offset correction
JSN-SR04T: Waterproof version for outdoor/liquid applications
US-100: Includes temperature compensation and serial output
VL53L0X: Laser-based alternative for higher precision
HC-SR04 Ultrasonic Sensor Arduino FAQs
What is the maximum range of the HC-SR04 sensor?
The datasheet specifies 400cm (about 13 feet), but in practice, reliable detection typically maxes out around 200-300cm depending on the target size and surface characteristics. Large, flat, hard surfaces reflect ultrasound better than small, soft, or angled objects. For distances beyond 2 meters, verify detection reliability with your specific target before committing to a design.
Can the HC-SR04 detect transparent objects like glass?
Yes, the HC-SR04 detects glass and other transparent materials effectively because ultrasonic waves reflect off physical surfaces regardless of optical properties. This is actually an advantage over infrared sensors, which can pass through transparent materials. However, very thin glass might allow some sound through, reducing echo strength.
Why does my HC-SR04 give inconsistent readings?
Inconsistent readings typically stem from electrical noise, inadequate delays between measurements, or environmental factors. Start troubleshooting by adding a 100µF capacitor across the sensor’s power pins and implementing software filtering. Ensure at least 60ms between measurements, and check that no other electronics are creating electromagnetic interference near the sensor.
Can I use the HC-SR04 with 3.3V Arduino boards like the Due or ESP32?
The HC-SR04 requires 5V for the VCC pin to function properly. However, the Echo output is 5V TTL, which can damage 3.3V inputs. Use a logic level converter or voltage divider on the Echo line when interfacing with 3.3V microcontrollers. Alternatively, use the HC-SR04P variant specifically designed for 3.3V-5V operation.
How do I measure distance to water or other liquids?
The HC-SR04 can measure liquid levels when mounted above the surface pointing downward. The ultrasonic waves reflect off the water surface effectively. For submersible applications or outdoor use where moisture is a concern, use the waterproof JSN-SR04T variant instead. Mount the sensor perpendicular to the water surface and account for any ripples or waves that might cause reading variations.
Conclusion
The HC-SR04 ultrasonic sensor Arduino pairing delivers exceptional value for distance measurement applications. Its simplicity, accuracy, and rock-bottom cost have made it the default choice for makers and engineers worldwide. Understanding the underlying principles, proper wiring techniques, and software optimization strategies transforms this basic sensor into a reliable measurement tool suitable for everything from weekend projects to professional prototypes.
Start with the basic code to understand the fundamentals, then graduate to the NewPing library for production applications. Pay attention to mounting, filtering, and environmental factors, and you’ll achieve the consistent, accurate measurements that make your projects truly impressive.
The sensor’s limitations are real but manageable with proper design considerations. For applications pushing beyond its capabilities, alternatives exist, but for the vast majority of distance-sensing needs, the HC-SR04 remains the sensor I reach for first.
Inquire: Call 0086-755-23203480, or reach out via the form below/your sales contact to discuss our design, manufacturing, and assembly capabilities.
Quote: Email your PCB files to Sales@pcbsync.com (Preferred for large files) or submit online. We will contact you promptly. Please ensure your email is correct.
Notes: For PCB fabrication, we require PCB design file in Gerber RS-274X format (most preferred), *.PCB/DDB (Protel, inform your program version) format or *.BRD (Eagle) format. For PCB assembly, we require PCB design file in above mentioned format, drilling file and BOM. Click to download BOM template To avoid file missing, please include all files into one folder and compress it into .zip or .rar format.