SunFounder ESP32 Starter Kit
will be reflected back.
By recording the time it takes from sending to receiving the signal, dividing it by 2, and multiplying it by the speed of
light, you can determine the distance to the obstacle.
Wiring
Code
Note:
• Open the 5.12_ultrasonic.py file located in the esp32-starter-kit-main\micropython\codes path,
or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.
• Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.
import machine
import time
# Define the trigger and echo pins for the distance sensor
TRIG = machine.Pin(26, machine.Pin.OUT)
ECHO = machine.Pin(25, machine.Pin.IN)
# Calculate the distance using the ultrasonic sensor
def distance():
# Ensure trigger is off initially
TRIG.off()
time.sleep_us(2) # Wait for 2 microseconds
# Send a 10-microsecond pulse to the trigger pin
TRIG.on()
time.sleep_us(10)
TRIG.off()
# Wait for the echo pin to go high
while not ECHO.value():
pass
(continues on next page)
3.30. 5.12 Measuring Distance 397