// Define the pins for the ultrasonic sensor
const int trigPin = 12; // Trig pin of the ultrasonic sensor
const int echoPin = 13; // Echo pin of the ultrasonic sensor
// Define the pins for the LEDs
const int pin1 = 1; // Pin for the LED indicating a near object
const int pin2 = 2; // Pin for the LED indicating a far object
const int pin3 = 3;
const int pin4 = 4;
const int pin5 = 5;
// 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(pin1, OUTPUT); // Set near LED pin as output
pinMode(pin2, OUTPUT); // Set far LED pin as output
pinMode(pin3, OUTPUT);
pinMode(pin4, OUTPUT);
pinMode(pin5, 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;
// Print the distance for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check the distance and control LEDs accordingly
if (distance <= 100) {
digitalWrite(pin1, HIGH);
}
if (distance <= 80) {
digitalWrite(pin2, HIGH);
}
if (distance <= 60) {
digitalWrite(pin3, HIGH);
}
if (distance <= 45) {
digitalWrite(pin4, HIGH);
}
if (distance <= 30) {
digitalWrite(pin5, HIGH);
}
delay(100); // Delay before next reading
}