Skip to content

Instantly share code, notes, and snippets.

@codelectron
Last active December 11, 2019 20:23
Show Gist options
  • Save codelectron/c2b6604da028fa459fb6749c7b0de047 to your computer and use it in GitHub Desktop.
Save codelectron/c2b6604da028fa459fb6749c7b0de047 to your computer and use it in GitHub Desktop.

Revisions

  1. codelectron revised this gist Apr 23, 2018. No changes.
  2. codelectron created this gist Apr 16, 2018.
    47 changes: 47 additions & 0 deletions distance.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    import RPi.GPIO as GPIO
    import time

    GPIO.setmode(GPIO.BCM)

    GPIO_TRIGGER = 23
    GPIO_ECHO = 24

    GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
    GPIO.setup(GPIO_ECHO, GPIO.IN)

    def distance():
    GPIO.output(GPIO_TRIGGER, True)

    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)

    StartTime = time.time()
    StopTime = time.time()

    while GPIO.input(GPIO_ECHO) == 0:
    StartTime = time.time()

    # save time of arrival
    while GPIO.input(GPIO_ECHO) == 1:
    StopTime = time.time()

    # time difference between start and arrival
    TimeElapsed = StopTime - StartTime
    # multiply with the sonic speed (34300 cm/s)
    # and divide by 2, because there and back
    distance = (TimeElapsed * 34300) / 2

    return distance

    if __name__ == '__main__':
    try:
    while True:
    dist = distance()
    print ("Measured Distance = %.1f cm" % dist)
    time.sleep(1)

    # Reset by pressing CTRL + C
    except KeyboardInterrupt:
    print("Measurement stopped by User")
    GPIO.cleanup()