Back to Robotics Hub
Beginner Projects Beginner Mar 21, 2026

Ultrasonic Distance Meter

Ultrasonic Distance Meter

Project Overview

Moving beyond blinky lights, this project uses the popular HC-SR04 sonar sensor to calculate distance based on the speed of sound. We output the result to an I2C LCD display, making a practical digital tape measure.

Components Required

  • 1x Arduino Nano or Uno
  • 1x HC-SR04 Ultrasonic Sensor
  • 1x 16x2 LCD Display with I2C Backpack
  • Jumper Wires (Female-to-Male)

Wiring Guide

HC-SR04: VCC to 5V, GND to GND, TRIG to Pin 9, ECHO to Pin 10.
LCD I2C: VCC to 5V, GND to GND, SDA to A4, SCL to A5.

Source Code


#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);
const int trigPin = 9;
const int echoPin = 10;

void setup() {
  lcd.init();
  lcd.backlight();
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1; // Convert to cm
  
  lcd.setCursor(0, 0);
  lcd.print("Dist: ");
  lcd.print(distance);
  lcd.print(" cm   ");
  delay(500);
}