import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
Trig = 38
Echo = 40
GPIO.setup(Trig,GPIO.OUT)
GPIO.setup(Echo,GPIO.IN)
def distance():
GPIO.output(Trig,True)
time.sleep(0.00001)
GPIO.output(Trig,False)
start_time = time.time()
stop_time = time.time()
while GPIO.input(Echo) == 0:
start_time = time.time()
while GPIO.input(Echo) == 1:
stop_time = time.time()
time_elapsed = stop_time - start_time
distance = (time_elapsed * 34300) / 2
return distance
if __name__ == '__main__':
try:
while True:
dist = distance()
print('测量距离 = : %1.1f cm' %(dist))
time.sleep(1)
except KeyboardInterrupt:
print("用户停止")
GPIO.cleanup()
>>> %Run distance. py
Traceback (most recent call last) :
File "/usr/lib/python3.7/ast.py", line 35,in parse
return compile( source, filename, mode, PyCF_ ONLY_ AST)
File "/home/ pi/Desktop/distance.py", line 10
GPIO. output(Trig, True)
^
IndentationError: expected an indented block