from machine import Pin, PWM
import time
# Pin definitions
LED_PIN = 15 # GPIO pin for the LED
TRIGGER_PIN = 26 # GPIO pin connected to the trigger pin of ultrasonic sensor
ECHO_PIN = 25 # GPIO pin connected to the echo pin of ultrasonic sensor
# Setup LED
led = Pin(LED_PIN, Pin.OUT)
# Setup ultrasonic sensor
trigger = Pin(TRIGGER_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
# Function to measure distance using ultrasonic sensor
def measure_distance():
# Send a pulse to trigger the sensor
trigger.value(1)
time.sleep_us(10)
trigger.value(0)
# Wait for the echo pin to go high
while echo.value() == 0:
pulse_start = time.ticks_us()
# Wait for the echo pin to go low
while echo.value() == 1:
pulse_end = time.ticks_us()
# Calculate pulse duration
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
# Calculate distance (in cm) based on the speed of sound
distance_cm = (pulse_duration * 0.0343) / 2
return distance_cm
# Main loop
while True:
# Measure distance
distance = measure_distance()
# Toggle LED based on distance
if distance < 10: # If object is closer than 10cm
led.value(1) # Turn on LED
else:
led.value(0) # Turn off LED
# Print distance
print("Distance:", distance, "cm")
# Delay before next measurement
time.sleep(1)