/*
Wokwi | questions
Hi can someone help me pls! T^T
bea - Tuesday, June 30, 2026 11:20 AM
I want the LCD to display the distance like if the buzzer
detects the object less than XX cm away from sensor.
Which wires do I connect the LCD to where?
*/
#include <LiquidCrystal.h>
const int THRESHOLD = 50; // buzz if less than 50cm
const int ECHO_PIN = 2;
const int TRIG_PIN = 3;
const int BUZZ_PIN = 4;
const int RS = 10, EN = 9, D4 = 8, D5 = 7, D6 = 6, D7 = 5;
LiquidCrystal lcd(RS, EN, D4, D5, D6, D7);
// function to measure distance
int getRange() {
// send trigger pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// read pulse duration
long duration = pulseIn(ECHO_PIN, HIGH);
// calculate distance
long distance = duration * 0.0343 / 2;
return (int)distance + 0.5;
}
void showRange(int range) {
lcd.setCursor(2, 0);
lcd.print("Range:");
lcd.setCursor(6, 1);
lcd.print(range);
lcd.print(" cm ");
Serial.print("Range: ");
Serial.print(range);
Serial.println(" cm");
}
void showSplash() {
lcd.setCursor(2, 0);
lcd.print("HC-SR04 Demo");
lcd.setCursor(6, 1);
lcd.print("V1.0");
delay(2000);
lcd.clear();
Serial.println("HC-SR04 Demo");
}
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
pinMode(ECHO_PIN, INPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(BUZZ_PIN, OUTPUT);
showSplash();
}
void loop() {
int distance = getRange();
if (distance <= THRESHOLD)
tone(BUZZ_PIN, 440, 500);
showRange(distance);
delay(1000);
}