-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistance.py
78 lines (61 loc) · 1.81 KB
/
distance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# Import Libraries
import RPi.GPIO as GPIO
import board
import neopixel
import time
# GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
# Set GPIO Pins
GPIO_TRIGGER = 25
GPIO_ECHO = 12
# Distance Tracker
LastDist = 0.0
Distance = 0.0
# Visualization
pixels = neopixel.NeoPixel(board.D18, 16)
RenderDistance = 0
BLACK = (0, 0, 0)
LILAC = (100, 0, 100)
# Set Directions of the GPIO-Pins (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def get_distance():
# set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)
# set Trigger to LOW after 0.01ms
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
StartTime = time.time()
StopTime = time.time()
# save starting time
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
# save end time
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
# Difference between start and end time
TimeElapsed = StopTime - StartTime
# multiply with the velocity of sound (34300 cm/s)
# divide by two, the away and back way
dist = (TimeElapsed * 34300) / 2
return dist
if __name__ == "__main__":
try:
while True:
LastDist = Distance
Distance = get_distance()
if abs(Distance - LastDist) >= 160:
Distance = LastDist
print("Measured Distance: %.1f cm" % Distance)
print("Difference to last Distance: %.1f cm" % abs(Distance - LastDist))
RenderDistance = int(Distance / 10)
for i in range(16):
if i <= RenderDistance:
pixels[i] = LILAC
else:
pixels[i] = BLACK
pixels.show()
time.sleep(0.1)
except KeyboardInterrupt:
print("Measuring was Aborted by User")
GPIO.cleanup()