-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathultrasonic.py
executable file
·51 lines (41 loc) · 1.21 KB
/
ultrasonic.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
import RPi.GPIO as GPIO
import time
def distance():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
trig, echo = 24, 23
GPIO.setup(trig, GPIO.OUT)
GPIO.setup(echo, GPIO.IN)
# 发送高电平信号到 Trig 引脚
GPIO.output(trig, True)
# 持续 10 us
time.sleep(0.00001)
GPIO.output(trig, False)
start_time = time.time()
stop_time = time.time()
# 记录发送超声波的时刻1
while GPIO.input(echo) == 0:
start_time = time.time()
# 记录接收到返回超声波的时刻2
while GPIO.input(echo) == 1:
stop_time = time.time()
# 计算超声波的往返时间 = 时刻2 - 时刻1
time_elapsed = stop_time - start_time
# 声波的速度为 343m/s, 转化为 34300cm/s。
distance = (time_elapsed * 34300) / 2
GPIO.cleanup()
return distance
# print(distance())
#
# if __name__ == '__main__':
# try:
# while True:
# dist = distance()
# print(dist)
# print("Measured Distance = {:.2f} cm".format(dist))
# time.sleep(1)
#
# # Reset by pressing CTRL + C
# except KeyboardInterrupt:
# print("Measurement stopped by User")
# GPIO.cleanup()