from machine import Pin, PWM
import time, utime
trigger = Pin(20, Pin.OUT)
echo = Pin(21, Pin.IN)
# Buzzer configuration
buzzer_pin = Pin(6) # Change this to the appropriate GPIO pin (GP6 on Raspberry Pi Pico)
buzzer_pwm = PWM(buzzer_pin)
def ultra():
trigger.low()
utime.sleep_us(10)
trigger.high()
utime.sleep_us(10)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance = round((timepassed * 0.0343) / 2, 0)
return distance
def play_tone(frequency, duration):
# Set the frequency of the PWM to the desired tone
buzzer_pwm.freq(frequency)
# Start the PWM
buzzer_pwm.duty_u16(32767) # 50% duty cycle
# Wait for the specified duration
time.sleep_ms(duration)
# Stop the PWM
buzzer_pwm.duty_u16(0)
# Play a simple melody with a frequency
melody = 200
#duration = 200 # in milliseconds
#uss = [10,11,12,20,30,35,20,70,56,49,23,70,60]
#x=40
while True:
x = ultra()
if (50>x>0):
for i in range(3):
play_tone(melody, 50)
time.sleep_ms(200) # Add a short delay between tones
elif (100>x>49):
for i in range(3):
play_tone(melody, 50)
time.sleep_ms(600) # Add a short delay between tones
elif (150>x>99):
for i in range(3):
play_tone(melody, 50)
time.sleep_ms(1200) # Add a short delay between tones
else:
pass