Skip to main content

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

Noch überprüfen!!!!

from machine import Pin
from time import sleep
import utime

class Ultra:
   def __init__(self, pinNo):
       self.trigger = Pin(pinNo, Pin.OUT) # to trigger a sound impulse
       self.echo = Pin(pinNo+1, Pin.IN) # records the echo of the trigger pulse      

   def getDist(self):
       global echo
       global trigger
       timepassed = 0
       signalon = 0
       signaloff = 0
       self.trigger.low()
       utime.sleep_us(2)
       self.trigger.high()
       utime.sleep_us(5)
       self.trigger.low()
       while self.echo.value() == 0:
           #print(self.echo.value())
           signaloff = utime.ticks_us()
       while self.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