Distance measurement using Ultrasonic sensor and Arduino
Last Updated :
30 Apr, 2024
In This Article, We will learn how to measure the distance using an Ultrasonic sensor & Arduino.
Arduino:
It is an open-source electronics platform. It consists ATmega328 8-bit Microcontroller. It can be able to read inputs from different sensors & we can send instructions to the microcontroller in the Arduino. It provides Arduino IDE to write code & connect the hardware devices like Arduino boards & sensors.
Ultrasonic Sensor:
An ultrasonic Sensor is a device used to measure the distance between the sensor and an object without physical contact. This device works based on time-to-distance conversion.
Working Principle of Ultrasonic Sensor:
Ultrasonic sensors measure distance by sending and receiving the ultrasonic wave. The ultrasonic sensor has a sender to emit the ultrasonic waves and a receiver to receive the ultrasonic waves. The transmitted ultrasonic wave travels through the air and is reflected by hitting the Object. Arduino calculates the time taken by the ultrasonic pulse wave to reach the receiver from the sender.
We know that the speed of sound in air is nearly 344 m/s,
So, the known parameters are time and speed (constant). Using these parameters, we can calculate the distance traveled by the sound wave.
Formula: Distance = Speed * Time
In the code, the "duration" variable stores the time taken by the sound wave traveling from the emitter to the receiver. That is double the time to reach the object, whereas the sensor returns the total time including sender to object and object to receiver. Then, the time taken to reach the object is half of the time taken to reach the receiver.
so we can write the expression as,
Distance = Speed of Sound in Air * (Time Taken / 2)
Note: Speed of sound in air = 344 m/s.
Components Required:
- Arduino Uno R3 board
- Ultrasonic sensor (HC-SR04)
- 16x2 LCD I2C Display
- Jumper Wires
Circuit Diagram:
Ultrasonic Distance measurement circuitSetup:
- Connect the Echo pin of the sensor to the D2 pin of the Arduino.
- Connect the Trig pin of the sensor to the D3 pin of the Arduino.
- Navigate to Tools and select board and port.
- Verify and compile the code, then upload the code to the Arduino Uno R3 board.
- Monitor the output in the Serial monitor (Set the baud rate as 9600). To open Serial monitor Tools>Serial Monitor or (Ctrl+Shift+M).
Arduino Code (Output in Serial monitor):
The following code will show the output on the serial monitor of Arduino software with a baud rate of 9600.
C++
#define echoPin \
2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin \
3 // attach pin D3 Arduino to pin Trig of HC-SR04 \
long duration; // Variable to store time taken to the pulse
// to reach receiver
int distance; // Variable to store distance calculated using
// formula
void setup()
{
pinMode(trigPin,
OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
// Serial Communication is starting with 9600 of
// baudrate speed
Serial.begin(9600);
// The text to be printed in serial monitor
Serial.println(
"Distance measurement using Arduino Uno.");
delay(500);
}
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // wait for 2 ms to avoid
// collision in serial monitor
digitalWrite(
trigPin,
HIGH); // turn on the Trigger to generate pulse
delayMicroseconds(
10); // keep the trigger "ON" for 10 ms to generate
// pulse for 10 ms.
digitalWrite(trigPin,
LOW); // Turn off the pulse trigger to stop
// pulse generation
// If pulse reached the receiver echoPin
// become high Then pulseIn() returns the
// time taken by the pulse to reach the
// receiver
duration = pulseIn(echoPin, HIGH);
distance
= duration * 0.0344 / 2; // Expression to calculate
// distance using time
Serial.print("Distance: ");
Serial.print(
distance); // Print the output in serial monitor
Serial.println(" cm");
delay(100);
}
Output in External Display device (LCD Display):
To monitor the output without a PC, we have to interface display devices to monitor the output. Here, we are using "a 16x2 LCD display with I2C communication.
To interface with the LCD display, we need to install the supporting library to the Arduino IDE.
Steps to Interface LCD display:
1. Install driver library for Liquid Crystal Display.
- Navigate Tools>Library Manager (or) Enter ( Ctrl+Shift+I ) to open library manager.
- Search for "LiquidCrystal I2C" and install the "LiquidCrystal I2C" library.
Library Installation2. Import the header file "LiquidCrystal_I2C.h" in the code.
3. Connect the SDA pin of an LCD display to the SDA pin of the Arduino Board and the SCL pin of an LCD display to the SCL of the Arduino Board.
4. Connect VCC to 5V pin and GND to GND pin.
5. Include the below code to define the display device.
C++
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C
lcd(0x20, 16, 2); // Format => (ADDRESS,Width,Height )
void setup()
{
lcd.init(); // Initialize the lcd
lcd.backlight(); // Turn on the Backlight
// ....
}
Note: For ADDRESS, Try "0x27" or "0x3F". If those addresses are not working. Refer manufacturer page.
Or
To find the address, Run the following code to find the address.
Arduino code for I2C device Address Finding:
C++
// I2C address scanner program
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(9600);
Serial.println("I2C Scanner");
}
void loop()
{
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for (address = 1; address < 127; address++) {
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0) {
Serial.print("I2C device found at address 0x");
if (address < 16)
Serial.print("0");
Serial.print(address, HEX);
Serial.println(" !");
nDevices++;
}
else if (error == 4) {
Serial.print("Unknown error at address 0x");
if (address < 16)
Serial.print("0");
Serial.println(address, HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found");
else
Serial.println("done");
delay(5000); // wait 5 seconds for next scan
}
Serial monitor Output:
LCD Address FindingHere I2C Address is "0x20", So replace the address with "0x20" in the code.
(Ensure that you have connected the LCD display device as per the instruction while running this program in the Arduino).
Circuit Diagram with LCD display:
Ultrasonic Distance Measurement Output in LCD DisplayArduino code (Output in Serial Monitor + LCD display):
C++
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x20, 16, 2); // Format -> (Address,Width,Height )
#define echoPin 2 // attach pin D2 Arduino to Echo pin of Sensor module
#define trigPin 3 // attach pin D3 Arduino to Trig pin of Sensor module
long duration; // Declare variable to store echo time duration
int distance; // Declare variable to store the result (distance)
void setup()
{
lcd.init(); // initialize the lcd
lcd.backlight(); // Turn on the Backlight
pinMode(trigPin,OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
// Serial Communication is starting with 9600 of baudrate speed
Serial.begin(9600);
// The text to be printed in serial monitor
Serial.println("Distance measurement using Arduino Uno");
delay(500);
}
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.0344 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
lcd.clear(); // Clear the display buffer
lcd.setCursor(0, 0); // Set cursor for "Distance:" (Column, Row)
lcd.print("Distance:"); // print "Distance:" at (0, 0)
lcd.setCursor(0,1); // Set cursor for output value (0, 1)
lcd.print(distance); // print Output in cm at (0, 1)
lcd.setCursor(4, 1); // move cursor to (4, 1)
lcd.print("cm"); // print "cm" at (4, 1)
delay(100);
}
Output:
Applications of Ultrasonic Distance Measurement:
- Used in RADAR system.
- To measure distance without physical contact with measuring instruments.
- Used in object detection for security purposes.
Similar Reads
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. Balance Factor = left subtree height - right subtree heightFor a Balanced Tree(for every node): -1 ⤠Balance Factor ⤠1Example of an
4 min read
Half Wave Rectifier A Half-wave rectifier is an electronic device that is used to convert Alternating current (AC) to Direct current (DC). A half-wave rectifier allows either a positive or negative half-cycle of AC to pass and blocks the other half-cycle. Half-wave rectifier selectively allows only one half-cycle of th
15 min read
Python Match Case Statement Introduced in Python 3.10, the match case statement offers a powerful mechanism for pattern matching in Python. It allows us to perform more expressive and readable conditional checks. Unlike traditional if-elif-else chains, which can become unwieldy with complex conditions, the match-case statement
7 min read
Bridge Rectifier In the world of electronics, the bridge rectifier is a component that plays a role, in converting alternating current (AC) to direct current (DC). This article explores the concept of the bridge including how it's constructed how it operates, its benefits and drawbacks different types available, imp
11 min read
Schmitt Trigger We use Schmitt Triggers in digital electronics. It is used for rejecting the noise from the input signals by using the hysteresis curve. To provide accurate and more stable results, it uses two threshold voltages i.e., upper threshold voltage (VUT) and lower threshold voltage (VLT). It is mainly use
11 min read
8051 MicroController Architecture For many years, the 8051 microcontroller architecture is vital and important component in embedded systems design due to its common use. Its strong architecture and multiple uses in a variety of industries from consumer electronics to industrial automation are the main causes of its appeal.What is 8
6 min read
RJ45 Color Code Pre-requisites: RJ Full Form RJ45 is a well-known ethernet connectivity connector that allows users to connect through wired internet. there are other ports also which do the same, but RJ45 is widely used and most common in wired internet connection interfaces. It is an ethernet cable consisting of
3 min read
History of Operating System An operating system is a type of software that acts as an interface between the user and the hardware. It is responsible for handling various critical functions of the computer and utilizing resources very efficiently so the operating system is also known as a resource manager. The operating system
8 min read
Introduction of Microprocessor In this article we will go through the Microprocessor, we will first define what is a Microprocessor, then we will go through its different types with its block diagram and we will see different types of processors, At last, we will conclude our article with some applications and FAQs.What is Microp
6 min read