Interfacing HC-SR04 Ultrasonic Sensor with Arduino and LCD1602 I2C
Measuring distance with Arduino is one of the most common tasks in any beginner-friendly project. The HC-SR04 Ultrasonic Sensor is the best choice for this job. It is cheap, accurate, and easy to use. In this tutorial, you will learn how to interface the HC-SR04 with Arduino in a very simple way.
We will start by reading the distance on the Serial Monitor, and then display the same distance on an I2C LCD1602 module. If you are new to the LCD module, you can also read my detailed guide here: I2C LCD1602 Arduino Tutorial.
By the end of this tutorial, you will understand all the important functions of the HC-SR04 sensor. You will also learn how to create clean, reusable code for your future Arduino projects.

- What is HC-SR04 Ultrasonic Sensor?
- HC-SR04 to Arduino Wiring Guide
- Arduino Code to Read Distance from HC-SR04 (Serial Monitor)
- Read and Display Distance on Serial Monitor
- Display Distance on I2C LCD1602 (Using Your LCD Tutorial)
- Advanced HC-SR04 Functions and Features
- Error Handling: Out-of-Range Detection
- Common Issues and Fixes
- Conclusion
What is HC-SR04 Ultrasonic Sensor?
The HC-SR04 Ultrasonic Sensor is a popular distance-measuring module used with Arduino. It works by sending sound waves and measuring how long they take to bounce back. Because of this simple working method, it becomes very useful in many projects like obstacle detection, automatic lights, and water-level monitoring.

The sensor is reliable, low-cost, and easy to connect. In the sections below, you will learn how the sensor works, what each pin does, and what voltage it needs.
How HC-SR04 Measures Distance
The HC-SR04 uses ultrasonic waves at 40 kHz. These sound waves are not heard by humans. The process is simple:
- Arduino sends a tiny pulse to the TRIG pin.
- The sensor emits an ultrasonic burst.
- The wave travels forward and hits an object.
- The reflected wave returns to the sensor.
- The ECHO pin stays HIGH for the time the wave takes to return.
Arduino measures this time and converts it into distance using the formula:
distance (cm) = (duration * 0.0343) / 2;The duration is measured in microseconds. Speed of sound in air is 0.0342cm/us, simply use Distance = Speed * Time. We divide by 2 because the wave travels to the object and then back.
HC-SR04 Pinout Explanation
The sensor has four pins, and each one has a specific role. The image below shows the pinout of HC-SR04.
The pin functions are explained in the table below.
| Pin Name | Direction | Description |
|---|---|---|
| VCC | Input to the sensor | Powers the sensor |
| TRIG | Input to the sensor | Receives trigger pulse from Arduino |
| ECHO | Output from the sensor | Sends pulse duration back to Arduino |
| GND | Input to the sensor | Ground reference |
Voltage and Timing Requirements
The HC-SR04 needs the following voltage and timing values to work correctly:
- Operating Voltage: 5V
- Trigger Pulse Width: Minimum 10 microseconds
- Echo Output Voltage: 5V
- Measuring Range: 2 cm to 400 cm
- Accuracy: Around ±3 mm
- Ultrasonic Frequency: 40 kHz
HC-SR04 to Arduino Wiring Guide
Connecting the HC-SR04 to Arduino is very easy. You only need four wires, and the sensor works directly with the Arduino’s 5V supply. The image below shows the connection between HC-SR04 and Arduino Uno.
The tables below show the wiring and tips for stable distance readings. Follow them to avoid noise and get accurate results.
Connection Diagram (Table Format)
| HC-SR04 Pin | Arduino Pin | Purpose |
|---|---|---|
| VCC | 5V | Power supply for the sensor |
| GND | GND | Ground reference |
| TRIG | D9 | Sends trigger pulse |
| ECHO | D10 | Receives echo pulse |
Tips for Stable Distance Readings
| Tip | Reason / Benefit |
|---|---|
| Keep sensor straight | Ensures accurate reflection of ultrasonic waves |
| Avoid soft or curved surfaces | These surfaces absorb or scatter sound |
| Maintain at least 2 cm minimum distance | Sensor cannot detect below 2 cm |
| Use short jumper wires | Reduces electrical noise |
| Add small delay between readings | Prevents false triggers |
| Avoid angular surfaces | Ultrasonic waves reflect best on flat objects |
Arduino Code to Read Distance from HC-SR04 (Serial Monitor)
To read the distance from the HC-SR04 sensor, we must first trigger the sensor, capture the echo pulse time, and then convert that time into distance. In this section, you will find simple and clean Arduino codes for each step. These small code blocks help you understand how the sensor works internally. Later, we will combine everything into a full sketch that prints the distance on the Serial Monitor.
Basic Code to Trigger and Read Echo Pulse
Below is the simplest code to send a trigger pulse and read the echo pulse width:
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);The Arduino sends a short 10-microsecond pulse to the TRIG pin to trigger the ultrasonic sensor.
The sensor emits an ultrasonic burst and waits for the echo to return.
The pulseIn() function measures how long the ECHO pin stays HIGH, which represents the time taken for the sound wave to travel to the object and back.
Code to Convert Time to Distance (cm & inch)
Here is the code that converts the measured time into centimeters and inches:
long duration = pulseIn(echoPin, HIGH);
float distanceCM = (duration * 0.0343) / 2; // Speed of sound = 0.0343 cm/us
float distanceIN = distanceCM / 2.54; // Convert cm to inchesThis code converts the pulse value (in microseconds) to Distance using the formula (duration * 0.0343) / 2.
The speed of sound in air is 0.0343cm/µs. The division by 2 is performed because the wave travels to the object and then back. Hence it covers twice the actual distance.
Read and Display Distance on Serial Monitor
Now that you understand how to trigger the HC-SR04 and convert the echo time into distance, let’s combine everything into one clean and complete Arduino sketch. This code is ready to upload and will continuously print the measured distance on the Serial Monitor. It gives you smooth and readable output, which helps you verify that the sensor is working correctly before moving to the LCD display part.
Complete Arduino Sketch
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Clear trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send 10us pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read echo time
long duration = pulseIn(echoPin, HIGH);
// Convert to distance
float distanceCM = (duration * 0.0343) / 2;
// Print output
Serial.print("Distance: ");
Serial.print(distanceCM);
Serial.println(" cm");
delay(500);
}Output on Serial Monitor
The video below shows the measured distance on the serial monitor.
| Reading | Meaning |
|---|---|
| The value changes smoothly | Sensor is working correctly |
| Sudden spikes | Object surface may be reflective or angled |
| Very large values (0 or 400+) | Object is out of range or no reflection detected |
Display Distance on I2C LCD1602 (Using Your LCD Tutorial)
In this part, we will display the measured distance directly on the I2C LCD1602 display. If you are new to I2C LCDs or do not know how to set them up, you should first read my full guide here: https://controllerstech.com/i2c-lcd1602-arduino-tutorial/
This tutorial explains everything: wiring, address scanning, and LCD functions. Now let’s combine the HC-SR04 sensor with the LCD and show the distance on the screen.
Wiring HC-SR04 + I2C LCD1602 with Arduino
The image below shows the wiring connection between HC-SR04, LCD1602 and Arduino Uno.
Here is the complete wiring table for both the sensor and the LCD:
HC-SR04 Wiring
| HC-SR04 Pin | Arduino Pin | Purpose |
|---|---|---|
| VCC | 5V | Power for sensor |
| GND | GND | Ground |
| TRIG | D9 | Trigger pulse |
| ECHO | D10 | Echo reading |
I2C LCD1602 Wiring
| LCD Pin | Arduino Pin | Purpose |
|---|---|---|
| VCC | 5V | Power |
| GND | GND | Ground |
| SDA | A4 | I2C Data |
| SCL | A5 | I2C Clock |
Both modules work on 5V, so wiring is very simple.
Installing the LiquidCrystal_I2C Library
Before writing the code, install the LiquidCrystal_I2C library:
- Open Arduino IDE.
- Go to Sketch → Include Library → Manage Libraries.
- Search for “LiquidCrystal_I2C”.
- Install the version by Frank de Brabander or Marco Schwartz.
Complete Arduino Code (HC-SR04 + LCD1602 I2C)
The code below is used to read the data from HC-SR04, convert it to distance in Centimeters and finally display the distance on the LCD16x2.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // LCD address may be 0x27 or 0x3F
const int trigPin = 9;
const int echoPin = 10;
void setup() {
lcd.init();
lcd.backlight();
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
// Trigger pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read echo
long duration = pulseIn(echoPin, HIGH);
// Convert to cm
float distanceCM = (duration * 0.0343) / 2;
// Display on Serial Monitor
Serial.print("Distance: ");
Serial.print(distanceCM);
Serial.println(" cm");
// Display on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance:");
lcd.setCursor(0, 1);
lcd.print(distanceCM);
lcd.print(" cm");
delay(500);
}Explanation
1. LCD and Sensor Setup
The code initializes a 16×2 I2C LCD at address 0x27 and sets up the ultrasonic sensor pins, trigPin as OUTPUT and echoPin as INPUT. Serial communication is also started for debugging.
2. Sending the Trigger Pulse
Inside the loop, the trig pin is pulled LOW briefly, then set HIGH for 10 microseconds. This creates an ultrasonic burst from the HC-SR04 sensor.
3. Reading the Echo
The pulseIn() function measures how long the echo pin stays HIGH. This duration represents the time taken by the ultrasonic wave to travel to an object and back.
4. Calculating Distance
The duration is converted into centimeters using the formula:
distance = (duration * speedOfSound) / 2Speed of sound = 0.0343 cm/µs, and we divide by 2 because the wave travels twice the distance.
5. Displaying the Results
The measured distance is printed on both:
- Serial Monitor (for debugging)
- I2C LCD display, showing “Distance” on the first line and the distance value on the second line.
The loop repeats every 500 ms.
Output on the LCD
The video below shows the complete working. The distance calculated is printed on the LCD1602 display.
Advanced HC-SR04 Functions and Features
Once you understand the basic working of the HC-SR04, you can build more advanced and reliable projects. In this section, we will create reusable functions, remove noisy readings, and even perform non-blocking distance measurements using millis(). These features help you write cleaner, smarter, and more accurate Arduino programs. You will also learn how to detect out-of-range readings and handle errors properly.
Function to Filter Noise (Median or Average Filter)
Distance readings may jump due to noise. A small filter makes your results much more stable.
Average Filter (Simple and Effective)
long averageDistanceCM(int trigPin, int echoPin) {
long sum = 0;
for (int i = 0; i < 5; i++) {
sum += readDistanceCM(trigPin, echoPin);
delay(20);
}
return sum / 5;
}Here we simply take the average of 5 readings before displaying the result on the LCD.
Median Filter (Better for Sudden Spikes)
Very useful when some readings are way off.
long medianDistanceCM(int trigPin, int echoPin) {
long values[5];
for (int i = 0; i < 5; i++) {
values[i] = readDistanceCM(trigPin, echoPin);
delay(20);
}
// Simple bubble sort
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
if (values[j] < values[i]) {
long temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
return values[2]; // Middle value
}This function reads the ultrasonic distance five times, sorts those readings, and returns the middle (median) value. This helps remove noisy or incorrect readings and gives a more stable distance result.
You can choose either of these filters depending on how the HC-SR04 is behaving.
Error Handling: Out-of-Range Detection
The HC-SR04 ultrasonic sensor can measure distances from about 2 cm to 400 cm, and its echo signal times out after roughly 38 ms if no object is detected. The code below handles all common edge cases by checking when no echo is received, when the object is too close to measure, and when it is too far or beyond the sensor’s reliable range.
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
float readDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
unsigned long duration = pulseIn(echoPin, HIGH, 38000);
// 38ms timeout = ~400cm
if (duration == 0) {
Serial.println("Error: No echo received (Object too far or sensor misaligned)");
return -1;
}
float distance = duration * 0.0343 / 2;
if (distance < 2) {
Serial.println("Error: Object too close (<2cm)");
return -1;
}
if (distance > 400) {
Serial.println("Error: Out of range (>400cm)");
return -1;
}
return distance;
}
void loop() {
float d = readDistance();
if (d != -1) {
Serial.print("Distance: ");
Serial.print(d);
Serial.println(" cm");
}
delay(200);
}This code triggers the HC-SR04 sensor, measures the echo time with a 38 ms timeout, and converts it to distance.
It also checks for common errors:
- no echo (object too far or misaligned)
- object too close
- distance beyond 400 cm.
If the reading is valid, it prints the distance; otherwise, it reports an error.
Common Issues and Fixes
Even after writing the correct code, you may still face problems like the LCD not displaying values, unstable measurements from the HC-SR04, or sudden errors caused by wiring or power. In this section, we’ll quickly look at the most common issues you might encounter and the simple fixes that usually solve them.
LCD Not Showing Distance
If your LCD1602 I2C display is not showing the measured distance:
- Make sure you are using the correct I2C address (often
0x27or0x3F). - Run an I2C Scanner to detect the accurate address.
- Confirm that SDA → A4 and SCL → A5 (for Arduino UNO) are connected properly.
- Ensure you have installed the required LiquidCrystal_I2C library.
- If the LCD screen lights up but characters are not visible, adjust the contrast potentiometer on the I2C module.
Unstable HC-SR04 Readings
If your readings keep jumping or fluctuating:
- Ensure the sensor is not tilted or vibrating.
- Avoid using HC-SR04 on soft or angled surfaces—sound waves scatter and cause errors.
- Place the sensor at least 5 cm above the table to prevent echo reflections.
- Use a median or average filter to smooth out noisy readings.
- Keep the sensor away from ultrasonic noise sources like motors or fans.
Power Supply and Cable Length Issues
HC-SR04 and LCD modules can behave unpredictably if the power supply is unstable:
- Always power your setup with a stable 5V supply. Avoid long USB cables.
- If using jumper wires longer than 30–40 cm, signal quality may drop.
- Keep GND of all modules connected to a common ground.
- If the sensor randomly resets, add a 100 µF capacitor across 5V and GND to stabilize power.
Conclusion
In this tutorial, you learned how to interface the HC-SR04 ultrasonic sensor with Arduino and use it to measure distance accurately. We started with the basic working principle, wiring, and simple code to read distance on the Serial Monitor. Then we moved ahead and displayed the same distance on the I2C LCD1602, using the same method explained in my detailed LCD tutorial.
You also explored advanced features like creating reusable functions, applying noise filters, running non-blocking measurements using millis(), and handling out-of-range errors for reliable performance.
With all these techniques, you can now use the HC-SR04 confidently in your own Arduino projects—whether it’s a robot, obstacle detector, parking sensor, or a full automation system. This small sensor is powerful, simple, and perfect for beginners as well as advanced users.
Browse More Arduino Sensors Tutorials
Interfacing SHT3X Temperature and Humidity Sensors with Arduino using I2C
Interface SHT21 Temperature and Humidity Sensor with Arduino | Display on Serial Monitor and I2C LCD
Arduino DS18B20 Temperature Sensor Tutorial: Single and Multiple Sensors with SSD1306 OLED
MPU6050 Arduino I2C Tutorial: Pinout, Wiring, Calibration, Raw Data, and Code Examples
IR Sensor Arduino Tutorial: Interfacing, Calibration, Detection Modes, Codes & LCD1602 Display
Arduino BME280 Tutorial: Wiring, Pinout, Code and LCD1602 Display Output
ADXL345 Arduino I2C Tutorial: Pinout, Wiring, Calibration, and Accelerometer Data Reading Explained
Arduino HC-SR04 Project Download
Info
You can help with the development by DONATING Below.
To download the project, click the DOWNLOAD button.
Arduino HC-SR04 FAQs
No, the HC-SR04 requires 5V logic. Using it directly with 3.3V boards may give unreliable readings. Use a logic level converter if needed.
You can trigger it every 50–60 ms. Faster readings may give inaccurate results due to echo overlap.
Flat, hard, and reflective surfaces give the most accurate readings. Soft or angled surfaces can scatter ultrasonic waves.
Yes, but trigger each sensor separately to avoid interference. Ensure each sensor has its own TRIG and ECHO pins.
Use median or average filtering on the readings and keep the sensor away from ultrasonic noise sources like motors or fans.




