// Define ultrasonic sensor pins
const int trigPins[] = {2, 4, 7, 8};
const int echoPins[] = {3, 5, 6, 9};
// Define distance thresholds
const int frontThreshold = 20; // in centimeters
const int rearThreshold = 20; // in centimeters
void setup() {
Serial.begin(9600); // Initialize serial communication for debugging
}
void loop() {
// Read distances from ultrasonic sensors
int frontDistance = getDistance(trigPins[0], echoPins[0]);
int rearDistance = getDistance(trigPins[1], echoPins[1]);
// Check and display obstacle warnings
checkObstacle(frontDistance, "Front");
checkObstacle(rearDistance, "Rear");
delay(100); // Delay for stability and to avoid rapid readings
}
// Function to get distance from an ultrasonic sensor
int getDistance(int trigPin, int echoPin) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
return pulseIn(echoPin, HIGH) * 0.034 / 2; // Convert pulse duration to distance in centimeters
}
// Function to check and display obstacle warnings
void checkObstacle(int distance, String position) {
Serial.print(position + " Distance: ");
Serial.println(distance);
if (position == "Front" && distance < frontThreshold) {
Serial.println("Obstacle in front! Stop or take evasive action.");
// Implement additional actions if needed (e.g., stop the vehicle)
}
if (position == "Rear" && distance < rearThreshold) {
Serial.println("Obstacle in rear! Stop or take evasive action.");
// Implement additional actions if needed (e.g., activate reverse gear)
}
}