from machine import Pin
import machine
import time
echoTimeout = 23200# 等待截止時間
#GPIO 4 設為輸出,接超音波的Trig腳
trigPin_1 = Pin(4, Pin.OUT)
#GPIO 5 設為輸入,接超音波的Echo腳
echoPin_1 = Pin(0, Pin.OUT)
trigPin_1.value(0)# 將Trig腳的電壓預設為低電位
trigPin_2 = Pin(12, Pin.OUT)
#GPIO 32 設為輸入,接超音波的Echo腳
echoPin_2 = Pin(14, Pin.OUT)
trigPin_2.value(0)# 將Trig腳的電壓預設為低電位
# 設定一測試距離的自定義副函式,單位為公分
def distance_1():
trigPin_1.value(1)
time.sleep_us(10)
trigPin_1.value(0)
pulseTime = machine.time_pulse_us(echoPin_1, 1, echoTimeout)
if pulseTime > 0:
return pulseTime / 58
else:
return pulseTime
def distance_2():
trigPin_2.value(1)
time.sleep_us(10)
trigPin_2.value(0)
pulseTime = machine.time_pulse_us(echoPin_2, 1, echoTimeout)
if pulseTime > 0:
return pulseTime / 58
else:
return pulseTime
while True:
cm = distance_1()# 開始測距
print("right:")
if cm > 0:
print('Distance:', cm, 'cm')
else:
print('Out of the detection range.')
print("left:")
cm = distance_2()# 開始測距
if cm > 0:
print('Distance:', cm, 'cm')
else:
print('Out of the detection range.')
time.sleep(1)