// Define pins for the first ultrasonic sensor
const int trigPin1 = 9;
const int echoPin1 = 10;
// Define pins for the second ultrasonic sensor
const int trigPin2 = 11;
const int echoPin2 = 12;
// Define pins for the LEDs
const int ledRed = 13;
const int ledGreen = 8;
// Variables to store the duration and distance for both sensors
long duration1, duration2;
int distance1, distance2;
void setup() {
// Initialize serial communication at 9600 baud rate
Serial.begin(9600);
// Set trig and echo pins for both sensors
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
// Set LED pins as output
pinMode(ledRed, OUTPUT);
pinMode(ledGreen, OUTPUT);
}
void loop() {
// Measure distance with the first sensor
distance1 = getDistance(trigPin1, echoPin1);
Serial.print("Distance 1: ");
Serial.print(distance1);
Serial.println(" cm");
// Measure distance with the second sensor
distance2 = getDistance(trigPin2, echoPin2);
Serial.print("Distance 2: ");
Serial.print(distance2);
Serial.println(" cm");
// Determine LED status based on distances
if (distance1 < 20 || distance2 < 20) {
// Distance is less than 20 cm
digitalWrite(ledRed, HIGH);
digitalWrite(ledGreen, LOW);
} else {
// Distance is 20 cm or more
digitalWrite(ledRed, LOW);
digitalWrite(ledGreen, HIGH);
}
// Wait for a bit before the next loop
delay(1000);
}
// Function to get distance from a sensor
int getDistance(int trigPin, int echoPin) {
long duration;
int distance;
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
distance = duration * 0.034 / 2;
return distance;
}