How to Measure Distance Using Raspberry Pi Zero 2 W, Waterproof Ultrasonic Sensor and 16×2 LCD
Welcome to Engineers Butty Lab BD
Phone: 01888-011500
Address: 31 A/B, Seyed Villa, Jobbar Housing Society, Mazar Road, Mirpur -1, Dhaka.
Introduction
Measuring distance is one of the most common applications in electronics and automation projects. Whether you are building a water level monitoring system, an obstacle detection system, or an industrial automation project, ultrasonic sensors provide an accurate and cost-effective solution.
In this tutorial, we will learn how to measure distance using a Raspberry Pi Zero 2 W, a Waterproof Ultrasonic Sensor, and a 16×2 LCD with I2C interface. The measured distance will be displayed both on the terminal and on the LCD screen in real time.
Project Overview
The Waterproof Ultrasonic Sensor emits ultrasonic sound waves and measures the time taken for the echo to return after hitting an object. The Raspberry Pi calculates the distance based on this time interval and displays the result on the LCD.
Features
- Real-time distance measurement
- Waterproof sensor suitable for outdoor applications
- LCD display for local monitoring
- Raspberry Pi-based processing and control
- Easy integration into water level monitoring projects
Components Required
| Component | Quantity |
|---|---|
| Raspberry Pi Zero 2 W | 1 |
| Waterproof Ultrasonic Sensor (JSN-SR04T or similar) | 1 |
| 16×2 LCD with I2C Module | 1 |
| Voltage Divider Resistors (1kΩ and 2kΩ) | 1 Set |
| Jumper Wires | As Required |
| 5V Power Supply | 1 |
Understanding the Ultrasonic Sensor
The ultrasonic sensor works by:
- Sending an ultrasonic pulse through the TRIG pin.
- Waiting for the reflected echo.
- Measuring the duration of the echo pulse.
- Calculating the distance using the speed of sound.
Distance Formula
Distance = (Time × Speed of Sound) ÷ 2
Where:
- Speed of Sound = 343 m/s
- Time = Echo pulse duration
The division by 2 is necessary because the sound travels to the object and back.
Circuit Connections
Ultrasonic Sensor Connections
| Sensor Pin | Raspberry Pi Pin |
| VCC | 5V |
| GND | GND |
| TRIG | GPIO23 |
| ECHO | GPIO24 (through voltage divider) |
Important Note
The ECHO pin outputs a 5V signal, while Raspberry Pi GPIO pins are only 3.3V tolerant. Therefore, a voltage divider must be used between the ECHO pin and GPIO24.
LCD I2C Connections
| LCD Pin | Raspberry Pi Pin |
| VCC | 5V |
| GND | GND |
| SDA | GPIO2 (SDA) |
| SCL | GPIO3 (SCL) |
Enabling I2C on Raspberry Pi
Before connecting the LCD, enable I2C:
sudo raspi-config
Navigate to:
Interface Options → I2C → Enable
Reboot the Raspberry Pi:
sudo reboot
Verify the LCD address:
sudo i2cdetect -y 1
Most LCD modules will appear at:
0x27
or
0x3F
Installing Required Libraries
Update your Raspberry Pi:
sudo apt update
Install required packages:
sudo apt install python3-smbus i2c-tools
Install Python libraries:
pip3 install RPLCD smbus2 --break-system-packages
Python Program
The Python program triggers the ultrasonic sensor, calculates the distance, averages multiple readings for improved accuracy, and displays the result on the LCD.
The LCD shows:
Water Level
Dist:125.4cm
The same value is also displayed in the terminal for debugging and monitoring purposes.
Complete Code
import RPi.GPIO as GPIO
import time
from RPLCD.i2c import CharLCD
# LCD Address
lcd = CharLCD(
i2c_expander='PCF8574',
address=0x27,
port=1,
cols=16,
rows=2
)
TRIG_PIN = 23
ECHO_PIN = 24
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)
GPIO.output(TRIG_PIN, False)
lcd.clear()
lcd.write_string("System Starting")
time.sleep(2)
def read_distance():
GPIO.output(TRIG_PIN, False)
time.sleep(0.000005)
GPIO.output(TRIG_PIN, True)
time.sleep(0.00002)
GPIO.output(TRIG_PIN, False)
timeout = time.perf_counter() + 0.03
while GPIO.input(ECHO_PIN) == 0:
pulse_start = time.perf_counter()
if time.perf_counter() > timeout:
return -1
timeout = time.perf_counter() + 0.03
while GPIO.input(ECHO_PIN) == 1:
pulse_end = time.perf_counter()
if time.perf_counter() > timeout:
return -1
pulse_duration = pulse_end - pulse_start
distance = (pulse_duration * 34300) / 2
return distance
try:
while True:
readings = []
for i in range(5):
d = read_distance()
if 0 < d < 600:
readings.append(d)
time.sleep(0.05)
lcd.clear()
if len(readings) > 0:
avg_distance = sum(readings) / len(readings)
print(f"Distance = {avg_distance:.2f} cm")
lcd.cursor_pos = (0, 0)
lcd.write_string("Water Level")
lcd.cursor_pos = (1, 0)
lcd.write_string(f"Dist:{avg_distance:5.1f}cm")
else:
print("No Valid Reading")
lcd.cursor_pos = (0, 0)
lcd.write_string("Sensor Error")
lcd.cursor_pos = (1, 0)
lcd.write_string("No Echo")
time.sleep(0.5)
except KeyboardInterrupt:
lcd.clear()
lcd.write_string("Program Stopped")
finally:
GPIO.cleanup()
lcd.close(clear=True)
Sample Output
LCD Display:
Water Level
Dist: 85.7cm
Terminal Output:
Distance = 85.70 cm
Distance = 85.65 cm
Distance = 85.73 cm
Applications
This project can be used in a variety of practical applications:
Water Tank Monitoring
Monitor water levels in overhead or underground tanks.
River and Canal Monitoring
Measure water levels in outdoor environments using the waterproof sensor.
Obstacle Detection
Detect objects and obstacles in robotic systems.
Smart Agriculture
Monitor water storage tanks and irrigation systems.
Industrial Automation
Measure distances in storage and material handling systems.
Advantages of Using a Waterproof Ultrasonic Sensor
- Suitable for outdoor environments
- Resistant to moisture and humidity
- Long measurement range
- Reliable operation in harsh conditions
- Ideal for water level monitoring systems
Troubleshooting
LCD Not Detected
Check:
sudo i2cdetect -y 1
Verify SDA and SCL connections.
No Distance Reading
Check:
- Sensor wiring
- Power supply voltage
- Voltage divider on ECHO pin
Unstable Readings
- Ensure a stable 5V supply.
- Average multiple readings.
- Keep the sensor surface clean.
- Avoid highly angled targets.
Conclusion
Using a Raspberry Pi Zero 2 W with a Waterproof Ultrasonic Sensor and a 16×2 LCD provides an excellent solution for accurate distance measurement and water level monitoring applications. The project is easy to build, cost-effective, and suitable for both educational and industrial applications.
0-40kg Scale Load Cell Weight Sensor
In stock
1 chamber ABS 18650 Battery Holder Storage Box Case With Hard Pin
In stock