import time
from machine import Pin, ADC
# Ultrasonic Sensor (HC-SR04)
trigger = Pin(2, Pin.OUT)
echo = Pin(3, Pin.IN)
# LDR Module (AO pin connected to GPIO1)
ldr = ADC(Pin(1))
ldr.atten(ADC.ATTN_11DB) # Full range 0-3.3V
# LEDs
red_led = Pin(4, Pin.OUT) # Obstacle detected
yellow_led = Pin(5, Pin.OUT) # Low light detected
# Thresholds
OBSTACLE_DISTANCE = 20 # cm
LIGHT_THRESHOLD = 200 # Below this value = low light (0-4095)
TIMEOUT = 100000 # microseconds (100ms)
def measure_distance():
# Send pulse
trigger.value(0)
time.sleep_us(2)
trigger.value(1)
time.sleep_us(10)
trigger.value(0)
# Initialize with timeout
timeout_start = time.ticks_us()
# Wait for echo start
while echo.value() == 0:
if time.ticks_diff(time.ticks_us(), timeout_start) > TIMEOUT:
return -1 # Timeout
pulse_start = time.ticks_us()
# Wait for echo end
while echo.value() == 1:
if time.ticks_diff(time.ticks_us(), timeout_start) > TIMEOUT:
return -1 # Timeout
pulse_end = time.ticks_us()
# Calculate distance
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
return pulse_duration / 58.0 # cm
def read_light():
return ldr.read() # Returns 0-4095
while True:
# Read sensors
distance = measure_distance()
light = read_light()
# Reset LEDs
red_led.value(0)
yellow_led.value(0)
# Check conditions
if distance != -1 and distance <= OBSTACLE_DISTANCE:
red_led.value(1)
print(f"Obstacle Detected! Distance: {distance:.1f} cm")
elif light < LIGHT_THRESHOLD:
yellow_led.value(1)
print("Low Light Detected.")
else:
print("Environment Clear.")
time.sleep(1)Loading
esp32-s3-devkitc-1
esp32-s3-devkitc-1