import machine
import utime
import random
# Define GPIO pins
TRIG_PIN = machine.Pin(9, machine.Pin.OUT)
ECHO_PIN = machine.Pin(8, machine.Pin.IN)
def measure_distance():
# Send a 10us pulse to trigger the HC-SR04
TRIG_PIN.value(1)
utime.sleep_us(10)
TRIG_PIN.value(0)
# Measure the duration of the echo pulse with a timeout
pulse_duration = machine.time_pulse_us(ECHO_PIN, 1, 1000000) # Set timeout to 1 second
# Calculate distance in centimeters (speed of sound is approximately 34300 cm/s)
if pulse_duration > 0: # Ensure valid pulse duration
return pulse_duration / 2 / 29.1
else:
return None # Return None to indicate an error
while True:
# Generate a random distance between 0 and 500 cm
random_distance = random.uniform(0, 500)
print("Random Distance:", random_distance, "cm")
# Simulate measuring the random distance with the sensor
# For the sake of simulation, we'll just wait for a random duration
utime.sleep(random.uniform(0.5, 2)) # Simulate measurement delay
# Get actual distance measurement from the sensor (comment this out if not using an actual sensor)
# actual_distance = measure_distance()
# if actual_distance is not None:
# print("Actual Distance:", actual_distance, "cm")
# else:
# print("Error: Unable to measure distance")
utime.sleep(2) # Delay between measurements