The objective of this project is to measure the distance of an object from the sensor using an HC-SR04 ultrasonic distance sensor, and display the measured distance in real time on a 16×2 I2C LCD using a Raspberry Pi Pico. This project helps in understanding how ultrasonic distance measurement works, how to interface sensors and I2C-based displays with the Pico, and how to process timing-based data in Micro Python.
This setup can be used in applications such as distance monitoring, obstacle detection, liquid level sensing, or as a basic module in robotic or automation projects where proximity sensing is required.
Buy Basic Raspberry Pi Pico Kit
Item Required:
- Raspberry Pi Pico
- HC-SR04 Ultrasonic Sensor
- I2C 16×2 LCD (with PCF8574)
- Breadboard
- Jumper Wires
- USB Cable Micro B
- Computer with Thonny IDE
Connections:

Important Note:
If using 5V for VCC, place a voltage divider (e.g., 1kΩ + 2kΩ) on the Echo pin to safely drop 5V to ~3.3V for the Pico input.
Code:
from machine import Pin,PWM
from time import sleep
import dht
import time
from machine import I2C
from pico_i2c_lcd import I2cLcd
sensor = dht.DHT11(Pin(22))
print("Starting DHT11 test...")
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
# getting I2C address
I2C_ADDR = 0x3f
# creating an LCD object using the I2C address and specifying number of rows and columns in the LCD
# LCD number of rows = 2, number of columns = 16
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
def buzzerFunc():
buzzer= PWM(Pin(26))
buzzer.freq(500)
buzzer.duty_u16(1000)
sleep(1)
buzzer.duty_u16(0)
while True:
print("Loop running")
try:
sensor.measure()
temp = sensor.temperature
hum = sensor.humidity
print("Temp:", temp, "°C")
print("Humidity:", hum, "%")
lcd.clear()
lcd.putstr(f" Temp: {temp}")
lcd.move_to(0, 1)
lcd.putstr(f" Humidity: {hum}%")
if(temp > 30 or hum > 30):
buzzerFunc()
else:
None
except Exception as e:
print("Sensor error:", repr(e))
time.sleep(2)
How It Works
Trigger Pin sends a 10μs HIGH pulse to start measurement.
Echo Pin stays HIGH for the time it takes the sound wave to return.
This time is used to calculate distance using the formula:
distance_cm = (time_passed * 0.0343) / 2
The result is displayed on the second line of the LCD.