#define TRIG_PIN 32 // Arduino pin connected to the TRIG pin of the ultrasonic sensor
#define ECHO_PIN 33 // Arduino pin connected to the ECHO pin of the ultrasonic sensor
#define GREEN_LED_PIN 16 // Arduino pin connected to the green LED
#define YELLOW_LED_PIN 15 // Arduino pin connected to the yellow LED
#define RED_LED_PIN 0 // Arduino pin connected to the red LED
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
pinMode(YELLOW_LED_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
// Initialize LEDs
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(YELLOW_LED_PIN, LOW);
digitalWrite(RED_LED_PIN, LOW);
}
void loop() {
long duration, distance;
// Send ultrasonic pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read ultrasonic echo
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in cm
distance = (duration * 0.0343) / 2;
// Display distance on the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Control LEDs based on distance
if (distance > 150) {
// Distance > 150 cm
digitalWrite(GREEN_LED_PIN, HIGH);
digitalWrite(YELLOW_LED_PIN, LOW);
digitalWrite(RED_LED_PIN, LOW);
} else if (distance > 50 && distance <= 150) {
// 50 cm < Distance <= 150 cm
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(YELLOW_LED_PIN, HIGH);
digitalWrite(RED_LED_PIN, LOW);
} else {
// Distance <= 50 cm
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(YELLOW_LED_PIN, LOW);
digitalWrite(RED_LED_PIN, HIGH);
}
delay(1000); // Delay for stability
}