const int trigPin = 2;
const int echoPin = 3;
const int buzzerPin = 4;
const int ledPin = 5;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo duration
unsigned long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
float distance_cm = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
// Check if the distance is less than a threshold (adjust as needed)
if (distance_cm < 30) {
// Activate the buzzer and LED to indicate an obstacle
digitalWrite(buzzerPin, HIGH);
digitalWrite(ledPin, HIGH);
Serial.println("Obstacle detected! Parking assist active.");
} else {
// Turn off the buzzer and LED
digitalWrite(buzzerPin, LOW);
digitalWrite(ledPin, LOW);
}
delay(500); // Delay for stability and to avoid rapid readings
}