#define TRIG_PIN 9 // Pin for Trigger
#define ECHO_PIN 10 // Pin for Echo
#define LED_PIN 8 // Pin for LED
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// Get the distance from the ultrasonic sensor
long duration = getUltrasonicDistance();
float distance = duration * 0.034 / 2; // Convert to centimeters
// Display the distance in the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// If distance is less than 10 cm, turn on the LED
if (distance < 10) {
digitalWrite(LED_PIN, HIGH); // Turn LED on
} else {
digitalWrite(LED_PIN, LOW); // Turn LED off
}
delay(1000); // Wait for 1 second before measuring again
}
// Function to get the distance from the ultrasonic sensor
long getUltrasonicDistance() {
// Clear the trigger pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Send a 10µs pulse to trigger the sensor
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration for the echo pin to go HIGH
long duration = pulseIn(ECHO_PIN, HIGH);
return duration;
}