#write a code in mircopyhton to display the distace in oled according to the ultrasonic and if the distance is less than 100 cm then turn on the led reverse parking sensor and led intensitry will increase when object is near
import machine
from machine import Pin, PWM, I2C
import time
import ssd1306
Trigger = Pin(12, Pin.OUT)
Echo = Pin(14, Pin.IN)
led_pwm = PWM(Pin(23))
threshold_distance_cm = 100
i2c = I2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
def measure_distance():
Trigger.value(0)
time.sleep_us(2)
Trigger.value(1)
time.sleep_us(10)
Trigger.value(0)
total_time = machine.time_pulse_us(Echo, 1)
distance = (total_time * 0.034) / 2
return distance
def adjust_led_intensity(distance):
intensity = int(1023 - (distance * 10))
intensity = max(0, min(1023, intensity))
led_pwm.duty(intensity)
duty_cycle = int((intensity / 1023) * 100) # Calculate duty cycle percentage
return duty_cycle
def display_distance(distance, duty_cycle):
oled.fill(0)
oled.text("Distance:", 0, 0)
oled.text(str(distance) + " cm", 0, 10)
oled.text("Duty cycle: " + str(duty_cycle) + "%", 0, 20) # Print duty cycle percentage
oled.show()
while True:
distance = measure_distance()
print("Distance in cm:", distance)
if distance < threshold_distance_cm:
duty_cycle = adjust_led_intensity(distance)
else:
led_pwm.duty(0)
duty_cycle = 0
display_distance(distance, duty_cycle)
time.sleep(0.5)