#define trigger_pin 2
#define echo_pin 3
#define led_pin 12
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(trigger_pin, OUTPUT);
pinMode(echo_pin, INPUT);
pinMode(led_pin, OUTPUT);
}
void loop() {
// Send a short pulse to trigger the sensor
digitalWrite(trigger_pin, LOW);
delayMicroseconds(2);
digitalWrite(trigger_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trigger_pin, LOW);
// Measure the time for the echo to return
long duration = pulseIn(echo_pin, HIGH);
// Calculate distance in cm
float distance = (duration / 2.0) * 0.0343;
// Print the distance
if (distance >= 10) {
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
} else {
Serial.println("Error: Out of range");
delay(500);
}
// Control the LED based on distance
if (distance <= 10) {
digitalWrite(led_pin, HIGH); // Turn LED ON
} else {
digitalWrite(led_pin, LOW); // Turn LED OFF
}
// Short delay before next measurement
delay(100);
}