# Code in Micropython für den Raspberry Pi Pico
from machine import Pin, time_pulse_us
import time
# Pin-Definitionen
TRIG_PIN = 27 # GPIO-Pin für Trig
ECHO_PIN = 26 # GPIO-Pin für Echo
# Initialisierung der Pins
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
def measure_distance():
# Trigger-Puls erzeugen
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10)
trig.low()
# Zeit messen, wie lange das Echo ankommt
try:
duration = time_pulse_us(echo, 1, 30000) # Timeout nach 30ms
except OSError: # Wenn kein Signal zurückkommt
return -1
# Entfernung berechnen (Schallgeschwindigkeit = 343 m/s)
distance = (duration * 0.0343) / 2 # Zeit in cm umrechnen
return distance
# Hauptprogramm
while True:
distance = measure_distance()
if distance == -1:
print("Kein Signal")
else:
print("Entfernung: {:.2f} cm".format(distance))
time.sleep(1)