#Ali Rashidi
from machine import Pin, PWM
from time import sleep_us, ticks_us, ticks_diff, sleep
#pin haye mored estefadeh
trig_pin = Pin(28, Pin.OUT)
echo_pin = Pin(27, Pin.IN)
led = PWM(Pin(26))
#tanzim ferq led
led.freq(1000)
def measure_distance():
#ersal palse kotah baraye tahrik sensor
trig_pin.off()
sleep_us(2) #zaman kami baraye khamosh kardan triger
trig_pin.on()
sleep_us(10) #ersal palse 10micro.s
trig_pin.off()
#andaze giriye zaman bazgasht palse echo
while echo_pin.value() == 0:
start_time = ticks_us() #zaman shoroee palse echo
while echo_pin.value() == 1:
end_time = ticks_us() #zaman payan palse echo
#mohasebe modat zaman palse va tabdil be fasele
duration = ticks_diff(end_time, start_time)
distance_cm = (duration * 0.0343) / 2
return distance_cm
def set_led_brightness(distance):
max_distance = 100 #hadaksar fasele baraye roshanaee kamel
min_distance = 2 #hadaghal fasele baraye khamosh kardan kamel
#mahdod kardan fasele andazegiri shode be mahdode mojaz
distance = max(min_distance, min(max_distance, distance))
#mohasebe duty cycle be sorat maqoos
duty = int(((max_distance - distance) / (max_distance - min_distance)) * 65535)
led.duty_u16(duty) #tanzim duty cycle led
#mohasebe darsad roshanaee
brightness_percent = (duty / 65535) * 100
return brightness_percent
while True:
distance = measure_distance() #andaze giriye fasele
brightness = set_led_brightness(distance) #tanzim shedat noor led bar asas fasele
print(f"Distance: {distance:.2f} cm, LED Brightness: {brightness:.2f}%") #namayesh fasele va darsad roshanaee
sleep(0.1)