const int trigPin1 = 9;
const int echoPin1 = 10;
const int trigPin2 = 11;
const int echoPin2 = 12;
const int ledRed1 = 2;
const int ledYellow1 = 3;
const int ledGreen1 = 4;
const int ledRed2 = 5;
const int ledYellow2 = 6;
const int ledGreen2 = 7;
long duration;
int distance;
void setup() {
// Set up the serial communication
Serial.begin(9600);
// Set up the ultrasonic sensors
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
// Set up the LEDs
pinMode(ledRed1, OUTPUT);
pinMode(ledYellow1, OUTPUT);
pinMode(ledGreen1, OUTPUT);
pinMode(ledRed2, OUTPUT);
pinMode(ledYellow2, OUTPUT);
pinMode(ledGreen2, OUTPUT);
}
void loop() {
// Measure distance from sensor 1
distance = measureDistance(trigPin1, echoPin1);
Serial.print("Sensor 1: ");
Serial.print(distance);
Serial.println(" cm");
controlLEDs(distance, ledRed1, ledYellow1, ledGreen1);
// Measure distance from sensor 2
distance = measureDistance(trigPin2, echoPin2);
Serial.print("Sensor 2: ");
Serial.print(distance);
Serial.println(" cm");
controlLEDs(distance, ledRed2, ledYellow2, ledGreen2);
delay(500);
}
int measureDistance(int trigPin, int echoPin) {
// 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
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
int distance = duration * 0.034 / 2;
return distance;
}
void controlLEDs(int distance, int ledRed, int ledYellow, int ledGreen) {
// Turn off all LEDs
digitalWrite(ledRed, LOW);
digitalWrite(ledYellow, LOW);
digitalWrite(ledGreen, LOW);
// Turn on the appropriate LED based on the distance
if (distance < 10) {
digitalWrite(ledRed, HIGH);
} else if (distance < 20) {
digitalWrite(ledYellow, HIGH);
} else {
digitalWrite(ledGreen, HIGH);
}
}