// Pin definitions for the Ultrasonic Sensor
const int TRIG_PIN = 25;
const int ECHO_PIN = 26;
// Pin definitions for the LEDs
const int GREEN_LED = 32;
const int YELLOW_LED = 33;
const int RED_LED = 18;
// Variables for distance measurement
long duration;
float distance_cm;
void setup() {
Serial.begin(115200);
// Set up sensor pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Set up LED pins
pinMode(GREEN_LED, OUTPUT);
pinMode(YELLOW_LED, OUTPUT);
pinMode(RED_LED, OUTPUT);
}
void loop() {
// Clear the TRIG pin and send the ultrasonic pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in cm
distance_cm = duration * 0.034 / 2.0;
// Control the LEDs based on the distance using if-else if-else logic
if (distance_cm > 100) {
// Distance > 100 cm: Green LED on, others off
digitalWrite(GREEN_LED, HIGH);
digitalWrite(YELLOW_LED, LOW);
digitalWrite(RED_LED, LOW);
} else if (distance_cm >= 30 && distance_cm <= 100) {
// 30 <= Distance <= 100 cm: Yellow LED on, others off
digitalWrite(GREEN_LED, LOW);
digitalWrite(YELLOW_LED, HIGH);
digitalWrite(RED_LED, LOW);
} else if (distance_cm < 30) {
// Distance < 30 cm: Red LED on, others off
digitalWrite(GREEN_LED, LOW);
digitalWrite(YELLOW_LED, LOW);
digitalWrite(RED_LED, HIGH);
}
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
// Wait before the next measurement
delay(500);
}