import machine
import time
# Define GPIO pins for the HC-SR04 sensor
TRIGGER_PIN = 4
ECHO_PIN = 5
# Define GPIO pins for the LEDs
LED_RED_PIN = 10
LED_YELLOW_PIN = 11
LED_GREEN_PIN = 12
# Initialize GPIO pins for the sensor
trigger = machine.Pin(TRIGGER_PIN, machine.Pin.OUT)
echo = machine.Pin(ECHO_PIN, machine.Pin.IN)
# Initialize GPIO pins for the LEDs
led_red = machine.Pin(LED_RED_PIN, machine.Pin.OUT)
led_yellow = machine.Pin(LED_YELLOW_PIN, machine.Pin.OUT)
led_green = machine.Pin(LED_GREEN_PIN, machine.Pin.OUT)
# Function to measure distance using HC-SR04 sensor
def measure_distance():
# Send a 10us pulse to the trigger pin to start the measurement
trigger.high()
time.sleep_us(10)
trigger.low()
# Wait for the echo pin to go high and start the timer
while echo.value() == 0:
pass
start_time = time.ticks_us()
# Wait for the echo pin to go low and stop the timer
while echo.value() == 1:
pass
end_time = time.ticks_us()
# Calculate the duration and convert it to distance in centimeters
duration = time.ticks_diff(end_time, start_time)
distance = duration / 58 # Speed of sound is approximately 58 microseconds/cm
return distance
# Function to control LEDs based on the measured distance
def control_leds(distance):
if distance <= 30:
led_red.high()
led_yellow.low()
led_green.low()
elif distance <= 50:
led_red.low()
led_yellow.high()
led_green.low()
else:
led_red.low()
led_yellow.low()
led_green.high()
# Main program loop
while True:
# Measure distance
distance = measure_distance()
# Control LEDs based on distance
control_leds(distance)
# Delay for a short period
time.sleep(0.1)