// Pin definitions (compatible with ESP32; change to 9, 10, 13 for Arduino Uno)
#define TRIG_PIN 26
#define ECHO_PIN 27
#define LED_PIN 25
void setup() {
Serial.begin(115200); // Use 9600 if on Arduino Uno
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// 1. Clear the TRIG_PIN
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// 2. Send a 10-microsecond HIGH pulse to trigger the sensor
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// 3. Read the echo pulse duration (timeout after 30,000 µs / ~5 meters)
long duration = pulseIn(ECHO_PIN, HIGH, 30000);
// 4. Calculate distance in cm (Speed of sound = 0.0343 cm/µs)
float distance = (duration * 0.0343) / 2.0;
// 5. Print the result and control the LED
if (duration == 0) {
Serial.println("Out of range");
digitalWrite(LED_PIN, LOW);
} else {
Serial.print("Distance: ");
Serial.print(distance, 1);
Serial.println(" cm");
// Turn on LED if an object is closer than 15 cm
if (distance < 15.0) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
}
delay(200); // Short delay between readings
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4