#define echoPin 2
#define trigPin 3
int maximumRange = 400; // Adjusted to the maximum reliable range of the sensor
int minimumRange = 2; // A realistic minimum range to avoid zero or negative readings
long duration, distance;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
}
void loop() {
// Trigger the ultrasonic burst
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(echoPin, HIGH);
// Calculate the distance based on the duration
distance = duration / 58.2;
// Check if the distance is within the measurable range of the sensor
if (distance > maximumRange || distance < minimumRange) {
Serial.println("Di Luar jangkauan");
} else {
// Print the measured distance to the serial monitor
Serial.print("Jarak: ");
Serial.print(distance);
Serial.println(" cm");
// Control the LEDs based on the distance
if (distance <= 100) {
digitalWrite(11, HIGH);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
} else if (distance > 100 && distance < 200) {
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
} else if (distance >= 200) {
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
}
delay(1000);
}
}