Optional ESP32 Implementation (HC-SR04)
Optional ESP32 Implementation (HC-SR04)
animation
sensors
NoteOptional ESP32 Implementation
This example reads the sensor and reports its output. Use it after checking the wiring, then compare the reported values with the physical test described above.
#define TRIG_PIN 5
#define ECHO_PIN 18
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
float distance = measureDistance();
Serial.print("Distance: ");
Serial.print(distance, 1);
Serial.println(" cm");
// Object detection
if (distance > 0 && distance < 50) {
Serial.println("Object detected nearby!");
}
delay(100);
}
float measureDistance() {
// Send 10us pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure echo pulse duration
long duration = pulseIn(ECHO_PIN, HIGH, 30000); // 30ms timeout
// Calculate distance (speed of sound = 343 m/s at 20°C)
// distance = (duration * 0.0343) / 2
float distance = duration * 0.0343 / 2.0;
return distance;
}