Preview build — page text is a draft awaiting human review. Code badges come from real compiles. The flasher is real but not yet hardware-tested; the Playground is still a preview.

HC-SR04 with LOLIN S2 Mini — 5 V sensor, 3.3 V board

Measure distance with an HC-SR04 on a LOLIN S2 Mini: VCC from VBUS, Trig on GPIO5, Echo on GPIO7 through a 1 kΩ / 2 kΩ divider.

Arduino C++Verified — core esp32 3.3.12, 3 Nov 2026Compile-only

Community draft — report a mistake

The HC-SR04 is a 5 V sensor, so on the 3.3 V S2 Mini it takes one extra step: a divider on ECHO. Power it from VBUS, trigger from GPIO5, and read the echo on GPIO7.

The sketch pings five times a second and prints the distance in centimetres.

Wiring

LOLIN S2 MiniOnly the pins used are shown · 3.3 V logicHC-SR04 ultrasonic sensor1k│2k5 · 57 · 7GNDVBUSVCCTrigEchoGND
Also needed: 1 kΩ resistor, 2 kΩ resistor.
Every connection
LOLIN S2 MiniHC-SR04 ultrasonic sensorWireNotes
VBUSVCCred5 V from USB-C.
5Trigpurple
7EchogreenVia 1 kΩ / 2 kΩ divider — 1 kΩ from ECHO to GPIO7, 2 kΩ from GPIO7 to GND.
GNDGNDblack

5 V (HC-SR04P / RCWL-1601: 3–5.5 V) part, 3.3 V board. The classic HC-SR04 needs 5 V and its ECHO pin outputs 5 V. On a 3.3 V board (ESP32, Pico) send ECHO through a 1 kΩ / 2 kΩ divider. A 3.3 V trigger signal is enough for TRIG.

Board quirks

  • The S2’s pins are not 5 V tolerant, and the HC-SR04’s ECHO is a 5 V pulse — hence the divider. TRIG at 3.3 V works fine.
  • VBUS is the S2 Mini’s only 5 V pin and is live only on USB (or 5 V fed in there). On battery, use an HC-SR04P that runs at 3.3 V with no divider.
  • GPIO5 and GPIO7 sit side by side on the outer row (D1 mini D0 and D5 positions) and have no boot role.

Code

hc-sr04-s2mini.inoArduino C++Open in PlaygroundOpen in PlaygroundFlash
// HC-SR04 ultrasonic sensor on a LOLIN S2 Mini.
// VCC → VBUS (USB 5 V), GND → GND, Trig → GPIO5, Echo → GPIO7 through a 1 kΩ / 2 kΩ divider
// (ECHO is a 5 V signal; the S2's pins are 3.3 V only).
constexpr uint8_t TRIG_PIN = 5;
constexpr uint8_t ECHO_PIN = 7;

void setup() {
  Serial.begin(115200);
  uint32_t t0 = millis();
  while (!Serial && millis() - t0 < 3000) {}
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);
  pinMode(ECHO_PIN, INPUT);
  Serial.println("HC-SR04: Trig GPIO5, Echo GPIO7");
}

void loop() {
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long us = pulseIn(ECHO_PIN, HIGH, 30000UL);
  if (us == 0) Serial.println("Out of range (no echo)");
  else Serial.printf("Distance: %.1f cm\n", us * 0.0343f / 2.0f);
  delay(200);
}

Expected serial output

Serial Monitor · 115200Output
HC-SR04: Trig GPIO5, Echo GPIO7
Distance: 64.2 cm
Distance: 64.0 cm
Out of range (no echo)

Common errors

Always out of range

VCC on 3V3, or the divider reversed. Full fix.

Readings jump

Soft or angled target. Average several pings.

↑↓ to move · Enter to open