// Define pins for the ultrasonic sensor and LED
const int trigPin = 5;
const int echoPin = 18;
const int ledPin = 19;
// Variable for storing the duration of the sound wave travel
long duration;
// Variable for storing the distance
int distance;
void setup() {
// Initialize the serial communication
Serial.begin(115200);
// Set the ultrasonic sensor pins as output and input
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set the LED pin as output
pinMode(ledPin, OUTPUT);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is less than 10 cm
if (distance < 100) {
digitalWrite(ledPin, HIGH); // Turn on LED
} else {
digitalWrite(ledPin, LOW); // Turn off LED
}
// Wait for a short period before the next loop
delay(100);
}