Skip to content

ArnavGRao/Distance-Finding-With-Ultrasonic-Sensor

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SimpleUltrasonic (ESP-IDF)

Minimal ESP-IDF project that reads an ultrasonic distance sensor and prints distance (cm) over the serial monitor.

Components used

  • ESP32 development board (ESP-IDF compatible)
  • Ultrasonic distance sensor (commonly HC-SR04-compatible)
  • Jumper wires
  • (Recommended) Voltage divider / level shifter for the ECHO signal

Wiring

The code uses these GPIOs:

  • TRIG_PIN: GPIO4
  • ECHO_PIN: GPIO18

Typical HC-SR04 wiring:

  • Sensor VCC5V
  • Sensor GNDGND (must share ground with ESP32)
  • Sensor TRIGESP32 GPIO4
  • Sensor ECHOESP32 GPIO18 (through level shifting)

Important: ECHO voltage level

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.

Software prerequisites

  • ESP-IDF installed and working (the top-level CMakeLists.txt uses $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.

Build, flash, and monitor

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 monitor

Exit the monitor with Ctrl+].

What it does

  • 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 cm or Out of range.

Configuration

Change these defines if your wiring differs.

Notes / troubleshooting

  • 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.

About

Use an ultrasonic sensor to find distance

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors