SunFounder ESP32 Starter Kit
(continued from previous page)
# Beep function for the buzzer
def beep():
buzzer.value(1)
time.sleep(0.1)
buzzer.value(0)
time.sleep(0.1)
# Initialize the intervals variable
intervals = 10000000
previousMills = time.ticks_ms()
time.sleep(1)
# Main loop
while True:
# Update intervals based on distance
if dis < 0 and dis > 500:
pass
elif dis <= 10:
intervals = 300
elif dis <= 20:
intervals = 500
elif dis <= 50:
intervals = 1000
else:
intervals = 2000
# Print the distance if it's not -1
if dis != -1:
print('Distance: %.2f ' % dis)
time.sleep_ms(100)
# Check if it's time to beep
currentMills = time.ticks_ms()
if time.ticks_diff(currentMills, previousMills) >= intervals:
beep()
previousMills = currentMills
• When the script is running, the ultrasonic module will continuously detect the distance of obstacles in front of
it, and display the distance on the Shell and I2C LCD1602.
• As the obstacle gets closer, the beeping frequency of the buzzer will become more rapid.
• The ultrasonic_thread() function runs in a separate thread so that it can update the distance measurement
continuously without blocking the main loop.
Note: If the code and wiring are correct, but the LCD still fails to display any content, you can adjust the potentiometer
on the back to increase the contrast.
3.36. 6.4 Reversing Aid 423