"""
What is an Ultrasonic Sensor and How Does It Measure Distance?
- An ultrasonic sensor like the HC-SR04 uses sound waves to measure the distance between the sensor and an object.
📦 Components:
TRIG Pin:
- The microcontroller sends a short HIGH pulse (typically 10 μs) to this pin to trigger the ultrasonic burst.
ECHO Pin:
- This pin goes HIGH once the sound is emitted and returns LOW once the echo is received.
- The duration of this HIGH signal is proportional to the time it took for the sound to travel to the object and back.
📐 Physics Behind It:
- Speed of sound ≈ 340 m/s ≈ 0.034 cm/μs
- Since sound travels to the object and back, distance is calculated as:
- Distance(cm)= Echo time (μs) ÷ 58 (approx.)
- (Note: The exact divisor may vary slightly, e.g., 57 to 59 depending on temperature/humidity)
🧠 Why Divide by 58?
Because:
Distance = (Time x Speed) ÷ 2 = (T x 0.034 cm/μs) ÷ 2 = T ÷ 58.8
So, Distance = T ÷ 58.8
"""
from machine import Pin, time_pulse_us # Import GPIO and pulse duration tool
import time # Import time library for delays
# 🎯 Setup TRIG as output pin and ECHO as input pin
trig = Pin(3, Pin.OUT) # Trigger pin on GPIO 3
echo = Pin(2, Pin.IN) # Echo pin on GPIO 2
# 📏 Function to measure distance using HC-SR04
def measure_distance():
trig.low() # Ensure trigger is LOW
time.sleep_us(4) # Small delay to stabilize
trig.high() # Send 4µs HIGH pulse to start the measurement
time.sleep_us(4) # Hold HIGH for 4µs (sometimes 10µs is standard)
trig.low() # Pull trigger LOW again to complete the pulse
# ⏱ Measure duration of HIGH signal on echo pin
duration = time_pulse_us(echo, 1) # Time echo pin stays HIGH (which is set by 1) (in µs)
# 📐 Convert time to distance using the speed of sound
return duration / 58.82 # Return distance in centimeters
# 🔁 Main loop to print distance every second
while True:
distance = measure_distance()
print("Distance: {:.1f} cm".format(distance)) # Print with 1 decimal
time.sleep(1) # Delay 1 second between readings