void setup() {
// Set pins as input or output
pinMode(D0, OUTPUT); // LED 1
pinMode(D7, OUTPUT); // LED 2
pinMode(D5, INPUT); // Echo Pin (Input)
pinMode(D4, OUTPUT); // Trig Pin (Output)
pinMode(D6, OUTPUT); // LED 3
}
void loop() {
long duration;
int distance;
// Generate a short pulse on Trig pin
digitalWrite(D4, LOW);
delayMicroseconds(2);
digitalWrite(D4, HIGH);
delayMicroseconds(10);
digitalWrite(D4, LOW);
// Measure the duration of echo pulse on Echo pin
duration = pulseIn(D5, HIGH);
// Calculate distance in centimeters
distance = duration * 0.0343 / 2;
// Show distance on Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Turn on LEDs based on measured distance
if (distance < 20) {
digitalWrite(D0, HIGH); // LED 1
digitalWrite(D7, HIGH); // LED 2
digitalWrite(D6, HIGH); // LED 3
} else if (distance >= 20 && distance < 50) {
digitalWrite(D0, HIGH);
digitalWrite(D7, HIGH);
digitalWrite(D6, LOW);
} else if (distance >= 50 && distance < 90) {
digitalWrite(D0, HIGH);
digitalWrite(D7, LOW);
digitalWrite(D6, LOW);
} else {
digitalWrite(D0, LOW);
digitalWrite(D7, LOW);
digitalWrite(D6, LOW);
}
delay(100); // Adjust the wait time as needed
}