from machine import Pin, PWM
import time
# Define pins for ultrasonic sensor and LED
TRIG_PIN = 5 # GPIO Pin for Trigger
ECHO_PIN = 18 # GPIO Pin for Echo
LED_PIN = 21 # GPIO Pin for LED
# Setup ultrasonic sensor pins
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
# Setup PWM for LED
led = PWM(Pin(LED_PIN), freq=1000) # 1kHz frequency for the LED
# Function to measure distance using ultrasonic sensor
def measure_distance():
"""Measures distance using the ultrasonic sensor and returns it in cm."""
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
while echo.value() == 0:
signal_start = time.ticks_us()
while echo.value() == 1:
signal_end = time.ticks_us()
duration = time.ticks_diff(signal_end, signal_start) # Time difference in microseconds
distance = (duration * 0.0343) / 2 # Convert to cm (speed of sound = 343m/s)
return distance
# Function to set LED brightness (0 to 1023 for ESP32 PWM range)
def set_led_brightness(brightness_percentage):
"""Sets the LED brightness according to the percentage (0-100%)."""
duty_cycle = int((brightness_percentage / 100) * 1023) # Scale percentage to 0-1023
led.duty(duty_cycle)
# Function to smoothly change LED brightness to a target brightness
def smooth_brightness_change(current_brightness, target_brightness):
"""Smoothly changes the LED brightness to the target brightness."""
step = 1 if target_brightness > current_brightness else -1
for brightness in range(current_brightness, target_brightness + step, step):
duty_cycle = int((brightness / 100) * 1023) # Scale percentage to 0-1023
led.duty(duty_cycle)
time.sleep_ms(10) # Small delay to create smooth transition
try:
current_brightness = 0 # Track the current brightness to avoid abrupt changes
while True:
distance = measure_distance()
print("Distance: {:.2f} cm".format(distance))
if distance < 199: # Dead zone to avoid rapid switching
target_brightness = 100 # 100% brightness
elif distance > 200: # Dead zone to avoid rapid switching
target_brightness = 30 # 30% brightness
else:
continue # Do nothing if distance is within dead zone
if current_brightness != target_brightness: # Only update if brightness has changed
smooth_brightness_change(current_brightness, target_brightness)
current_brightness = target_brightness # Update the current brightness
except KeyboardInterrupt:
print("Program stopped.")
led.deinit() # Deinitialize the PWM for the LED