void setup() {
// Initialize pins
pinMode(2, INPUT); // Set echoPin as an output
pinMode(5, OUTPUT); // Set echoPin as an input
pinMode(7, OUTPUT); // Set ledPin as an output
Serial.begin(9600); //Start serial communication for debugging
}
void loop() {
// Generate a 10 microsecond pulse to start the measurement
digitalWrite(5, LOW);
delayMicroseconds(2);
digitalWrite(5, HIGH);
delayMicroseconds(10);
digitalWrite(5, LOW);
long duration = pulseIn(2, HIGH); // Measure the duration of the pulse on the echoPin
long distance = duration * 0.034 / 2; // Calculate the distance in cm
Serial.print("Distance: "); // Print the distance to the serial monitor
Serial.print(distance);
Serial.println(" cm");
if (distance <= 20) { // Check if the distance is less than 20 cm
digitalWrite(7, HIGH); // Turn on the LED
} else {
digitalWrite(7, LOW); // Turn off the LED
}
delay(100); // Wait for a short period before taking the next measurement
}