from machine import Pin, time_pulse_us
from time import sleep, sleep_ms, sleep_us
# Ultrasonic Sensor Pins
TRIG = Pin(15, Pin.OUT)
ECHO = Pin(14, Pin.IN)
# CSV file name
log_file = "/distance_log.csv"
# Create CSV file and add header if it doesn't exist
with open(log_file, "a") as f:
f.seek(0, 0)
if not f.read(1):
f.write("Sr No.,Distance (cm)\n")
# Function to measure distance
def get_distance():
TRIG.low()
sleep_ms(2)
TRIG.high()
sleep_us(10)
TRIG.low()
duration = time_pulse_us(ECHO, 1, 30000)
# If no echo is received
if duration < 0:
return -1
# Convert time to distance in cm
distance = (duration * 0.0343) / 2
return round(distance, 2)
# Serial number
sr_no = 1
# Main loop
while True:
distance = get_distance()
# Save to CSV file
with open(log_file, "a") as f:
f.write(str(sr_no) + "," + str(distance) + "\n")
# Display on Serial Monitor
print("Reading", sr_no, ": Distance =", distance, "cm")
sr_no += 1
# Wait 0.5 seconds before next reading
sleep(0.5)