Minimal ESP-IDF project that reads an ultrasonic distance sensor and prints distance (cm) over the serial monitor.
- ESP32 development board (ESP-IDF compatible)
- Ultrasonic distance sensor (commonly HC-SR04-compatible)
- Jumper wires
- (Recommended) Voltage divider / level shifter for the ECHO signal
The code uses these GPIOs:
TRIG_PIN: GPIO4ECHO_PIN: GPIO18
Typical HC-SR04 wiring:
- Sensor VCC → 5V
- Sensor GND → GND (must share ground with ESP32)
- Sensor TRIG → ESP32 GPIO4
- Sensor ECHO → ESP32 GPIO18 (through level shifting)
Many ultrasonic sensors output 5V on ECHO. ESP32 GPIOs are not 5V tolerant.
- Use a level shifter or a voltage divider (e.g., 1 kΩ on top + 2 kΩ to GND gives ~3.3V from 5V).
- If your sensor is genuinely 3.3V ECHO, you can connect directly.
- ESP-IDF installed and working (the top-level
CMakeLists.txtuses$IDF_PATH). - Toolchain prerequisites for ESP-IDF (Python, CMake, Ninja, etc.).
If you haven’t set up ESP-IDF yet, follow Espressif’s installation guide for your OS, then ensure you can run idf.py from a terminal.
From the repo root:
# (One-time per shell) load ESP-IDF environment
. $IDF_PATH/export.sh
# Configure target (choose the one that matches your board)
idf.py set-target esp32
# Build
idf.py build
# Flash + open serial monitor
idf.py -p /dev/ttyUSB0 flash monitorExit the monitor with Ctrl+].
- Sends a ~10 µs trigger pulse on GPIO4.
- Measures ECHO pulse width on GPIO18 using
esp_timer_get_time(). - Converts pulse duration to distance:
- Speed of sound ≈ 0.0343 cm/µs
- Distance =
(pulse_duration * 0.0343) / 2
- Prints either
Distance: XX.XX cmorOut of range.
- Pin selection is in main/simpleUltrasonic.c:
#define TRIG_PIN GPIO_NUM_4#define ECHO_PIN GPIO_NUM_18
Change these defines if your wiring differs.
- If readings are stuck or always
Out of range:- Confirm common ground between sensor and ESP32.
- Verify ECHO is level-shifted to 3.3V.
- Double-check the selected serial port (
/dev/ttyUSB0,/dev/ttyACM0, etc.).
- The code includes basic timeouts (~100 ms) to avoid hanging if the sensor is disconnected.