// Define the pins for the ultrasonic sensor
const int trigPin = 2; // Trig pin of the ultrasonic sensor
const int echoPin = 3; // Echo pin of the ultrasonic sensor
// Define the pins for the LEDs
const int nearLedPin = 13; // Pin for the LED indicating a near object
const int farLedPin = 12; // Pin for the LED indicating a far object
// Variables for ultrasonic sensor
long duration; // To store the time it takes for the sound wave to return
int distance; // To store the calculated distance in centimeters
void setup() {
pinMode(trigPin, OUTPUT); // Set trig pin as output
pinMode(echoPin, INPUT); // Set echo pin as input
pinMode(nearLedPin, OUTPUT); // Set near LED pin as output
pinMode(farLedPin, OUTPUT); // Set far LED pin as output
Serial.begin(9600); // Initialize serial communication for debugging
}
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to the trigger pin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2 * 10;
// Print the distance for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" mm");
// Check the distance and control LEDs accordingly
if (distance <= 250) {
digitalWrite(nearLedPin, HIGH); // Turn on the near LED
digitalWrite(farLedPin, LOW); // Turn off the far LED
} else {
digitalWrite(nearLedPin, LOW); // Turn off the near LED
digitalWrite(farLedPin, HIGH); // Turn on the far LED
}
delay(100); // Delay before next reading
}