Redo Ultrasonic Ranging using a pre-built hcsr04 driver module instead of hand-rolling the trigger/echo timing — much shorter code, same result.
This python module encapsulates all the logic to use the sensor and exposes a function to get the distance. See reference/Class_hcsr04.md for detail about the library
Identical to Ultrasonic Ranging.
File: 03_sensors/code/Ultrasonic_Ranging_2.py
Module: 03_sensors/code/hcsr04.py
from hcsr04 import SR04
import time
SR=SR04(13,14)
time.sleep_ms(2000)
try:
while True:
print('Distance: ',SR.distance(),'cm')
time.sleep_ms(500)
except:
pass
03_sensors/code/.hcsr04.py → Upload to / — wait for it to finish uploading to the ESP32-S3.Ultrasonic_Ranging_2.py.SR=SR04(13,14)
SR04(13,14) does everything Ultrasonic Ranging’s getSonar() function did manually — sets up the Trig/Echo pins — but hides it behind one constructor call.
print('Distance: ',SR.distance(),'cm')
SR.distance() replaces the entire trigger-pulse-and-timing dance with a single method call, returning the distance in cm as a float.
hcsr04.py) must be uploaded to the device alongside it — the same pattern seen in Flowing Light with PWM’s pwm.pySee Class hcsr04 for the full API reference, including distanceCM() and distanceMM().
SR.distanceMM() for millimeter precision instead of distance()’s centimeters.Adapted from Python_Tutorial.pdf Project 21.2