#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 3, 2);
#define TRIG_PIN 5
#define ECHO_PIN 18
#define BUZZER_PIN 23
void setup() {
pinMode(TRIG_PIN, OUTPUT); // Set the trigger pin as an output
pinMode(ECHO_PIN, INPUT); // Set the echo pin as an input
pinMode(BUZZER_PIN, OUTPUT); // Set buzzer pin as output
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Crash Distance: ");
Serial.begin(115200); // Start serial communication
}
void loop() {
long duration, distance;
digitalWrite(TRIG_PIN, HIGH); // send a high trigger for 10 microseconds
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH); // read the echo signal to measure the return time.
distance = duration * 0.034 / 2; // calculate the distance in cm
Serial.print("Distance: " );
Serial.println(distance);
lcd.setCursor(0, 1);
lcd.print(distance);
delay(100);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Crash Distance: ");
// Change beep duration based on distance
if (distance < 50 && distance > 0) { // Check for a valid distance reading
long beepDuration = map(distance, 0, 50, 50, 500); // Map distance to beep duration
tone(BUZZER_PIN, 10, beepDuration); // Constant frequency of 1000 Hz, variable duration
delay(beepDuration + 200); // Wait for the beep to finish plus a short pause
lcd.setCursor(1, 1);
lcd.print(distance);
lcd.print(" TOO CLOSE!!!!!!!!");
delay(100);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Crash Distance: ");
} else {
noTone(BUZZER_PIN); // Turn off the buzzer if the distance is out of range
delay(10000); // Longer pause when nothing is detected
}
}