print("Hello, Pi Pico W!")
from machine import Pin, time_pulse_us
import utime
# Set up the pins
trig = Pin(15, Pin.OUT)
echo = Pin(14, Pin.IN)
led = Pin(13, Pin.OUT)
buzzer = Pin(12, Pin.OUT)
switch = Pin(11, Pin.IN, Pin.PULL_DOWN) # Sliding switch with pull-down resistor
def measure_distance():
# Send a 10us pulse to trigger the sensor
trig.low()
utime.sleep_us(2)
trig.high()
utime.sleep_us(10)
trig.low()
# Measure the duration of the pulse on the echo pin
duration = time_pulse_us(echo, 1)
# Calculate distance in cm
distance = (duration / 2) / 29.1
return distance
while True:
if switch.value() == 1: # Sliding switch is on
distance = measure_distance()
print('Distance:', distance, 'cm')
if distance < 250:
# Blink LED and sound buzzer
for _ in range(10):
led.toggle()
buzzer.value(1)
utime.sleep(0.1)
led.toggle()
buzzer.value(0)
utime.sleep(0.1)
else:
# Turn off LED and buzzer if distance >= 250
led.value(0)
buzzer.value(0)
else:
# Turn off LED and buzzer if switch is off
led.value(0)
buzzer.value(0)
utime.sleep(0.1) # Small delay to stabilize readings