How to connect an HC-SR04 to ESP32

Echo through a 1 kΩ and 2 kΩ divider, 5 V power.

Wiring diagram

Open in the builder

Connections

StepFromToColor
1ESP32 DOIT GNDHC-SR04 GNDblack
2ESP32 DOIT VINHC-SR04 Vccred
3ESP32 DOIT D18HC-SR04 Trigwhite
4HC-SR04 EchoResistor 1 kΩ 2white
5ESP32 DOIT D19Resistor 1 kΩ 1white
6Resistor 1 kΩ 1Resistor 2 kΩ 1white
7ESP32 DOIT GNDResistor 2 kΩ 2black

Power and wiring check

  • The schematic check, the same as in the builder, found no errors: pin voltages match, ground is common, buses are fully connected.
  • HC-SR04 draws about 15 mA from the VIN pin of ESP32 DOIT, the pin supplies about 300 mA: USB gives 500 mA, the board takes part of it.

Current of the whole circuit and how long it runs on a battery: power budget. Where to plug what: breadboard layout.

Example code

Arduino IDE, no libraries, ESP32 Arduino core 3.x.

const int TRIG = 18, ECHO = 19;

void setup() {
  Serial.begin(115200);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
}

void loop() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  // no echo within 30 ms: farther than 5 m or nothing ahead
  unsigned long us = pulseIn(ECHO, HIGH, 30000);
  if (us) Serial.printf("%.1f cm\n", us / 58.0);
  delay(200);
}

Part pinouts

Next steps for this circuit

How it is connected

The HC-SR04 runs on 5 V: on an ESP32 DevKit that is the VIN pin, which carries 5 V from USB. Trig gets a 10 µs pulse from GPIO18. Echo returns its answer at 5 V, while the ESP32 pins are rated for 3.3 V. Echo goes to GPIO19 through a divider: 1 kΩ on top and 2 kΩ to ground give 5 × 2 / 3 = 3.3 V.

The pulse length on Echo in microseconds is divided by 58 to get centimeters, as the module's manual says (ElecFreaks HC-SR04 User Guide). pulseIn with a limit of 30,000 µs returns 0 if no echo came back.

Common mistakes

  • People connect Echo to an ESP32 directly. The builder flags such a wire as an error: 5 V on a 3.3 V pin. The pin may work for a while and then fail.
  • People swap the resistors: 2 kΩ on top and 1 kΩ to ground give 1.7 V. In the ESP32 datasheet a high level starts at 0.75 × 3.3 = 2.5 V, and the pin won't see the Echo pulse.

FAQ

Does Trig work from 3.3 V?
The module's makers don't say. On most modules a 3.3 V pulse is enough. If it isn't, there are the HC-SR04P and RCWL-1601, which run entirely on 3.3 V.
Which ESP32 pins should I use for the HC-SR04?
Any GPIO with an output for Trig and any input for Echo, except the strapping pins 0, 2, 5, 12 and 15 and the flash pins 6-11. GPIO34-39 are only good for Echo: they are input only.

You might also need