An inexpensive way to measure longer distances is with an ultrasonic sensor, fitted with a horn, such as the DYP-A01. Range is nominated at 0.28-7.5m and the sensor has serial and PWM outputs. The serial connection is used in this sample, at 9600 baud. The sample app runs periodically, to range the distance and exit. Triggering of a measurement is possible, by driving the sensor RX line, but not implemented here.

Connection to the ESP32 is shown in the photo below:


Minimal sample code is available on github.