A digital distance meter — HC-SR04 ultrasonic sensor, 16x2 LCD display, and a buzzer that beeps faster as objects approach. No libraries needed for the sensor.
The sensor sends an ultrasonic pulse and measures how long it takes to bounce back. Speed of sound = 340 m/s.
// HC-SR04 Wiring:
// VCC → 5V
// GND → GND
// TRIG → Digital Pin 9
// ECHO → Digital Pin 10
const int TRIG = 9;
const int ECHO = 10;
void setup() {
Serial.begin(9600);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
}
long measureCm() {
// Send a 10-microsecond trigger pulse
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
digitalWrite(TRIG, LOW);
// Measure echo duration
long duration = pulseIn(ECHO, HIGH, 30000); // 30ms timeout
// Distance = (duration * speed of sound) / 2
// Speed = 0.0343 cm/us
return duration * 0.0343 / 2;
}
void loop() {
long cm = measureCm();
if (cm > 0 && cm < 400) {
Serial.print("Distance: ");
Serial.print(cm);
Serial.println(" cm");
} else {
Serial.println("Out of range");
}
delay(100);
}
Show the distance on an LCD using the LiquidCrystal_I2C library.
// Install: Library Manager -> Search "LiquidCrystal I2C" -> Install
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Address 0x27 is most common
const int TRIG = 9;
const int ECHO = 10;
const int BUZZ = 6;
void setup() {
lcd.init();
lcd.backlight();
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(BUZZ, OUTPUT);
lcd.print("Distance Meter");
delay(1500);
lcd.clear();
}
long measureCm() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long d = pulseIn(ECHO, HIGH, 30000);
return d * 0.0343 / 2;
}
void loop() {
long cm = measureCm();
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.setCursor(0, 1);
if (cm > 0 && cm < 400) {
lcd.print(cm);
lcd.print(" cm ");
// Beep faster when closer
int beepDelay = constrain(cm * 5, 50, 1000);
tone(BUZZ, 2000, 50);
delay(beepDelay);
} else {
lcd.print("Out of range ");
noTone(BUZZ);
delay(300);
}
}
An HC-SR04 costs about $1 and can measure anything from 2 cm to 4 m. This same sensor is used in robot obstacle avoidance, parking sensors, water level monitors, and automatic door openers.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.