Introduction to Python and Microcontrollers

Ultrasonic Ranging (with the hcsr04 module)

Redo Ultrasonic Ranging using a pre-built hcsr04 driver module instead of hand-rolling the trigger/echo timing — much shorter code, same result.

New Concepts

HCSR04 driver module

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

Component List & Circuit

Identical to Ultrasonic Ranging.

Code

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

How to Run

Online

  1. Open Thonny → 03_sensors/code/.
  2. Right-click hcsr04.pyUpload to / — wait for it to finish uploading to the ESP32-S3.
  3. Double-click Ultrasonic_Ranging_2.py.
  4. Click Run current script — same distance readings as before, with far less code.

Code Explanation

Create the sensor object

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.

Read the distance

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.


Key Concepts

See Class hcsr04 for the full API reference, including distanceCM() and distanceMM().

Further Exploration

Back to Module

Adapted from Python_Tutorial.pdf Project 21.2