// Define pins for the HC-SR04
const int trigPin = 13;
const int echoPin = 12;
// Define pin for the LED
const int ledPin = 11;
// Define distance threshold (in centimeters)
const int thresholdDistance = 100;
// Define variables
long duration;
int distance;
void setup() {
// Start serial communication
Serial.begin(9600);
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigger pin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.0344 / 2; // Speed of sound: 0.0344 cm/us, divided by 2 for the round-trip
// Print the distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Control the LED based on distance
if (distance < thresholdDistance) {
digitalWrite(ledPin, HIGH); // Turn LED ON
} else {
digitalWrite(ledPin, LOW); // Turn LED OFF
}
// Wait before the next measurement
delay(500);
}