// Define pins for Ultrasonic Sensor
const int trigPin = 9; // Trigger pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor
const int ledPin = 13; // Pin for the LED (optional for object detection)
void setup() {
// Initialize the trigger and echo pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize the LED pin (optional)
pinMode(ledPin, OUTPUT);
// Start serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Send a 10us pulse to the trigger pin to start the measurement
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the time duration between sending and receiving the signal
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance (Speed of sound is ~343 m/s)
// Distance in cm = duration / 58.2
float distance = duration / 58.2;
// Print the distance in the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Optional: Light up the LED if the object is within 10 cm
if (distance <= 10) {
digitalWrite(ledPin, HIGH); // Turn on LED if object is close
Serial.println("Object detected within 10 cm!");
} else {
digitalWrite(ledPin, LOW); // Turn off LED if object is far
}
// Small delay before the next measurement
delay(500);
}