import machine
import time
# Define pins for HC-SR04 sensor
TRIG_PIN = machine.Pin(14, machine.Pin.OUT)
ECHO_PIN = machine.Pin(12, machine.Pin.IN)
# Define pin for the relay connected to LED
RELAY_PIN = machine.Pin(13, machine.Pin.OUT)
# Function to measure distance using HC-SR04
def measure_distance():
# Send a 10us pulse to the trigger pin
TRIG_PIN.off()
time.sleep_us(2)
TRIG_PIN.on()
time.sleep_us(10)
TRIG_PIN.off()
# Initialize variables to hold pulse start and end time
pulse_start = 0
pulse_end = 0
# Wait for the echo pin to go high (pulse start)
while ECHO_PIN.value() == 0:
pulse_start = time.ticks_us()
# Wait for the echo pin to go low (pulse end)
while ECHO_PIN.value() == 1:
pulse_end = time.ticks_us()
# Ensure we have valid values for pulse_start and pulse_end
if pulse_start and pulse_end:
# Calculate pulse duration
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
# Calculate distance in cm (speed of sound is 34300 cm/s)
distance = (pulse_duration * 0.0343) / 2
return distance
else:
# Return an invalid distance if measurement failed
return -1
# Threshold distance to control the LED (in cm)
DISTANCE_THRESHOLD = 100
while True:
# Measure the current distance
distance = measure_distance()
# If the distance is valid and less than the threshold, control the relay
if distance != -1:
print("Distance: {:.2f} cm".format(distance))
# If the distance is less than the threshold, turn ON the LED (activate relay)
if distance < DISTANCE_THRESHOLD:
RELAY_PIN.on() # Activate relay (LED ON)
print('Turned ON Led')
else:
RELAY_PIN.off() # Deactivate relay (LED OFF)
print('Turned OFF Led')
# Wait for a second before measuring again
time.sleep(1)