SunFounder ESP32 Starter Kit
(continued from previous page)
# Initialize the LCD1602 display
lcd = LCD()
dis = 100
# Calculate the distance
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
# Record the time when the echo pin goes high
time1 = time.ticks_us()
# Wait for the echo pin to go low
while ECHO.value():
pass
# Record the time when the echo pin goes low
time2 = time.ticks_us()
# Calculate the time difference between the two recorded times
during = time.ticks_diff(time2, time1)
# Calculate and return the distance (in cm) using the speed of sound (340 m/s)
return during * 340 / 2 / 10000
# Thread to continuously update the ultrasonic sensor reading
def ultrasonic_thread():
global dis
while True:
dis = distance()
# Clear the LCD screen
lcd.clear()
# Display the distance
lcd.write(0, 0, 'Dis: %.2f cm' % dis)
time.sleep(0.5)
# Start the ultrasonic sensor reading thread
_thread.start_new_thread(ultrasonic_thread, ())
(continues on next page)
422 Chapter 3. For MicroPython User