ElectroMartBDElectroMartBD

Build an Ultrasonic Distance Meter with Arduino

The HC-SR04 sends out a sound pulse and measures how long the echo takes to come back. With an Arduino and a 16x2 LCD you can turn that into a handy digital distance meter — a great first sensor project.

1. Wiring

HC-SR04:

  • VCC → 5V
  • GND → GND
  • TRIG → Pin 9
  • ECHO → Pin 10

I2C LCD:

  • VCC → 5V, GND → GND
  • SDA → A4, SCL → A5

2. The Code

Install the LiquidCrystal_I2C library from the Library Manager first. If the screen stays blank, try address 0x3F instead of 0x27.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int trigPin = 9, echoPin = 10;

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

void loop() {
  digitalWrite(trigPin, LOW); delayMicroseconds(2);
  digitalWrite(trigPin, HIGH); delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH, 30000);
  float cm = duration * 0.0343 / 2;
  lcd.setCursor(0, 0); lcd.print("Distance:       ");
  lcd.setCursor(0, 1); lcd.print(cm, 1); lcd.print(" cm      ");
  delay(300);
}

3. Ideas to Extend It

  • Add a buzzer that beeps faster as objects get closer (a parking sensor).
  • Mount it on a robot car for obstacle avoidance.

Need help? Stuck on wiring or code? Message us on WhatsApp at +880 1577-098376 and we will help you with your project.