from machine import Pin, time_pulse_us
import time
trig_pin = Pin(16, Pin.OUT) # D0 or GPIO-16 of NodeMCU
echo_pin = Pin(5, Pin.IN) # D1 or GPIO-5 of NodeMCU
def measure_distance():
trig_pin.off() # Make trigPin low
time.sleep_us(2) # Wait for 2 microseconds
trig_pin.on() # Set trigPin high to start ultrasonic measurement
time.sleep_us(10) # Keep trigPin high for 10 microseconds
trig_pin.off() # Make trigPin low again
duration = time_pulse_us(echo_pin, 1) # Read echo pin to get the duration of the echo pulse in microseconds
distance = duration * 0.034 / 2 # Calculate distance using the speed of sound (approximately 34,000 cm/s)
return distance
# Main program
def main():
trig_pin.init(Pin.OUT)
echo_pin.init(Pin.IN)
while True:
distance = measure_distance()
print("Distance = {} cm".format(distance))
time.sleep(3) # Pause for 3 seconds before starting the next measurement
if __name__ == "__main__":
main()