# Sample code to test HC-SR04 Ultrasonice Ping Sensor# Connect GND to any GND pin on the Pico# Connnect VCC to VBUS or 5 Volt powerfrommachineimportPin,TimerimportutimeTRIGGER_PIN=15# With USB on the top, this pin is the bottom left cornerECHO_PIN=14# One up from bottom left corner# Init HC-SR04 pinstrigger=Pin(TRIGGER_PIN,Pin.OUT)# send trigger out to sensorecho=Pin(ECHO_PIN,Pin.IN)# get the delay interval backdefping():trigger.low()utime.sleep_us(2)# Wait 2 microseconds lowtrigger.high()utime.sleep_us(5)# Stay high for 5 mirosecondstrigger.low()whileecho.value()==0:signaloff=utime.ticks_us()whileecho.value()==1:signalon=utime.ticks_us()timepassed=signalon-signaloffdistance=(timepassed*0.0343)/2returndistancewhileTrue:print("Distance:",ping()," cm")utime.sleep(.25)
OLED
If you have a small OLED screen, you can also display the results
of the distance measurement directly on an OLED screen.