// Define the pins used for the ultrasonic sensor
const int trigPin = 4;
const int echoPin = 5;
// Define the pins used for the LEDs
const int redPin = 12;
const int greenPin = 13;
const int yellowPin = 14;
void setup() {
// Initialize the serial communication
Serial.begin(9600);
// Initialize the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize the LED pins
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
}
void loop() {
// Trigger the ultrasonic sensor by sending a 10 microsecond pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse from the ultrasonic sensor
long duration = pulseIn(echoPin, HIGH);
// Convert the duration to distance in centimeters
int distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Blink the LED colors based on the distance
if (distance < 10) {
digitalWrite(redPin, HIGH);
delay(100);
digitalWrite(redPin, LOW);
delay(100);
digitalWrite(greenPin, LOW);
digitalWrite(yellowPin, LOW);
} else if (distance < 20) {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
digitalWrite(yellowPin, LOW);
digitalWrite(yellowPin, HIGH);
delay(250);
digitalWrite(yellowPin, LOW);
delay(250);
} else {
digitalWrite(redPin, LOW);
digitalWrite(yellowPin, LOW);
digitalWrite(greenPin, HIGH);
}
}