-
Notifications
You must be signed in to change notification settings - Fork 0
/
ultra.py
46 lines (35 loc) · 1006 Bytes
/
ultra.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
#!/usr/bin/python3
# File name : Ultrasonic.py
# Description : Detection distance and tracking with ultrasonic
# Website : www.gewbot.com
# Author : William
# Date : 2019/02/23
import RPi.GPIO as GPIO
import time
Tr = 11 # transmitter attached to pin 11?
Ec = 8 # receiver attache to pin 8
def initUltrasonicSensor():
#GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(Tr, GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(Ec, GPIO.IN)
#Read the distance using ultrasonic time of flight
def getDistance():
initUltrasonicSensor()
# send a pulse
GPIO.output(Tr, GPIO.HIGH)
time.sleep(0.000015)
GPIO.output(Tr, GPIO.LOW)
# measure the time between the high and the low
while not GPIO.input(Ec):
pass
t1 = time.time()
while GPIO.input(Ec):
pass
t2 = time.time()
# return the distance derived from flight time
return round((t2-t1)*340/2,2)
if __name__ == '__main__':
while 1:
print(getDistance())
time.sleep(1)