Close Menu
  • Articles
    • Learn Electronics
    • Product Review
    • Tech Articles
  • Electronics Circuits
    • 555 Timer Projects
    • Op-Amp Circuits
    • Power Electronics
  • Microcontrollers
    • Arduino Projects
    • STM32 Projects
    • AMB82-Mini IoT AI Camera
    • BLE Projects
  • IoT Projects
    • ESP8266 Projects
    • ESP32 Projects
    • ESP32 MicroPython
    • ESP32-CAM Projects
    • LoRa/LoRaWAN Projects
  • Raspberry Pi
    • Raspberry Pi Projects
    • Raspberry Pi Pico Projects
    • Raspberry Pi Pico W Projects
  • Electronics Calculator
Facebook X (Twitter) Instagram
  • About Us
  • Disclaimer
  • Privacy Policy
  • Contact Us
  • Advertise With Us
Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
How To Electronics
  • Articles
    • Learn Electronics
    • Product Review
    • Tech Articles
  • Electronics Circuits
    • 555 Timer Projects
    • Op-Amp Circuits
    • Power Electronics
  • Microcontrollers
    • Arduino Projects
    • STM32 Projects
    • AMB82-Mini IoT AI Camera
    • BLE Projects
  • IoT Projects
    • ESP8266 Projects
    • ESP32 Projects
    • ESP32 MicroPython
    • ESP32-CAM Projects
    • LoRa/LoRaWAN Projects
  • Raspberry Pi
    • Raspberry Pi Projects
    • Raspberry Pi Pico Projects
    • Raspberry Pi Pico W Projects
  • Electronics Calculator
How To Electronics
Home » How to use HC-SR04 Ultrasonic Distance Sensor with Arduino
Arduino Projects

How to use HC-SR04 Ultrasonic Distance Sensor with Arduino

Mamtaz AlamBy Mamtaz AlamUpdated:February 2, 20256 Mins Read
Share Facebook Twitter LinkedIn Telegram Reddit WhatsApp
HC-SR04 Ultrasonic Distance Sensor with Arduino
Share
Facebook Twitter LinkedIn Pinterest Email Reddit Telegram WhatsApp

Overview

In this project, we use HC-SR04 Ultrasonic Distance Sensor with Arduino for displaying the measured distance on an LCD screen. The HC-SR04 sensor operates on the principle of sonar, emitting an ultrasonic wave at a specific frequency that reflects off an object and returns to the sensor. The system then calculates the distance to the object by measuring the time taken for the ultrasonic wave to travel to the object and back.

First we will interface the HC-SR04 Ultrasonic Distance Sensor with Arduino Code and display the measured distance in Serial Monitor. Later, we will add an additional 16×2 I2C LCD Display to the system which will display the measured distance in Screen. The HC-SR04 Ultrasonic Sensor can be used for a variety of applications, such as obstacle detection systems, automation projects, and more.


Components Required

For this tutorial I am using the SunFounder Arduino Starter Kit which has 90+ components.

Here are the list of components I am using from this Kit.

S.N.ComponentsQuantityPurchase Links
1Arduino UNO R4/R3 Board1Amazon | AliExpress
2Ultrasonic Sensor HC-SR041Amazon | AliExpress | SunFounder
316X2 I2C LCD Display1Amazon | AliExpress | SunFounder
4Connecting Wires10Amazon | AliExpress | SunFounder
5Type C USB Cable1Amazon | AliExpress
6Breadboard1Amazon | AliExpress | SunFounder


HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 ultrasonic sensor uses sonar to determine the distance to an object like bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package.

From 2cm to 400 cm or 1” to 13 feet. Its operation is not affected by sunlight or black material like sharp rangefinders are (although acoustically soft materials like cloth can be difficult to detect). It comes complete with the ultrasonic transmitter and a receiver module. A waterproof version of this Ultrasonic Sensor is also available called as JSN-SR04T/AJ-SR04M.

How Does the Ultrasonic Sensor HC-SR04 Work?

Ultrasonic sensors function by emitting a sequence of short, high-frequency sound waves. These sound waves are produced at regular intervals and travel through the air at a consistent speed, known as the speed of sound. When these ultrasonic waves encounter any object in their path, they are reflected back toward the sensor, creating an echo that is detected by the sensor’s receiver.

Distance Measurement Using Arduino & HC-SR04

The sensor is equipped with the capability to calculate the distance to the object by analyzing the time interval between the moment the sound pulse is emitted and the moment the echo is received. This time interval is directly related to the round-trip distance that the sound waves have traveled.

To convert this time interval into a distance measurement, we use the formula:

S=(v×t)/2

Where:

  • S is the distance to the object (in centimeters),
  • v is the speed of sound in air (approximately 340 meters per second or 0.034 centimeters per microsecond),
  • t is the time interval measured from when the sound wave is emitted to when the echo is received (in seconds).

It’s important to note that the time measured is the total time for the sound wave to travel to the object and back to the sensor. Since we are interested in the distance from the sensor to the object, not the round trip, we divide the time by 2.

By using this formula, the ultrasonic sensor can provide a precise measurement of the distance to an object, which can be utilized in various applications such as collision avoidance systems, robotics, level sensing, and more.

Specifications of HC-SR04 Ultrasonic Distance Sensor

The specifications of the HC-SR04 Ultrasonic Distance Sensor are below:

  1. Minimum measuring range – 2 cm
  2. Maximum measuring range: 400 cm or 4 meter
  3. Accuracy : 3 mm
  4. Operating Voltage: +5V
  5. Operating Current: 15mA
  6. Working Frequency: 40 KHz
  7. Trigger Input signal: 10us pulse
  8. Measuring angle: 15 degrees

Pinout of HC-SR04

The HC-SR04 ultrasonic sensor has 4 Pins.

HC-SR04 Pinout

  1. VCC (Power): This pin powers the sensor, typically with +5V from the microcontroller board.
  2. Trig (Trigger): This pin is used to initiate the ultrasonic pulse. A short pulse of 10 microseconds sent to this pin starts the ultrasonic burst.
  3. Echo (Echo Pulse): This pin outputs a pulse from the sensor. The duration of this pulse is proportional to the time taken for the ultrasonic wave to travel to the object and back to the sensor.
  4. GND (Ground): This pin is connected to the ground of the circuit.

Interfacing HC-SR04 Ultrasonic Distance Sensor with Arduino

Now lets interface the HC-SR04 Ultrasonic Distance Sensor with Arduino. Here is the simple connection diagram.

Hardware Connection

HC-SR04 Arduino UNO Connection

  • VCC connects to the 5V output on the Arduino.
  • Trig connects to a D2 pin on the Arduino.
  • Echo connects to D3 pin on the Arduino.
  • GND connects to the ground pin on the Arduino.

You can use a breadboard and jumper wires for connection.

Arduino Ultrasonic Sensor Connection


Source Code/Program

Here is the simple code for reading the distance value from HC-SR04 Ultrasonic Sensor using the Arduino Code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
  Read data from an ultrasonic sensor connected to the Arduino board
  and print the distance measurement in centimeters
  through the serial communication.
 
  Board: Arduino Uno R4 (or R3)
  Component: Ultrasonic distance Sensor(HC-SR04)
*/
 
// Define the pin numbers for the ultrasonic sensor
const int echoPin = 3;
const int trigPin = 2;
 
void setup() {
  Serial.begin(9600);                    // Start serial communication with a baud rate of 9600
  pinMode(echoPin, INPUT);               // Set echo pin as input
  pinMode(trigPin, OUTPUT);              // Set trig pin as output
  Serial.println("Ultrasonic sensor:");  // Print a message indicating the ultrasonic sensor is ready
}
 
void loop() {
  float distance = readDistance();       // Call the function to read the sensor data and get the distance
  
  if (distance > 400) {                  // Check if the distance is greater than 400 cm
    Serial.println("Out of Range");      // Print "Out of Range"
  } else {
    Serial.print(distance);              // Print the distance value
    Serial.println(" cm");               // Print " cm" to indicate the unit of measurement
  }
  
  delay(400);                            // Delay for 400 milliseconds before repeating the loop
}
 
// Function to read the sensor data and calculate the distance
float readDistance() {
  digitalWrite(trigPin, LOW);            // Set trig pin to low to ensure a clean pulse
  delayMicroseconds(2);                  // Delay for 2 microseconds
  digitalWrite(trigPin, HIGH);           // Send a 10 microsecond pulse by setting trig pin to high
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);            // Set trig pin back to low
 
  // Measure the pulse width of the echo pin and calculate the distance value
  float pulse_duration = pulseIn(echoPin, HIGH); // Read pulse duration
  float distance = pulse_duration / 58.00;       // Calculate the distance
  
  return distance;                               // Return the calculated distance
}

To upload the code to the Arduino Board, Select the Arduino UNO Board from Tools Menu and also select the COM port. Then upload the code by clicking on upload button.


Testing & Results

The device is ready for testing after the code uploading is done.

Place some solid flat object in front of the Ultrasonic Sensor.

Then open the Serial Monitor on the Arduino IDE. The Serial Monitor will show the measured distance.

To test it further place the obstacle at far distance from the Sensor.

Observe the distance on the Serial Monitor. The Serial Monitor will show the measured distance again.

You can increase or decrease the distance between 2cm to 400cm and measurement will be shown in Serial Monitor.


Interfacing HC-SR04 Ultrasonic Sensor with Arduino & LCD Display

Now lets add an extra component to the above circuit for distance visualization. We can use 16×2 I2C LCD Display with the Arduino UNO.

Hardware Connection

Here is a connection between Arduino and 16×2 I2C LCD Display along with HC-SR04 Ultrasonic Sensor.

Arduino HC-SR04 Ultrasonic Sensor LCD Display

  • VCC connects to the 5V output on the Arduino.
  • SDA connects to a A4 pin on the Arduino.
  • SCL connects to A5 pin on the Arduino.
  • GND connects to the ground pin on the Arduino.

Ultrasonic Sensor Arduino LCD

You can again use Jumper Wires for connections.

Source Code/Program

We can modify the above code by adding the extra code for LCD Display. Then we can print the Measured Distance on LCD Screen.

Before that, we need to add I2C LCD Library to the Arduino Library Folder.

Here is the complete code for this project.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
 
// Define the pin numbers for the ultrasonic sensor
const int echoPin = 3;
const int trigPin = 2;
 
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
 
void setup() {
  // Initialize the LCD
  lcd.init();
  // Turn on the backlight.
  lcd.backlight();
 
  pinMode(echoPin, INPUT);               // Set echo pin as input
  pinMode(trigPin, OUTPUT);              // Set trig pin as output
  lcd.print("Ultrasonic Sensor");        // Print a message on the LCD
}
 
void loop() {
  float distance = readDistance();       // Call the function to read the sensor data and get the distance
  
  lcd.clear();                           // Clear the LCD display
  lcd.setCursor(0,0);
  lcd.print("Distance: ");
  lcd.setCursor(0,1);
  if (distance > 400)                   // Check if the distance is greater than 400 cm
  {                  
    lcd.print("Out of Range");           // Print "Out of Range" on the LCD
  }
  else
  {
    lcd.print(distance);                 // Print the distance value on the LCD
    lcd.print(" cm");                    // Print " cm" to indicate the unit of measurement
  }
  
  delay(750);                            // Delay for 750 milliseconds before repeating the loop
}
 
// Function to read the sensor data and calculate the distance
float readDistance() {
  digitalWrite(trigPin, LOW);            // Set trig pin to low to ensure a clean pulse
  delayMicroseconds(2);                  // Delay for 2 microseconds
  digitalWrite(trigPin, HIGH);           // Send a 10 microsecond pulse by setting trig pin to high
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);            // Set trig pin back to low
 
  // Measure the pulse width of the echo pin and calculate the distance value
  float pulse_duration = pulseIn(echoPin, HIGH); // Read pulse duration
  float distance = pulse_duration / 58.00;       // Calculate the distance
  
  return distance;                               // Return the calculated distance
}

Upload the code to the Arduino UNO Board.

Testing & Results

After uploading the code, the LCD will print the measured distance.

You can put some barrier in front of Ultrasonic Sensor and observe the distance on LCD Screen.

How to use HC-SR04 Ultrasonic Distance Sensor with Arduino


Projects using HC-SR04 Ultrasonic Sensor

There are many projects that can be done using the Ultrasonic Sensor such as distance measurement applications, such as robotic obstacle avoidance systems, and liquid level monitoring in tanks. Another common use is in interactive installations, like parking sensors and automated doors, where distance-triggered actions are required.

Here are some projects that has been done using this sensor.

  1. Obstacle Avoidance Robot
  2. Ultrasonic Range Finder with TFT LCD
  3. Blind Walking Stick
  4. Density Based Traffic Light Controller
  5. IoT Water Level Indicator
  6. Ultrasonic RADAR Model
Share. Facebook Twitter Pinterest LinkedIn Tumblr Email Reddit Telegram WhatsApp
Previous ArticleSmart Density Based Traffic Light Control System with ESP32 & Blynk
Next Article Gas Leak Detection & Alarm using MQ2 Sensor & Arduino

Related Posts

DC Energy Meter using Arduino

Build a DC Energy Meter using Arduino – 32V/5A

Updated:August 26, 20252K
Interfacing ADXL375 Accelerometer with Arduino

Interfacing ADXL375 Accelerometer with Arduino (±200g)

Updated:June 28, 2025
PZEM-004T Arduino Energy Meter

DIY AC Energy Meter using PZEM-004T & Arduino

Updated:March 6, 20258K
Interfacing BMI160 Accelerometer & Gyroscope with Arduino

Interfacing BMI160 Accelerometer & Gyroscope with Arduino

Updated:February 2, 20259K
Password Based Door Lock Security System Using Arduino & Keypad

Password Based Door Lock Security System Using Arduino & Keypad

Updated:February 2, 20252436K
Earthquake Detector Alarm with with Accelerometer & Arduino

Earthquake Detector Alarm with Accelerometer & Arduino

Updated:February 2, 2025661K
Add A Comment

CommentsCancel reply

Latest Posts
IoT Based PM & Air Quality Monitoring System using ESP32

IoT Based PM & Air Quality Monitoring System using ESP32

May 31, 2026
DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

May 10, 2026
IoT Activity Tracker with ESP32 & Accelerometer Gyroscope

IoT Activity Tracker with ESP32 & Accelerometer/Gyroscope

May 2, 2026
A Guide to Sourcing Obsolete ICs for Vintage Projects

Beyond AliExpress: A Guide to Sourcing Obsolete ICs for Vintage Projects

April 21, 2026

ESP32 IoT Vehicle Motion Analyzer with MPU6050 & LIS3MDL

April 27, 2026
Building a Smart Sensor Node with a BLE Microcontroller

Building a Smart Sensor Node with a BLE Microcontroller

February 26, 2026
High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU

High-Accuracy Pitch, Roll, Yaw with ESP32 & BNO08x IMU

April 27, 2026
DIY Colorimeter using AS7265x Spectroscopy Sensor & ESP32

DIY Colorimeter using AS7265x Spectroscopy Sensor & ESP32

February 1, 2026
Top Posts & Pages
  • 12V DC to 220V AC Inverter Circuit & PCB
    12V DC to 220V AC Inverter Circuit & PCB
  • IoT AC Energy Meter with PZEM-004T & ESP32 WebServer
    IoT AC Energy Meter with PZEM-004T & ESP32 WebServer
  • IoT Based Drinking Water Quality Monitoring with ESP32
    IoT Based Drinking Water Quality Monitoring with ESP32
  • LD2410 Sensor with ESP32 - Human Presence Detection
    LD2410 Sensor with ESP32 - Human Presence Detection
  • ESP32 CAN Bus Tutorial | Interfacing MCP2515 CAN Module with ESP32
    ESP32 CAN Bus Tutorial | Interfacing MCP2515 CAN Module with ESP32
  • DIY IoT Water pH Meter using pH Sensor & ESP32
    DIY IoT Water pH Meter using pH Sensor & ESP32
  • Buck Converter: Basics, Working, Design & Application
    Buck Converter: Basics, Working, Design & Application
  • How to use Modbus RTU with ESP32 to read Sensor Data
    How to use Modbus RTU with ESP32 to read Sensor Data
Categories
  • Arduino Projects (197)
  • Articles (60)
    • Learn Electronics (19)
    • Product Review (15)
    • Tech Articles (28)
  • Electronics Circuits (46)
    • 555 Timer Projects (21)
    • Op-Amp Circuits (7)
    • Power Electronics (13)
  • IoT Projects (204)
    • ESP32 MicroPython (7)
    • ESP32 Projects (81)
    • ESP32-CAM Projects (15)
    • ESP8266 Projects (76)
    • LoRa/LoRaWAN Projects (22)
  • Microcontrollers (38)
    • AMB82-Mini IoT AI Camera (4)
    • BLE Projects (18)
    • STM32 Projects (19)
  • Raspberry Pi (93)
    • Raspberry Pi Pico Projects (57)
    • Raspberry Pi Pico W Projects (12)
    • Raspberry Pi Projects (24)
Follow Us
  • Facebook
  • Twitter
  • Pinterest
  • Instagram
  • YouTube
About Us

“‘How to Electronics’ is a vibrant community for electronics enthusiasts and professionals. We deliver latest insights in areas such as Embedded Systems, Power Electronics, AI, IoT, and Robotics. Our goal is to stimulate innovation and provide practical solutions for students, organizations, and industries. Join us to transform learning into a joyful journey of discovery and innovation.

Copyright © How To Electronics. All rights reserved.
  • About Us
  • Disclaimer
  • Privacy Policy
  • Contact Us
  • Advertise With Us

Type above and press Enter to search. Press Esc to cancel.

Ad Blocker Enabled!
Ad Blocker Enabled!
Looks like you're using an ad blocker. Please allow ads on our site. We rely on advertising to help fund our site.