04 - RPi Pico - Measure Distance With Ultrasonic Sensor HC-SR04
04 - RPi Pico - Measure Distance With Ultrasonic Sensor HC-SR04
HC-SR04
Required Components
▶ Required Hardware
◼ Raspberry Pi Pico
◼ 4 jumper wires
◼ HC-SR04 Ultrasonic Sensor
Diagram
VCC VCC
GND GND
Trig GP14
Echo GP15
With LCD Display
VCC VCC
GND GND
SDA GP0
SCL GP1
HC-SR04 consists of two ultrasonic transducers.
One of them transmits ultrasonic sound pulse, while the other listen for the transmitted
pulses reflected by an object.
This sensor can measure distance to an object ranging from 2 to 400 centimeters.
Code
def calcDistance():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(10)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
return distance
while True:
led.toggle()
d = calcDistance()
if (d):
print ("Distance : {:.1f} cm".format(d))
utime.sleep(1)
Final Version
def lcdClear():
lcd.clear()
# Distance function
def calcDistance():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(10)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
return distance
lcdClear()
lcdPrint(0, 0, "I'm counting...")
while True:
led.toggle()
d = calcDistance()
if (d):
print ("Distance : {:.1f} cm".format(d))
lcdPrint(0, 1, " ")
lcdPrint(0, 1, "d = {:.1f} cm".format(d))
utime.sleep(1)
if __name__ == "__main__":
main()