1. Wire the Ultrasonic Sensor according to the diagram.
Connect VCC to VIN (5V).
Connect GND to GND.
Connect Trig to D5 (GPIO 5).
Connect Echo to D18 (GPIO 18).
2. Copy and paste the source code.
Copy the ultrasonic sensor code and paste it into the editor.
Click the Run button (or press F5) to start the program.
from machine import Pin, time_pulse_us
import time
# 1. Setup Pins
trig = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
def get_distance():
# Ensure Trig is low
trig.value(0)
time.sleep_us(5)
# Send a 10us pulse to trigger the sensor
trig.value(1)
time.sleep_us(10)
trig.value(0)
# Measure the duration of the echo pulse in microseconds
# 30000us is the timeout (approx 5 meters)
duration = time_pulse_us(echo, 1, 30000)
if duration < 0:
return 0 # Out of range
# Calculate distance in cm (Speed of sound is ~340m/s or 0.034 cm/us)
distance = (duration * 0.034) / 2
return round(distance, 2)
print("Ultrasonic Sensor Ready!")
print("Open Thonny Plotter (View -> Plotter) to see the graph.")
while True:
dist = get_distance()
print((dist,)) # Tuple format for Thonny Plotter
time.sleep(0.1)
3. Verify the data and open the Plotter.
Check the Shell window to ensure distance data (numbers) is appearing.
Go to the top menu: View -> Plotter.
A real-time graph will appear on the right side of the screen.