Imagine giving your Arduino project the superpower to see with sound. That’s basically what the HC-SR04 ultrasonic sensor does! At its core, ultrasonic sensing leverages the principle of echolocation. You might recognize echolocation from our bat friends, who navigate the night skies by emitting sound waves and listening for the echoes bouncing off objects.
What makes the HC-SR04 ultrasonic sensor so cool is its versatility. This sensor is a go-to for a variety of Arduino projects, from measuring distances and detecting obstacles to acting as a proximity sensor. It can help your robot avoid bumping into walls or even help you create a touchless water level indicator. The possibilities are endless, limited only by your imagination and, okay, maybe a bit of your coding skills. But don’t worry, we’ll fix that!
How do Ultrasonic Sensors Work?
The most prominent feature of any ultrasonic sensor module are the two large transducers mounted to the front that look like a set of round eyes. One is a transmitter that sends out ultrasonic sound pulses and the other is a receiver, which listens for those pulses reflecting back when they bounce off an object.
By measuring the time it takes for the waves to return, the sensor can calculate the distance to the object with impressive accuracy. It’s like having a tiny, invisible tape measure that works at the speed of sound!

Ultrasonic Sensor Pinout
- VCC: Powers the HC-SR04 ultrasonic sensor. You can connect it to the 5V output from your Arduino.
- Trig (Trigger): This pin is used to trigger ultrasonic sound pulses. By setting this pin to HIGH for 10µs from the Arduino, it causes the transmitter to send out an ultrasonic burst of eight short pulses at 40kHz that travel at the speed of sound. This unique 8-pulse pattern helps the receiver to distinguish between the transmitted pulses from ambient ultrasonic noise.
- Echo: When the transmitter sends out its 8-pulse ultrasonic burst, the Echo pin goes HIGH and stays that way as it listens for the burst to reflect back. As soon as the reflected pulses come back to the receiver, the Echo pin goes LOW. By measuring the time the Echo pin stays HIGH, we can calculate the distance to the object that caused the bounce back. If there’s no object or reflected pulse, the Echo pin will time-out after 38ms and go back to a LOW state.
- GND: Connect it to a GND (ground) pin of the Arduino.
How to Calculate Distance from an Ultrasonic Sensor
This is where we have to dust off that DeLorean time machine sitting in the garage, and go back to our high school math class – red puffer vest optional. Since mine is missing it’s flux capacitor, I’ll just give you the formula from my internet search travels instead.
Distance = Speed x Time
- Speed: This is the speed of sound which is 340 m/s. Since the ultrasonic sensor counts time in microseconds (µs), we need to convert the speed of sound into cm/µs. This gives us 0.034 cm/µs.
- Time: In the Arduino sketch below, we’ll use the
pulseIn()function to get the travel time in microseconds (µs) of the ultrasonic burst. This is the length of time that the Echo pin is HIGH.
For this example, let’s say that the pulseIn() function returns a value of 750 µs:
Distance = 0.034 cm/µs x 750 µs = 25.5 cm
But wait! There’s one more step. Keep in mind that the time the Echo pin remains HIGH includes the time it takes for the burst to travel to the object PLUS the time it takes to be reflected back. This means that we have to cut the distance we got (25.5 cm) in half so that we’re only calculating the time it takes for the burst to reach the object.
25.5 cm / 2 = 12.75 cm
So the entire formula is:
Distance = (0.034 cm/µs x Time) / 2
You’ll see this formula again in the Arduino sketch below.
HOOK-UP GUIDE: How to Wire a HC-SR04 Ultrasonic Sensor to Arduino
Now that the boring stuff is out of they way, let’s wire up our ultrasonic sensor to an Arduino Uno. Although you don’t necessarily need a breadboard for this, I prefer using one so that I can mount the sensor in an upright position.

PIN CONNECTIONS
| ULTRASONIC SENSOR | ARDUINO UNO |
|---|---|
| Vcc | 5V |
| Trig | 9 |
| Echo | 10 |
| GND | GND |
Arduino Code: Get Distance in CM and Inches from Ultrasonic Sensor
You can get distance readings in just about any metric you want. If you plan on measuring short distances, centimeters or inches probably make the most sense. But you can convert from centimeters to feet or even meters.
Just keep in mind that the range of the ultrasonic sensor is 2 cm to 400 cm (about 1 inch to 13 feet).
Here’s an Arduino sketch that shows distance readings in both centimeters and inches in the Serial Monitor:
const int trigPin = 9;
const int echoPin = 10;
float duration; // variable to store pulse duration
float distanceCM; // variable to store distance in CM
float distanceIN; // variable to store distance in IN
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// start with a clean signal
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// send trigger signal
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// return pulse duration in microseconds
// if set to HIGH, pulseIn() waits for the pin to go from LOW to HIGH
// stops timing when pin goes back LOW
duration = pulseIn(echoPin, HIGH);
// convert m/s to in/microsec
// 343 m/s = .034 cm/microseconds
distanceCM = (duration * 0.034) / 2;
// convert to inches, 1in = 2.54cm
distanceIN = distanceCM / 2.54;
// print distance to Serial Monitor
Serial.print("Distance: ");
Serial.print(distanceCM);
Serial.print(" cm | ");
Serial.print(distanceIN);
Serial.println(" in");
delay(100);
}
Upload this Arduino sketch and pop open your Serial Monitor. You’ll immediately see distance readings in both centimeters and inches coming from the ultrasonic sensor.
Let’s see how accurate this thing is!
Place a ruler in front of the transducers of the ultrasonic sensor and move an object with a flat surface to different spots on the ruler. Watch the readings on the Serial Monitor and see how closely they match up with your actual position on the ruler.
Keep in mind that the sensor can only start reading 2 cm away from the transducers so if you get too close, you’re in its blind spot.
Arduino Code Explanation
This is a relatively short Arduino program so let’s run through it line-by-line! This way, you know exactly how it works and how to use it for your own Arduino projects.
Define the Pin Connections
At the very top of all my Arduino sketches, I like to start by defining my pin connections as variables:
const int trigPin = 9;
const int echoPin = 10;
I’m letting the Arduino program know that the trigger pin, trigPin, of the ultrasonic sensor is equal to (=) pin 9 of the Arduino Uno. The echo pin, or echoPin, is equal to (=) pin 10.
Additional Program Variables
Before we get into the two main code blocks, there are a few more variables I need to set up. Variables act as storage containers for values that change throughout a program. In our case, this allows us to measure distances that update in real-time.
float duration;
float distanceCM;
float distanceIN;
The first one, duration, will store the Time in microseconds that the Echo pin is HIGH. We’ll use this value later on in code to calculate distance in centimeters. Remember this equation?
- Distance = (0.034 cm/µs x Time) / 2
You’ll see it pop up later on in the code.
Since we’re going to be calculating distances in both centimeters and inches, I created variables to store those as well: distanceCM and distanceIN.
setup() Function
Now that I’ve finished defining all the variables we’ll need later on in the code, let’s move on to the setup() section. Any code you put in here runs only once when the Arduino boots up.
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
The very first line, Serial.begin(9600), initializes the serial monitor. That’s fancy for telling the Arduino IDE to prepare the serial monitor for use at a baud rate of 9600.
Arduino pins can either act as inputs or outputs. The next two lines tell the Arduino how we want each of the ultrasonic sensor pins connected to it to behave.
Since the trigger pin is going to be sending, or outputting pulses, I set the pinMode of the trigPin to OUTPUT. The echo pin will be receiving the signal, so the pinMode for the echoPin is set to INPUT.
loop() Function
Any instructions in this code block get executed over and over again in the order that you write each line of code. That allows the Arduino and ultrasonic sensor to take measurements repeatedly and show you the real-time results on the serial monitor.
Step 1: Start with a Clean Signal
Before I instruct the trigger pin to send out its 8-pulse burst, let’s make sure we’re starting with a clean signal.
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
In the very first line, I set the trigPin to LOW. Then I hold it, or delay the program for 2 microseconds.
It seems like a very short amount of time, but it’s enough to separate this burst from other ambient ultrasonic noise bouncing around.
Step 2: Send the Trigger Signal
Now that the coast is clear, signal-wise, let’s send out our 8-pulse ultrasonic burst.
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
I start by setting (digitalWrite) the trigger pin, or trigPin, to HIGH. Next, I delay, or pause the program for 10 microseconds, holding that pin HIGH. That’s the magic number that tells the sensor to send out that specific 8-pulse burst at 40 kHz. Then in the third line, I shut the pin off by setting the trigPin to LOW.
Step 3: Determine the Time it Takes for the Signal to Travel to the Object and Back
Start your stop watch because now we need to time how long it takes for the ultrasonic signal to travel from the transmitter to the object and bounce back to the sensor’s receiver. This signal is traveling at the speed of sound so you better be quick!
Luckily, the echo pin handles the timing for us. As soon as the 8-pulse burst leaves the transmitter, the echo pin changes from LOW to HIGH. It will stay HIGH until the signal returns. When it does, the echo pin changes back to LOW.
We need a way to find out how long that echo pin was HIGH. With one line of code, the pulseIn() function does just that:
duration = pulseIn(echoPin, HIGH);
The pulseIn() function will read how long the echoPin was HIGH in microseconds and store that value in our duration variable.
Step 4: Calculate Distance in Centimeters and Inches
Using the formula above, Distance = (0.034 cm/µs x Time) / 2, let’s use the duration in place of Time to calculate distance.
distanceCM = (duration * 0.034) / 2;
distanceIN = distanceCM / 2.54;
I calculate for distance in centimeters, or distanceCM first.
This is equal to (=) the duration multiplied by 0.034, which is the speed of sound in cm/µs, and then divided by 2.
Now that I have the distance in centimeters, let’s convert that to inches:
- 1 inch is equal to 2.54 centimeters
To get the distance in inches, or distanceIN, I divide the distanceCM by 2.54.
Step 5: Print the Distance Values to the Serial Monitor
Now that we’ve gone through all the calculating and carry over the 1’s, we deserve to see the results of our labor!
The Arduino IDE has a built-in serial monitor to allow us to see values from sensors and a variety of other components. Let’s see the values we calculated:
Serial.print("Distance: ");
Serial.print(distanceCM);
Serial.print(" cm | ");
Serial.print(distanceIN);
Serial.println(" in");
delay(100);
I want each round of readings to be formatted like this:
Distance: XXX cm | XXX in
That way, I can see the value (XXX) in both centimeters and inches on the same line.
Finally, I add a small delay of 100 milliseconds to slow down the readings just enough so they don’t fly by too fast.
Cool Arduino Project Ideas Using HC-SR04 Ultrasonic Sensors
Looking for some cool project ideas to unleash the potential of your HC-SR04 ultrasonic sensor? Here are a few to get your creative juices flowing:
- Obstacle-Avoiding Robot: Combine the HC-SR04 with some wheels and a bit of code to create a robot that navigates its environment like it can really see. This little guy will detect obstacles in its path and gracefully change direction, making it a perfect entry point for robotics enthusiasts.
- Parking Assistant System: Ever struggled with parking in tight spots or backing into your garage? Use the ultrasonic sensor to build a parking assistant that beeps or flashes lights when you get too close to another car or the back wall. It’s like having a co-pilot, but way cooler.
- Interactive Art Installation: Transform your art projects into interactive experiences! Place the ultrasonic sensor in front of your artwork to trigger lights, sounds, or animations as viewers approach. It’s a surefire way to make your creations more engaging.
- Touchless Water Level Indicator: Keep tabs on the water level in your tank or aquarium without dipping a finger. The HC-SR04 can measure the distance from the top of the tank to the water surface, providing real-time updates on water levels and preventing overflows.
- Security Systems: Add an extra layer of security to your home with an ultrasonic sensor. Set up the sensor to detect movement in specific areas and trigger alarms or notifications if something—or someone—crosses its path.
With just a bit of imagination and some tinkering, the HC-SR04 ultrasonic sensor can bring a whole new interactive dimension to your projects. I can’t wait to see what you build!
