print("Hello, ESP32!")
from machine import Pin
import time
import utime
# Pin setup
trig = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
led_red = Pin(12, Pin.OUT)
led_yellow = Pin(14, Pin.OUT)
led_green = Pin(27, Pin.OUT)
def get_distance():
# Trigger the ultrasonic sensor
trig.off()
utime.sleep_us(2)
trig.on()
utime.sleep_us(10)
trig.off()
# Initialize start_time and end_time to avoid unbound variable errors
start_time = 0
end_time = 0
# Measure the time it takes for echo to go high and low
while echo.value() == 0:
start_time = utime.ticks_us()
while echo.value() == 1:
end_time = utime.ticks_us()
# Calculate the duration and distance
duration = utime.ticks_diff(end_time, start_time)
distance = (duration * 0.0343) / 2 # Convert time to distance
return distance
while True:
distance = get_distance()
if distance <= 100: # <= 1 meter
led_red.on()
led_yellow.off()
led_green.off()
elif distance <= 200: # <= 2 meters
led_red.off()
led_yellow.on()
led_green.off()
else:
led_red.off()
led_yellow.off()
led_green.on()
time.sleep(0.5)