Labs / Sensors · Intermediate · 30 min
Ultrasonic distance
Convert echo time to distance.
Engineering instrumentation: This lab includes an instrument-style virtual test setup and parameter-driven waveform. For physical measurements, use the Practical Bench.
Parts
- HC-SR04
- ESP32
- Voltage divider 5.1k and 10k
- Buzzer
Steps
- Connect TRIG to GPIO 5.
- Connect ECHO through the divider to GPIO 18.
- Upload the code.
- Compare with a ruler.
Safety: check polarity and power off before changing the circuit.
ESP32 code (Arduino IDE)
const int TRIG=5, ECHO=18;
void setup(){ Serial.begin(115200); pinMode(TRIG,OUTPUT); pinMode(ECHO,INPUT); }
void loop(){ digitalWrite(TRIG,HIGH); delayMicroseconds(10); digitalWrite(TRIG,LOW);
long us=pulseIn(ECHO,HIGH,30000); Serial.println(us*0.0343/2); delay(100); }Viva questions
Why divide by 2?
The sound travels to the object and back.
Does temperature matter?
Yes, speed of sound is about 331.3 + 0.606 x T m/s.
Why a voltage divider on ECHO?
ECHO is 5 V but ESP32 inputs are 3.3 V.