Ultraschallsensor
# Pins for ultrasonic sensor
trigger = Pin(3, Pin.OUT) # to trigger a sound impulse
echo = Pin(4, Pin.IN) # records the echo of the trigger pulse
## Read the distance of object in front of the robot with the ultrasonic sensor. Distance is returned in cm.
def ultra():
distance = 0
timepassed = 0
signalon = 0
signaloff = 0
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance = round((timepassed * 0.0343) / 2, 2)
# print("The distance from object is ", distance, "cm")
utime.sleep_ms(100) # Wait necessary or program halts
return distance