#define TRIG_PIN 9
#define ECHO_PIN 10
#define LED_PIN 13 // Optional LED
#define BUZZER_PIN 12 // Optional Buzzer
#define SAFE_DISTANCE 20 // Distance threshold in cm for obstacle detection
void setup() {
// Initialize serial communication:
Serial.begin(9600);
// Set the trigger pin as output and echo pin as input
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Set LED and Buzzer pins as output (if used)
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
// Send a pulse to the TRIG pin to start measuring distance
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2); // Wait for a short time
digitalWrite(TRIG_PIN, HIGH); // Send a pulse
delayMicroseconds(10); // Pulse duration
digitalWrite(TRIG_PIN, LOW); // Stop sending pulse
// Measure the pulse duration on the ECHO pin
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance (in cm)
long distance = (duration / 2) / 29.1; // Speed of sound is 343 m/s
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is below the threshold (obstacle detected)
if (distance < SAFE_DISTANCE) {
// Turn on LED and Buzzer if obstacle is detected
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);
} else {
// Turn off LED and Buzzer if no obstacle is detected
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
}
// Wait for a short period before the next reading
delay(500);
}