from machine import Pin, time_pulse_us
import time
# Define pins
TRIG_PIN = Pin(5, Pin.OUT)
ECHO_PIN = Pin(18, Pin.IN)
BUZZER_PIN = Pin(19, Pin.OUT)
LED_GREEN = Pin(13, Pin.OUT)
LED_YELLOW = Pin(12, Pin.OUT)
LED_RED = Pin(14, Pin.OUT)
def get_distance():
# Send a pulse to trigger the ultrasonic sensor
TRIG_PIN.value(0)
time.sleep_us(2)
TRIG_PIN.value(1)
time.sleep_us(10)
TRIG_PIN.value(0)
# Measure the duration of the echo pulse
duration = time_pulse_us(ECHO_PIN, 1, 1000000)
# Calculate distance (duration in microseconds * speed of sound / 2)
distance = (duration / 2) / 29.1 # cm
return distance
def update_leds(distance):
# Set LED states based on distance
if distance > 100:
LED_GREEN.value(1)
LED_YELLOW.value(0)
LED_RED.value(0)
elif distance <= 100 and distance > 10:
LED_GREEN.value(0)
LED_YELLOW.value(1)
LED_RED.value(0)
else:
LED_GREEN.value(0)
LED_YELLOW.value(0)
LED_RED.value(1)
def main():
while True:
distance = get_distance()
print("Distance:", distance, "cm")
# Update LEDs based on distance
update_leds(distance)
# Activate buzzer if distance is less than 10 cm
if distance <= 10:
BUZZER_PIN.value(1)
else:
BUZZER_PIN.value(0)
time.sleep(0.2)
# Run the main loop
main()