// Define pins
const int trigPin = 5; // Trig pin of ultrasonic sensor
const int echoPin = 18; // Echo pin of ultrasonic sensor
const int ledPin = 2; // LED pin
// Variables to store distance
long duration;
int distance;
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and calculate the distance
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2; // Convert duration to distance (cm)
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is less than 5 cm
if (distance < 5) {
// Blink the LED
digitalWrite(ledPin, HIGH);
delay(500); // LED on for 500ms
digitalWrite(ledPin, LOW);
delay(500); // LED off for 500ms
} else {
// Turn off the LED
digitalWrite(ledPin, LOW);
}
// Small delay before next reading
delay(100);
}