from machine import Pin, PWM
import time
TRIGGER_PIN = 12 # 超音波感應器的觸發引腳
ECHO_PIN = 14 # 超音波感應器的回音引腳
BUZZER_PIN = 2 # 蜂鳴器的引腳
trigger = Pin(TRIGGER_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
buzzer = PWM(Pin(BUZZER_PIN))
def get_distance():
# 使用超音波感應器測量距離(單位:厘米)
trigger.value(1)
time.sleep_us(10)
trigger.value(0)
pulse_time = machine.time_pulse_us(echo, 1)
return pulse_time / 58 # 將脈衝時間轉換為距離
def play_short_tone():
# 發出0.5秒的短音
buzzer.freq(1000)
buzzer.duty(50)
time.sleep(0.5)
buzzer.duty(0)
def play_continuous_tone():
# 發出連續長音
buzzer.freq(1000)
buzzer.duty(50)
def stop_tone():
# 停止發聲
buzzer.duty(0)
while True:
distance = get_distance()
print("Distance: {} cm".format(distance))
if distance < 100:
# 如果距離小於100厘米,發出0.5秒的短音
play_short_tone()
time.sleep(0.5)
if distance < 30:
# 如果距離小於30厘米,發出連續長音
play_continuous_tone()
else:
stop_tone()