// menentukan pin untuk sensor ultrasonik
const int trigPin = 9;
const int echoPin = 10;
// menentukan pin untuk LED
const int ledPin = 13;
// menentukan jarak ambang batas dalam cm
const int thresholdDistance = 10;
void setup() {
// menginisiasi komunikasi serial
Serial.begin(9600);
// mengatur pin sebagai input atau output
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
// Matikan LED terlebih dahulu
digitalWrite(ledPin, LOW);
}
void loop() {
// Send a 10us pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance
int distance = duration * 0.034 / 2;
// Print the distance for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Turn on the LED if the object is within the threshold distance
if (distance <= thresholdDistance) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
// Small delay before the next measurement
delay(100);
}