Arduino Ultrasonic Sensor Tutorial: From Basics to Examples

An ultrasonic sensor is an electronic device that measures distance by emitting high-frequency sound waves and analyzing their reflections. This sensor operates based on the principle of echolocation, similar to how bats and dolphins navigate their surroundings. Compared to optical sensors, ultrasonic sensors can function reliably in low-light conditions or when detecting transparent materials such as glass and water. As a result, they are widely used in robotics, smart parking systems, and industrial automation.

If you’re looking to DIY an ultrasonic sensor project, this article is the perfect guide for you. We’ll start with the basics of ultrasonic sensors, walk you through using Arduino for distance measurement, and explore practical applications of this technology in projects like smart parking systems. Whether you’re interested in sensor technology or want to achieve precise distance measurement in your projects, this article will provide you with a comprehensive guide.

Basics of Ultrasonic Sensors

Structure Analysis (HC-SR04 Example)

HC-SR04 sensor schematic

In Arduino projects, although there are various ultrasonic sensors, the HC-SR04 remains the most commonly used model. Below is an overview of its key components and functions:

  • Trigger Pin

Responsible for sending ultrasonic pulses.

When the trigger pin receives a 10-microsecond high signal, the sensor emits an ultrasonic wave.

  • Echo Pin

Responsible for receiving the reflected waves from an object.

By calculating the time difference between transmission and reception, the distance to the object can be accurately measured.

  • Power Pins (VCC & GND)

VCC is connected to 5V to provide power to the sensor.

GND is connected to the ground of the Arduino or other microcontrollers.

Working Principle

Schematic diagram of ultrasonic sensor sound wave status

The working principle of an ultrasonic sensor is based on the transmission and reception of sound waves. It operates in three key stages:

  • Transmission

When a high signal is applied to the Trigger Pin, the sensor emits a burst of high-frequency ultrasonic pulses (typically around 40 kHz), which travel through the air.

At the same time, the Echo Pin is set to high.

  • Reflection

When these pulse encounter an object, they bounce back toward the sensor.

  • Reception

The sensor detects the reflected wave and calculates the time taken for the signal to return.

Once the reflected pulse is received, the Echo Pin transitions from high to low.

By analyzing the time delay between transmission and reception, the sensor accurately determines the distance to the object.

Calculating Distance

The distance between the sensor and an object is determined using the simple physics formula:

Distance= (Speed of Sound × Time)/2

Time (Duration) refers to the total time taken for the sound wave to travel to the object and reflect back to the sensor.

We divide by 2 because the measured time includes both the outgoing journey (sensor to object) and the return journey (object to sensor). We only need the one-way distance.

The speed of sound in air is approximately 343 meters per second (m/s) at 20°C. However, for easier calculations with Arduino in centimeters, it is often expressed as:

0.034 cm/µs(or 34 cm/ms)

Suppose an ultrasonic sensor emits a sound wave, and it takes 500 microseconds (µs) for the wave to bounce off an object and return.

We calculate the total distance the sound wave traveled (round trip) as:

500 µs×0.034 cm/µs=17 cm

Since this represents the round-trip distance, we divide by 2 to get the one-way distance:

17 cm/2=8.5 cm

Thus, the object is 8.5 cm away from the ultrasonic sensor.

Limitations of Ultrasonic Sensors

Temperature Effects:

As temperature rises, the speed of sound increases, which may cause ultrasonic sensors to underestimate distances if proper compensation is not applied. Additionally, high humidity can increase the absorption of ultrasonic waves, reducing their effective range. Air turbulence and wind further complicate measurements by disrupting wave propagation, leading to unpredictable deflections and inaccurate readings.

Object Shape and Material:

The physical properties of the target object significantly affect sensor performance. Soft or porous materials, such as fabric or foam, tend to absorb ultrasonic waves rather than reflecting them, potentially resulting in weak or undetectable echoes.

Effect of Object Shape and Material on Ultrasonic Sensor Accuracy

Blind Zone:

The blind zone of an ultrasonic sensor refers to the minimum distance at which it can reliably detect an object. This occurs because the sensor requires time to switch from transmitting an ultrasonic pulse to receiving its echo. During this transition period, signals reflected from very close objects may be missed or misinterpreted. The size of the blind zone varies based on the sensor’s design and operating frequency.

Ultrasonic sensor blind spot effect

Transceiver vs Ultrasonic Sensor

Transceiver and ultrasonic sensors are closely related while their functions are bit different from each other:

FeatureTransceiverUltrasonic Sensor
FunctionTransmits and receives signals for communication.Emits ultrasonic waves and detects reflected signals to measure distance.
Working PrincipleUses electrical, radio, or optical signals for data transmission.Uses high-frequency sound waves for object detection and distance measurement.
ApplicationWireless communication, networking, automotive systems, and satellite communication.Robotics, vehicle parking sensors, industrial level measurement, and obstacle detection.
Signal TypeElectrical, radio, or optical signals.Sound waves (ultrasonic frequency).
Dependency on EnvironmentAffected by interference from other signals, electromagnetic noise, or obstructions.Can be affected by soft surfaces that absorb sound or environmental noise.
Usage ExampleEthernet transceivers in networking, RF transceivers in wireless communication.Car parking sensors, robotic obstacle avoidance systems.
Main PurposeFacilitates data exchange between devices.Measures distance and detects objects.

Arduino Ultrasonic Sensor Distance Measurement

Arduino Ultrasonic Sensor Distance Measurement Project Pin Connections

				
					const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;
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);
    distance = duration * 0.034 / 2;
    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println(" cm");
    delay(500);
}
				
			

Defines the pins connected to the sensor’s trigger(pin 9) and echo(pin10) signals.

Declares variables to store the echo pulse duration and calculated distance.

Initializes the pins as output (trigPin) and input (echoPin), and starts serial communication for displaying results.

Repeatedly triggers the sensor, measures the echo duration using pulseIn(), calculates the distance, and prints it to the serial monitor with a delay.

Code Upload:

Upload the Ultrasonic Sensor Distance Measurement project code to Arduino

First of all, check the microcontroller that you use. In my case i use Arduino Nano so i go to the tools>>board>>arduino AVR board>>arduino nano.

choose the right processor

Then you choose the right processor to by again going to the tools>>processor>>ATmega328P(old bootloader).

After completing all above process just paste the code in the Arduino and upload in the micro-controller. The result of the distance between the sensor and object is shown in the serial monitor.

Serial Monitor Interface

Ultrasonic Sensor Distance Measurement Project Final Connection Example

				
					#define trigPin 8
#define echoPin 9
#define Buzzer 10
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(Buzzer, OUTPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
int duration = pulseIn(echoPin, HIGH);
int distance = (duration/2) / 29.1;
if (distance < 30)
{
digitalWrite(Buzzer,HIGH); //less than 30cm then buzzer will produce beep sound
}
else {
digitalWrite(Buzzer,LOW);
}
if (distance >= 200 || distance <= 0)
{
Serial.print("Out of range");
}
else {
Serial.print(distance);
Serial.print("cm");
}
delay(500);
}
				
			

Arduino Ultrasonic Sensor Smart Parking System

Arduino Ultrasonic Sensor Smart Parking System Pin Connection Diagram

In this smart parking assistant project, the system uses LEDs and a buzzer to indicate distance. When the distance is greater than 50 cm, only the green LED is on, signaling a safe zone. As the vehicle moves closer, between 20 cm and 50 cm, the green LED turns off, and the yellow LED lights up, warning the driver to slow down. If the distance falls below 20 cm, the red LED turns on, and the buzzer activates, indicating immediate danger and the need to stop to avoid a collision.

Code:

				
					const int trigPin = 9;
const int echoPin = 10;
const int greenLED = 6;
const int yellowLED = 5;
const int redLED = 4;
const int buzzer = 3;
long duration;
int distance;
void setup() {
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(greenLED, OUTPUT);
    pinMode(yellowLED, OUTPUT);
    pinMode(redLED, OUTPUT);
    pinMode(buzzer, OUTPUT);
    Serial.begin(9600);
}
void loop() {
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = duration * 0.034 / 2;
    if (distance > 50) {
        digitalWrite(greenLED, HIGH);
        digitalWrite(yellowLED, LOW);
        digitalWrite(redLED, LOW);
        digitalWrite(buzzer, LOW);
    } else if (distance > 20) {
        digitalWrite(greenLED, LOW);
        digitalWrite(yellowLED, HIGH);
        digitalWrite(redLED, LOW);
        digitalWrite(buzzer, LOW);
    } else {
        digitalWrite(greenLED, LOW);
        digitalWrite(yellowLED, LOW);
        digitalWrite(redLED, HIGH);
        digitalWrite(buzzer, HIGH);
    }
				
			

Ending

Ultrasonic sensors are a powerful tool for distance measurement, offering reliable performance in various environments where optical sensors might fail. From understanding their working principles to implementing practical projects with Arduino, this tutorial has covered essential aspects to help you get started. Whether you’re building a simple distance meter or an advanced smart parking system, integrating ultrasonic sensors into your projects can enhance automation and precision. As you continue exploring sensor-based applications, experimenting with different configurations and integrating additional components will open new possibilities for innovation. Happy coding!

You Might Be Interested

What is Arduino UNO
What is Arduino UNO?

Unlock the power of Arduino UNO! This versatile development board lets you build everything from automated systems to robots. Explore its features and discover how it can turn your creative

How to Enable Multi-Core on ESP32 Microcontroller
How to Enable Multi-Core on ESP32 Microcontroller

This comprehensive guide elucidates the process of enabling multi-core functionality on the ESP32 microcontroller, leveraging its dual-core architecture for enhanced parallel processing capabilities. Through detailed steps and code examples, developers

Heart Rate Monitor Project
Homemade Arduino Heart Rate Monitor Project

Looking for a simple and efficient way to monitor your heart rate? Check out our latest project: the Arduino Heart Rate Monitor. With this easy-to-use device, you can keep track

arduino vibration sensor
Arduino Vibration Sensor Project

This Arduino project employs a vibration sensor, ball switch, and LED to detect tilt or collision events. The LED lights up when vibrations occur and turns off afterward. By connecting

Arduino Nano Pinout Guide
A Comprehensive Guide to Arduino Nano Pinout

This article will explore the Arduino Nano’s pinout, explaining each pin’s function and providing practical insights on how to effectively use them in your DIY projects—whether you’re working with digital

Simple Arduino UNO Projects
6 Simple Arduino UNO Projects

This article introduces six beginner-friendly projects for Arduino UNO, a popular microcontroller board. These projects cover a range of applications, from marquee lights and stepper motor control to ultrasonic ranging,

Scroll to Top