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)
try:
while True:
distance = measure_distance()
print("Distance: {:.2f} cm".format(distance))
if distance < 199:
set_led_brightness(100) # 100% brightness
elif distance > 200:
set_led_brightness(65) # 65% brightness
time.sleep(1) # Wait for 1 second before taking another measurement
except KeyboardInterrupt:
print("Program stopped.")
led.deinit() # Deinitialize the PWM for the LED