// Define the pins for the ultrasonic sensor
const int trigPin = 3;
const int echoPin = 2;
// Define the pins for the LEDs
const int led1Pin =11;
const int led2Pin = 10;
const int led3Pin = 9;
void setup() {
// Set the pins for the ultrasonic sensor
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set the pins for the LEDs
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
pinMode(led3Pin, OUTPUT);
// Turn off all the LEDs initially
digitalWrite(led1Pin, LOW);
digitalWrite(led2Pin, LOW);
digitalWrite(led3Pin, LOW);
// Start the serial communication
Serial.begin(9600);
}
void loop() {
// Send a pulse to the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the distance from the ultrasonic sensor
long duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.println(distance);
// Turn on the appropriate LED based on the distance
if (distance < 100) {
digitalWrite(led1Pin, HIGH);
digitalWrite(led2Pin, LOW);
digitalWrite(led3Pin, LOW);
} else if (distance >= 100 && distance <= 200) {
digitalWrite(led1Pin, LOW);
digitalWrite(led2Pin, HIGH);
digitalWrite(led3Pin, LOW);
} else {
digitalWrite(led1Pin, LOW);
digitalWrite(led2Pin, LOW);
digitalWrite(led3Pin, HIGH);
}
// Wait for a short period before taking the next measurement
delay(100);
}