Ultrasonic Distance Meter with Arduino
Build a digital distance measuring tool using ultrasonic sensor and LCD display.
Parts List
- Arduino Uno
- HC-SR04 Ultrasonic Sensor
- 16x2 LCD Display
- Potentiometer (10kΩ)
- Breadboard
Step-by-Step Instructions
Wire Ultrasonic Sensor
Connect the HC-SR04 sensor's VCC pin to Arduino 5V and GND to ground. Wire the Trig pin to digital pin 9 and the Echo pin to digital pin 10 on the Arduino. Position the sensor facing the target surface and ensure nothing is blocking the path between the sensor and the object being measured.
Connect LCD
Wire the 16x2 LCD display using the I2C backpack or direct parallel connection, connecting RS to pin 12, EN to pin 11, D4 to pin 5, D5 to pin 4, D6 to pin 3, and D7 to pin 2. Connect the LCD's VCC to 5V, GND to ground, and the backlight anode to 5V through a current-limiting resistor. Attach the 10kΩ potentiometer to the V0 contrast pin and adjust it until the display characters are clearly visible.
Write Distance Code
Write an Arduino sketch that sends a 10-microsecond pulse on the Trig pin to trigger the ultrasonic measurement. Read the duration of the Echo pulse using pulseIn() and calculate the distance in centimeters by multiplying the duration by 0.034 and dividing by two. Filter out invalid readings by ignoring measurements outside the sensor's reliable range of 2-400 centimeters.
const int trigPin = 9;
const int echoPin = 10;
float minDist = 999, maxDist = 0;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
float measure() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long dur = pulseIn(echoPin, HIGH, 30000);
float dist = dur * 0.034 / 2.0;
if (dist >= 2 && dist <= 400) {
if (dist < minDist) minDist = dist;
if (dist > maxDist) maxDist = dist;
return dist;
}
return -1;
}Display Results
Initialize the LCD in the setup function and clear the display before each new reading. Format the distance value as a string with one decimal place and display it on the first line with a 'Distance:' label. Add a minimum/maximum tracker that records and displays the closest and farthest readings since the last reset, useful for measuring room dimensions or checking clearance.