Raspberry Pi Pico: Measure Distance with Ultrasonic Sensor
HC-SR04
Required Components
▶ Required Hardware
◼ Raspberry Pi Pico
◼ 4 jumper wires
◼ HC-SR04 Ultrasonic Sensor
▶ LCD related requirements (optional)
◼ See video #3 (16x2 LCD with I2C Protocol)
Diagram
Without LCD Display
Raspberry Pi Pico HC-SR04
VCC VCC
GND GND
Trig GP14
Echo GP15
With LCD Display
Raspberry Pi Pico LCD 16x2 with I2C
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():
[Link]()
utime.sleep_us(2)
[Link]()
utime.sleep_us(10)
[Link]()
while [Link]() == 0:
signaloff = utime.ticks_us()
while [Link]() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
# speed of sound travel in air is approximately 343 meters/second
# that's equals to 34300 cm/second or 0.034300 cm/microsecond
distance = (timepassed * 0.0343) / 2
if (distance < 2) or (distance > 400):
distance = None
return distance
while True:
[Link]()
d = calcDistance()
if (d):
print ("Distance : {:.1f} cm".format(d))
[Link](1)
Final Version
from machine import Pin, I2C
import utime
from pico_i2c_lcd import I2cLcd
# Internal led init
led = Pin(25, [Link])
[Link]()
# LCD section ------------------------------------
I2C_ADDR = 0x27
I2C_NUM_ROWS = 2
I2C_NUM_COLS = 16
i2c = I2C(0, sda=[Link](0), scl=[Link](1))
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)
def lcdPrint(col, row, s):
lcd.move_to(col, row)
[Link](s)
def lcdClear():
[Link]()
# HC-SR04 section --------------------------------
trigger = Pin(14, [Link])
echo = Pin(15, [Link])
# Distance function
def calcDistance():
[Link]()
utime.sleep_us(2)
[Link]()
utime.sleep_us(10)
[Link]()
while [Link]() == 0:
signaloff = utime.ticks_us()
while [Link]() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance = (timepassed * 0.0343) / 2
if (distance < 0.1) or (distance > 450):
distance = None
return distance
# Main program -----------------------------------
def main():
lcdPrint(0, 0, "Hello ...")
lcdPrint(0, 1, "Simple Tutorials")
[Link](2)
lcdClear()
lcdPrint(0, 0, "I'm counting...")
while True:
[Link]()
d = calcDistance()
if (d):
print ("Distance : {:.1f} cm".format(d))
lcdPrint(0, 1, " ")
lcdPrint(0, 1, "d = {:.1f} cm".format(d))
[Link](1)
if __name__ == "__main__":
main()