// Define the pins for the ultrasonic sensor
const int trigPin = 9; // Trigger pin of the sensor
const int echoPin = 10; // Echo pin of the sensor
// Define the pins for the indicator LEDs
const int greenLed = 3; // Green LED pin
const int yellowLed = 5; // Yellow LED pin
const int redLed = 6; // Red LED pin
// Define the distance thresholds for indicating proximity
const int greenThreshold = 100; // Green LED threshold in cm
const int yellowThreshold = 50; // Yellow LED threshold in cm
const int redThreshold = 10; // Red LED threshold in cm
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
// Initialize ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize LED pins
pinMode(greenLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(redLed, OUTPUT);
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pulse duration
long duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
int distance = duration * 0.034 / 2;
// Print distance to serial monitor for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Turn off all LEDs
digitalWrite(greenLed, LOW);
digitalWrite(yellowLed, LOW);
digitalWrite(redLed, LOW);
// Determine which LED to light based on distance
if (distance > greenThreshold) {
digitalWrite(greenLed, HIGH);
} else if (distance > yellowThreshold) {
digitalWrite(yellowLed, HIGH);
} else if (distance > redThreshold) {
digitalWrite(redLed, HIGH);
} else {
// Distance less than red threshold
digitalWrite(redLed, HIGH);
}
// Delay before taking next reading
delay(500); // Adjust the delay based on your requirements
}