In this project, we will build an Arduino-based Ultrasonic Distance Meter using an HC-SR04 ultrasonic sensor and a 16x2 I2C LCD display. The system measures the distance of an object and displays the result in centimetres on the LCD screen.
The ultrasonic sensor sends sound waves and calculates the distance by measuring the time taken for the echo to return. Arduino processes this data and displays the measured distance on the LCD. This project is useful for understanding ultrasonic sensors, I2C communication, and distance measurement using Arduino UNO.
| Component | Quantity |
|---|---|
| Arduino UNO | 1 |
| HC-SR04 Ultrasonic Sensor | 1 |
| 16x2 LCD with I2C Module | 1 |
| Breadboard | 1 |
| Jumper Wires | As required |
Connect the HC-SR04 ultrasonic sensor and I2C LCD display to the Arduino UNO according to the connection table below.
| Ultrasonic Sensor Pin | Arduino UNO Pin |
|---|---|
| VCC | 5V |
| GND | GND |
| TRIG | D9 |
| ECHO | D10 |
| LCD I2C Pin | Arduino UNO Pin |
|---|---|
| VCC | 5V |
| GND | GND |
| SDA | A4 |
| SCL | A5 |
The HC-SR04 sensor sends ultrasonic waves towards an object. When these waves hit the object, they return to the sensor as an echo. Arduino measures the time taken by the echo to return and calculates the distance using the speed of sound. Finally, the measured distance is displayed on the 16x2 I2C LCD in centimetres.
// Creative Inventions
// Subscribe to my YouTube channel
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Initialize LCD (I2C address: 0x27)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Ultrasonic Sensor Pins
const int trigPin = 9;
const int echoPin = 10;
unsigned long duration;
float distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Distance Meter");
lcd.setCursor(0, 1);
lcd.print("Initializing...");
delay(1500);
lcd.clear();
Serial.begin(9600);
}
void loop() {
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read echo duration
duration = pulseIn(echoPin, HIGH, 30000UL);
lcd.setCursor(0, 0);
lcd.print("Distance:");
lcd.setCursor(0, 1);
if (duration == 0) {
lcd.print("Out of range ");
Serial.println("Out of range");
} else {
// Calculate distance in cm
distance = duration * 0.0343 / 2.0;
lcd.print(distance, 1);
lcd.print(" cm ");
Serial.print("Distance: ");
Serial.print(distance, 1);
Serial.println(" cm");
}
delay(200);
}