from machine import Pin
from utime import sleep, ticks_us, sleep_us, ticks_diff
PIN_TRIG = 3
PIN_ECHO = 2
sleep(0.01) # Wait for USB to connect
print("Hello, Pi Pico!")
pin_trig = Pin(PIN_TRIG, Pin.OUT);
echo_pin = Pin(PIN_ECHO, Pin.IN)
yourface = Pin(5, Pin.OUT)
newPin = Pin(10, Pin.OUT)
def get_distance():
# 1. Start a new measurement (similar to void loop() block):
# Set trigger low for a moment to ensure a clean signal start
pin_trig.value(0)
sleep_us(2)
print("now i am here")
# Send a 10us pulse to trigger the sensor
pin_trig.value(1)
sleep_us(10)
pin_trig.value(0)
# 2. Read the result using pulseIn equivalent:
# Measure the duration of the incoming echo pulse (MicroPython's equivalent)
# The 'machine.time_pulse_us()' function is often used, but some
# MicroPython ports (like the one for Raspberry Pi Pico)
# rely on manual timing or a custom 'pulse_in' function.
# We will use a standard loop to measure the pulse duration:
# Wait for the echo pin to go HIGH
while echo_pin.value() == 0:
signaloff = ticks_us()
# Wait for the echo pin to go LOW
while echo_pin.value() == 1:
signalon = ticks_us()
# Calculate the duration in microseconds
duration = ticks_diff(signalon, signaloff)
# 3. Calculate and Print:
# Distance = Time * Speed of Sound / 2
# Distance in CM = duration / 58 (since 1 second / 58 = ~17.2 milliseconds per cm)
distance_cm = duration / 58
# Distance in Inches = duration / 148 (since 1 second / 148 = ~6.75 milliseconds per inch)
distance_in = duration / 148
# Use standard Python 'print' for serial output
print(f"Distance in CM: {distance_cm:.2f}")
print(f"Distance in inches: {distance_in:.2f}")
# Return a usable value (optional)
return distance_cm
while True:
yourface.toggle()
sleep(0.5)
print("i am here")
get_distance()
sleep(1) # Delay for 1 second between measurements