// Define pins for ultrasonic sensor
const int trigPin = 6; // Trigger pin
const int echoPin = 5; // Echo pin
// Define pins for LEDs
const int greenLed = 2;
const int yellowLed = 3;
const int redLed = 4;
// Variables to store distance and duration
long duration;
int distance;
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(trigPin, OUTPUT); // Set trigger pin as output
pinMode(echoPin, INPUT); // Set echo pin as input
// Set LED pins as output
pinMode(greenLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(redLed, OUTPUT);
}
void loop() {
// Clear trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10us pulse to trigger pin to start ranging
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of pulse from echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2; // Speed of sound in air is 343 m/s (34.3 cm/ms), divide by 2 because sound travels to the object and back
// Print distance to serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Turn on appropriate LED based on distance
if (distance < 20) { // If distance is less than 20 cm
digitalWrite(greenLed, LOW);
digitalWrite(yellowLed, LOW);
digitalWrite(redLed, HIGH); // Turn on red LED
} else if (distance >= 20 && distance < 50) { // If distance is between 20 cm and 50 cm
digitalWrite(greenLed, LOW);
digitalWrite(yellowLed, HIGH); // Turn on yellow LED
digitalWrite(redLed, LOW);
} else { // If distance is greater than or equal to 50 cm
digitalWrite(greenLed, HIGH); // Turn on green LED
digitalWrite(yellowLed, LOW);
digitalWrite(redLed, LOW);
}
// Delay before next reading
delay(1000); // Adjust delay according to your requirement
}